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())
647bool LLParser::parseModuleAsm() {
655 Module::GlobalAsmProperties Props;
659 SMLoc Loc = Lex.getLoc();
661 return error(Loc,
"expected property name followed by ':'");
663 Key = Lex.getStrVal();
666 if (parseStringConstant(
Value))
670 return error(Loc,
"unknown property name");
680 std::string AsmStrPart;
681 if (parseStringConstant(AsmStrPart))
683 AsmStr += AsmStrPart +
"\n";
686 M->appendModuleInlineAsm({AsmStr, Props});
693bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
699 return tokError(
"unknown target property");
702 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
703 parseStringConstant(Str))
705 M->setTargetTriple(Triple(std::move(Str)));
709 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
711 DLStrLoc = Lex.getLoc();
712 if (parseStringConstant(TentativeDLStr))
720bool LLParser::parseSourceFileName() {
723 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
724 parseStringConstant(SourceFileName))
727 M->setSourceFileName(SourceFileName);
733bool LLParser::parseUnnamedType() {
734 LocTy TypeLoc = Lex.getLoc();
735 unsigned TypeID = Lex.getUIntVal();
738 if (parseToken(
lltok::equal,
"expected '=' after name") ||
743 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
747 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
749 return error(TypeLoc,
"non-struct types may not be recursive");
751 Entry.second = SMLoc();
759bool LLParser::parseNamedType() {
760 std::string
Name = Lex.getStrVal();
761 LocTy NameLoc = Lex.getLoc();
764 if (parseToken(
lltok::equal,
"expected '=' after name") ||
769 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
773 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
775 return error(NameLoc,
"non-struct types may not be recursive");
777 Entry.second = SMLoc();
785bool LLParser::parseDeclare() {
789 std::vector<std::pair<unsigned, MDNode *>> MDs;
793 if (parseMetadataAttachment(MDK,
N))
795 MDs.push_back({MDK,
N});
799 unsigned FunctionNumber = -1;
800 SmallVector<unsigned> UnnamedArgNums;
801 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
804 F->addMetadata(MD.first, *MD.second);
810bool LLParser::parseDefine() {
813 FileLoc FunctionStart = getTokLineColumnPos();
817 unsigned FunctionNumber = -1;
818 SmallVector<unsigned> UnnamedArgNums;
820 parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
821 parseOptionalFunctionMetadata(*
F) ||
822 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
824 ParserContext->addFunctionLocation(
825 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
833bool LLParser::parseGlobalType(
bool &IsConstant) {
840 return tokError(
"expected 'global' or 'constant'");
846bool LLParser::parseOptionalUnnamedAddr(
867bool LLParser::parseUnnamedGlobal() {
870 LocTy NameLoc = Lex.getLoc();
874 VarID = Lex.getUIntVal();
875 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
879 if (parseToken(
lltok::equal,
"expected '=' after name"))
882 VarID = NumberedVals.getNext();
886 unsigned Linkage, Visibility, DLLStorageClass;
890 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
892 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
895 switch (Lex.getKind()) {
897 return parseGlobal(Name,
VarID, NameLoc,
Linkage, HasLinkage, Visibility,
898 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
901 return parseAliasOrIFunc(Name,
VarID, NameLoc,
Linkage, Visibility,
902 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
911bool LLParser::parseNamedGlobal() {
913 LocTy NameLoc = Lex.getLoc();
914 std::string
Name = Lex.getStrVal();
918 unsigned Linkage, Visibility, DLLStorageClass;
922 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
923 parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
925 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
928 switch (Lex.getKind()) {
930 return parseGlobal(Name, -1, NameLoc,
Linkage, HasLinkage, Visibility,
931 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
934 return parseAliasOrIFunc(Name, -1, NameLoc,
Linkage, Visibility,
935 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
939bool LLParser::parseComdat() {
941 std::string
Name = Lex.getStrVal();
942 LocTy NameLoc = Lex.getLoc();
949 return tokError(
"expected comdat type");
952 switch (Lex.getKind()) {
954 return tokError(
"unknown selection kind");
976 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
977 return error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
980 if (
I != ComdatSymTab.
end())
983 C = M->getOrInsertComdat(Name);
984 C->setSelectionKind(SK);
991bool LLParser::parseMDString(
MDString *&Result) {
993 if (parseStringConstant(Str))
1001bool LLParser::parseMDNodeID(
MDNode *&Result) {
1003 LocTy IDLoc = Lex.getLoc();
1005 if (parseUInt32(MID))
1009 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
1016 auto &FwdRef = ForwardRefMDNodes[MID];
1019 Result = FwdRef.first.get();
1020 It->second.reset(Result);
1026bool LLParser::parseNamedMetadata() {
1028 std::string
Name = Lex.getStrVal();
1036 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1039 MDNode *
N =
nullptr;
1044 Lex.getStrVal() ==
"DIExpression") {
1045 if (parseDIExpression(
N,
false))
1050 Lex.getStrVal() ==
"DIArgList") {
1051 return tokError(
"found DIArgList outside of function");
1059 return parseToken(
lltok::rbrace,
"expected end of metadata node");
1064bool LLParser::parseStandaloneMetadata() {
1067 unsigned MetadataID = 0;
1070 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1075 return tokError(
"unexpected type in metadata definition");
1079 if (parseSpecializedMDNode(Init, IsDistinct))
1082 parseMDTuple(Init, IsDistinct))
1086 auto FI = ForwardRefMDNodes.find(MetadataID);
1087 if (FI != ForwardRefMDNodes.end()) {
1088 auto *ToReplace = FI->second.first.get();
1092 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1093 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1094 "Inst unexpectedly already has DIAssignID attachment");
1095 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1099 ToReplace->replaceAllUsesWith(Init);
1100 ForwardRefMDNodes.erase(FI);
1102 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
1104 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1106 return tokError(
"Metadata id is already used");
1107 It->second.reset(Init);
1114bool LLParser::skipModuleSummaryEntry() {
1124 return tokError(
"Expected 'gv', 'module', 'typeid', "
1125 "'typeidCompatibleVTable', 'flags' or 'blockcount' at the "
1126 "start of summary entry");
1128 return parseSummaryIndexFlags();
1130 return parseBlockCount();
1132 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1133 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1137 unsigned NumOpenParen = 1;
1139 switch (Lex.getKind()) {
1147 return tokError(
"found end of file while parsing summary entry");
1153 }
while (NumOpenParen > 0);
1159bool LLParser::parseSummaryEntry() {
1165 Lex.setIgnoreColonInIdentifiers(
true);
1173 return skipModuleSummaryEntry();
1175 bool result =
false;
1176 switch (Lex.getKind()) {
1178 result = parseGVEntry(SummaryID);
1181 result = parseModuleEntry(SummaryID);
1184 result = parseTypeIdEntry(SummaryID);
1187 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1190 result = parseSummaryIndexFlags();
1193 result = parseBlockCount();
1196 result =
error(Lex.getLoc(),
"unexpected summary kind");
1199 Lex.setIgnoreColonInIdentifiers(
false);
1233bool LLParser::parseAliasOrIFunc(
const std::string &Name,
unsigned NameID,
1234 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1235 unsigned DLLStorageClass,
bool DSOLocal,
1250 return error(NameLoc,
"invalid linkage type for alias");
1253 return error(NameLoc,
1254 "symbol with local linkage must have default visibility");
1257 return error(NameLoc,
1258 "symbol with local linkage cannot have a DLL storage class");
1261 LocTy ExplicitTypeLoc = Lex.getLoc();
1262 if (parseType(Ty) ||
1263 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1267 LocTy AliaseeLoc = Lex.getLoc();
1272 if (parseGlobalTypeAndValue(Aliasee))
1277 if (parseValID(
ID,
nullptr))
1280 return error(AliaseeLoc,
"invalid aliasee");
1281 Aliasee =
ID.ConstantVal;
1287 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1288 unsigned AddrSpace = PTy->getAddressSpace();
1290 GlobalValue *GVal =
nullptr;
1294 if (!
Name.empty()) {
1295 auto I = ForwardRefVals.find(Name);
1296 if (
I != ForwardRefVals.end()) {
1297 GVal =
I->second.first;
1298 ForwardRefVals.erase(Name);
1299 }
else if (M->getNamedValue(Name)) {
1300 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1303 auto I = ForwardRefValIDs.find(NameID);
1304 if (
I != ForwardRefValIDs.end()) {
1305 GVal =
I->second.first;
1306 ForwardRefValIDs.erase(
I);
1311 std::unique_ptr<GlobalAlias> GA;
1312 std::unique_ptr<GlobalIFunc> GI;
1340 if (parseGlobalObjectMetadataAttachment(*GI))
1343 return tokError(
"unknown alias or ifunc property!");
1348 NumberedVals.add(NameID, GV);
1355 "forward reference and definition of alias have different types");
1365 M->insertAlias(GA.release());
1367 M->insertIFunc(GI.release());
1368 assert(GV->
getName() == Name &&
"Should not be a name conflict!");
1377 case lltok::kw_sanitize_memtag:
1391 switch (Lex.getKind()) {
1393 Meta.NoAddress =
true;
1396 Meta.NoHWAddress =
true;
1398 case lltok::kw_sanitize_memtag:
1402 Meta.IsDynInit =
true;
1405 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1425bool LLParser::parseGlobal(
const std::string &Name,
unsigned NameID,
1426 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1427 unsigned Visibility,
unsigned DLLStorageClass,
1431 return error(NameLoc,
1432 "symbol with local linkage must have default visibility");
1435 return error(NameLoc,
1436 "symbol with local linkage cannot have a DLL storage class");
1440 LocTy IsExternallyInitializedLoc;
1444 if (parseOptionalAddrSpace(AddrSpace) ||
1446 IsExternallyInitialized,
1447 &IsExternallyInitializedLoc) ||
1448 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1457 if (parseGlobalValue(Ty, Init))
1462 return error(TyLoc,
"invalid type for global variable");
1464 GlobalValue *GVal =
nullptr;
1467 if (!
Name.empty()) {
1468 auto I = ForwardRefVals.find(Name);
1469 if (
I != ForwardRefVals.end()) {
1470 GVal =
I->second.first;
1471 ForwardRefVals.erase(
I);
1472 }
else if (M->getNamedValue(Name)) {
1473 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1478 if (NameID == (
unsigned)-1)
1479 NameID = NumberedVals.getNext();
1481 auto I = ForwardRefValIDs.find(NameID);
1482 if (
I != ForwardRefValIDs.end()) {
1483 GVal =
I->second.first;
1484 ForwardRefValIDs.erase(
I);
1488 GlobalVariable *GV =
new GlobalVariable(
1493 NumberedVals.add(NameID, GV);
1511 "forward reference and definition of global have different types");
1531 }
else if (Lex.getKind() == lltok::kw_align) {
1532 MaybeAlign Alignment;
1533 if (parseOptionalAlignment(Alignment))
1539 if (parseOptionalCodeModel(CodeModel))
1543 if (parseGlobalObjectMetadataAttachment(*GV))
1546 if (parseSanitizer(GV))
1550 if (parseOptionalComdat(Name,
C))
1555 return tokError(
"unknown global variable property!");
1559 AttrBuilder
Attrs(M->getContext());
1561 std::vector<unsigned> FwdRefAttrGrps;
1562 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1564 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1566 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1574bool LLParser::parseUnnamedAttrGrp() {
1576 LocTy AttrGrpLoc = Lex.getLoc();
1580 return tokError(
"expected attribute group id");
1582 unsigned VarID = Lex.getUIntVal();
1583 std::vector<unsigned> unused;
1591 auto R = NumberedAttrBuilders.find(
VarID);
1592 if (R == NumberedAttrBuilders.end())
1593 R = NumberedAttrBuilders.emplace(
VarID, AttrBuilder(M->getContext())).first;
1595 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1596 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1599 if (!
R->second.hasAttributes())
1600 return error(AttrGrpLoc,
"attribute group has no attributes");
1607#define GET_ATTR_NAMES
1608#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1609 case lltok::kw_##DISPLAY_NAME: \
1610 return Attribute::ENUM_NAME;
1611#include "llvm/IR/Attributes.inc"
1620 return parseRequiredTypeAttr(
B, Lex.getKind(), Attr);
1623 case Attribute::Alignment: {
1624 MaybeAlign Alignment;
1632 if (parseOptionalAlignment(Alignment,
true))
1635 B.addAlignmentAttr(Alignment);
1638 case Attribute::StackAlignment: {
1643 parseUInt32(Alignment))
1646 if (parseOptionalStackAlignment(Alignment))
1649 B.addStackAlignmentAttr(Alignment);
1652 case Attribute::AllocSize: {
1653 unsigned ElemSizeArg;
1654 std::optional<unsigned> NumElemsArg;
1655 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1657 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1660 case Attribute::VScaleRange: {
1661 unsigned MinValue, MaxValue;
1662 if (parseVScaleRangeArguments(MinValue, MaxValue))
1664 B.addVScaleRangeAttr(MinValue,
1665 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1668 case Attribute::Dereferenceable: {
1669 std::optional<uint64_t> Bytes;
1670 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1672 assert(Bytes.has_value());
1673 B.addDereferenceableAttr(Bytes.value());
1676 case Attribute::DeadOnReturn: {
1677 std::optional<uint64_t> Bytes;
1678 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1681 if (Bytes.has_value()) {
1682 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1684 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1688 case Attribute::DereferenceableOrNull: {
1689 std::optional<uint64_t> Bytes;
1690 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1692 assert(Bytes.has_value());
1693 B.addDereferenceableOrNullAttr(Bytes.value());
1696 case Attribute::UWTable: {
1698 if (parseOptionalUWTableKind(Kind))
1700 B.addUWTableAttr(Kind);
1703 case Attribute::AllocKind: {
1705 if (parseAllocKind(Kind))
1707 B.addAllocKindAttr(Kind);
1710 case Attribute::Memory: {
1711 std::optional<MemoryEffects> ME = parseMemoryAttr();
1714 B.addMemoryAttr(*ME);
1717 case Attribute::DenormalFPEnv: {
1718 std::optional<DenormalFPEnv>
Mode = parseDenormalFPEnvAttr();
1722 B.addDenormalFPEnvAttr(*
Mode);
1725 case Attribute::NoFPClass: {
1728 B.addNoFPClassAttr(NoFPClass);
1734 case Attribute::Range:
1735 return parseRangeAttr(
B);
1736 case Attribute::Initializes:
1737 return parseInitializesAttr(
B);
1738 case Attribute::Captures:
1739 return parseCapturesAttr(
B);
1741 B.addAttribute(Attr);
1749 case lltok::kw_readnone:
1752 case lltok::kw_readonly:
1755 case lltok::kw_writeonly:
1774bool LLParser::parseFnAttributeValuePairs(AttrBuilder &
B,
1775 std::vector<unsigned> &FwdRefAttrGrps,
1776 bool InAttrGrp, LocTy &BuiltinLoc) {
1777 bool HaveError =
false;
1788 if (parseStringAttribute(
B))
1800 "cannot have an attribute group reference in an attribute group");
1803 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1809 SMLoc Loc = Lex.getLoc();
1810 if (Token == lltok::kw_builtin)
1822 return error(Lex.getLoc(),
"unterminated attribute group");
1825 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1832 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1836 B.addMemoryAttr(ME);
1850 PTy->getAddressSpace());
1859 error(Loc,
"'" + Name +
"' is not a basic block");
1861 error(Loc,
"'" + Name +
"' defined with type '" +
1874 error(Loc,
"global variable reference must have pointer type");
1885 auto I = ForwardRefVals.find(Name);
1886 if (
I != ForwardRefVals.end())
1887 Val =
I->second.first;
1893 checkValidVariableType(Loc,
"@" + Name, Ty, Val));
1897 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1904 error(Loc,
"global variable reference must have pointer type");
1908 GlobalValue *Val = NumberedVals.get(
ID);
1913 auto I = ForwardRefValIDs.find(
ID);
1914 if (
I != ForwardRefValIDs.end())
1915 Val =
I->second.first;
1921 checkValidVariableType(Loc,
"@" + Twine(
ID), Ty, Val));
1925 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1933Comdat *LLParser::getComdat(
const std::string &Name, LocTy
Loc) {
1937 if (
I != ComdatSymTab.
end())
1941 Comdat *
C = M->getOrInsertComdat(Name);
1942 ForwardRefComdats[
Name] = Loc;
1952bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1953 if (Lex.getKind() !=
T)
1954 return tokError(ErrMsg);
1961bool LLParser::parseStringConstant(std::string &Result) {
1963 return tokError(
"expected string constant");
1964 Result = Lex.getStrVal();
1971bool LLParser::parseUInt32(uint32_t &Val) {
1972 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1973 return tokError(
"expected integer");
1974 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1975 if (Val64 !=
unsigned(Val64))
1976 return tokError(
"expected 32-bit integer (too large)");
1984bool LLParser::parseUInt64(uint64_t &Val) {
1985 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1986 return tokError(
"expected integer");
1987 Val = Lex.getAPSIntVal().getLimitedValue();
1997 switch (Lex.getKind()) {
1999 return tokError(
"expected localdynamic, initialexec or localexec");
2027 return parseTLSModel(TLM) ||
2028 parseToken(
lltok::rparen,
"expected ')' after thread local model");
2036bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
2037 AddrSpace = DefaultAS;
2041 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
2043 const std::string &AddrSpaceStr = Lex.getStrVal();
2044 if (AddrSpaceStr ==
"A") {
2045 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2046 }
else if (AddrSpaceStr ==
"G") {
2047 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2048 }
else if (AddrSpaceStr ==
"P") {
2049 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2050 }
else if (std::optional<unsigned> AS =
2051 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2054 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
2060 return tokError(
"expected integer or string constant");
2061 SMLoc Loc = Lex.getLoc();
2062 if (parseUInt32(AddrSpace))
2065 return error(Loc,
"invalid address space, must be a 24-bit integer");
2069 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
2070 ParseAddrspaceValue(AddrSpace) ||
2077bool LLParser::parseStringAttribute(AttrBuilder &
B) {
2078 std::string Attr = Lex.getStrVal();
2081 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
2083 B.addAttribute(Attr, Val);
2088bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &
B,
bool IsParam) {
2089 bool HaveError =
false;
2096 if (parseStringAttribute(
B))
2107 SMLoc Loc = Lex.getLoc();
2112 if (parseEnumAttribute(Attr,
B,
false))
2116 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2118 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2166bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2167 unsigned &Visibility,
2168 unsigned &DLLStorageClass,
bool &DSOLocal) {
2172 parseOptionalDSOLocal(DSOLocal);
2173 parseOptionalVisibility(Visibility);
2174 parseOptionalDLLStorageClass(DLLStorageClass);
2177 return error(Lex.getLoc(),
"dso_location and DLL-StorageClass mismatch");
2183void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2184 switch (Lex.getKind()) {
2205void LLParser::parseOptionalVisibility(
unsigned &Res) {
2206 switch (Lex.getKind()) {
2223bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2227 return tokError(
"unknown import kind. Expect definition or declaration.");
2242void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2243 switch (Lex.getKind()) {
2313bool LLParser::parseOptionalCallingConv(
unsigned &CC) {
2314 switch (Lex.getKind()) {
2401 return tokError(
"unknown RISC-V ABI VLEN");
2402#define CC_VLS_CASE(ABIVlen) \
2404 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2432 return parseUInt32(CC);
2442bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2445 std::string
Name = Lex.getStrVal();
2446 Kind = M->getMDKindID(Name);
2449 return parseMDNode(MD);
2454bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2457 return tokError(
"expected metadata after comma");
2461 auto Loc = Lex.getLoc();
2462 if (parseMetadataAttachment(MDK,
N))
2465 if (MDK == LLVMContext::MD_DIAssignID)
2466 TempDIAssignIDAttachments[
N].push_back(&Inst);
2467 else if (MDK == LLVMContext::MD_dbg)
2468 PendingDbgInsts.emplace_back(Loc, &Inst,
N);
2472 if (MDK == LLVMContext::MD_tbaa)
2473 InstsWithTBAATag.push_back(&Inst);
2482bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2485 if (parseMetadataAttachment(MDK,
N))
2494bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2496 if (parseGlobalObjectMetadataAttachment(
F))
2504bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2505 Alignment = std::nullopt;
2506 if (!EatIfPresent(lltok::kw_align))
2508 LocTy AlignLoc = Lex.getLoc();
2511 LocTy ParenLoc = Lex.getLoc();
2512 bool HaveParens =
false;
2518 if (parseUInt64(
Value))
2522 return error(ParenLoc,
"expected ')'");
2525 return error(AlignLoc,
"alignment is not a power of two");
2527 return error(AlignLoc,
"huge alignments are not supported yet");
2535bool LLParser::parseOptionalPrefAlignment(
MaybeAlign &Alignment) {
2536 Alignment = std::nullopt;
2539 LocTy AlignLoc = Lex.getLoc();
2542 LocTy ParenLoc = Lex.getLoc();
2544 return error(ParenLoc,
"expected '('");
2546 if (parseUInt64(
Value))
2549 ParenLoc = Lex.getLoc();
2551 return error(ParenLoc,
"expected ')'");
2554 return error(AlignLoc,
"alignment is not a power of two");
2556 return error(AlignLoc,
"huge alignments are not supported yet");
2566 auto StrVal = Lex.getStrVal();
2567 auto ErrMsg =
"expected global code model string";
2568 if (StrVal ==
"tiny")
2570 else if (StrVal ==
"small")
2572 else if (StrVal ==
"kernel")
2574 else if (StrVal ==
"medium")
2576 else if (StrVal ==
"large")
2579 return tokError(ErrMsg);
2591bool LLParser::parseOptionalAttrBytes(
lltok::Kind AttrKind,
2592 std::optional<uint64_t> &Bytes,
2593 bool ErrorNoBytes) {
2594 assert((AttrKind == lltok::kw_dereferenceable ||
2595 AttrKind == lltok::kw_dereferenceable_or_null ||
2596 AttrKind == lltok::kw_dead_on_return) &&
2600 if (!EatIfPresent(AttrKind))
2602 LocTy ParenLoc = Lex.getLoc();
2605 return error(ParenLoc,
"expected '('");
2606 Bytes = std::nullopt;
2609 LocTy DerefLoc = Lex.getLoc();
2610 if (parseUInt64(Bytes.value()))
2612 ParenLoc = Lex.getLoc();
2614 return error(ParenLoc,
"expected ')'");
2616 return error(DerefLoc,
"byte count specified must be non-zero");
2620bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2625 LocTy KindLoc = Lex.getLoc();
2631 return error(KindLoc,
"expected unwind table kind");
2638 LocTy ParenLoc = Lex.getLoc();
2640 return error(ParenLoc,
"expected '('");
2641 LocTy KindLoc = Lex.getLoc();
2643 if (parseStringConstant(Arg))
2644 return error(KindLoc,
"expected allockind value");
2648 }
else if (
A ==
"realloc") {
2650 }
else if (
A ==
"free") {
2652 }
else if (
A ==
"uninitialized") {
2654 }
else if (
A ==
"zeroed") {
2656 }
else if (
A ==
"aligned") {
2659 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2662 ParenLoc = Lex.getLoc();
2664 return error(ParenLoc,
"expected ')'");
2666 return error(KindLoc,
"expected allockind value");
2675 return {Loc::ArgMem};
2677 return {Loc::InaccessibleMem};
2679 return {Loc::ErrnoMem};
2681 return {Loc::TargetMem0};
2683 return {Loc::TargetMem1};
2706 return std::nullopt;
2710static std::optional<DenormalMode::DenormalModeKind>
2722 return std::nullopt;
2726std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2731 Lex.setIgnoreColonInIdentifiers(
true);
2736 tokError(
"expected '('");
2737 return std::nullopt;
2740 bool SeenLoc =
false;
2741 bool SeenTargetLoc =
false;
2744 if (!Locs.
empty()) {
2747 tokError(
"expected ':' after location");
2748 return std::nullopt;
2755 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2756 "or access kind (none, read, write, readwrite)");
2758 tokError(
"expected access kind (none, read, write, readwrite)");
2759 return std::nullopt;
2763 if (!Locs.
empty()) {
2768 SeenTargetLoc =
true;
2770 if (Locs.size() > 1 && SeenTargetLoc) {
2771 tokError(
"target memory default access kind must be specified first");
2772 return std::nullopt;
2777 tokError(
"default access kind must be specified first");
2778 return std::nullopt;
2787 tokError(
"unterminated memory attribute");
2788 return std::nullopt;
2791std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2792 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2795 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2796 "positivezero, dynamic)");
2802 std::optional<DenormalMode::DenormalModeKind> InputMode;
2806 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2807 "positivezero, dynamic)");
2814 InputMode = OutputMode;
2817 return DenormalMode(*OutputMode, *InputMode);
2820std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2823 Lex.setIgnoreColonInIdentifiers(
true);
2834 bool HasDefaultSection =
false;
2836 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2837 if (!ParsedDefaultMode)
2839 DefaultMode = *ParsedDefaultMode;
2840 HasDefaultSection =
true;
2845 if (HasDefaultSection && !HasComma) {
2846 tokError(
"expected ',' before float:");
2851 if (parseType(Ty) || !Ty->
isFloatTy()) {
2852 tokError(
"expected float:");
2856 if (parseToken(
lltok::colon,
"expected ':' before float denormal_fpenv"))
2859 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2863 F32Mode = *ParsedF32Mode;
2866 if (parseToken(
lltok::rparen,
"unterminated denormal_fpenv"))
2869 return DenormalFPEnv(DefaultMode, F32Mode);
2911unsigned LLParser::parseNoFPClassAttr() {
2916 tokError(
"expected '('");
2923 if (TestMask != 0) {
2927 !parseUInt64(
Value)) {
2929 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
2934 error(Lex.getLoc(),
"expected ')'");
2940 error(Lex.getLoc(),
"expected nofpclass test mask");
2958bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2959 bool &AteExtraComma) {
2960 AteExtraComma =
false;
2964 AteExtraComma =
true;
2968 if (Lex.getKind() != lltok::kw_align)
2969 return error(Lex.getLoc(),
"expected metadata or 'align'");
2971 if (parseOptionalAlignment(Alignment))
2984bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
2985 bool &AteExtraComma) {
2986 AteExtraComma =
false;
2990 AteExtraComma =
true;
2996 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
2998 if (parseOptionalAddrSpace(AddrSpace))
3005bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
3006 std::optional<unsigned> &HowManyArg) {
3009 auto StartParen = Lex.getLoc();
3011 return error(StartParen,
"expected '('");
3013 if (parseUInt32(BaseSizeArg))
3017 auto HowManyAt = Lex.getLoc();
3019 if (parseUInt32(HowMany))
3021 if (HowMany == BaseSizeArg)
3022 return error(HowManyAt,
3023 "'allocsize' indices can't refer to the same parameter");
3024 HowManyArg = HowMany;
3026 HowManyArg = std::nullopt;
3028 auto EndParen = Lex.getLoc();
3030 return error(EndParen,
"expected ')'");
3034bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
3035 unsigned &MaxValue) {
3038 auto StartParen = Lex.getLoc();
3040 return error(StartParen,
"expected '('");
3042 if (parseUInt32(MinValue))
3046 if (parseUInt32(MaxValue))
3049 MaxValue = MinValue;
3051 auto EndParen = Lex.getLoc();
3053 return error(EndParen,
"expected ')'");
3062bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
3067 return parseScope(SSID) || parseOrdering(Ordering);
3077 auto StartParenAt = Lex.getLoc();
3079 return error(StartParenAt,
"Expected '(' in syncscope");
3082 auto SSNAt = Lex.getLoc();
3083 if (parseStringConstant(SSN))
3084 return error(SSNAt,
"Expected synchronization scope name");
3086 auto EndParenAt = Lex.getLoc();
3088 return error(EndParenAt,
"Expected ')' in syncscope");
3090 SSID = Context.getOrInsertSyncScopeID(SSN);
3101 switch (Lex.getKind()) {
3103 return tokError(
"Expected ordering on atomic instruction");
3122bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
3124 if (!EatIfPresent(lltok::kw_alignstack))
3126 LocTy ParenLoc = Lex.getLoc();
3128 return error(ParenLoc,
"expected '('");
3129 LocTy AlignLoc = Lex.getLoc();
3130 if (parseUInt32(Alignment))
3132 ParenLoc = Lex.getLoc();
3134 return error(ParenLoc,
"expected ')'");
3136 return error(AlignLoc,
"stack alignment is not a power of two");
3150 bool &AteExtraComma) {
3151 AteExtraComma =
false;
3154 return tokError(
"expected ',' as start of index list");
3158 if (Indices.
empty())
3159 return tokError(
"expected index");
3160 AteExtraComma =
true;
3164 if (parseUInt32(Idx))
3177bool LLParser::parseType(
Type *&Result,
const Twine &
Msg,
bool AllowVoid) {
3178 SMLoc TypeLoc = Lex.getLoc();
3179 switch (Lex.getKind()) {
3181 return tokError(
Msg);
3190 if (
Result->isPointerTy()) {
3192 if (parseOptionalAddrSpace(AddrSpace))
3198 return tokError(
"ptr* is invalid - use ptr instead");
3209 if (parseTargetExtType(Result))
3215 if (parseAnonStructType(Result,
false))
3221 if (parseArrayVectorType(Result,
false))
3228 if (parseAnonStructType(Result,
true) ||
3229 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
3231 }
else if (parseArrayVectorType(Result,
true))
3236 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
3242 Entry.second = Lex.getLoc();
3251 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
3257 Entry.second = Lex.getLoc();
3267 switch (Lex.getKind()) {
3270 if (!AllowVoid &&
Result->isVoidTy())
3271 return error(TypeLoc,
"void type only allowed for function results");
3277 return tokError(
"basic block pointers are invalid");
3279 return tokError(
"pointers to void are invalid - use i8* instead");
3281 return tokError(
"pointer to this type is invalid");
3289 return tokError(
"basic block pointers are invalid");
3291 return tokError(
"pointers to void are invalid; use i8* instead");
3293 return tokError(
"pointer to this type is invalid");
3295 if (parseOptionalAddrSpace(AddrSpace) ||
3296 parseToken(
lltok::star,
"expected '*' in address space"))
3305 if (parseFunctionType(Result))
3318 PerFunctionState &PFS,
bool IsMustTailCall,
3319 bool InVarArgsFunc) {
3325 if (!ArgList.
empty() &&
3326 parseToken(
lltok::comma,
"expected ',' in argument list"))
3331 const char *
Msg =
"unexpected ellipsis in argument list for ";
3332 if (!IsMustTailCall)
3333 return tokError(Twine(
Msg) +
"non-musttail call");
3335 return tokError(Twine(
Msg) +
"musttail call in non-varargs function");
3337 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3342 Type *ArgTy =
nullptr;
3344 if (parseType(ArgTy, ArgLoc))
3347 return error(ArgLoc,
"invalid type for function argument");
3349 AttrBuilder ArgAttrs(M->getContext());
3352 if (parseMetadataAsValue(V, PFS))
3356 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3363 if (IsMustTailCall && InVarArgsFunc)
3364 return tokError(
"expected '...' at end of argument list for musttail call "
3365 "in varargs function");
3373bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3376 if (!EatIfPresent(AttrToken))
3379 return error(Lex.getLoc(),
"expected '('");
3383 return error(Lex.getLoc(),
"expected ')'");
3385 B.addTypeAttr(AttrKind, Ty);
3391bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3399 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3401 return tokError(
"expected integer");
3402 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3404 "integer is too large for the bit width of specified type");
3405 Val = Lex.getAPSIntVal().extend(
BitWidth);
3410 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3413 return error(TyLoc,
"the range must have integer type!");
3421 return tokError(
"the range represent the empty set but limits aren't 0!");
3432bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3435 auto ParseAPSInt = [&](APInt &Val) {
3437 return tokError(
"expected integer");
3438 Val = Lex.getAPSIntVal().extend(64);
3458 return tokError(
"the range should not represent the full or empty set!");
3470 if (!CRLOrNull.has_value())
3471 return tokError(
"Invalid (unordered or overlapping) range list");
3472 B.addInitializesAttr(*CRLOrNull);
3476bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3478 std::optional<CaptureComponents> Ret;
3482 Lex.setIgnoreColonInIdentifiers(
true);
3490 bool SeenComponent =
false;
3496 return tokError(
"duplicate 'ret' location");
3499 SeenComponent =
false;
3504 return tokError(
"cannot use 'none' with other component");
3508 return tokError(
"cannot use 'none' with other component");
3519 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3520 "'provenance' or 'read_provenance'");
3523 SeenComponent =
true;
3531 B.addCapturesAttr(CaptureInfo(
Other, Ret.value_or(
Other)));
3544bool LLParser::parseOptionalOperandBundles(
3546 LocTy BeginLoc = Lex.getLoc();
3552 if (!BundleList.
empty() &&
3553 parseToken(
lltok::comma,
"expected ',' in input list"))
3557 if (parseStringConstant(
Tag))
3560 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3563 std::vector<Value *> Inputs;
3566 if (!Inputs.empty() &&
3567 parseToken(
lltok::comma,
"expected ',' in input list"))
3571 Value *Input =
nullptr;
3575 if (parseMetadataAsValue(Input, PFS))
3577 }
else if (parseValue(Ty, Input, PFS)) {
3580 Inputs.push_back(Input);
3588 if (BundleList.
empty())
3589 return error(BeginLoc,
"operand bundle set must not be empty");
3596 unsigned NextID,
unsigned ID) {
3598 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3599 Twine(NextID) +
"' or greater");
3616 unsigned CurValID = 0;
3630 LocTy TypeLoc = Lex.getLoc();
3631 Type *ArgTy =
nullptr;
3632 AttrBuilder
Attrs(M->getContext());
3633 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3637 return error(TypeLoc,
"argument can not have void type");
3642 bool Unnamed =
false;
3644 Name = Lex.getStrVal();
3645 IdentStart = getTokLineColumnPos();
3647 IdentEnd = getPrevTokEndLineColumnPos();
3651 ArgID = Lex.getUIntVal();
3652 IdentStart = getTokLineColumnPos();
3653 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3656 IdentEnd = getPrevTokEndLineColumnPos();
3662 CurValID = ArgID + 1;
3666 return error(TypeLoc,
"invalid type for function argument");
3670 Unnamed ? std::nullopt
3671 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3676 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3681bool LLParser::parseFunctionType(
Type *&Result) {
3685 return tokError(
"invalid function return type");
3689 SmallVector<unsigned> UnnamedArgNums;
3690 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3694 for (
const ArgInfo &Arg : ArgList) {
3695 if (!Arg.Name.empty())
3696 return error(Arg.Loc,
"argument name invalid in function type");
3697 if (Arg.Attrs.hasAttributes())
3698 return error(Arg.Loc,
"argument attributes invalid in function type");
3702 for (
const ArgInfo &Arg : ArgList)
3711bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3713 if (parseStructBody(Elts))
3721bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3722 std::pair<Type *, LocTy> &Entry,
3726 return error(TypeLoc,
"redefinition of type");
3732 Entry.second = SMLoc();
3737 ResultTy =
Entry.first;
3749 return error(TypeLoc,
"forward references to non-struct type");
3753 return parseArrayVectorType(ResultTy,
true);
3754 return parseType(ResultTy);
3758 Entry.second = SMLoc();
3767 if (parseStructBody(Body) ||
3768 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3772 return tokError(
toString(std::move(
E)));
3792 LocTy EltTyLoc = Lex.getLoc();
3799 return error(EltTyLoc,
"invalid element type for struct");
3802 EltTyLoc = Lex.getLoc();
3807 return error(EltTyLoc,
"invalid element type for struct");
3812 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3821bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3822 bool Scalable =
false;
3826 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3832 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3833 Lex.getAPSIntVal().getBitWidth() > 64)
3834 return tokError(
"expected number in address space");
3836 LocTy SizeLoc = Lex.getLoc();
3837 uint64_t
Size = Lex.getAPSIntVal().getZExtValue();
3840 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3843 LocTy TypeLoc = Lex.getLoc();
3844 Type *EltTy =
nullptr;
3845 if (parseType(EltTy))
3849 "expected end of sequential type"))
3854 return error(SizeLoc,
"zero element vector is illegal");
3856 return error(SizeLoc,
"size too large for vector");
3858 return error(TypeLoc,
"invalid vector element type");
3862 return error(TypeLoc,
"invalid array element type");
3879bool LLParser::parseTargetExtType(
Type *&Result) {
3884 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3885 parseStringConstant(TypeName))
3892 SmallVector<unsigned> IntParams;
3893 bool SeenInt =
false;
3900 if (parseUInt32(IntVal))
3903 }
else if (SeenInt) {
3906 return tokError(
"expected uint32 param");
3909 if (parseType(TypeParam,
true))
3915 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3920 if (
auto E = TTy.takeError())
3921 return tokError(
toString(std::move(
E)));
3934 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3937 auto It = UnnamedArgNums.
begin();
3940 unsigned ArgNum = *It++;
3941 NumberedVals.add(ArgNum, &A);
3946LLParser::PerFunctionState::~PerFunctionState() {
3949 for (
const auto &P : ForwardRefVals) {
3952 P.second.first->replaceAllUsesWith(
3954 P.second.first->deleteValue();
3957 for (
const auto &P : ForwardRefValIDs) {
3960 P.second.first->replaceAllUsesWith(
3962 P.second.first->deleteValue();
3966bool LLParser::PerFunctionState::finishFunction() {
3967 if (!ForwardRefVals.empty())
3968 return P.error(ForwardRefVals.begin()->second.second,
3969 "use of undefined value '%" + ForwardRefVals.begin()->first +
3971 if (!ForwardRefValIDs.empty())
3972 return P.error(ForwardRefValIDs.begin()->second.second,
3973 "use of undefined value '%" +
3974 Twine(ForwardRefValIDs.begin()->first) +
"'");
3981Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
3984 Value *Val =
F.getValueSymbolTable()->lookup(Name);
3989 auto I = ForwardRefVals.find(Name);
3990 if (
I != ForwardRefVals.end())
3991 Val =
I->second.first;
3996 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
4000 P.error(Loc,
"invalid use of a non-first-class type");
4011 if (FwdVal->
getName() != Name) {
4012 P.error(Loc,
"name is too long which can result in name collisions, "
4013 "consider making the name shorter or "
4014 "increasing -non-global-value-max-name-size");
4018 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
4022Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
4024 Value *Val = NumberedVals.get(
ID);
4029 auto I = ForwardRefValIDs.find(
ID);
4030 if (
I != ForwardRefValIDs.end())
4031 Val =
I->second.first;
4036 return P.checkValidVariableType(Loc,
"%" + Twine(
ID), Ty, Val);
4039 P.error(Loc,
"invalid use of a non-first-class type");
4051 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
4057bool LLParser::PerFunctionState::setInstName(
int NameID,
4058 const std::string &NameStr,
4059 LocTy NameLoc, Instruction *Inst) {
4062 if (NameID != -1 || !NameStr.empty())
4063 return P.error(NameLoc,
"instructions returning void cannot have a name");
4069 if (NameStr.empty()) {
4072 NameID = NumberedVals.getNext();
4074 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
4078 auto FI = ForwardRefValIDs.find(NameID);
4079 if (FI != ForwardRefValIDs.end()) {
4082 return P.error(NameLoc,
"instruction forward referenced with type '" +
4086 Sentinel->replaceAllUsesWith(Inst);
4088 ForwardRefValIDs.erase(FI);
4091 NumberedVals.add(NameID, Inst);
4096 auto FI = ForwardRefVals.find(NameStr);
4097 if (FI != ForwardRefVals.end()) {
4100 return P.error(NameLoc,
"instruction forward referenced with type '" +
4104 Sentinel->replaceAllUsesWith(Inst);
4106 ForwardRefVals.erase(FI);
4112 if (Inst->
getName() != NameStr)
4113 return P.error(NameLoc,
"multiple definition of local value named '" +
4120BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
4134BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
4135 int NameID,
LocTy Loc) {
4139 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
4142 NameID = NumberedVals.getNext();
4144 BB = getBB(NameID, Loc);
4146 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
4150 BB = getBB(Name, Loc);
4152 P.error(Loc,
"unable to create block named '" + Name +
"'");
4163 ForwardRefValIDs.erase(NameID);
4164 NumberedVals.add(NameID, BB);
4167 ForwardRefVals.erase(Name);
4184bool LLParser::parseValID(ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
4185 ID.Loc = Lex.getLoc();
4186 switch (Lex.getKind()) {
4188 return tokError(
"expected value token");
4190 ID.UIntVal = Lex.getUIntVal();
4194 ID.StrVal = Lex.getStrVal();
4198 ID.UIntVal = Lex.getUIntVal();
4202 ID.StrVal = Lex.getStrVal();
4206 ID.APSIntVal = Lex.getAPSIntVal();
4210 ID.APFloatVal = Lex.getAPFloatVal();
4216 return error(
ID.Loc,
"unexpected floating-point literal");
4218 return error(
ID.Loc,
"floating-point constant invalid for type");
4223 "Invalid float strings should be caught by the lexer");
4228 return error(
ID.Loc,
"floating-point constant overflowed type");
4230 return error(
ID.Loc,
"floating-point constant underflowed type");
4236 return error(
ID.Loc,
"unexpected floating-point literal");
4238 const APInt &
Bits = Lex.getAPSIntVal();
4240 return error(
ID.Loc,
"float hex literal has incorrect number of bits");
4241 ID.APFloatVal =
APFloat(Semantics, Bits);
4263 if (parseGlobalValueVector(Elts) ||
4264 parseToken(
lltok::rbrace,
"expected end of struct constant"))
4267 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4268 ID.UIntVal = Elts.
size();
4269 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4270 Elts.
size() *
sizeof(Elts[0]));
4281 LocTy FirstEltLoc = Lex.getLoc();
4282 if (parseGlobalValueVector(Elts) ||
4284 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
4288 if (isPackedStruct) {
4289 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4290 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4291 Elts.
size() *
sizeof(Elts[0]));
4292 ID.UIntVal = Elts.
size();
4298 return error(
ID.Loc,
"constant vector must not be empty");
4300 if (!Elts[0]->
getType()->isIntegerTy() && !Elts[0]->
getType()->isByteTy() &&
4301 !Elts[0]->
getType()->isFloatingPointTy() &&
4305 "vector elements must have integer, byte, pointer or floating point "
4309 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
4311 return error(FirstEltLoc,
"vector element #" + Twine(i) +
4312 " is not of type '" +
4322 LocTy FirstEltLoc = Lex.getLoc();
4323 if (parseGlobalValueVector(Elts) ||
4335 if (!Elts[0]->
getType()->isFirstClassType())
4336 return error(FirstEltLoc,
"invalid array element type: " +
4342 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4344 return error(FirstEltLoc,
"array element #" + Twine(i) +
4345 " is not of type '" +
4357 Context, Lex.getStrVal(),
false, ATy->getElementType()->isByteTy());
4366 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4369 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4372 parseStringConstant(
ID.StrVal) ||
4373 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4376 ID.StrVal2 = Lex.getStrVal();
4377 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4378 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4389 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4390 parseValID(Fn, PFS) ||
4392 "expected comma in block address expression") ||
4393 parseValID(Label, PFS) ||
4394 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4398 return error(Fn.
Loc,
"expected function name in blockaddress");
4400 return error(
Label.Loc,
"expected basic block name in blockaddress");
4403 GlobalValue *GV =
nullptr;
4405 GV = NumberedVals.get(Fn.
UIntVal);
4406 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4407 GV = M->getNamedValue(Fn.
StrVal);
4413 return error(Fn.
Loc,
"expected function name in blockaddress");
4415 if (
F->isDeclaration())
4416 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4421 GlobalValue *&FwdRef =
4422 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4430 "type of blockaddress must be a pointer and not '" +
4435 FwdDeclAS = PFS->getFunction().getAddressSpace();
4439 FwdRef =
new GlobalVariable(
4444 ID.ConstantVal = FwdRef;
4452 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4454 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4456 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4458 return error(
Label.Loc,
"referenced value is not a basic block");
4461 return error(
Label.Loc,
"cannot take address of numeric label after "
4462 "the function is defined");
4464 F->getValueSymbolTable()->lookup(
Label.StrVal));
4466 return error(
Label.Loc,
"referenced value is not a basic block");
4480 if (parseValID(Fn, PFS))
4485 "expected global value name in dso_local_equivalent");
4488 GlobalValue *GV =
nullptr;
4490 GV = NumberedVals.get(Fn.
UIntVal);
4491 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4492 GV = M->getNamedValue(Fn.
StrVal);
4498 ? ForwardRefDSOLocalEquivalentIDs
4499 : ForwardRefDSOLocalEquivalentNames;
4500 GlobalValue *&FwdRef = FwdRefMap[Fn];
4507 ID.ConstantVal = FwdRef;
4513 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4514 "in dso_local_equivalent");
4525 if (parseValID(
ID, PFS))
4529 return error(
ID.Loc,
"expected global value name in no_cfi");
4541 Constant *Disc =
nullptr, *AddrDisc =
nullptr,
4542 *DeactivationSymbol =
nullptr;
4545 "expected '(' in constant ptrauth expression") ||
4546 parseGlobalTypeAndValue(Ptr) ||
4548 "expected comma in constant ptrauth expression") ||
4549 parseGlobalTypeAndValue(
Key))
4552 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(Disc))
4554 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4557 parseGlobalTypeAndValue(DeactivationSymbol))
4560 "expected ')' in constant ptrauth expression"))
4564 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4567 if (!KeyC || KeyC->getBitWidth() != 32)
4568 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4570 ConstantInt *DiscC =
nullptr;
4576 "constant ptrauth integer discriminator must be i64 constant");
4582 if (!AddrDisc->getType()->isPointerTy())
4584 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4589 if (!DeactivationSymbol)
4590 DeactivationSymbol =
4592 if (!DeactivationSymbol->getType()->isPointerTy())
4594 "constant ptrauth deactivation symbol must be a pointer");
4608 unsigned Opc = Lex.getUIntVal();
4609 Type *DestTy =
nullptr;
4612 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4613 parseGlobalTypeAndValue(SrcVal) ||
4614 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4615 parseType(DestTy) ||
4616 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4619 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4628 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4630 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4632 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4634 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4636 return error(
ID.Loc,
"urem constexprs are no longer supported");
4638 return error(
ID.Loc,
"srem constexprs are no longer supported");
4640 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4642 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4644 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4646 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4648 return error(
ID.Loc,
"frem constexprs are no longer supported");
4650 return error(
ID.Loc,
"and constexprs are no longer supported");
4652 return error(
ID.Loc,
"or constexprs are no longer supported");
4654 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4656 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4658 return error(
ID.Loc,
"shl constexprs are no longer supported");
4660 return error(
ID.Loc,
"mul constexprs are no longer supported");
4662 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4664 return error(
ID.Loc,
"select constexprs are no longer supported");
4666 return error(
ID.Loc,
"zext constexprs are no longer supported");
4668 return error(
ID.Loc,
"sext constexprs are no longer supported");
4670 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4672 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4674 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4676 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4678 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4680 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4682 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4684 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4692 unsigned Opc = Lex.getUIntVal();
4695 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4696 Opc == Instruction::Mul) {
4705 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4706 parseGlobalTypeAndValue(Val0) ||
4707 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4708 parseGlobalTypeAndValue(Val1) ||
4709 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4712 return error(
ID.Loc,
"operands of constexpr must have same type");
4716 "constexpr requires integer or integer vector operands");
4727 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4730 if (parseGlobalTypeAndValue(
C))
4732 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4744 unsigned Opc = Lex.getUIntVal();
4747 bool HasInRange =
false;
4753 if (
Opc == Instruction::GetElementPtr) {
4769 return tokError(
"expected integer");
4770 InRangeStart = Lex.getAPSIntVal();
4775 return tokError(
"expected integer");
4776 InRangeEnd = Lex.getAPSIntVal();
4784 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4787 if (
Opc == Instruction::GetElementPtr) {
4788 if (parseType(Ty) ||
4789 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4793 if (parseGlobalValueVector(Elts) ||
4797 if (
Opc == Instruction::GetElementPtr) {
4798 if (Elts.
size() == 0 ||
4799 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4800 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4803 std::optional<ConstantRange>
InRange;
4805 unsigned IndexWidth =
4806 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4807 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4808 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4809 if (InRangeStart.
sge(InRangeEnd))
4810 return error(
ID.Loc,
"expected end to be larger than start");
4820 for (Constant *Val : Indices) {
4823 return error(
ID.Loc,
"getelementptr index must be an integer");
4826 if (GEPWidth && (ValNumEl != GEPWidth))
4829 "getelementptr vector index has a wrong number of elements");
4832 GEPWidth = ValNumEl;
4836 SmallPtrSet<Type*, 4> Visited;
4837 if (!Indices.empty() && !Ty->
isSized(&Visited))
4838 return error(
ID.Loc,
"base element of getelementptr must be sized");
4841 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4844 return error(
ID.Loc,
"invalid getelementptr indices");
4848 }
else if (
Opc == Instruction::ShuffleVector) {
4849 if (Elts.
size() != 3)
4850 return error(
ID.Loc,
"expected three operands to shufflevector");
4852 return error(
ID.Loc,
"invalid operands to shufflevector");
4853 SmallVector<int, 16>
Mask;
4856 }
else if (
Opc == Instruction::ExtractElement) {
4857 if (Elts.
size() != 2)
4858 return error(
ID.Loc,
"expected two operands to extractelement");
4860 return error(
ID.Loc,
"invalid extractelement operands");
4863 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4864 if (Elts.
size() != 3)
4865 return error(
ID.Loc,
"expected three operands to insertelement");
4867 return error(
ID.Loc,
"invalid insertelement operands");
4882bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4886 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4887 convertValIDToValue(Ty,
ID, V,
nullptr);
4889 return error(
ID.Loc,
"global values must be constants");
4893bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4895 return parseType(Ty) || parseGlobalValue(Ty, V);
4898bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4901 LocTy KwLoc = Lex.getLoc();
4907 return tokError(
"expected comdat variable");
4908 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4910 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4913 if (GlobalName.
empty())
4914 return tokError(
"comdat cannot be unnamed");
4915 C = getComdat(std::string(GlobalName), KwLoc);
4924bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4938 if (parseGlobalTypeAndValue(
C))
4946bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
4948 if (parseMDNodeVector(Elts))
4959bool LLParser::parseMDNode(MDNode *&
N) {
4961 return parseSpecializedMDNode(
N);
4963 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4966bool LLParser::parseMDNodeTail(MDNode *&
N) {
4969 return parseMDTuple(
N);
4972 return parseMDNodeID(
N);
4978template <
class FieldTy>
struct MDFieldImpl {
4979 typedef MDFieldImpl ImplTy;
4983 void assign(FieldTy Val) {
4985 this->Val = std::move(Val);
4988 explicit MDFieldImpl(FieldTy
Default)
4996template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4997 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5010 this->
A = std::move(
A);
5016 this->
B = std::move(
B);
5020 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5022 WhatIs(IsInvalid) {}
5025struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
5032struct LineField :
public MDUnsignedField {
5033 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5036struct ColumnField :
public MDUnsignedField {
5037 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5040struct DwarfTagField :
public MDUnsignedField {
5046struct DwarfMacinfoTypeField :
public MDUnsignedField {
5052struct DwarfAttEncodingField :
public MDUnsignedField {
5053 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
5056struct DwarfVirtualityField :
public MDUnsignedField {
5060struct DwarfLangField :
public MDUnsignedField {
5064struct DwarfSourceLangNameField :
public MDUnsignedField {
5065 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5068struct DwarfLangDialectField :
public MDUnsignedField {
5069 DwarfLangDialectField()
5073struct DwarfCCField :
public MDUnsignedField {
5074 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
5077struct DwarfEnumKindField :
public MDUnsignedField {
5078 DwarfEnumKindField()
5083struct EmissionKindField :
public MDUnsignedField {
5084 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5087struct FixedPointKindField :
public MDUnsignedField {
5088 FixedPointKindField()
5089 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5092struct NameTableKindField :
public MDUnsignedField {
5093 NameTableKindField()
5096 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5099struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
5100 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5103struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
5104 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5107struct MDAPSIntField :
public MDFieldImpl<APSInt> {
5108 MDAPSIntField() : ImplTy(
APSInt()) {}
5111struct MDSignedField :
public MDFieldImpl<int64_t> {
5115 MDSignedField(int64_t
Default = 0)
5117 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5121struct MDBoolField :
public MDFieldImpl<bool> {
5125struct MDField :
public MDFieldImpl<Metadata *> {
5128 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5131struct MDStringField :
public MDFieldImpl<MDString *> {
5132 enum class EmptyIs {
5137 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5138 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5141struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5145struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5149struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5150 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5151 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5153 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5154 bool AllowNull =
true)
5155 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5157 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5158 bool isMDField()
const {
return WhatIs == IsTypeB; }
5159 int64_t getMDSignedValue()
const {
5160 assert(isMDSignedField() &&
"Wrong field type");
5163 Metadata *getMDFieldValue()
const {
5164 assert(isMDField() &&
"Wrong field type");
5169struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5170 MDUnsignedOrMDField(uint64_t
Default = 0,
bool AllowNull =
true)
5171 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5173 MDUnsignedOrMDField(uint64_t
Default, uint64_t Max,
bool AllowNull =
true)
5174 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5176 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5177 bool isMDField()
const {
return WhatIs == IsTypeB; }
5178 uint64_t getMDUnsignedValue()
const {
5179 assert(isMDUnsignedField() &&
"Wrong field type");
5182 Metadata *getMDFieldValue()
const {
5183 assert(isMDField() &&
"Wrong field type");
5188 if (isMDUnsignedField())
5190 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5192 return getMDFieldValue();
5204 return tokError(
"expected integer");
5206 Result.assign(Lex.getAPSIntVal());
5213 MDUnsignedField &Result) {
5214 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5215 return tokError(
"expected unsigned integer");
5217 auto &U = Lex.getAPSIntVal();
5218 if (U.ugt(Result.Max))
5219 return tokError(
"value for '" + Name +
"' too large, limit is " +
5221 Result.assign(U.getZExtValue());
5222 assert(Result.Val <= Result.Max &&
"Expected value in range");
5229 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5233 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5239 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5242 return tokError(
"expected DWARF tag");
5246 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5247 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5256 DwarfMacinfoTypeField &Result) {
5258 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5261 return tokError(
"expected DWARF macinfo type");
5265 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5266 Lex.getStrVal() +
"'");
5267 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5269 Result.assign(Macinfo);
5276 DwarfVirtualityField &Result) {
5278 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5281 return tokError(
"expected DWARF virtuality code");
5285 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5286 Lex.getStrVal() +
"'");
5287 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5288 Result.assign(Virtuality);
5295 DwarfEnumKindField &Result) {
5297 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5300 return tokError(
"expected DWARF enum kind code");
5304 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5305 Lex.getStrVal() +
"'");
5306 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5307 Result.assign(EnumKind);
5315 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5318 return tokError(
"expected DWARF language");
5322 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5324 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5325 Result.assign(Lang);
5332 DwarfSourceLangNameField &Result) {
5334 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5337 return tokError(
"expected DWARF source language name");
5341 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5342 Lex.getStrVal() +
"'");
5343 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5344 Result.assign(Lang);
5351 DwarfLangDialectField &Result) {
5356 if (Lex.getAPSIntVal() == 0)
5357 return tokError(
"value for 'dialect' must be a known DWARF language "
5358 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5359 "DW_LLVM_LANG_DIALECT_tile)");
5360 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5364 return tokError(
"expected DWARF language dialect");
5366 StringRef DialectString = Lex.getStrVal();
5371 if (Dialect > Result.Max)
5372 return tokError(
"invalid DWARF language dialect" +
Twine(
" '") +
5373 DialectString +
"'");
5374 Result.assign(Dialect);
5382 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5385 return tokError(
"expected DWARF calling convention");
5389 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5390 Lex.getStrVal() +
"'");
5391 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
5399 EmissionKindField &Result) {
5401 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5404 return tokError(
"expected emission kind");
5408 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5410 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5411 Result.assign(*Kind);
5418 FixedPointKindField &Result) {
5420 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5423 return tokError(
"expected fixed-point kind");
5427 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5429 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5430 Result.assign(*Kind);
5437 NameTableKindField &Result) {
5439 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5442 return tokError(
"expected nameTable kind");
5446 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5448 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5449 Result.assign((
unsigned)*Kind);
5456 DwarfAttEncodingField &Result) {
5458 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5461 return tokError(
"expected DWARF type attribute encoding");
5465 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5466 Lex.getStrVal() +
"'");
5467 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5468 Result.assign(Encoding);
5482 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5484 bool Res = parseUInt32(TempVal);
5490 return tokError(
"expected debug info flag");
5494 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5509 Result.assign(Combined);
5522 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5524 bool Res = parseUInt32(TempVal);
5530 return tokError(
"expected debug info flag");
5534 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5535 Lex.getStrVal() +
"'");
5549 Result.assign(Combined);
5556 return tokError(
"expected signed integer");
5558 auto &S = Lex.getAPSIntVal();
5560 return tokError(
"value for '" + Name +
"' too small, limit is " +
5563 return tokError(
"value for '" + Name +
"' too large, limit is " +
5565 Result.assign(S.getExtValue());
5566 assert(Result.Val >= Result.Min &&
"Expected value in range");
5567 assert(Result.Val <= Result.Max &&
"Expected value in range");
5574 switch (Lex.getKind()) {
5576 return tokError(
"expected 'true' or 'false'");
5578 Result.assign(
true);
5581 Result.assign(
false);
5591 if (!Result.AllowNull)
5592 return tokError(
"'" + Name +
"' cannot be null");
5594 Result.assign(
nullptr);
5599 if (parseMetadata(MD,
nullptr))
5608 MDSignedOrMDField &Result) {
5611 MDSignedField Res = Result.A;
5612 if (!parseMDField(
Loc, Name, Res)) {
5620 MDField Res = Result.B;
5621 if (!parseMDField(
Loc, Name, Res)) {
5631 MDUnsignedOrMDField &Result) {
5634 MDUnsignedField Res = Result.A;
5635 if (!parseMDField(
Loc, Name, Res)) {
5643 MDField Res = Result.B;
5644 if (!parseMDField(
Loc, Name, Res)) {
5654 LocTy ValueLoc = Lex.getLoc();
5656 if (parseStringConstant(S))
5660 switch (Result.EmptyIs) {
5661 case MDStringField::EmptyIs::Null:
5662 Result.assign(
nullptr);
5664 case MDStringField::EmptyIs::Empty:
5666 case MDStringField::EmptyIs::Error:
5667 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5678 if (parseMDNodeVector(MDs))
5681 Result.assign(std::move(MDs));
5687 ChecksumKindField &Result) {
5688 std::optional<DIFile::ChecksumKind> CSKind =
5692 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5695 Result.assign(*CSKind);
5702template <
class ParserTy>
5703bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5706 return tokError(
"expected field label here");
5715template <
class ParserTy>
5716bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5723 if (parseMDFieldsImplBody(ParseField))
5726 ClosingLoc = Lex.getLoc();
5730template <
class FieldTy>
5731bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5733 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5735 LocTy Loc = Lex.getLoc();
5737 return parseMDField(Loc, Name, Result);
5740bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5743#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5744 if (Lex.getStrVal() == #CLASS) \
5745 return parse##CLASS(N, IsDistinct);
5746#include "llvm/IR/Metadata.def"
5748 return tokError(
"expected metadata type");
5751#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5752#define NOP_FIELD(NAME, TYPE, INIT)
5753#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5755 return error(ClosingLoc, "missing required field '" #NAME "'");
5756#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5757 if (Lex.getStrVal() == #NAME) \
5758 return parseMDField(#NAME, NAME);
5759#define PARSE_MD_FIELDS() \
5760 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5763 if (parseMDFieldsImpl( \
5765 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5766 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5771 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5773#define GET_OR_DISTINCT(CLASS, ARGS) \
5774 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5779bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5780#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5781 OPTIONAL(line, LineField, ); \
5782 OPTIONAL(column, ColumnField, ); \
5783 REQUIRED(scope, MDField, ( false)); \
5784 OPTIONAL(inlinedAt, MDField, ); \
5785 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5786 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5787 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5789#undef VISIT_MD_FIELDS
5792 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5793 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5799bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5801 return tokError(
"missing 'distinct', required for !DIAssignID()");
5817bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5818#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5819 REQUIRED(tag, DwarfTagField, ); \
5820 OPTIONAL(header, MDStringField, ); \
5821 OPTIONAL(operands, MDFieldList, );
5823#undef VISIT_MD_FIELDS
5826 (Context, tag.Val, header.Val, operands.Val));
5835bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5836#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5837 OPTIONAL(name, MDStringField, ); \
5838 OPTIONAL(file, MDField, ); \
5839 OPTIONAL(line, LineField, ); \
5840 OPTIONAL(scope, MDField, ); \
5841 OPTIONAL(baseType, MDField, ); \
5842 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5843 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5844 OPTIONAL(flags, DIFlagField, ); \
5845 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5846 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5847 OPTIONAL(stride, MDSignedOrMDField, ); \
5848 OPTIONAL(bias, MDSignedOrMDField, );
5850#undef VISIT_MD_FIELDS
5852 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5853 if (Bound.isMDSignedField())
5856 if (Bound.isMDField())
5857 return Bound.getMDFieldValue();
5861 Metadata *LowerBound = convToMetadata(lowerBound);
5863 Metadata *Stride = convToMetadata(stride);
5864 Metadata *Bias = convToMetadata(bias);
5867 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5868 size.getValueAsMetadata(Context),
align.Val, flags.Val,
5869 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5878bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5879#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5880 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5881 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5882 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5883 OPTIONAL(stride, MDSignedOrMDField, );
5885#undef VISIT_MD_FIELDS
5892 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5893 if (Bound.isMDSignedField())
5896 if (Bound.isMDField())
5897 return Bound.getMDFieldValue();
5902 LowerBound = convToMetadata(lowerBound);
5904 Stride = convToMetadata(stride);
5907 (Context,
Count, LowerBound, UpperBound, Stride));
5915bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5916#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5917 OPTIONAL(count, MDSignedOrMDField, ); \
5918 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5919 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5920 OPTIONAL(stride, MDSignedOrMDField, );
5922#undef VISIT_MD_FIELDS
5924 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5925 if (Bound.isMDSignedField())
5927 Context, {dwarf::DW_OP_consts,
5928 static_cast<uint64_t
>(Bound.getMDSignedValue())});
5929 if (Bound.isMDField())
5930 return Bound.getMDFieldValue();
5935 Metadata *LowerBound = ConvToMetadata(lowerBound);
5937 Metadata *Stride = ConvToMetadata(stride);
5940 (Context,
Count, LowerBound, UpperBound, Stride));
5947bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5948#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5949 REQUIRED(name, MDStringField, ); \
5950 REQUIRED(value, MDAPSIntField, ); \
5951 OPTIONAL(isUnsigned, MDBoolField, (false));
5953#undef VISIT_MD_FIELDS
5955 if (isUnsigned.Val && value.Val.isNegative())
5956 return tokError(
"unsigned enumerator with negative value");
5961 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5973bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5974#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5975 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5976 OPTIONAL(name, MDStringField, ); \
5977 OPTIONAL(file, MDField, ); \
5978 OPTIONAL(line, LineField, ); \
5979 OPTIONAL(scope, MDField, ); \
5980 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5981 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5982 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5983 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5984 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5985 OPTIONAL(flags, DIFlagField, );
5987#undef VISIT_MD_FIELDS
5990 DIBasicType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
5991 size.getValueAsMetadata(Context),
align.Val, encoding.Val,
5992 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6001bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
6002#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6003 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6004 OPTIONAL(name, MDStringField, ); \
6005 OPTIONAL(file, MDField, ); \
6006 OPTIONAL(line, LineField, ); \
6007 OPTIONAL(scope, MDField, ); \
6008 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6009 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6010 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6011 OPTIONAL(flags, DIFlagField, ); \
6012 OPTIONAL(kind, FixedPointKindField, ); \
6013 OPTIONAL(factor, MDSignedField, ); \
6014 OPTIONAL(numerator, MDAPSIntField, ); \
6015 OPTIONAL(denominator, MDAPSIntField, );
6017#undef VISIT_MD_FIELDS
6020 (Context, tag.Val,
name.Val,
file.Val, line.Val,
6021 scope.Val,
size.getValueAsMetadata(Context),
6022 align.Val, encoding.Val, flags.Val, kind.Val,
6023 factor.Val, numerator.Val, denominator.Val));
6029bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
6030#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6031 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6032 OPTIONAL(name, MDStringField, ); \
6033 OPTIONAL(stringLength, MDField, ); \
6034 OPTIONAL(stringLengthExpression, MDField, ); \
6035 OPTIONAL(stringLocationExpression, MDField, ); \
6036 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6037 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6038 OPTIONAL(encoding, DwarfAttEncodingField, );
6040#undef VISIT_MD_FIELDS
6044 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
6045 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
6046 align.Val, encoding.Val));
6059bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
6060#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6061 REQUIRED(tag, DwarfTagField, ); \
6062 OPTIONAL(name, MDStringField, ); \
6063 OPTIONAL(file, MDField, ); \
6064 OPTIONAL(line, LineField, ); \
6065 OPTIONAL(scope, MDField, ); \
6066 REQUIRED(baseType, MDField, ); \
6067 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6068 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6069 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6070 OPTIONAL(flags, DIFlagField, ); \
6071 OPTIONAL(extraData, MDField, ); \
6072 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6073 OPTIONAL(annotations, MDField, ); \
6074 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6075 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6076 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6077 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6078 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6080#undef VISIT_MD_FIELDS
6082 std::optional<unsigned> DWARFAddressSpace;
6083 if (dwarfAddressSpace.Val != UINT32_MAX)
6084 DWARFAddressSpace = dwarfAddressSpace.Val;
6085 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6087 PtrAuthData.emplace(
6088 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6089 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6090 ptrAuthAuthenticatesNullValues.Val);
6093 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6094 baseType.Val,
size.getValueAsMetadata(Context),
align.Val,
6095 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6096 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6100bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
6101#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6102 REQUIRED(tag, DwarfTagField, ); \
6103 OPTIONAL(name, MDStringField, ); \
6104 OPTIONAL(file, MDField, ); \
6105 OPTIONAL(line, LineField, ); \
6106 OPTIONAL(scope, MDField, ); \
6107 OPTIONAL(baseType, MDField, ); \
6108 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6109 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6110 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6111 OPTIONAL(flags, DIFlagField, ); \
6112 OPTIONAL(elements, MDField, ); \
6113 OPTIONAL(runtimeLang, DwarfLangField, ); \
6114 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6115 OPTIONAL(vtableHolder, MDField, ); \
6116 OPTIONAL(templateParams, MDField, ); \
6117 OPTIONAL(identifier, MDStringField, ); \
6118 OPTIONAL(discriminator, MDField, ); \
6119 OPTIONAL(dataLocation, MDField, ); \
6120 OPTIONAL(associated, MDField, ); \
6121 OPTIONAL(allocated, MDField, ); \
6122 OPTIONAL(rank, MDSignedOrMDField, ); \
6123 OPTIONAL(annotations, MDField, ); \
6124 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6125 OPTIONAL(specification, MDField, ); \
6126 OPTIONAL(bitStride, MDField, );
6128#undef VISIT_MD_FIELDS
6131 if (rank.isMDSignedField())
6134 else if (rank.isMDField())
6135 Rank = rank.getMDFieldValue();
6137 std::optional<unsigned> EnumKind;
6139 EnumKind = enumKind.Val;
6144 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
6145 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
6146 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6147 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6148 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6149 dataLocation.Val, associated.Val, allocated.Val, Rank,
6150 annotations.Val, bitStride.Val)) {
6159 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6160 size.getValueAsMetadata(Context),
align.Val,
6161 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6162 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6163 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6164 allocated.Val, Rank, annotations.Val, specification.Val,
6165 num_extra_inhabitants.Val, bitStride.Val));
6169bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6170#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6171 OPTIONAL(flags, DIFlagField, ); \
6172 OPTIONAL(cc, DwarfCCField, ); \
6173 REQUIRED(types, MDField, );
6175#undef VISIT_MD_FIELDS
6178 (Context, flags.Val, cc.Val, types.Val));
6187bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6191#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6192 REQUIRED(filename, MDStringField, ); \
6193 REQUIRED(directory, MDStringField, ); \
6194 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6195 OPTIONAL(checksum, MDStringField, ); \
6196 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6198#undef VISIT_MD_FIELDS
6200 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6201 if (checksumkind.Seen && checksum.Seen)
6202 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6203 else if (checksumkind.Seen || checksum.Seen)
6204 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6206 MDString *
Source =
nullptr;
6210 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6222bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6224 return tokError(
"missing 'distinct', required for !DICompileUnit");
6226 LocTy Loc = Lex.getLoc();
6228#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6229 REQUIRED(file, MDField, ( false)); \
6230 OPTIONAL(language, DwarfLangField, ); \
6231 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6232 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6233 OPTIONAL(producer, MDStringField, ); \
6234 OPTIONAL(isOptimized, MDBoolField, ); \
6235 OPTIONAL(flags, MDStringField, ); \
6236 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6237 OPTIONAL(splitDebugFilename, MDStringField, ); \
6238 OPTIONAL(emissionKind, EmissionKindField, ); \
6239 OPTIONAL(enums, MDField, ); \
6240 OPTIONAL(retainedTypes, MDField, ); \
6241 OPTIONAL(globals, MDField, ); \
6242 OPTIONAL(imports, MDField, ); \
6243 OPTIONAL(macros, MDField, ); \
6244 OPTIONAL(dwoId, MDUnsignedField, ); \
6245 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6246 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6247 OPTIONAL(nameTableKind, NameTableKindField, ); \
6248 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6249 OPTIONAL(sysroot, MDStringField, ); \
6250 OPTIONAL(sdk, MDStringField, ); \
6251 OPTIONAL(dialect, DwarfLangDialectField, );
6253#undef VISIT_MD_FIELDS
6255 if (!language.Seen && !sourceLanguageName.Seen)
6256 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6257 "required for !DICompileUnit");
6259 if (language.Seen && sourceLanguageName.Seen)
6260 return error(Loc,
"can only specify one of 'language' and "
6261 "'sourceLanguageName' on !DICompileUnit");
6263 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6264 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6265 "'sourceLanguageName' on !DICompileUnit");
6267 uint16_t Dialect =
static_cast<uint16_t
>(dialect.Val);
6270 ? DISourceLanguageName(
static_cast<uint16_t
>(language.Val), Dialect)
6271 : DISourceLanguageName(
6272 static_cast<uint16_t>(sourceLanguageName.Val),
6273 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6276 Context, SourceLanguage,
file.Val, producer.Val, isOptimized.Val,
6277 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6278 enums.Val, retainedTypes.Val,
globals.Val, imports.Val, macros.Val,
6279 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6280 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6293bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6294 auto Loc = Lex.getLoc();
6295#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6296 OPTIONAL(scope, MDField, ); \
6297 OPTIONAL(name, MDStringField, ); \
6298 OPTIONAL(linkageName, MDStringField, ); \
6299 OPTIONAL(file, MDField, ); \
6300 OPTIONAL(line, LineField, ); \
6301 REQUIRED(type, MDField, ( false)); \
6302 OPTIONAL(isLocal, MDBoolField, ); \
6303 OPTIONAL(isDefinition, MDBoolField, (true)); \
6304 OPTIONAL(scopeLine, LineField, ); \
6305 OPTIONAL(containingType, MDField, ); \
6306 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6307 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6308 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6309 OPTIONAL(flags, DIFlagField, ); \
6310 OPTIONAL(spFlags, DISPFlagField, ); \
6311 OPTIONAL(isOptimized, MDBoolField, ); \
6312 OPTIONAL(unit, MDField, ); \
6313 OPTIONAL(templateParams, MDField, ); \
6314 OPTIONAL(declaration, MDField, ); \
6315 OPTIONAL(retainedNodes, MDField, ); \
6316 OPTIONAL(thrownTypes, MDField, ); \
6317 OPTIONAL(annotations, MDField, ); \
6318 OPTIONAL(targetFuncName, MDStringField, ); \
6319 OPTIONAL(keyInstructions, MDBoolField, );
6321#undef VISIT_MD_FIELDS
6326 spFlags.Seen ? spFlags.Val
6328 isOptimized.Val, virtuality.Val);
6329 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6332 "missing 'distinct', required for !DISubprogram that is a Definition");
6335 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6336 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6337 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6338 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6339 targetFuncName.Val, keyInstructions.Val));
6349bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6350#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6351 REQUIRED(scope, MDField, ( false)); \
6352 OPTIONAL(file, MDField, ); \
6353 OPTIONAL(line, LineField, ); \
6354 OPTIONAL(column, ColumnField, );
6356#undef VISIT_MD_FIELDS
6359 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6365bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6366#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6367 REQUIRED(scope, MDField, ( false)); \
6368 OPTIONAL(file, MDField, ); \
6369 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6371#undef VISIT_MD_FIELDS
6374 (Context, scope.Val,
file.Val, discriminator.Val));
6380bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6381#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6382 REQUIRED(scope, MDField, ); \
6383 OPTIONAL(declaration, MDField, ); \
6384 OPTIONAL(name, MDStringField, ); \
6385 OPTIONAL(file, MDField, ); \
6386 OPTIONAL(line, LineField, );
6388#undef VISIT_MD_FIELDS
6391 (Context, scope.Val, declaration.Val,
name.Val,
6392 file.Val, line.Val));
6398bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6399#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6400 REQUIRED(scope, MDField, ); \
6401 OPTIONAL(name, MDStringField, ); \
6402 OPTIONAL(exportSymbols, MDBoolField, );
6404#undef VISIT_MD_FIELDS
6407 (Context, scope.Val,
name.Val, exportSymbols.Val));
6414bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6415#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6416 REQUIRED(type, DwarfMacinfoTypeField, ); \
6417 OPTIONAL(line, LineField, ); \
6418 REQUIRED(name, MDStringField, ); \
6419 OPTIONAL(value, MDStringField, );
6421#undef VISIT_MD_FIELDS
6424 (Context, type.Val, line.Val,
name.Val, value.Val));
6430bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6431#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6432 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6433 OPTIONAL(line, LineField, ); \
6434 REQUIRED(file, MDField, ); \
6435 OPTIONAL(nodes, MDField, );
6437#undef VISIT_MD_FIELDS
6440 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6448bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6449#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6450 REQUIRED(scope, MDField, ); \
6451 REQUIRED(name, MDStringField, ); \
6452 OPTIONAL(configMacros, MDStringField, ); \
6453 OPTIONAL(includePath, MDStringField, ); \
6454 OPTIONAL(apinotes, MDStringField, ); \
6455 OPTIONAL(file, MDField, ); \
6456 OPTIONAL(line, LineField, ); \
6457 OPTIONAL(isDecl, MDBoolField, );
6459#undef VISIT_MD_FIELDS
6462 configMacros.Val, includePath.Val,
6463 apinotes.Val, line.Val, isDecl.Val));
6469bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6470#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6471 OPTIONAL(name, MDStringField, ); \
6472 REQUIRED(type, MDField, ); \
6473 OPTIONAL(defaulted, MDBoolField, );
6475#undef VISIT_MD_FIELDS
6478 (Context,
name.Val, type.Val, defaulted.Val));
6486bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6487#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6488 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6489 OPTIONAL(name, MDStringField, ); \
6490 OPTIONAL(type, MDField, ); \
6491 OPTIONAL(defaulted, MDBoolField, ); \
6492 REQUIRED(value, MDField, );
6495#undef VISIT_MD_FIELDS
6498 DITemplateValueParameter,
6499 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6508bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6509#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6510 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6511 OPTIONAL(scope, MDField, ); \
6512 OPTIONAL(linkageName, MDStringField, ); \
6513 OPTIONAL(file, MDField, ); \
6514 OPTIONAL(line, LineField, ); \
6515 OPTIONAL(type, MDField, ); \
6516 OPTIONAL(isLocal, MDBoolField, ); \
6517 OPTIONAL(isDefinition, MDBoolField, (true)); \
6518 OPTIONAL(templateParams, MDField, ); \
6519 OPTIONAL(declaration, MDField, ); \
6520 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6521 OPTIONAL(annotations, MDField, );
6523#undef VISIT_MD_FIELDS
6527 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6528 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6529 declaration.Val, templateParams.Val,
align.Val,
6541bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6542#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6543 REQUIRED(scope, MDField, ( false)); \
6544 OPTIONAL(name, MDStringField, ); \
6545 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6546 OPTIONAL(file, MDField, ); \
6547 OPTIONAL(line, LineField, ); \
6548 OPTIONAL(type, MDField, ); \
6549 OPTIONAL(flags, DIFlagField, ); \
6550 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6551 OPTIONAL(annotations, MDField, );
6553#undef VISIT_MD_FIELDS
6556 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6557 type.Val, arg.Val, flags.Val,
align.Val,
6564bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6565#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6566 REQUIRED(scope, MDField, ( false)); \
6567 REQUIRED(name, MDStringField, ); \
6568 REQUIRED(file, MDField, ); \
6569 REQUIRED(line, LineField, ); \
6570 OPTIONAL(column, ColumnField, ); \
6571 OPTIONAL(isArtificial, MDBoolField, ); \
6572 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6574#undef VISIT_MD_FIELDS
6576 std::optional<unsigned> CoroSuspendIdx =
6577 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6581 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6582 column.Val, isArtificial.Val, CoroSuspendIdx));
6588bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6601 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6610 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6611 Lex.getStrVal() +
"'");
6614 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6615 return tokError(
"expected unsigned integer");
6617 auto &
U = Lex.getAPSIntVal();
6619 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6633bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6635 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6638 return parseDIExpressionBody(Result, IsDistinct);
6643bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6644 assert(PFS &&
"Expected valid function state");
6655 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6669bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6671#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6672 REQUIRED(var, MDField, ); \
6673 REQUIRED(expr, MDField, );
6675#undef VISIT_MD_FIELDS
6678 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6685bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6686#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6687 OPTIONAL(name, MDStringField, ); \
6688 OPTIONAL(file, MDField, ); \
6689 OPTIONAL(line, LineField, ); \
6690 OPTIONAL(setter, MDStringField, ); \
6691 OPTIONAL(getter, MDStringField, ); \
6692 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6693 OPTIONAL(type, MDField, );
6695#undef VISIT_MD_FIELDS
6698 (Context,
name.Val,
file.Val, line.Val, getter.Val,
6699 setter.Val, attributes.Val, type.Val));
6706bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6707#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6708 REQUIRED(tag, DwarfTagField, ); \
6709 REQUIRED(scope, MDField, ); \
6710 OPTIONAL(entity, MDField, ); \
6711 OPTIONAL(file, MDField, ); \
6712 OPTIONAL(line, LineField, ); \
6713 OPTIONAL(name, MDStringField, ); \
6714 OPTIONAL(elements, MDField, );
6716#undef VISIT_MD_FIELDS
6719 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6720 line.Val,
name.Val, elements.Val));
6724#undef PARSE_MD_FIELD
6736bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6739 if (parseMetadata(MD, &PFS))
6750bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6751 PerFunctionState *PFS) {
6754 if (parseType(Ty, TypeMsg, Loc))
6757 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6760 if (parseValue(Ty, V, PFS))
6775bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6779 if (Lex.getStrVal() ==
"DIArgList") {
6781 if (parseDIArgList(AL, PFS))
6787 if (parseSpecializedMDNode(
N)) {
6797 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6807 if (parseMDString(S))
6817 if (parseMDNodeTail(
N))
6828 PerFunctionState *PFS) {
6830 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6835 return error(
ID.Loc,
"invalid use of function-local name");
6836 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6837 return V ==
nullptr;
6840 return error(
ID.Loc,
"invalid use of function-local name");
6841 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6842 return V ==
nullptr;
6845 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6849 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6854 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6857 return V ==
nullptr;
6859 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6862 return V ==
nullptr;
6865 return error(
ID.Loc,
"integer/byte constant must have integer/byte type");
6868 :
V = ConstantByte::
get(Context,
ID.APSIntVal);
6873 return error(
ID.Loc,
"floating point constant invalid for type");
6879 bool IsSNAN = ID.APFloatVal.isSignaling();
6882 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6884 else if (Ty->isBFloatTy())
6885 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6887 else if (Ty->isFloatTy())
6888 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6894 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6895 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6896 ID.APFloatVal.isNegative(), &Payload);
6899 V = ConstantFP::get(Context,
ID.APFloatVal);
6901 if (
V->getType() != Ty)
6902 return error(
ID.Loc,
"floating point constant does not have type '" +
6908 return error(
ID.Loc,
"null must be a pointer type");
6914 return error(
ID.Loc,
"invalid type for undef constant");
6919 return error(
ID.Loc,
"invalid empty array initializer");
6925 return error(
ID.Loc,
"invalid type for null constant");
6928 return error(
ID.Loc,
"invalid type for null constant");
6933 return error(
ID.Loc,
"invalid type for none constant");
6939 return error(
ID.Loc,
"invalid type for poison constant");
6943 if (
ID.ConstantVal->getType() != Ty)
6944 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6951 return error(
ID.Loc,
"vector constant must have vector type");
6953 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6955 "' but expected '" +
6963 if (
ST->getNumElements() !=
ID.UIntVal)
6965 "initializer with struct type has wrong # elements");
6967 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6970 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6971 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6974 "element " + Twine(i) +
6975 " of struct initializer doesn't match struct element type");
6978 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6980 return error(
ID.Loc,
"constant expression type mismatch");
6989 auto Loc = Lex.getLoc();
6990 if (parseValID(
ID,
nullptr, Ty))
7003 if (convertValIDToValue(Ty,
ID, V,
nullptr))
7013 return error(Loc,
"expected a constant value");
7017bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
7021 FileLoc
Start = getTokLineColumnPos();
7022 bool Ret = parseValID(
ID, PFS, Ty) || convertValIDToValue(Ty,
ID, V, PFS);
7023 if (!Ret && ParserContext) {
7024 FileLoc End = getPrevTokEndLineColumnPos();
7025 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
7030bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
7032 return parseType(Ty) || parseValue(Ty, V, PFS);
7035bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
7036 PerFunctionState &PFS) {
7039 if (parseTypeAndValue(V, PFS))
7042 return error(Loc,
"expected a basic block");
7051 if (!Name.starts_with(
"llvm.dbg."))
7054 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7055 FnID == Intrinsic::dbg_assign;
7063bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
7064 unsigned &FunctionNumber,
7067 LocTy LinkageLoc = Lex.getLoc();
7069 unsigned Visibility;
7070 unsigned DLLStorageClass;
7072 AttrBuilder RetAttrs(M->getContext());
7075 Type *RetType =
nullptr;
7076 LocTy RetTypeLoc = Lex.getLoc();
7077 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
7079 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7080 parseType(RetType, RetTypeLoc,
true ))
7089 return error(LinkageLoc,
"invalid linkage for function definition");
7099 return error(LinkageLoc,
"invalid linkage for function declaration");
7103 return error(LinkageLoc,
"invalid function linkage type");
7107 return error(LinkageLoc,
7108 "symbol with local linkage must have default visibility");
7111 return error(LinkageLoc,
7112 "symbol with local linkage cannot have a DLL storage class");
7115 return error(RetTypeLoc,
"invalid function return type");
7117 LocTy NameLoc = Lex.getLoc();
7119 std::string FunctionName;
7121 FunctionName = Lex.getStrVal();
7123 FunctionNumber = Lex.getUIntVal();
7124 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
7128 return tokError(
"expected function name");
7134 return tokError(
"expected '(' in function argument list");
7138 AttrBuilder FuncAttrs(M->getContext());
7139 std::vector<unsigned> FwdRefAttrGrps;
7142 std::string Partition;
7143 MaybeAlign Alignment, PrefAlignment;
7146 unsigned AddrSpace = 0;
7152 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7153 parseOptionalUnnamedAddr(UnnamedAddr) ||
7154 parseOptionalProgramAddrSpace(AddrSpace) ||
7155 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7159 parseOptionalComdat(FunctionName,
C) ||
7160 parseOptionalAlignment(Alignment) ||
7161 parseOptionalPrefAlignment(PrefAlignment) ||
7162 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7166 parseGlobalTypeAndValue(PersonalityFn)))
7169 if (FuncAttrs.contains(Attribute::Builtin))
7170 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7173 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7175 FuncAttrs.removeAttribute(Attribute::Alignment);
7180 std::vector<Type*> ParamTypeList;
7183 for (
const ArgInfo &Arg : ArgList) {
7184 ParamTypeList.push_back(Arg.Ty);
7185 Attrs.push_back(Arg.Attrs);
7192 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7193 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7199 GlobalValue *FwdFn =
nullptr;
7200 if (!FunctionName.empty()) {
7203 auto FRVI = ForwardRefVals.find(FunctionName);
7204 if (FRVI != ForwardRefVals.end()) {
7205 FwdFn = FRVI->second.first;
7207 return error(FRVI->second.second,
7208 "invalid forward reference to "
7211 "' with wrong type: "
7215 ForwardRefVals.erase(FRVI);
7216 }
else if ((Fn = M->getFunction(FunctionName))) {
7218 return error(NameLoc,
7219 "invalid redefinition of function '" + FunctionName +
"'");
7220 }
else if (M->getNamedValue(FunctionName)) {
7221 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7227 if (FunctionNumber == (
unsigned)-1)
7228 FunctionNumber = NumberedVals.getNext();
7232 auto I = ForwardRefValIDs.find(FunctionNumber);
7233 if (
I != ForwardRefValIDs.end()) {
7234 FwdFn =
I->second.first;
7236 return error(NameLoc,
"type of definition and forward reference of '@" +
7237 Twine(FunctionNumber) +
7242 ForwardRefValIDs.erase(
I);
7251 if (FunctionName.empty())
7252 NumberedVals.add(FunctionNumber, Fn);
7268 if (!
GC.empty()) Fn->
setGC(GC);
7271 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7275 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7276 if (ParserContext && ArgList[i].IdentLoc)
7277 ParserContext->addInstructionOrArgumentLocation(
7278 &*ArgIt, ArgList[i].IdentLoc.value());
7280 if (ArgList[i].
Name.empty())
continue;
7283 ArgIt->
setName(ArgList[i].Name);
7285 if (ArgIt->
getName() != ArgList[i].Name)
7286 return error(ArgList[i].Loc,
7287 "redefinition of argument '%" + ArgList[i].Name +
"'");
7300 if (FunctionName.empty()) {
7302 ID.UIntVal = FunctionNumber;
7305 ID.StrVal = FunctionName;
7307 auto Blocks = ForwardRefBlockAddresses.find(
ID);
7308 if (Blocks != ForwardRefBlockAddresses.end())
7309 return error(Blocks->first.Loc,
7310 "cannot take blockaddress inside a declaration");
7314bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7316 if (FunctionNumber == -1) {
7318 ID.StrVal = std::string(F.getName());
7321 ID.UIntVal = FunctionNumber;
7324 auto Blocks = P.ForwardRefBlockAddresses.find(
ID);
7325 if (Blocks == P.ForwardRefBlockAddresses.end())
7328 for (
const auto &
I : Blocks->second) {
7329 const ValID &BBID =
I.first;
7330 GlobalValue *GV =
I.second;
7333 "Expected local id or name");
7340 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7343 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7351 P.ForwardRefBlockAddresses.erase(Blocks);
7357bool LLParser::parseFunctionBody(Function &Fn,
unsigned FunctionNumber,
7358 ArrayRef<unsigned> UnnamedArgNums) {
7360 return tokError(
"expected '{' in function body");
7363 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7367 if (PFS.resolveForwardRefBlockAddresses())
7373 return tokError(
"function body requires at least one basic block");
7377 if (parseBasicBlock(PFS))
7381 if (parseUseListOrder(&PFS))
7388 return PFS.finishFunction();
7393bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7394 FileLoc BBStart = getTokLineColumnPos();
7399 LocTy NameLoc = Lex.getLoc();
7401 Name = Lex.getStrVal();
7404 NameID = Lex.getUIntVal();
7408 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7412 std::string NameStr;
7417 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7418 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7425 if (SeenOldDbgInfoFormat)
7426 return error(Lex.getLoc(),
"debug record should not appear in a module "
7427 "containing debug info intrinsics");
7428 SeenNewDbgInfoFormat =
true;
7432 if (parseDebugRecord(DR, PFS))
7434 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7437 FileLoc InstStart = getTokLineColumnPos();
7440 LocTy NameLoc = Lex.getLoc();
7445 NameID = Lex.getUIntVal();
7447 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7450 NameStr = Lex.getStrVal();
7452 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7456 switch (parseInstruction(Inst, BB, PFS)) {
7459 case InstError:
return true;
7466 if (parseInstructionMetadata(*Inst))
7469 case InstExtraComma:
7474 if (parseInstructionMetadata(*Inst))
7480 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7484 for (DbgRecordPtr &DR : TrailingDbgRecord)
7486 TrailingDbgRecord.clear();
7487 if (ParserContext) {
7488 ParserContext->addInstructionOrArgumentLocation(
7489 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7494 ParserContext->addBlockLocation(
7495 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7497 assert(TrailingDbgRecord.empty() &&
7498 "All debug values should have been attached to an instruction.");
7507bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7510 LocTy DVRLoc = Lex.getLoc();
7512 return error(DVRLoc,
"expected debug record type here");
7513 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7514 .Case(
"declare", RecordKind::ValueKind)
7515 .Case(
"value", RecordKind::ValueKind)
7516 .Case(
"assign", RecordKind::ValueKind)
7517 .Case(
"label", RecordKind::LabelKind)
7518 .Case(
"declare_value", RecordKind::ValueKind);
7527 if (parseMDNode(Label))
7532 if (parseMDNode(DbgLoc))
7537 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7541 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7542 .Case(
"declare", LocType::Declare)
7543 .Case(
"value", LocType::Value)
7544 .Case(
"assign", LocType::Assign)
7545 .Case(
"declare_value", LocType::DeclareValue);
7553 if (parseMetadata(ValLocMD, &PFS))
7560 if (parseMDNode(Variable))
7567 if (parseMDNode(Expression))
7573 MDNode *AssignID =
nullptr;
7574 Metadata *AddressLocation =
nullptr;
7575 MDNode *AddressExpression =
nullptr;
7578 if (parseMDNode(AssignID))
7584 if (parseMetadata(AddressLocation, &PFS))
7590 if (parseMDNode(AddressExpression))
7604 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7606 PendingDbgRecords.emplace_back(DVRLoc, DR,
DebugLoc);
7615int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7616 PerFunctionState &PFS) {
7619 return tokError(
"found end of file when expecting more instructions");
7620 LocTy Loc = Lex.getLoc();
7621 unsigned KeywordVal = Lex.getUIntVal();
7626 return error(Loc,
"expected instruction opcode");
7630 return parseRet(Inst, BB, PFS);
7632 return parseBr(Inst, PFS);
7634 return parseSwitch(Inst, PFS);
7636 return parseIndirectBr(Inst, PFS);
7638 return parseInvoke(Inst, PFS);
7640 return parseResume(Inst, PFS);
7642 return parseCleanupRet(Inst, PFS);
7644 return parseCatchRet(Inst, PFS);
7646 return parseCatchSwitch(Inst, PFS);
7648 return parseCatchPad(Inst, PFS);
7650 return parseCleanupPad(Inst, PFS);
7652 return parseCallBr(Inst, PFS);
7655 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7656 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7672 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7684 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7685 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7699 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7707 return parseArithmetic(Inst, PFS, KeywordVal,
7711 if (parseLogical(Inst, PFS, KeywordVal))
7719 return parseLogical(Inst, PFS, KeywordVal);
7722 if (parseCompare(Inst, PFS, KeywordVal))
7729 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7730 int Res = parseCompare(Inst, PFS, KeywordVal);
7740 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7742 bool Res = parseCast(Inst, PFS, KeywordVal);
7752 bool Res = parseCast(Inst, PFS, KeywordVal);
7764 if (parseCast(Inst, PFS, KeywordVal))
7780 return parseCast(Inst, PFS, KeywordVal);
7784 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7785 if (parseCast(Inst, PFS, KeywordVal))
7794 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7795 int Res = parseSelect(Inst, PFS);
7801 return error(Loc,
"fast-math-flags specified for select without "
7802 "floating-point scalar or vector return type");
7809 return parseVAArg(Inst, PFS);
7811 return parseExtractElement(Inst, PFS);
7813 return parseInsertElement(Inst, PFS);
7815 return parseShuffleVector(Inst, PFS);
7817 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7818 int Res = parsePHI(Inst, PFS);
7824 return error(Loc,
"fast-math-flags specified for phi without "
7825 "floating-point scalar or vector return type");
7832 return parseLandingPad(Inst, PFS);
7834 return parseFreeze(Inst, PFS);
7846 return parseAlloc(Inst, PFS);
7848 return parseLoad(Inst, PFS);
7850 return parseStore(Inst, PFS);
7852 return parseCmpXchg(Inst, PFS);
7854 return parseAtomicRMW(Inst, PFS);
7856 return parseFence(Inst, PFS);
7858 return parseGetElementPtr(Inst, PFS);
7860 return parseExtractValue(Inst, PFS);
7862 return parseInsertValue(Inst, PFS);
7867bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7868 if (
Opc == Instruction::FCmp) {
7869 switch (Lex.getKind()) {
7871 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7890 switch (Lex.getKind()) {
7892 return tokError(
"expected icmp predicate (e.g. 'eq')");
7916bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7917 PerFunctionState &PFS) {
7918 SMLoc TypeLoc = Lex.getLoc();
7920 if (parseType(Ty,
true ))
7923 Type *ResType = PFS.getFunction().getReturnType();
7927 return error(TypeLoc,
"value doesn't match function result type '" +
7935 if (parseValue(Ty, RV, PFS))
7939 return error(TypeLoc,
"value doesn't match function result type '" +
7949bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7953 if (parseTypeAndValue(Op0, Loc, PFS))
7962 return error(Loc,
"branch condition must have 'i1' type");
7964 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7965 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7966 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7967 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7979bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7980 LocTy CondLoc, BBLoc;
7983 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7984 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7985 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7989 if (!
Cond->getType()->isIntegerTy())
7990 return error(CondLoc,
"switch condition must have integer type");
7993 SmallPtrSet<Value*, 32> SeenCases;
7999 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8000 parseToken(
lltok::comma,
"expected ',' after case value") ||
8001 parseTypeAndBasicBlock(DestBB, PFS))
8004 if (!SeenCases.
insert(Constant).second)
8005 return error(CondLoc,
"duplicate case value in switch");
8007 return error(CondLoc,
"case value is not a constant integer");
8015 for (
const auto &[OnVal, Dest] : Table)
8016 SI->addCase(OnVal, Dest);
8024bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8027 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
8028 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
8032 if (!
Address->getType()->isPointerTy())
8033 return error(AddrLoc,
"indirectbr address must have pointer type");
8036 SmallVector<BasicBlock*, 16> DestList;
8040 if (parseTypeAndBasicBlock(DestBB, PFS))
8045 if (parseTypeAndBasicBlock(DestBB, PFS))
8051 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8055 for (BasicBlock *Dest : DestList)
8065 FunctionType *&FuncTy) {
8071 for (
const ParamInfo &Arg : ArgList)
8085bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8086 LocTy CallLoc = Lex.getLoc();
8087 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8088 std::vector<unsigned> FwdRefAttrGrps;
8091 unsigned InvokeAddrSpace;
8092 Type *RetType =
nullptr;
8099 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8100 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8101 parseType(RetType, RetTypeLoc,
true ) ||
8102 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8103 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8105 parseOptionalOperandBundles(BundleList, PFS) ||
8107 parseTypeAndBasicBlock(NormalBB, PFS) ||
8109 parseTypeAndBasicBlock(UnwindBB, PFS))
8116 if (resolveFunctionType(RetType, ArgList, Ty))
8117 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8123 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
8128 SmallVector<Value *, 8>
Args;
8135 for (
const ParamInfo &Arg : ArgList) {
8136 Type *ExpectedTy =
nullptr;
8139 }
else if (!Ty->isVarArg()) {
8140 return error(Arg.Loc,
"too many arguments specified");
8143 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8144 return error(Arg.Loc,
"argument is not of expected type '" +
8146 Args.push_back(Arg.V);
8151 return error(CallLoc,
"not enough parameters specified for call");
8160 II->setCallingConv(CC);
8161 II->setAttributes(PAL);
8162 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
8169bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8171 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8179bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8180 PerFunctionState &PFS) {
8181 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8186 if (!
Args.empty() &&
8187 parseToken(
lltok::comma,
"expected ',' in argument list"))
8192 Type *ArgTy =
nullptr;
8193 if (parseType(ArgTy, ArgLoc))
8198 if (parseMetadataAsValue(V, PFS))
8201 if (parseValue(ArgTy, V, PFS))
8213bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8214 Value *CleanupPad =
nullptr;
8216 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8231 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8242bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8243 Value *CatchPad =
nullptr;
8245 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8252 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8253 parseTypeAndBasicBlock(BB, PFS))
8262bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8270 return tokError(
"expected scope value for catchswitch");
8275 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8281 if (parseTypeAndBasicBlock(DestBB, PFS))
8286 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8289 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8297 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8303 for (BasicBlock *DestBB : Table)
8304 CatchSwitch->addHandler(DestBB);
8311bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8312 Value *CatchSwitch =
nullptr;
8318 return tokError(
"expected scope value for catchpad");
8323 SmallVector<Value *, 8>
Args;
8324 if (parseExceptionArgs(Args, PFS))
8333bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8334 Value *ParentPad =
nullptr;
8341 return tokError(
"expected scope value for cleanuppad");
8346 SmallVector<Value *, 8>
Args;
8347 if (parseExceptionArgs(Args, PFS))
8363bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8364 unsigned Opc,
bool IsFP) {
8366 if (parseTypeAndValue(
LHS, Loc, PFS))
8373 return error(Loc,
"invalid operand type for instruction");
8383bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8384 LocTy CallLoc = Lex.getLoc();
8385 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8386 std::vector<unsigned> FwdRefAttrGrps;
8389 Type *RetType =
nullptr;
8396 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8397 parseType(RetType, RetTypeLoc,
true ) ||
8398 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8399 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8401 parseOptionalOperandBundles(BundleList, PFS) ||
8403 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8408 SmallVector<BasicBlock *, 16> IndirectDests;
8412 if (parseTypeAndBasicBlock(DestBB, PFS))
8417 if (parseTypeAndBasicBlock(DestBB, PFS))
8423 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8430 if (resolveFunctionType(RetType, ArgList, Ty))
8431 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8442 SmallVector<Value *, 8>
Args;
8449 for (
const ParamInfo &Arg : ArgList) {
8450 Type *ExpectedTy =
nullptr;
8453 }
else if (!Ty->isVarArg()) {
8454 return error(Arg.Loc,
"too many arguments specified");
8457 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8458 return error(Arg.Loc,
"argument is not of expected type '" +
8460 Args.push_back(Arg.V);
8465 return error(CallLoc,
"not enough parameters specified for call");
8477 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8491bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8492 unsigned Opc,
bool IsFP) {
8494 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8495 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8503 return error(Loc,
"invalid operand type for instruction");
8511bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8514 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8515 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8521 "instruction requires integer or integer vector operands");
8530bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8536 if (parseCmpPredicate(Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8537 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8541 if (
Opc == Instruction::FCmp) {
8543 return error(Loc,
"fcmp requires floating point operands");
8546 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8549 return error(Loc,
"icmp requires integer operands");
8561bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8565 Type *DestTy =
nullptr;
8566 if (parseTypeAndValue(
Op, Loc, PFS) ||
8567 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8572 return error(Loc,
"invalid cast opcode for cast from '" +
8581bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8583 Value *Op0, *Op1, *Op2;
8584 if (parseTypeAndValue(Op0, Loc, PFS) ||
8585 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8586 parseTypeAndValue(Op1, PFS) ||
8587 parseToken(
lltok::comma,
"expected ',' after select value") ||
8588 parseTypeAndValue(Op2, PFS))
8592 return error(Loc, Reason);
8600bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8602 Type *EltTy =
nullptr;
8604 if (parseTypeAndValue(
Op, PFS) ||
8605 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8606 parseType(EltTy, TypeLoc))
8610 return error(TypeLoc,
"va_arg requires operand with first class type");
8612 Inst =
new VAArgInst(
Op, EltTy);
8618bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8621 if (parseTypeAndValue(Op0, Loc, PFS) ||
8622 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8623 parseTypeAndValue(Op1, PFS))
8627 return error(Loc,
"invalid extractelement operands");
8635bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8637 Value *Op0, *Op1, *Op2;
8638 if (parseTypeAndValue(Op0, Loc, PFS) ||
8639 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8640 parseTypeAndValue(Op1, PFS) ||
8641 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8642 parseTypeAndValue(Op2, PFS))
8646 return error(Loc,
"invalid insertelement operands");
8654bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8656 Value *Op0, *Op1, *Op2;
8657 if (parseTypeAndValue(Op0, Loc, PFS) ||
8658 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8659 parseTypeAndValue(Op1, PFS) ||
8660 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8661 parseTypeAndValue(Op2, PFS))
8665 return error(Loc,
"invalid shufflevector operands");
8667 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8673int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8677 if (parseType(Ty, TypeLoc))
8681 return error(TypeLoc,
"phi node must have first class type");
8684 bool AteExtraComma =
false;
8696 AteExtraComma =
true;
8700 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8701 parseValue(Ty, Op0, PFS) ||
8702 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8711 for (
const auto &[Val, BB] : PHIVals)
8714 return AteExtraComma ? InstExtraComma : InstNormal;
8723bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8726 if (parseType(Ty, TyLoc))
8739 return tokError(
"expected 'catch' or 'filter' clause type");
8743 if (parseTypeAndValue(V, VLoc, PFS))
8750 return error(VLoc,
"'catch' clause has an invalid type");
8753 return error(VLoc,
"'filter' clause has an invalid type");
8758 return error(VLoc,
"clause argument must be a constant");
8762 Inst = LP.release();
8768bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8771 if (parseTypeAndValue(
Op, Loc, PFS))
8774 Inst =
new FreezeInst(
Op);
8787bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8789 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8790 std::vector<unsigned> FwdRefAttrGrps;
8792 unsigned CallAddrSpace;
8794 Type *RetType =
nullptr;
8799 LocTy CallLoc = Lex.getLoc();
8803 "expected 'tail call', 'musttail call', or 'notail call'"))
8806 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8808 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8809 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8810 parseType(RetType, RetTypeLoc,
true ) ||
8811 parseValID(CalleeID, &PFS) ||
8813 PFS.getFunction().isVarArg()) ||
8814 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8815 parseOptionalOperandBundles(BundleList, PFS))
8822 if (resolveFunctionType(RetType, ArgList, Ty))
8823 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8829 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
8836 SmallVector<Value*, 8>
Args;
8842 for (
const ParamInfo &Arg : ArgList) {
8843 Type *ExpectedTy =
nullptr;
8846 }
else if (!Ty->isVarArg()) {
8847 return error(Arg.Loc,
"too many arguments specified");
8850 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8851 return error(Arg.Loc,
"argument is not of expected type '" +
8853 Args.push_back(Arg.V);
8854 Attrs.push_back(Arg.Attrs);
8858 return error(CallLoc,
"not enough parameters specified for call");
8871 return error(CallLoc,
"fast-math-flags specified for call without "
8872 "floating-point scalar or vector return type");
8879 if (SeenNewDbgInfoFormat) {
8881 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8882 "using non-intrinsic debug info");
8884 SeenOldDbgInfoFormat =
true;
8887 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8899int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8901 LocTy SizeLoc, TyLoc, ASLoc;
8902 MaybeAlign Alignment;
8903 unsigned AddrSpace = 0;
8906 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8907 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8909 if (parseType(Ty, TyLoc))
8913 return error(TyLoc,
"invalid type for alloca");
8915 bool AteExtraComma =
false;
8917 if (Lex.getKind() == lltok::kw_align) {
8918 if (parseOptionalAlignment(Alignment))
8920 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8923 ASLoc = Lex.getLoc();
8924 if (parseOptionalAddrSpace(AddrSpace))
8927 AteExtraComma =
true;
8929 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8932 if (Lex.getKind() == lltok::kw_align) {
8933 if (parseOptionalAlignment(Alignment))
8935 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8938 ASLoc = Lex.getLoc();
8939 if (parseOptionalAddrSpace(AddrSpace))
8942 AteExtraComma =
true;
8948 if (
Size && !
Size->getType()->isIntegerTy())
8949 return error(SizeLoc,
"element count must have integer type");
8951 SmallPtrSet<Type *, 4> Visited;
8952 if (!Alignment && !Ty->
isSized(&Visited))
8953 return error(TyLoc,
"Cannot allocate unsized type");
8955 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8956 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
8960 return AteExtraComma ? InstExtraComma : InstNormal;
8967int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8969 MaybeAlign Alignment;
8970 bool AteExtraComma =
false;
8980 bool isVolatile =
false;
8986 bool IsElementwise =
false;
8988 IsElementwise =
true;
8993 LocTy ExplicitTypeLoc = Lex.getLoc();
8994 if (parseType(Ty) ||
8995 parseToken(
lltok::comma,
"expected comma after load's type") ||
8996 parseTypeAndValue(Val, Loc, PFS) ||
8997 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8998 parseOptionalCommaAlign(Alignment, AteExtraComma))
9002 return error(Loc,
"load operand must be a pointer to a first class type");
9004 if (IsElementwise && !isAtomic)
9005 return error(Loc,
"elementwise load must be atomic");
9008 return error(ExplicitTypeLoc,
9009 "atomic elementwise load operand must have fixed vector type");
9011 if (isAtomic && !Alignment)
9012 return error(Loc,
"atomic load must have explicit non-zero alignment");
9016 return error(Loc,
"atomic load cannot use Release ordering");
9018 SmallPtrSet<Type *, 4> Visited;
9019 if (!Alignment && !Ty->
isSized(&Visited))
9020 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
9022 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9023 Inst =
new LoadInst(Ty, Val,
"",
9024 LoadStoreInstProperties{isVolatile, *Alignment,
Ordering,
9025 SSID, IsElementwise},
9027 return AteExtraComma ? InstExtraComma : InstNormal;
9035int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9037 MaybeAlign Alignment;
9038 bool AteExtraComma =
false;
9048 bool isVolatile =
false;
9054 if (parseTypeAndValue(Val, Loc, PFS) ||
9055 parseToken(
lltok::comma,
"expected ',' after store operand") ||
9056 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9057 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9058 parseOptionalCommaAlign(Alignment, AteExtraComma))
9062 return error(PtrLoc,
"store operand must be a pointer");
9064 return error(Loc,
"store operand must be a first class value");
9065 if (isAtomic && !Alignment)
9066 return error(Loc,
"atomic store must have explicit non-zero alignment");
9069 return error(Loc,
"atomic store cannot use Acquire ordering");
9070 SmallPtrSet<Type *, 4> Visited;
9072 return error(Loc,
"storing unsized types is not allowed");
9074 Alignment = M->getDataLayout().getABITypeAlign(Val->
getType());
9076 Inst =
new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
9077 return AteExtraComma ? InstExtraComma : InstNormal;
9084int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9086 bool AteExtraComma =
false;
9090 bool isVolatile =
false;
9091 bool isWeak =
false;
9092 MaybeAlign Alignment;
9100 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9101 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
9102 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9103 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
9104 parseTypeAndValue(New, NewLoc, PFS) ||
9105 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
9106 parseOrdering(FailureOrdering) ||
9107 parseOptionalCommaAlign(Alignment, AteExtraComma))
9111 return tokError(
"invalid cmpxchg success ordering");
9113 return tokError(
"invalid cmpxchg failure ordering");
9115 return error(PtrLoc,
"cmpxchg operand must be a pointer");
9116 if (
Cmp->getType() !=
New->getType())
9117 return error(NewLoc,
"compare value and new value type do not match");
9118 if (!
New->getType()->isFirstClassType())
9119 return error(NewLoc,
"cmpxchg operand must be a first class value");
9121 const Align DefaultAlignment(
9122 PFS.getFunction().getDataLayout().getTypeStoreSize(
9125 AtomicCmpXchgInst *CXI =
9126 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9127 SuccessOrdering, FailureOrdering, SSID);
9132 return AteExtraComma ? InstExtraComma : InstNormal;
9139int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9141 bool AteExtraComma =
false;
9145 bool IsElementwise =
false;
9148 MaybeAlign Alignment;
9153 IsElementwise =
true;
9155 switch (Lex.getKind()) {
9157 return tokError(
"expected binary operation in atomicrmw");
9216 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9217 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9218 parseTypeAndValue(Val, ValLoc, PFS) ||
9219 parseScopeAndOrdering(
true , SSID, Ordering) ||
9220 parseOptionalCommaAlign(Alignment, AteExtraComma))
9224 return tokError(
"atomicrmw cannot be unordered");
9226 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9228 return error(ValLoc,
"atomicrmw operand may not be scalable");
9234 if (IsElementwise) {
9237 return error(ValLoc,
9238 "atomicrmw elementwise operand must be a fixed vector type");
9239 ScalarTy = VecTy->getElementType();
9248 " operand must be an integer, floating point, or pointer type");
9252 return error(ValLoc,
"atomicrmw " +
9254 " operand must be a floating point or fixed "
9255 "vector of floating point type");
9262 " operand must be an integer or fixed vector of integer type");
9267 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(Val->
getType());
9269 return error(ValLoc,
9270 "atomicrmw operand must have a power-of-two byte size");
9271 const Align DefaultAlignment(
9272 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->
getType()));
9273 AtomicRMWInst *RMWI =
new AtomicRMWInst(
Operation, Ptr, Val,
9274 Alignment.value_or(DefaultAlignment),
9275 Ordering, SSID, IsElementwise);
9278 return AteExtraComma ? InstExtraComma : InstNormal;
9283int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9286 if (parseScopeAndOrdering(
true , SSID, Ordering))
9290 return tokError(
"fence cannot be unordered");
9292 return tokError(
"fence cannot be monotonic");
9294 Inst =
new FenceInst(Context, Ordering, SSID);
9300int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9301 Value *Ptr =
nullptr;
9302 Value *Val =
nullptr;
9318 if (parseType(Ty) ||
9319 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9320 parseTypeAndValue(Ptr, Loc, PFS))
9325 if (!BasePointerType)
9326 return error(Loc,
"base of getelementptr must be a pointer");
9328 SmallVector<Value*, 16> Indices;
9329 bool AteExtraComma =
false;
9332 ElementCount GEPWidth =
BaseType->isVectorTy()
9338 AteExtraComma =
true;
9341 if (parseTypeAndValue(Val, EltLoc, PFS))
9344 return error(EltLoc,
"getelementptr index must be an integer");
9347 ElementCount ValNumEl = ValVTy->getElementCount();
9351 "getelementptr vector index has a wrong number of elements");
9352 GEPWidth = ValNumEl;
9357 SmallPtrSet<Type*, 4> Visited;
9359 return error(Loc,
"base element of getelementptr must be sized");
9363 return error(Loc,
"getelementptr cannot target structure that contains "
9364 "scalable vector type");
9367 return error(Loc,
"invalid getelementptr indices");
9370 GEP->setNoWrapFlags(NW);
9371 return AteExtraComma ? InstExtraComma : InstNormal;
9376int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9378 SmallVector<unsigned, 4> Indices;
9380 if (parseTypeAndValue(Val, Loc, PFS) ||
9381 parseIndexList(Indices, AteExtraComma))
9385 return error(Loc,
"extractvalue operand must be aggregate type");
9388 return error(Loc,
"invalid indices for extractvalue");
9390 return AteExtraComma ? InstExtraComma : InstNormal;
9395int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9397 SmallVector<unsigned, 4> Indices;
9399 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9400 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9401 parseTypeAndValue(Val1, Loc1, PFS) ||
9402 parseIndexList(Indices, AteExtraComma))
9406 return error(Loc0,
"insertvalue operand must be aggregate type");
9410 return error(Loc0,
"invalid indices for insertvalue");
9411 if (IndexedType != Val1->
getType())
9412 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9416 return AteExtraComma ? InstExtraComma : InstNormal;
9427bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9442 if (parseMetadata(MD,
nullptr))
9447 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9453bool LLParser::sortUseListOrder(
Value *V, ArrayRef<unsigned> Indexes,
9455 if (!
V->hasUseList())
9458 return error(Loc,
"value has no uses");
9460 unsigned NumUses = 0;
9461 SmallDenseMap<const Use *, unsigned, 16> Order;
9462 for (
const Use &U :
V->uses()) {
9463 if (++NumUses > Indexes.
size())
9465 Order[&
U] = Indexes[NumUses - 1];
9468 return error(Loc,
"value only has one use");
9469 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9471 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9473 V->sortUseList([&](
const Use &L,
const Use &R) {
9481bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9482 SMLoc Loc = Lex.getLoc();
9486 return tokError(
"expected non-empty list of uselistorder indexes");
9493 bool IsOrdered =
true;
9494 assert(Indexes.
empty() &&
"Expected empty order vector");
9497 if (parseUInt32(Index))
9502 Max = std::max(Max, Index);
9503 IsOrdered &= Index == Indexes.
size();
9511 if (Indexes.
size() < 2)
9512 return error(Loc,
"expected >= 2 uselistorder indexes");
9515 "expected distinct uselistorder indexes in range [0, size)");
9517 return error(Loc,
"expected uselistorder indexes to change the order");
9524bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9525 SMLoc Loc = Lex.getLoc();
9530 SmallVector<unsigned, 16> Indexes;
9531 if (parseTypeAndValue(V, PFS) ||
9532 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9533 parseUseListOrderIndexes(Indexes))
9536 return sortUseListOrder(V, Indexes, Loc);
9542bool LLParser::parseModuleEntry(
unsigned ID) {
9551 parseStringConstant(Path) ||
9559 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9560 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9561 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9562 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9563 parseUInt32(Hash[4]))
9570 auto ModuleEntry = Index->addModule(Path, Hash);
9571 ModuleIdMap[
ID] = ModuleEntry->first();
9578bool LLParser::parseTypeIdEntry(
unsigned ID) {
9587 parseStringConstant(Name))
9590 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9592 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9597 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9598 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9599 for (
auto TIDRef : FwdRefTIDs->second) {
9601 "Forward referenced type id GUID expected to be 0");
9604 ForwardRefTypeIds.erase(FwdRefTIDs);
9612bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9616 parseTypeTestResolution(TIS.
TTRes))
9621 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9638bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9647 parseStringConstant(Name))
9651 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9658 IdToIndexMapType IdToIndexMap;
9671 if (parseGVReference(VI, GVId))
9678 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9679 TI.push_back({
Offset, VI});
9687 for (
auto I : IdToIndexMap) {
9688 auto &Infos = ForwardRefValueInfos[
I.first];
9689 for (
auto P :
I.second) {
9691 "Forward referenced ValueInfo expected to be empty");
9692 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9702 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9703 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9704 for (
auto TIDRef : FwdRefTIDs->second) {
9706 "Forward referenced type id GUID expected to be 0");
9709 ForwardRefTypeIds.erase(FwdRefTIDs);
9721bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9729 switch (Lex.getKind()) {
9749 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9761 switch (Lex.getKind()) {
9776 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9789 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
9802bool LLParser::parseOptionalWpdResolutions(
9803 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9811 WholeProgramDevirtResolution WPDRes;
9815 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9818 WPDResMap[
Offset] = WPDRes;
9835bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9843 switch (Lex.getKind()) {
9854 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9860 switch (Lex.getKind()) {
9868 if (parseOptionalResByArg(WPDRes.
ResByArg))
9872 return error(Lex.getLoc(),
9873 "expected optional WholeProgramDevirtResolution field");
9890bool LLParser::parseOptionalResByArg(
9891 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9899 std::vector<uint64_t>
Args;
9900 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
9908 WholeProgramDevirtResolution::ByArg ByArg;
9909 switch (Lex.getKind()) {
9923 return error(Lex.getLoc(),
9924 "unexpected WholeProgramDevirtResolution::ByArg kind");
9930 switch (Lex.getKind()) {
9934 parseUInt64(ByArg.
Info))
9940 parseUInt32(ByArg.
Byte))
9946 parseUInt32(ByArg.
Bit))
9950 return error(Lex.getLoc(),
9951 "expected optional whole program devirt field");
9958 ResByArg[
Args] = ByArg;
9969bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9977 if (parseUInt64(Val))
9979 Args.push_back(Val);
10003bool LLParser::addGlobalValueToIndex(
10005 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
10010 VI = Index->getOrInsertValueInfo(GUID);
10014 auto *GV = M->getNamedValue(Name);
10016 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
10022 VI = Index->getOrInsertValueInfo(GV, GUID);
10026 "Need a source_filename to compute GUID for local");
10029 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10034 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
10035 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10036 for (
auto VIRef : FwdRefVIs->second) {
10038 "Forward referenced ValueInfo expected to be empty");
10041 ForwardRefValueInfos.erase(FwdRefVIs);
10045 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
10046 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10047 for (
auto AliaseeRef : FwdRefAliasees->second) {
10048 assert(!AliaseeRef.first->hasAliasee() &&
10049 "Forward referencing alias already has aliasee");
10050 assert(Summary &&
"Aliasee must be a definition");
10051 AliaseeRef.first->setAliasee(VI,
Summary.get());
10053 ForwardRefAliasees.erase(FwdRefAliasees);
10058 Index->addGlobalValueSummary(VI, std::move(Summary));
10061 if (
ID == NumberedValueInfos.size())
10062 NumberedValueInfos.push_back(VI);
10065 if (
ID > NumberedValueInfos.size())
10066 NumberedValueInfos.resize(
ID + 1);
10067 NumberedValueInfos[
ID] =
VI;
10075bool LLParser::parseSummaryIndexFlags() {
10082 if (parseUInt64(Flags))
10085 Index->setFlags(Flags);
10091bool LLParser::parseBlockCount() {
10097 uint64_t BlockCount;
10098 if (parseUInt64(BlockCount))
10101 Index->setBlockCount(BlockCount);
10109bool LLParser::parseGVEntry(
unsigned ID) {
10117 LocTy Loc = Lex.getLoc();
10120 switch (Lex.getKind()) {
10124 parseStringConstant(Name))
10130 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
10134 return error(Lex.getLoc(),
"expected name or guid tag");
10157 switch (Lex.getKind()) {
10159 if (parseFunctionSummary(Name, GUID,
ID))
10163 if (parseVariableSummary(Name, GUID,
ID))
10167 if (parseAliasSummary(Name, GUID,
ID))
10171 return error(Lex.getLoc(),
"expected summary type");
10189 LocTy Loc = Lex.getLoc();
10193 StringRef ModulePath;
10194 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10197 false,
false,
false,
10199 unsigned InstCount;
10201 FunctionSummary::TypeIdInfo TypeIdInfo;
10202 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10204 std::vector<CallsiteInfo> Callsites;
10205 std::vector<AllocInfo> Allocs;
10207 FunctionSummary::FFlags FFlags = {};
10210 parseModuleReference(ModulePath) ||
10211 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10214 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10219 switch (Lex.getKind()) {
10221 if (parseOptionalFFlags(FFlags))
10225 if (parseOptionalCalls(Calls))
10229 if (parseOptionalTypeIdInfo(TypeIdInfo))
10233 if (parseOptionalRefs(Refs))
10237 if (parseOptionalParamAccesses(ParamAccesses))
10241 if (parseOptionalAllocs(Allocs))
10245 if (parseOptionalCallsites(Callsites))
10249 return error(Lex.getLoc(),
"expected optional function summary field");
10256 auto FS = std::make_unique<FunctionSummary>(
10257 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10263 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10265 FS->setModulePath(ModulePath);
10267 return addGlobalValueToIndex(Name, GUID,
10269 std::move(FS), Loc);
10277 LocTy Loc = Lex.getLoc();
10281 StringRef ModulePath;
10282 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10285 false,
false,
false,
10287 GlobalVarSummary::GVarFlags GVarFlags(
false,
10295 parseModuleReference(ModulePath) ||
10296 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10298 parseGVarFlags(GVarFlags))
10303 switch (Lex.getKind()) {
10305 if (parseOptionalVTableFuncs(VTableFuncs))
10309 if (parseOptionalRefs(Refs))
10313 return error(Lex.getLoc(),
"expected optional variable summary field");
10321 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10323 GS->setModulePath(ModulePath);
10324 GS->setVTableFuncs(std::move(VTableFuncs));
10326 return addGlobalValueToIndex(Name, GUID,
10328 std::move(GS), Loc);
10337 LocTy Loc = Lex.getLoc();
10340 StringRef ModulePath;
10341 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10344 false,
false,
false,
10348 parseModuleReference(ModulePath) ||
10349 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10355 ValueInfo AliaseeVI;
10357 auto AS = std::make_unique<AliasSummary>(GVFlags);
10358 AS->setModulePath(ModulePath);
10361 if (parseGVReference(AliaseeVI, GVId))
10366 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10368 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10369 assert(Summary &&
"Aliasee must be a definition");
10370 AS->setAliasee(AliaseeVI, Summary);
10377 return addGlobalValueToIndex(Name, GUID,
10379 std::move(AS), Loc);
10384bool LLParser::parseFlag(
unsigned &Val) {
10385 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10386 return tokError(
"expected integer");
10387 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10403bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10407 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10413 switch (Lex.getKind()) {
10416 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10422 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10428 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10434 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10440 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10446 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10452 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10458 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10464 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10470 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10475 return error(Lex.getLoc(),
"expected function flag type");
10479 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10490bool LLParser::parseOptionalCalls(
10491 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10495 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10499 IdToIndexMapType IdToIndexMap;
10508 LocTy Loc = Lex.getLoc();
10510 if (parseGVReference(VI, GVId))
10514 unsigned RelBF = 0;
10515 unsigned HasTailCall =
false;
10519 switch (Lex.getKind()) {
10522 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10528 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10533 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10537 return error(Lex.getLoc(),
"expected hotness, relbf, or tail");
10544 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10554 for (
auto I : IdToIndexMap) {
10555 auto &Infos = ForwardRefValueInfos[
I.first];
10556 for (
auto P :
I.second) {
10558 "Forward referenced ValueInfo expected to be empty");
10559 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10572 switch (Lex.getKind()) {
10576 case lltok::kw_cold:
10582 case lltok::kw_hot:
10589 return error(Lex.getLoc(),
"invalid call edge hotness");
10598bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10602 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10606 IdToIndexMapType IdToIndexMap;
10610 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10615 LocTy Loc = Lex.getLoc();
10617 if (parseGVReference(VI, GVId))
10630 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10631 VTableFuncs.push_back({
VI,
Offset});
10633 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10639 for (
auto I : IdToIndexMap) {
10640 auto &Infos = ForwardRefValueInfos[
I.first];
10641 for (
auto P :
I.second) {
10643 "Forward referenced ValueInfo expected to be empty");
10644 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10648 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10655bool LLParser::parseParamNo(uint64_t &ParamNo) {
10657 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10663bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10666 auto ParseAPSInt = [&](
APSInt &Val) {
10668 return tokError(
"expected integer");
10669 Val = Lex.getAPSIntVal();
10671 Val.setIsSigned(
true);
10693bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10694 IdLocListType &IdLocList) {
10702 LocTy Loc = Lex.getLoc();
10703 if (parseGVReference(VI, GVId))
10707 IdLocList.emplace_back(GVId, Loc);
10710 parseParamNo(
Call.ParamNo) ||
10712 parseParamAccessOffset(
Call.Offsets))
10724bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10725 IdLocListType &IdLocList) {
10727 parseParamNo(
Param.ParamNo) ||
10729 parseParamAccessOffset(
Param.Use))
10738 FunctionSummary::ParamAccess::Call
Call;
10739 if (parseParamAccessCall(
Call, IdLocList))
10756bool LLParser::parseOptionalParamAccesses(
10757 std::vector<FunctionSummary::ParamAccess> &Params) {
10765 IdLocListType VContexts;
10766 size_t CallsNum = 0;
10768 FunctionSummary::ParamAccess ParamAccess;
10769 if (parseParamAccess(ParamAccess, VContexts))
10771 CallsNum += ParamAccess.
Calls.size();
10772 assert(VContexts.size() == CallsNum);
10774 Params.emplace_back(std::move(ParamAccess));
10782 IdLocListType::const_iterator ItContext = VContexts.begin();
10783 for (
auto &PA : Params) {
10784 for (
auto &
C : PA.Calls) {
10786 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10787 ItContext->second);
10791 assert(ItContext == VContexts.end());
10798bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10802 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10806 struct ValueContext {
10811 std::vector<ValueContext> VContexts;
10815 VC.Loc = Lex.getLoc();
10816 if (parseGVReference(
VC.VI,
VC.GVId))
10818 VContexts.push_back(VC);
10824 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10825 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10828 IdToIndexMapType IdToIndexMap;
10829 for (
auto &VC : VContexts) {
10834 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
10840 for (
auto I : IdToIndexMap) {
10841 auto &Infos = ForwardRefValueInfos[
I.first];
10842 for (
auto P :
I.second) {
10844 "Forward referenced ValueInfo expected to be empty");
10845 Infos.emplace_back(&Refs[
P.first],
P.second);
10859bool LLParser::parseOptionalTypeIdInfo(
10860 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10869 switch (Lex.getKind()) {
10871 if (parseTypeTests(TypeIdInfo.
TypeTests))
10895 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
10899 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10908bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10916 IdToIndexMapType IdToIndexMap;
10920 unsigned ID = Lex.getUIntVal();
10921 LocTy Loc = Lex.getLoc();
10925 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
10927 }
else if (parseUInt64(GUID))
10929 TypeTests.push_back(GUID);
10934 for (
auto I : IdToIndexMap) {
10935 auto &Ids = ForwardRefTypeIds[
I.first];
10936 for (
auto P :
I.second) {
10937 assert(TypeTests[
P.first] == 0 &&
10938 "Forward referenced type id GUID expected to be 0");
10939 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10943 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10951bool LLParser::parseVFuncIdList(
10952 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10953 assert(Lex.getKind() == Kind);
10960 IdToIndexMapType IdToIndexMap;
10962 FunctionSummary::VFuncId VFuncId;
10963 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10965 VFuncIdList.push_back(VFuncId);
10973 for (
auto I : IdToIndexMap) {
10974 auto &Ids = ForwardRefTypeIds[
I.first];
10975 for (
auto P :
I.second) {
10976 assert(VFuncIdList[
P.first].GUID == 0 &&
10977 "Forward referenced type id GUID expected to be 0");
10978 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10987bool LLParser::parseConstVCallList(
10989 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10990 assert(Lex.getKind() == Kind);
10997 IdToIndexMapType IdToIndexMap;
10999 FunctionSummary::ConstVCall ConstVCall;
11000 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11002 ConstVCallList.push_back(ConstVCall);
11010 for (
auto I : IdToIndexMap) {
11011 auto &Ids = ForwardRefTypeIds[
I.first];
11012 for (
auto P :
I.second) {
11013 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
11014 "Forward referenced type id GUID expected to be 0");
11015 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
11024bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11025 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11027 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
11031 if (parseArgs(ConstVCall.
Args))
11043bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11044 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11054 unsigned ID = Lex.getUIntVal();
11055 LocTy Loc = Lex.getLoc();
11059 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
11061 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
11063 parseUInt64(VFuncId.
GUID))
11069 parseUInt64(VFuncId.
Offset) ||
11081bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11091 switch (Lex.getKind()) {
11098 assert(HasLinkage &&
"Linkage not optional in summary entry");
11105 parseOptionalVisibility(Flag);
11110 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11116 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11122 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11128 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11137 if (parseOptionalImportType(Lex.getKind(), IK))
11139 GVFlags.
ImportType =
static_cast<unsigned>(IK);
11144 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11149 return error(Lex.getLoc(),
"expected gv flag type");
11163bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11171 auto ParseRest = [
this](
unsigned int &Val) {
11175 return parseFlag(Val);
11180 switch (Lex.getKind()) {
11181 case lltok::kw_readonly:
11182 if (ParseRest(Flag))
11186 case lltok::kw_writeonly:
11187 if (ParseRest(Flag))
11192 if (ParseRest(Flag))
11197 if (ParseRest(Flag))
11202 return error(Lex.getLoc(),
"expected gvar flag type");
11210bool LLParser::parseModuleReference(StringRef &ModulePath) {
11217 unsigned ModuleID = Lex.getUIntVal();
11218 auto I = ModuleIdMap.find(ModuleID);
11220 assert(
I != ModuleIdMap.end());
11221 ModulePath =
I->second;
11227bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11230 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11234 GVId = Lex.getUIntVal();
11236 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11238 VI = NumberedValueInfos[GVId];
11255bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11259 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11271 SmallVector<uint8_t> Versions;
11274 if (parseAllocType(V))
11279 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11283 std::vector<MIBInfo> MIBs;
11284 if (parseMemProfs(MIBs))
11287 Allocs.push_back({Versions, MIBs});
11304bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11308 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11314 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11323 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11329 SmallVector<unsigned> StackIdIndices;
11333 uint64_t StackId = 0;
11334 if (parseUInt64(StackId))
11336 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11357bool LLParser::parseAllocType(uint8_t &
AllocType) {
11358 switch (Lex.getKind()) {
11365 case lltok::kw_cold:
11368 case lltok::kw_hot:
11372 return error(Lex.getLoc(),
"invalid alloc type");
11385bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11389 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11393 IdToIndexMapType IdToIndexMap;
11396 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11403 LocTy Loc = Lex.getLoc();
11405 if (parseGVReference(VI, GVId))
11409 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11415 SmallVector<unsigned> Clones;
11418 if (parseUInt32(V))
11424 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11430 SmallVector<unsigned> StackIdIndices;
11434 uint64_t StackId = 0;
11435 if (parseUInt64(StackId))
11437 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11448 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11449 Callsites.push_back({
VI, Clones, StackIdIndices});
11457 for (
auto I : IdToIndexMap) {
11458 auto &Infos = ForwardRefValueInfos[
I.first];
11459 for (
auto P :
I.second) {
11461 "Forward referenced ValueInfo expected to be empty");
11462 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11466 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)
LLVM_ABI 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.
std::pair< key_type, mapped_type > value_type
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.
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
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
LLVM_ABI bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
LLVMContext & getContext()
LLVM_ABI bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
LLVM_ABI bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
LLVM_ABI 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.
constexpr bool isAtomic(const T &...O)
constexpr bool isPacked(const T &...O)
@ 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.
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...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
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)
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
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
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.
LLVM_ABI bool set(StringRef Name, std::string Value)
Set a property using a string name.
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.