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);
194 if (
Info.first->getNumTemporaryUses() == 1) {
195 NumberedMetadata.erase(
ID);
196 ForwardRefMDNodes.erase(
ID);
209 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
210 "Mixed debug intrinsics/records seen without a parsing error?");
213 for (
const auto &RAG : ForwardRefAttrGroups) {
215 const std::vector<unsigned> &
Attrs = RAG.second;
216 AttrBuilder
B(Context);
218 for (
const auto &Attr : Attrs) {
219 auto R = NumberedAttrBuilders.find(Attr);
220 if (R != NumberedAttrBuilders.end())
225 AttributeList AS = Fn->getAttributes();
226 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
227 AS = AS.removeFnAttributes(Context);
233 if (MaybeAlign
A = FnAttrs.getAlignment()) {
234 Fn->setAlignment(*
A);
235 FnAttrs.removeAttribute(Attribute::Alignment);
238 AS = AS.addFnAttributes(Context, FnAttrs);
239 Fn->setAttributes(AS);
241 AttributeList AS = CI->getAttributes();
242 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
243 AS = AS.removeFnAttributes(Context);
245 AS = AS.addFnAttributes(Context, FnAttrs);
246 CI->setAttributes(AS);
248 AttributeList AS =
II->getAttributes();
249 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
250 AS = AS.removeFnAttributes(Context);
252 AS = AS.addFnAttributes(Context, FnAttrs);
253 II->setAttributes(AS);
255 AttributeList AS = CBI->getAttributes();
256 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
257 AS = AS.removeFnAttributes(Context);
259 AS = AS.addFnAttributes(Context, FnAttrs);
260 CBI->setAttributes(AS);
262 AttrBuilder
Attrs(M->getContext(), GV->getAttributes());
272 if (!ForwardRefBlockAddresses.empty())
273 return error(ForwardRefBlockAddresses.begin()->first.Loc,
274 "expected function name in blockaddress");
276 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
277 GlobalValue *FwdRef) {
278 GlobalValue *GV =
nullptr;
280 GV = M->getNamedValue(GVRef.
StrVal);
282 GV = NumberedVals.get(GVRef.
UIntVal);
287 "' referenced by dso_local_equivalent");
291 "expected a function, alias to function, or ifunc "
292 "in dso_local_equivalent");
295 FwdRef->replaceAllUsesWith(Equiv);
296 FwdRef->eraseFromParent();
303 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
304 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
307 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
308 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
311 ForwardRefDSOLocalEquivalentIDs.clear();
312 ForwardRefDSOLocalEquivalentNames.clear();
314 for (
const auto &NT : NumberedTypes)
315 if (
NT.second.second.isValid())
317 "use of undefined type '%" + Twine(
NT.first) +
"'");
319 for (
const auto &[Name, TypeInfo] : NamedTypes)
320 if (TypeInfo.second.isValid())
321 return error(TypeInfo.second,
322 "use of undefined type named '" + Name +
"'");
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first +
"'");
341 if (!CB || !CB->isCallee(&U))
342 return error(
Info.second,
"intrinsic can only be used as callee");
356 return error(
Info.second,
"unknown intrinsic '" + Name +
"'");
357 return error(
Info.second,
"invalid intrinsic signature");
367 Info.first->eraseFromParent();
368 ForwardRefVals.erase(Name);
377 auto GetCommonFunctionType = [](
Value *
V) -> FunctionType * {
378 FunctionType *FTy =
nullptr;
379 for (Use &U :
V->uses()) {
381 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
383 FTy = CB->getFunctionType();
391 Type *Ty = GetCommonFunctionType(
Info.first);
399 GV =
new GlobalVariable(*M, Ty,
false,
402 Info.first->replaceAllUsesWith(GV);
403 Info.first->eraseFromParent();
404 ForwardRefVals.erase(Name);
407 if (!ForwardRefVals.empty())
408 return error(ForwardRefVals.begin()->second.second,
409 "use of undefined value '@" + ForwardRefVals.begin()->first +
412 if (!ForwardRefValIDs.empty())
413 return error(ForwardRefValIDs.begin()->second.second,
414 "use of undefined value '@" +
415 Twine(ForwardRefValIDs.begin()->first) +
"'");
418 dropUnknownMetadataReferences();
420 if (!ForwardRefMDNodes.empty())
421 return error(ForwardRefMDNodes.begin()->second.second,
422 "use of undefined metadata '!" +
423 Twine(ForwardRefMDNodes.begin()->first) +
"'");
426 for (
auto &
N : NumberedMetadata) {
427 if (
N.second && !
N.second->isResolved())
428 N.second->resolveCycles();
432 NewDistinctSPs.clear();
434 for (
auto *Inst : InstsWithTBAATag) {
435 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
438 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
441 if (MD != UpgradedMD)
442 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
451 if (UpgradeDebugInfo)
464 Slots->GlobalValues = std::move(NumberedVals);
465 Slots->MetadataNodes = std::move(NumberedMetadata);
466 for (
const auto &
I : NamedTypes)
467 Slots->NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
468 for (
const auto &
I : NumberedTypes)
469 Slots->Types.insert(std::make_pair(
I.first,
I.second.first));
475bool LLParser::validateEndOfIndex() {
479 if (!ForwardRefValueInfos.empty())
480 return error(ForwardRefValueInfos.begin()->second.front().second,
481 "use of undefined summary '^" +
482 Twine(ForwardRefValueInfos.begin()->first) +
"'");
484 if (!ForwardRefAliasees.empty())
485 return error(ForwardRefAliasees.begin()->second.front().second,
486 "use of undefined summary '^" +
487 Twine(ForwardRefAliasees.begin()->first) +
"'");
489 if (!ForwardRefTypeIds.empty())
490 return error(ForwardRefTypeIds.begin()->second.front().second,
491 "use of undefined type id summary '^" +
492 Twine(ForwardRefTypeIds.begin()->first) +
"'");
506 std::string TentativeDLStr = M->getDataLayoutStr();
511 switch (Lex.getKind()) {
513 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
517 if (parseSourceFileName())
526 if (
auto LayoutOverride =
527 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
528 TentativeDLStr = *LayoutOverride;
534 M->setDataLayout(MaybeDL.
get());
538bool LLParser::parseTopLevelEntities() {
542 switch (Lex.getKind()) {
546 if (parseSummaryEntry())
550 if (parseSourceFileName())
560 switch (Lex.getKind()) {
562 return tokError(
"expected top-level entity");
573 if (parseModuleAsm())
577 if (parseUnnamedType())
581 if (parseNamedType())
585 if (parseUnnamedGlobal())
589 if (parseNamedGlobal())
594 if (parseStandaloneMetadata())
598 if (parseSummaryEntry())
602 if (parseNamedMetadata())
606 if (parseUnnamedAttrGrp())
610 if (parseUseListOrder())
614 if (parseUseListOrderBB())
623bool LLParser::parseModuleAsm() {
629 parseStringConstant(AsmStr))
632 M->appendModuleInlineAsm(AsmStr);
639bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
645 return tokError(
"unknown target property");
648 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
649 parseStringConstant(Str))
651 M->setTargetTriple(Triple(std::move(Str)));
655 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
657 DLStrLoc = Lex.getLoc();
658 if (parseStringConstant(TentativeDLStr))
666bool LLParser::parseSourceFileName() {
669 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
670 parseStringConstant(SourceFileName))
673 M->setSourceFileName(SourceFileName);
679bool LLParser::parseUnnamedType() {
680 LocTy TypeLoc = Lex.getLoc();
681 unsigned TypeID = Lex.getUIntVal();
684 if (parseToken(
lltok::equal,
"expected '=' after name") ||
689 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
693 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
695 return error(TypeLoc,
"non-struct types may not be recursive");
697 Entry.second = SMLoc();
705bool LLParser::parseNamedType() {
706 std::string
Name = Lex.getStrVal();
707 LocTy NameLoc = Lex.getLoc();
710 if (parseToken(
lltok::equal,
"expected '=' after name") ||
715 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
719 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
721 return error(NameLoc,
"non-struct types may not be recursive");
723 Entry.second = SMLoc();
731bool LLParser::parseDeclare() {
735 std::vector<std::pair<unsigned, MDNode *>> MDs;
739 if (parseMetadataAttachment(MDK,
N))
741 MDs.push_back({MDK,
N});
745 unsigned FunctionNumber = -1;
746 SmallVector<unsigned> UnnamedArgNums;
747 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
750 F->addMetadata(MD.first, *MD.second);
756bool LLParser::parseDefine() {
759 FileLoc FunctionStart = getTokLineColumnPos();
763 unsigned FunctionNumber = -1;
764 SmallVector<unsigned> UnnamedArgNums;
766 parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
767 parseOptionalFunctionMetadata(*
F) ||
768 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
770 ParserContext->addFunctionLocation(
771 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
779bool LLParser::parseGlobalType(
bool &IsConstant) {
786 return tokError(
"expected 'global' or 'constant'");
792bool LLParser::parseOptionalUnnamedAddr(
813bool LLParser::parseUnnamedGlobal() {
816 LocTy NameLoc = Lex.getLoc();
820 VarID = Lex.getUIntVal();
821 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
825 if (parseToken(
lltok::equal,
"expected '=' after name"))
828 VarID = NumberedVals.getNext();
832 unsigned Linkage, Visibility, DLLStorageClass;
836 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
838 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
841 switch (Lex.getKind()) {
843 return parseGlobal(Name,
VarID, NameLoc,
Linkage, HasLinkage, Visibility,
844 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
847 return parseAliasOrIFunc(Name,
VarID, NameLoc,
Linkage, Visibility,
848 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
857bool LLParser::parseNamedGlobal() {
859 LocTy NameLoc = Lex.getLoc();
860 std::string
Name = Lex.getStrVal();
864 unsigned Linkage, Visibility, DLLStorageClass;
868 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
869 parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
871 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
874 switch (Lex.getKind()) {
876 return parseGlobal(Name, -1, NameLoc,
Linkage, HasLinkage, Visibility,
877 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
880 return parseAliasOrIFunc(Name, -1, NameLoc,
Linkage, Visibility,
881 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
885bool LLParser::parseComdat() {
887 std::string
Name = Lex.getStrVal();
888 LocTy NameLoc = Lex.getLoc();
895 return tokError(
"expected comdat type");
898 switch (Lex.getKind()) {
900 return tokError(
"unknown selection kind");
922 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
923 return error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
926 if (
I != ComdatSymTab.
end())
929 C = M->getOrInsertComdat(Name);
930 C->setSelectionKind(SK);
937bool LLParser::parseMDString(
MDString *&Result) {
939 if (parseStringConstant(Str))
947bool LLParser::parseMDNodeID(
MDNode *&Result) {
949 LocTy IDLoc = Lex.getLoc();
951 if (parseUInt32(MID))
955 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
962 auto &FwdRef = ForwardRefMDNodes[MID];
965 Result = FwdRef.first.get();
966 It->second.reset(Result);
972bool LLParser::parseNamedMetadata() {
974 std::string
Name = Lex.getStrVal();
982 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
990 Lex.getStrVal() ==
"DIExpression") {
991 if (parseDIExpression(
N,
false))
996 Lex.getStrVal() ==
"DIArgList") {
997 return tokError(
"found DIArgList outside of function");
1005 return parseToken(
lltok::rbrace,
"expected end of metadata node");
1010bool LLParser::parseStandaloneMetadata() {
1013 unsigned MetadataID = 0;
1016 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1021 return tokError(
"unexpected type in metadata definition");
1025 if (parseSpecializedMDNode(Init, IsDistinct))
1028 parseMDTuple(Init, IsDistinct))
1032 auto FI = ForwardRefMDNodes.find(MetadataID);
1033 if (FI != ForwardRefMDNodes.end()) {
1034 auto *ToReplace = FI->second.first.get();
1038 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1039 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1040 "Inst unexpectedly already has DIAssignID attachment");
1041 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1045 ToReplace->replaceAllUsesWith(Init);
1046 ForwardRefMDNodes.erase(FI);
1048 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
1050 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1052 return tokError(
"Metadata id is already used");
1053 It->second.reset(Init);
1060bool LLParser::skipModuleSummaryEntry() {
1070 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1071 "start of summary entry");
1073 return parseSummaryIndexFlags();
1075 return parseBlockCount();
1077 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1078 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1082 unsigned NumOpenParen = 1;
1084 switch (Lex.getKind()) {
1092 return tokError(
"found end of file while parsing summary entry");
1098 }
while (NumOpenParen > 0);
1104bool LLParser::parseSummaryEntry() {
1110 Lex.setIgnoreColonInIdentifiers(
true);
1118 return skipModuleSummaryEntry();
1120 bool result =
false;
1121 switch (Lex.getKind()) {
1123 result = parseGVEntry(SummaryID);
1126 result = parseModuleEntry(SummaryID);
1129 result = parseTypeIdEntry(SummaryID);
1132 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1135 result = parseSummaryIndexFlags();
1138 result = parseBlockCount();
1141 result =
error(Lex.getLoc(),
"unexpected summary kind");
1144 Lex.setIgnoreColonInIdentifiers(
false);
1178bool LLParser::parseAliasOrIFunc(
const std::string &Name,
unsigned NameID,
1179 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1180 unsigned DLLStorageClass,
bool DSOLocal,
1195 return error(NameLoc,
"invalid linkage type for alias");
1198 return error(NameLoc,
1199 "symbol with local linkage must have default visibility");
1202 return error(NameLoc,
1203 "symbol with local linkage cannot have a DLL storage class");
1206 LocTy ExplicitTypeLoc = Lex.getLoc();
1207 if (parseType(Ty) ||
1208 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1212 LocTy AliaseeLoc = Lex.getLoc();
1217 if (parseGlobalTypeAndValue(Aliasee))
1222 if (parseValID(
ID,
nullptr))
1225 return error(AliaseeLoc,
"invalid aliasee");
1226 Aliasee =
ID.ConstantVal;
1232 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1233 unsigned AddrSpace = PTy->getAddressSpace();
1235 GlobalValue *GVal =
nullptr;
1239 if (!
Name.empty()) {
1240 auto I = ForwardRefVals.find(Name);
1241 if (
I != ForwardRefVals.end()) {
1242 GVal =
I->second.first;
1243 ForwardRefVals.erase(Name);
1244 }
else if (M->getNamedValue(Name)) {
1245 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1248 auto I = ForwardRefValIDs.find(NameID);
1249 if (
I != ForwardRefValIDs.end()) {
1250 GVal =
I->second.first;
1251 ForwardRefValIDs.erase(
I);
1256 std::unique_ptr<GlobalAlias> GA;
1257 std::unique_ptr<GlobalIFunc> GI;
1285 if (parseGlobalObjectMetadataAttachment(*GI))
1288 return tokError(
"unknown alias or ifunc property!");
1293 NumberedVals.add(NameID, GV);
1300 "forward reference and definition of alias have different types");
1310 M->insertAlias(GA.release());
1312 M->insertIFunc(GI.release());
1313 assert(GV->
getName() == Name &&
"Should not be a name conflict!");
1322 case lltok::kw_sanitize_memtag:
1336 switch (Lex.getKind()) {
1338 Meta.NoAddress =
true;
1341 Meta.NoHWAddress =
true;
1343 case lltok::kw_sanitize_memtag:
1347 Meta.IsDynInit =
true;
1350 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1370bool LLParser::parseGlobal(
const std::string &Name,
unsigned NameID,
1371 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1372 unsigned Visibility,
unsigned DLLStorageClass,
1376 return error(NameLoc,
1377 "symbol with local linkage must have default visibility");
1380 return error(NameLoc,
1381 "symbol with local linkage cannot have a DLL storage class");
1385 LocTy IsExternallyInitializedLoc;
1389 if (parseOptionalAddrSpace(AddrSpace) ||
1391 IsExternallyInitialized,
1392 &IsExternallyInitializedLoc) ||
1393 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1402 if (parseGlobalValue(Ty, Init))
1407 return error(TyLoc,
"invalid type for global variable");
1409 GlobalValue *GVal =
nullptr;
1412 if (!
Name.empty()) {
1413 auto I = ForwardRefVals.find(Name);
1414 if (
I != ForwardRefVals.end()) {
1415 GVal =
I->second.first;
1416 ForwardRefVals.erase(
I);
1417 }
else if (M->getNamedValue(Name)) {
1418 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1423 if (NameID == (
unsigned)-1)
1424 NameID = NumberedVals.getNext();
1426 auto I = ForwardRefValIDs.find(NameID);
1427 if (
I != ForwardRefValIDs.end()) {
1428 GVal =
I->second.first;
1429 ForwardRefValIDs.erase(
I);
1433 GlobalVariable *GV =
new GlobalVariable(
1438 NumberedVals.add(NameID, GV);
1456 "forward reference and definition of global have different types");
1476 }
else if (Lex.getKind() == lltok::kw_align) {
1477 MaybeAlign Alignment;
1478 if (parseOptionalAlignment(Alignment))
1484 if (parseOptionalCodeModel(CodeModel))
1488 if (parseGlobalObjectMetadataAttachment(*GV))
1491 if (parseSanitizer(GV))
1495 if (parseOptionalComdat(Name,
C))
1500 return tokError(
"unknown global variable property!");
1504 AttrBuilder
Attrs(M->getContext());
1506 std::vector<unsigned> FwdRefAttrGrps;
1507 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1509 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1511 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1519bool LLParser::parseUnnamedAttrGrp() {
1521 LocTy AttrGrpLoc = Lex.getLoc();
1525 return tokError(
"expected attribute group id");
1527 unsigned VarID = Lex.getUIntVal();
1528 std::vector<unsigned> unused;
1536 auto R = NumberedAttrBuilders.find(
VarID);
1537 if (R == NumberedAttrBuilders.end())
1538 R = NumberedAttrBuilders.emplace(
VarID, AttrBuilder(M->getContext())).first;
1540 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1541 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1544 if (!
R->second.hasAttributes())
1545 return error(AttrGrpLoc,
"attribute group has no attributes");
1552#define GET_ATTR_NAMES
1553#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1554 case lltok::kw_##DISPLAY_NAME: \
1555 return Attribute::ENUM_NAME;
1556#include "llvm/IR/Attributes.inc"
1565 return parseRequiredTypeAttr(
B, Lex.getKind(), Attr);
1568 case Attribute::Alignment: {
1569 MaybeAlign Alignment;
1577 if (parseOptionalAlignment(Alignment,
true))
1580 B.addAlignmentAttr(Alignment);
1583 case Attribute::StackAlignment: {
1588 parseUInt32(Alignment))
1591 if (parseOptionalStackAlignment(Alignment))
1594 B.addStackAlignmentAttr(Alignment);
1597 case Attribute::AllocSize: {
1598 unsigned ElemSizeArg;
1599 std::optional<unsigned> NumElemsArg;
1600 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1602 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1605 case Attribute::VScaleRange: {
1606 unsigned MinValue, MaxValue;
1607 if (parseVScaleRangeArguments(MinValue, MaxValue))
1609 B.addVScaleRangeAttr(MinValue,
1610 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1613 case Attribute::Dereferenceable: {
1614 std::optional<uint64_t> Bytes;
1615 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1617 assert(Bytes.has_value());
1618 B.addDereferenceableAttr(Bytes.value());
1621 case Attribute::DeadOnReturn: {
1622 std::optional<uint64_t> Bytes;
1623 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1626 if (Bytes.has_value()) {
1627 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1629 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1633 case Attribute::DereferenceableOrNull: {
1634 std::optional<uint64_t> Bytes;
1635 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1637 assert(Bytes.has_value());
1638 B.addDereferenceableOrNullAttr(Bytes.value());
1641 case Attribute::UWTable: {
1643 if (parseOptionalUWTableKind(Kind))
1645 B.addUWTableAttr(Kind);
1648 case Attribute::AllocKind: {
1650 if (parseAllocKind(Kind))
1652 B.addAllocKindAttr(Kind);
1655 case Attribute::Memory: {
1656 std::optional<MemoryEffects> ME = parseMemoryAttr();
1659 B.addMemoryAttr(*ME);
1662 case Attribute::DenormalFPEnv: {
1663 std::optional<DenormalFPEnv>
Mode = parseDenormalFPEnvAttr();
1667 B.addDenormalFPEnvAttr(*
Mode);
1670 case Attribute::NoFPClass: {
1673 B.addNoFPClassAttr(NoFPClass);
1679 case Attribute::Range:
1680 return parseRangeAttr(
B);
1681 case Attribute::Initializes:
1682 return parseInitializesAttr(
B);
1683 case Attribute::Captures:
1684 return parseCapturesAttr(
B);
1686 B.addAttribute(Attr);
1694 case lltok::kw_readnone:
1697 case lltok::kw_readonly:
1700 case lltok::kw_writeonly:
1719bool LLParser::parseFnAttributeValuePairs(AttrBuilder &
B,
1720 std::vector<unsigned> &FwdRefAttrGrps,
1721 bool InAttrGrp, LocTy &BuiltinLoc) {
1722 bool HaveError =
false;
1733 if (parseStringAttribute(
B))
1745 "cannot have an attribute group reference in an attribute group");
1748 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1754 SMLoc Loc = Lex.getLoc();
1755 if (Token == lltok::kw_builtin)
1767 return error(Lex.getLoc(),
"unterminated attribute group");
1770 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1777 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1781 B.addMemoryAttr(ME);
1795 PTy->getAddressSpace());
1804 error(Loc,
"'" + Name +
"' is not a basic block");
1806 error(Loc,
"'" + Name +
"' defined with type '" +
1819 error(Loc,
"global variable reference must have pointer type");
1830 auto I = ForwardRefVals.find(Name);
1831 if (
I != ForwardRefVals.end())
1832 Val =
I->second.first;
1838 checkValidVariableType(Loc,
"@" + Name, Ty, Val));
1842 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1849 error(Loc,
"global variable reference must have pointer type");
1853 GlobalValue *Val = NumberedVals.get(
ID);
1858 auto I = ForwardRefValIDs.find(
ID);
1859 if (
I != ForwardRefValIDs.end())
1860 Val =
I->second.first;
1866 checkValidVariableType(Loc,
"@" + Twine(
ID), Ty, Val));
1870 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1878Comdat *LLParser::getComdat(
const std::string &Name, LocTy
Loc) {
1882 if (
I != ComdatSymTab.
end())
1886 Comdat *
C = M->getOrInsertComdat(Name);
1887 ForwardRefComdats[
Name] = Loc;
1897bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1898 if (Lex.getKind() !=
T)
1899 return tokError(ErrMsg);
1906bool LLParser::parseStringConstant(std::string &Result) {
1908 return tokError(
"expected string constant");
1909 Result = Lex.getStrVal();
1916bool LLParser::parseUInt32(uint32_t &Val) {
1917 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1918 return tokError(
"expected integer");
1919 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1920 if (Val64 !=
unsigned(Val64))
1921 return tokError(
"expected 32-bit integer (too large)");
1929bool LLParser::parseUInt64(uint64_t &Val) {
1930 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1931 return tokError(
"expected integer");
1932 Val = Lex.getAPSIntVal().getLimitedValue();
1942 switch (Lex.getKind()) {
1944 return tokError(
"expected localdynamic, initialexec or localexec");
1972 return parseTLSModel(TLM) ||
1973 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1981bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1982 AddrSpace = DefaultAS;
1986 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1988 const std::string &AddrSpaceStr = Lex.getStrVal();
1989 if (AddrSpaceStr ==
"A") {
1990 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1991 }
else if (AddrSpaceStr ==
"G") {
1992 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1993 }
else if (AddrSpaceStr ==
"P") {
1994 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1995 }
else if (std::optional<unsigned> AS =
1996 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
1999 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
2005 return tokError(
"expected integer or string constant");
2006 SMLoc Loc = Lex.getLoc();
2007 if (parseUInt32(AddrSpace))
2010 return error(Loc,
"invalid address space, must be a 24-bit integer");
2014 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
2015 ParseAddrspaceValue(AddrSpace) ||
2022bool LLParser::parseStringAttribute(AttrBuilder &
B) {
2023 std::string Attr = Lex.getStrVal();
2026 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
2028 B.addAttribute(Attr, Val);
2033bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &
B,
bool IsParam) {
2034 bool HaveError =
false;
2041 if (parseStringAttribute(
B))
2052 SMLoc Loc = Lex.getLoc();
2057 if (parseEnumAttribute(Attr,
B,
false))
2061 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2063 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2111bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2112 unsigned &Visibility,
2113 unsigned &DLLStorageClass,
bool &DSOLocal) {
2117 parseOptionalDSOLocal(DSOLocal);
2118 parseOptionalVisibility(Visibility);
2119 parseOptionalDLLStorageClass(DLLStorageClass);
2122 return error(Lex.getLoc(),
"dso_location and DLL-StorageClass mismatch");
2128void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2129 switch (Lex.getKind()) {
2150void LLParser::parseOptionalVisibility(
unsigned &Res) {
2151 switch (Lex.getKind()) {
2168bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2172 return tokError(
"unknown import kind. Expect definition or declaration.");
2187void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2188 switch (Lex.getKind()) {
2258bool LLParser::parseOptionalCallingConv(
unsigned &CC) {
2259 switch (Lex.getKind()) {
2346 return tokError(
"unknown RISC-V ABI VLEN");
2347#define CC_VLS_CASE(ABIVlen) \
2349 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2377 return parseUInt32(CC);
2387bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2390 std::string
Name = Lex.getStrVal();
2391 Kind = M->getMDKindID(Name);
2394 return parseMDNode(MD);
2399bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2402 return tokError(
"expected metadata after comma");
2406 if (parseMetadataAttachment(MDK,
N))
2409 if (MDK == LLVMContext::MD_DIAssignID)
2410 TempDIAssignIDAttachments[
N].push_back(&Inst);
2414 if (MDK == LLVMContext::MD_tbaa)
2415 InstsWithTBAATag.push_back(&Inst);
2424bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2427 if (parseMetadataAttachment(MDK,
N))
2436bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2438 if (parseGlobalObjectMetadataAttachment(
F))
2446bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2447 Alignment = std::nullopt;
2448 if (!EatIfPresent(lltok::kw_align))
2450 LocTy AlignLoc = Lex.getLoc();
2453 LocTy ParenLoc = Lex.getLoc();
2454 bool HaveParens =
false;
2460 if (parseUInt64(
Value))
2464 return error(ParenLoc,
"expected ')'");
2467 return error(AlignLoc,
"alignment is not a power of two");
2469 return error(AlignLoc,
"huge alignments are not supported yet");
2477bool LLParser::parseOptionalPrefAlignment(
MaybeAlign &Alignment) {
2478 Alignment = std::nullopt;
2481 LocTy AlignLoc = Lex.getLoc();
2484 LocTy ParenLoc = Lex.getLoc();
2486 return error(ParenLoc,
"expected '('");
2488 if (parseUInt64(
Value))
2491 ParenLoc = Lex.getLoc();
2493 return error(ParenLoc,
"expected ')'");
2496 return error(AlignLoc,
"alignment is not a power of two");
2498 return error(AlignLoc,
"huge alignments are not supported yet");
2508 auto StrVal = Lex.getStrVal();
2509 auto ErrMsg =
"expected global code model string";
2510 if (StrVal ==
"tiny")
2512 else if (StrVal ==
"small")
2514 else if (StrVal ==
"kernel")
2516 else if (StrVal ==
"medium")
2518 else if (StrVal ==
"large")
2521 return tokError(ErrMsg);
2533bool LLParser::parseOptionalAttrBytes(
lltok::Kind AttrKind,
2534 std::optional<uint64_t> &Bytes,
2535 bool ErrorNoBytes) {
2536 assert((AttrKind == lltok::kw_dereferenceable ||
2537 AttrKind == lltok::kw_dereferenceable_or_null ||
2538 AttrKind == lltok::kw_dead_on_return) &&
2542 if (!EatIfPresent(AttrKind))
2544 LocTy ParenLoc = Lex.getLoc();
2547 return error(ParenLoc,
"expected '('");
2548 Bytes = std::nullopt;
2551 LocTy DerefLoc = Lex.getLoc();
2552 if (parseUInt64(Bytes.value()))
2554 ParenLoc = Lex.getLoc();
2556 return error(ParenLoc,
"expected ')'");
2558 return error(DerefLoc,
"byte count specified must be non-zero");
2562bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2567 LocTy KindLoc = Lex.getLoc();
2573 return error(KindLoc,
"expected unwind table kind");
2580 LocTy ParenLoc = Lex.getLoc();
2582 return error(ParenLoc,
"expected '('");
2583 LocTy KindLoc = Lex.getLoc();
2585 if (parseStringConstant(Arg))
2586 return error(KindLoc,
"expected allockind value");
2590 }
else if (
A ==
"realloc") {
2592 }
else if (
A ==
"free") {
2594 }
else if (
A ==
"uninitialized") {
2596 }
else if (
A ==
"zeroed") {
2598 }
else if (
A ==
"aligned") {
2601 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2604 ParenLoc = Lex.getLoc();
2606 return error(ParenLoc,
"expected ')'");
2608 return error(KindLoc,
"expected allockind value");
2617 return {Loc::ArgMem};
2619 return {Loc::InaccessibleMem};
2621 return {Loc::ErrnoMem};
2623 return {Loc::TargetMem0};
2625 return {Loc::TargetMem1};
2648 return std::nullopt;
2652static std::optional<DenormalMode::DenormalModeKind>
2664 return std::nullopt;
2668std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2673 Lex.setIgnoreColonInIdentifiers(
true);
2678 tokError(
"expected '('");
2679 return std::nullopt;
2682 bool SeenLoc =
false;
2683 bool SeenTargetLoc =
false;
2686 if (!Locs.
empty()) {
2689 tokError(
"expected ':' after location");
2690 return std::nullopt;
2697 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2698 "or access kind (none, read, write, readwrite)");
2700 tokError(
"expected access kind (none, read, write, readwrite)");
2701 return std::nullopt;
2705 if (!Locs.
empty()) {
2710 SeenTargetLoc =
true;
2712 if (Locs.size() > 1 && SeenTargetLoc) {
2713 tokError(
"target memory default access kind must be specified first");
2714 return std::nullopt;
2719 tokError(
"default access kind must be specified first");
2720 return std::nullopt;
2729 tokError(
"unterminated memory attribute");
2730 return std::nullopt;
2733std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2734 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2737 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2738 "positivezero, dynamic)");
2744 std::optional<DenormalMode::DenormalModeKind> InputMode;
2748 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2749 "positivezero, dynamic)");
2756 InputMode = OutputMode;
2759 return DenormalMode(*OutputMode, *InputMode);
2762std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2765 Lex.setIgnoreColonInIdentifiers(
true);
2776 bool HasDefaultSection =
false;
2778 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2779 if (!ParsedDefaultMode)
2781 DefaultMode = *ParsedDefaultMode;
2782 HasDefaultSection =
true;
2787 if (HasDefaultSection && !HasComma) {
2788 tokError(
"expected ',' before float:");
2793 if (parseType(Ty) || !Ty->
isFloatTy()) {
2794 tokError(
"expected float:");
2798 if (parseToken(
lltok::colon,
"expected ':' before float denormal_fpenv"))
2801 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2805 F32Mode = *ParsedF32Mode;
2808 if (parseToken(
lltok::rparen,
"unterminated denormal_fpenv"))
2811 return DenormalFPEnv(DefaultMode, F32Mode);
2853unsigned LLParser::parseNoFPClassAttr() {
2858 tokError(
"expected '('");
2865 if (TestMask != 0) {
2869 !parseUInt64(
Value)) {
2871 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
2876 error(Lex.getLoc(),
"expected ')'");
2882 error(Lex.getLoc(),
"expected nofpclass test mask");
2900bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2901 bool &AteExtraComma) {
2902 AteExtraComma =
false;
2906 AteExtraComma =
true;
2910 if (Lex.getKind() != lltok::kw_align)
2911 return error(Lex.getLoc(),
"expected metadata or 'align'");
2913 if (parseOptionalAlignment(Alignment))
2926bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
2927 bool &AteExtraComma) {
2928 AteExtraComma =
false;
2932 AteExtraComma =
true;
2938 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
2940 if (parseOptionalAddrSpace(AddrSpace))
2947bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2948 std::optional<unsigned> &HowManyArg) {
2951 auto StartParen = Lex.getLoc();
2953 return error(StartParen,
"expected '('");
2955 if (parseUInt32(BaseSizeArg))
2959 auto HowManyAt = Lex.getLoc();
2961 if (parseUInt32(HowMany))
2963 if (HowMany == BaseSizeArg)
2964 return error(HowManyAt,
2965 "'allocsize' indices can't refer to the same parameter");
2966 HowManyArg = HowMany;
2968 HowManyArg = std::nullopt;
2970 auto EndParen = Lex.getLoc();
2972 return error(EndParen,
"expected ')'");
2976bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2977 unsigned &MaxValue) {
2980 auto StartParen = Lex.getLoc();
2982 return error(StartParen,
"expected '('");
2984 if (parseUInt32(MinValue))
2988 if (parseUInt32(MaxValue))
2991 MaxValue = MinValue;
2993 auto EndParen = Lex.getLoc();
2995 return error(EndParen,
"expected ')'");
3004bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
3009 return parseScope(SSID) || parseOrdering(Ordering);
3019 auto StartParenAt = Lex.getLoc();
3021 return error(StartParenAt,
"Expected '(' in syncscope");
3024 auto SSNAt = Lex.getLoc();
3025 if (parseStringConstant(SSN))
3026 return error(SSNAt,
"Expected synchronization scope name");
3028 auto EndParenAt = Lex.getLoc();
3030 return error(EndParenAt,
"Expected ')' in syncscope");
3032 SSID = Context.getOrInsertSyncScopeID(SSN);
3043 switch (Lex.getKind()) {
3045 return tokError(
"Expected ordering on atomic instruction");
3064bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
3066 if (!EatIfPresent(lltok::kw_alignstack))
3068 LocTy ParenLoc = Lex.getLoc();
3070 return error(ParenLoc,
"expected '('");
3071 LocTy AlignLoc = Lex.getLoc();
3072 if (parseUInt32(Alignment))
3074 ParenLoc = Lex.getLoc();
3076 return error(ParenLoc,
"expected ')'");
3078 return error(AlignLoc,
"stack alignment is not a power of two");
3092 bool &AteExtraComma) {
3093 AteExtraComma =
false;
3096 return tokError(
"expected ',' as start of index list");
3100 if (Indices.
empty())
3101 return tokError(
"expected index");
3102 AteExtraComma =
true;
3106 if (parseUInt32(Idx))
3119bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
3120 SMLoc TypeLoc = Lex.getLoc();
3121 switch (Lex.getKind()) {
3123 return tokError(Msg);
3132 if (
Result->isPointerTy()) {
3134 if (parseOptionalAddrSpace(AddrSpace))
3140 return tokError(
"ptr* is invalid - use ptr instead");
3151 if (parseTargetExtType(Result))
3157 if (parseAnonStructType(Result,
false))
3163 if (parseArrayVectorType(Result,
false))
3170 if (parseAnonStructType(Result,
true) ||
3171 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
3173 }
else if (parseArrayVectorType(Result,
true))
3178 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
3184 Entry.second = Lex.getLoc();
3193 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
3199 Entry.second = Lex.getLoc();
3209 switch (Lex.getKind()) {
3212 if (!AllowVoid &&
Result->isVoidTy())
3213 return error(TypeLoc,
"void type only allowed for function results");
3219 return tokError(
"basic block pointers are invalid");
3221 return tokError(
"pointers to void are invalid - use i8* instead");
3223 return tokError(
"pointer to this type is invalid");
3231 return tokError(
"basic block pointers are invalid");
3233 return tokError(
"pointers to void are invalid; use i8* instead");
3235 return tokError(
"pointer to this type is invalid");
3237 if (parseOptionalAddrSpace(AddrSpace) ||
3238 parseToken(
lltok::star,
"expected '*' in address space"))
3247 if (parseFunctionType(Result))
3260 PerFunctionState &PFS,
bool IsMustTailCall,
3261 bool InVarArgsFunc) {
3267 if (!ArgList.
empty() &&
3268 parseToken(
lltok::comma,
"expected ',' in argument list"))
3273 const char *Msg =
"unexpected ellipsis in argument list for ";
3274 if (!IsMustTailCall)
3275 return tokError(Twine(Msg) +
"non-musttail call");
3277 return tokError(Twine(Msg) +
"musttail call in non-varargs function");
3279 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3284 Type *ArgTy =
nullptr;
3286 if (parseType(ArgTy, ArgLoc))
3289 return error(ArgLoc,
"invalid type for function argument");
3291 AttrBuilder ArgAttrs(M->getContext());
3294 if (parseMetadataAsValue(V, PFS))
3298 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3305 if (IsMustTailCall && InVarArgsFunc)
3306 return tokError(
"expected '...' at end of argument list for musttail call "
3307 "in varargs function");
3315bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3318 if (!EatIfPresent(AttrToken))
3321 return error(Lex.getLoc(),
"expected '('");
3325 return error(Lex.getLoc(),
"expected ')'");
3327 B.addTypeAttr(AttrKind, Ty);
3333bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3341 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3343 return tokError(
"expected integer");
3344 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3346 "integer is too large for the bit width of specified type");
3347 Val = Lex.getAPSIntVal().extend(
BitWidth);
3352 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3355 return error(TyLoc,
"the range must have integer type!");
3363 return tokError(
"the range represent the empty set but limits aren't 0!");
3374bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3377 auto ParseAPSInt = [&](APInt &Val) {
3379 return tokError(
"expected integer");
3380 Val = Lex.getAPSIntVal().extend(64);
3400 return tokError(
"the range should not represent the full or empty set!");
3412 if (!CRLOrNull.has_value())
3413 return tokError(
"Invalid (unordered or overlapping) range list");
3414 B.addInitializesAttr(*CRLOrNull);
3418bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3420 std::optional<CaptureComponents> Ret;
3424 Lex.setIgnoreColonInIdentifiers(
true);
3432 bool SeenComponent =
false;
3438 return tokError(
"duplicate 'ret' location");
3441 SeenComponent =
false;
3446 return tokError(
"cannot use 'none' with other component");
3450 return tokError(
"cannot use 'none' with other component");
3461 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3462 "'provenance' or 'read_provenance'");
3465 SeenComponent =
true;
3473 B.addCapturesAttr(CaptureInfo(
Other, Ret.value_or(
Other)));
3486bool LLParser::parseOptionalOperandBundles(
3488 LocTy BeginLoc = Lex.getLoc();
3494 if (!BundleList.
empty() &&
3495 parseToken(
lltok::comma,
"expected ',' in input list"))
3499 if (parseStringConstant(
Tag))
3502 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3505 std::vector<Value *> Inputs;
3508 if (!Inputs.empty() &&
3509 parseToken(
lltok::comma,
"expected ',' in input list"))
3513 Value *Input =
nullptr;
3517 if (parseMetadataAsValue(Input, PFS))
3519 }
else if (parseValue(Ty, Input, PFS)) {
3522 Inputs.push_back(Input);
3530 if (BundleList.
empty())
3531 return error(BeginLoc,
"operand bundle set must not be empty");
3538 unsigned NextID,
unsigned ID) {
3540 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3541 Twine(NextID) +
"' or greater");
3558 unsigned CurValID = 0;
3572 LocTy TypeLoc = Lex.getLoc();
3573 Type *ArgTy =
nullptr;
3574 AttrBuilder
Attrs(M->getContext());
3575 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3579 return error(TypeLoc,
"argument can not have void type");
3584 bool Unnamed =
false;
3586 Name = Lex.getStrVal();
3587 IdentStart = getTokLineColumnPos();
3589 IdentEnd = getPrevTokEndLineColumnPos();
3593 ArgID = Lex.getUIntVal();
3594 IdentStart = getTokLineColumnPos();
3595 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3598 IdentEnd = getPrevTokEndLineColumnPos();
3604 CurValID = ArgID + 1;
3608 return error(TypeLoc,
"invalid type for function argument");
3612 Unnamed ? std::nullopt
3613 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3618 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3623bool LLParser::parseFunctionType(
Type *&Result) {
3627 return tokError(
"invalid function return type");
3631 SmallVector<unsigned> UnnamedArgNums;
3632 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3636 for (
const ArgInfo &Arg : ArgList) {
3637 if (!Arg.Name.empty())
3638 return error(Arg.Loc,
"argument name invalid in function type");
3639 if (Arg.Attrs.hasAttributes())
3640 return error(Arg.Loc,
"argument attributes invalid in function type");
3644 for (
const ArgInfo &Arg : ArgList)
3653bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3655 if (parseStructBody(Elts))
3663bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3664 std::pair<Type *, LocTy> &Entry,
3668 return error(TypeLoc,
"redefinition of type");
3674 Entry.second = SMLoc();
3679 ResultTy =
Entry.first;
3691 return error(TypeLoc,
"forward references to non-struct type");
3695 return parseArrayVectorType(ResultTy,
true);
3696 return parseType(ResultTy);
3700 Entry.second = SMLoc();
3709 if (parseStructBody(Body) ||
3710 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3714 return tokError(
toString(std::move(
E)));
3734 LocTy EltTyLoc = Lex.getLoc();
3741 return error(EltTyLoc,
"invalid element type for struct");
3744 EltTyLoc = Lex.getLoc();
3749 return error(EltTyLoc,
"invalid element type for struct");
3754 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3763bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3764 bool Scalable =
false;
3768 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3774 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3775 Lex.getAPSIntVal().getBitWidth() > 64)
3776 return tokError(
"expected number in address space");
3778 LocTy SizeLoc = Lex.getLoc();
3779 uint64_t
Size = Lex.getAPSIntVal().getZExtValue();
3782 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3785 LocTy TypeLoc = Lex.getLoc();
3786 Type *EltTy =
nullptr;
3787 if (parseType(EltTy))
3791 "expected end of sequential type"))
3796 return error(SizeLoc,
"zero element vector is illegal");
3798 return error(SizeLoc,
"size too large for vector");
3800 return error(TypeLoc,
"invalid vector element type");
3804 return error(TypeLoc,
"invalid array element type");
3821bool LLParser::parseTargetExtType(
Type *&Result) {
3826 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3827 parseStringConstant(TypeName))
3834 SmallVector<unsigned> IntParams;
3835 bool SeenInt =
false;
3842 if (parseUInt32(IntVal))
3845 }
else if (SeenInt) {
3848 return tokError(
"expected uint32 param");
3851 if (parseType(TypeParam,
true))
3857 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3862 if (
auto E = TTy.takeError())
3863 return tokError(
toString(std::move(
E)));
3876 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3879 auto It = UnnamedArgNums.
begin();
3882 unsigned ArgNum = *It++;
3883 NumberedVals.add(ArgNum, &A);
3888LLParser::PerFunctionState::~PerFunctionState() {
3891 for (
const auto &P : ForwardRefVals) {
3894 P.second.first->replaceAllUsesWith(
3896 P.second.first->deleteValue();
3899 for (
const auto &P : ForwardRefValIDs) {
3902 P.second.first->replaceAllUsesWith(
3904 P.second.first->deleteValue();
3908bool LLParser::PerFunctionState::finishFunction() {
3909 if (!ForwardRefVals.empty())
3910 return P.error(ForwardRefVals.begin()->second.second,
3911 "use of undefined value '%" + ForwardRefVals.begin()->first +
3913 if (!ForwardRefValIDs.empty())
3914 return P.error(ForwardRefValIDs.begin()->second.second,
3915 "use of undefined value '%" +
3916 Twine(ForwardRefValIDs.begin()->first) +
"'");
3923Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
3926 Value *Val =
F.getValueSymbolTable()->lookup(Name);
3931 auto I = ForwardRefVals.find(Name);
3932 if (
I != ForwardRefVals.end())
3933 Val =
I->second.first;
3938 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
3942 P.error(Loc,
"invalid use of a non-first-class type");
3953 if (FwdVal->
getName() != Name) {
3954 P.error(Loc,
"name is too long which can result in name collisions, "
3955 "consider making the name shorter or "
3956 "increasing -non-global-value-max-name-size");
3960 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3964Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
3966 Value *Val = NumberedVals.get(
ID);
3971 auto I = ForwardRefValIDs.find(
ID);
3972 if (
I != ForwardRefValIDs.end())
3973 Val =
I->second.first;
3978 return P.checkValidVariableType(Loc,
"%" + Twine(
ID), Ty, Val);
3981 P.error(Loc,
"invalid use of a non-first-class type");
3993 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
3999bool LLParser::PerFunctionState::setInstName(
int NameID,
4000 const std::string &NameStr,
4001 LocTy NameLoc, Instruction *Inst) {
4004 if (NameID != -1 || !NameStr.empty())
4005 return P.error(NameLoc,
"instructions returning void cannot have a name");
4011 if (NameStr.empty()) {
4014 NameID = NumberedVals.getNext();
4016 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
4020 auto FI = ForwardRefValIDs.find(NameID);
4021 if (FI != ForwardRefValIDs.end()) {
4024 return P.error(NameLoc,
"instruction forward referenced with type '" +
4028 Sentinel->replaceAllUsesWith(Inst);
4030 ForwardRefValIDs.erase(FI);
4033 NumberedVals.add(NameID, Inst);
4038 auto FI = ForwardRefVals.find(NameStr);
4039 if (FI != ForwardRefVals.end()) {
4042 return P.error(NameLoc,
"instruction forward referenced with type '" +
4046 Sentinel->replaceAllUsesWith(Inst);
4048 ForwardRefVals.erase(FI);
4054 if (Inst->
getName() != NameStr)
4055 return P.error(NameLoc,
"multiple definition of local value named '" +
4062BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
4076BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
4077 int NameID,
LocTy Loc) {
4081 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
4084 NameID = NumberedVals.getNext();
4086 BB = getBB(NameID, Loc);
4088 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
4092 BB = getBB(Name, Loc);
4094 P.error(Loc,
"unable to create block named '" + Name +
"'");
4105 ForwardRefValIDs.erase(NameID);
4106 NumberedVals.add(NameID, BB);
4109 ForwardRefVals.erase(Name);
4126bool LLParser::parseValID(ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
4127 ID.Loc = Lex.getLoc();
4128 switch (Lex.getKind()) {
4130 return tokError(
"expected value token");
4132 ID.UIntVal = Lex.getUIntVal();
4136 ID.StrVal = Lex.getStrVal();
4140 ID.UIntVal = Lex.getUIntVal();
4144 ID.StrVal = Lex.getStrVal();
4148 ID.APSIntVal = Lex.getAPSIntVal();
4152 ID.APFloatVal = Lex.getAPFloatVal();
4158 return error(
ID.Loc,
"unexpected floating-point literal");
4160 return error(
ID.Loc,
"floating-point constant invalid for type");
4162 auto Except =
ID.APFloatVal.convertFromString(
4164 assert(Except &&
"Invalid float strings should be caught by the lexer");
4169 return error(
ID.Loc,
"floating-point constant overflowed type");
4171 return error(
ID.Loc,
"floating-point constant underflowed type");
4177 return error(
ID.Loc,
"unexpected floating-point literal");
4179 const APInt &
Bits = Lex.getAPSIntVal();
4181 return error(
ID.Loc,
"float hex literal has incorrect number of bits");
4182 ID.APFloatVal =
APFloat(Semantics, Bits);
4204 if (parseGlobalValueVector(Elts) ||
4205 parseToken(
lltok::rbrace,
"expected end of struct constant"))
4208 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4209 ID.UIntVal = Elts.
size();
4210 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4211 Elts.
size() *
sizeof(Elts[0]));
4222 LocTy FirstEltLoc = Lex.getLoc();
4223 if (parseGlobalValueVector(Elts) ||
4225 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
4229 if (isPackedStruct) {
4230 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4231 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4232 Elts.
size() *
sizeof(Elts[0]));
4233 ID.UIntVal = Elts.
size();
4239 return error(
ID.Loc,
"constant vector must not be empty");
4241 if (!Elts[0]->
getType()->isIntegerTy() && !Elts[0]->
getType()->isByteTy() &&
4242 !Elts[0]->
getType()->isFloatingPointTy() &&
4246 "vector elements must have integer, byte, pointer or floating point "
4250 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
4252 return error(FirstEltLoc,
"vector element #" + Twine(i) +
4253 " is not of type '" +
4263 LocTy FirstEltLoc = Lex.getLoc();
4264 if (parseGlobalValueVector(Elts) ||
4276 if (!Elts[0]->
getType()->isFirstClassType())
4277 return error(FirstEltLoc,
"invalid array element type: " +
4283 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4285 return error(FirstEltLoc,
"array element #" + Twine(i) +
4286 " is not of type '" +
4298 Context, Lex.getStrVal(),
false, ATy->getElementType()->isByteTy());
4307 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4310 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4313 parseStringConstant(
ID.StrVal) ||
4314 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4317 ID.StrVal2 = Lex.getStrVal();
4318 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4319 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4330 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4331 parseValID(Fn, PFS) ||
4333 "expected comma in block address expression") ||
4334 parseValID(Label, PFS) ||
4335 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4339 return error(Fn.
Loc,
"expected function name in blockaddress");
4341 return error(
Label.Loc,
"expected basic block name in blockaddress");
4344 GlobalValue *GV =
nullptr;
4346 GV = NumberedVals.get(Fn.
UIntVal);
4347 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4348 GV = M->getNamedValue(Fn.
StrVal);
4354 return error(Fn.
Loc,
"expected function name in blockaddress");
4356 if (
F->isDeclaration())
4357 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4362 GlobalValue *&FwdRef =
4363 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4371 "type of blockaddress must be a pointer and not '" +
4376 FwdDeclAS = PFS->getFunction().getAddressSpace();
4380 FwdRef =
new GlobalVariable(
4385 ID.ConstantVal = FwdRef;
4393 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4395 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4397 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4399 return error(
Label.Loc,
"referenced value is not a basic block");
4402 return error(
Label.Loc,
"cannot take address of numeric label after "
4403 "the function is defined");
4405 F->getValueSymbolTable()->lookup(
Label.StrVal));
4407 return error(
Label.Loc,
"referenced value is not a basic block");
4421 if (parseValID(Fn, PFS))
4426 "expected global value name in dso_local_equivalent");
4429 GlobalValue *GV =
nullptr;
4431 GV = NumberedVals.get(Fn.
UIntVal);
4432 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4433 GV = M->getNamedValue(Fn.
StrVal);
4439 ? ForwardRefDSOLocalEquivalentIDs
4440 : ForwardRefDSOLocalEquivalentNames;
4441 GlobalValue *&FwdRef = FwdRefMap[Fn];
4448 ID.ConstantVal = FwdRef;
4454 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4455 "in dso_local_equivalent");
4466 if (parseValID(
ID, PFS))
4470 return error(
ID.Loc,
"expected global value name in no_cfi");
4482 Constant *Disc =
nullptr, *AddrDisc =
nullptr,
4483 *DeactivationSymbol =
nullptr;
4486 "expected '(' in constant ptrauth expression") ||
4487 parseGlobalTypeAndValue(Ptr) ||
4489 "expected comma in constant ptrauth expression") ||
4490 parseGlobalTypeAndValue(
Key))
4493 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(Disc))
4495 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4498 parseGlobalTypeAndValue(DeactivationSymbol))
4501 "expected ')' in constant ptrauth expression"))
4505 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4508 if (!KeyC || KeyC->getBitWidth() != 32)
4509 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4511 ConstantInt *DiscC =
nullptr;
4517 "constant ptrauth integer discriminator must be i64 constant");
4523 if (!AddrDisc->getType()->isPointerTy())
4525 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4530 if (!DeactivationSymbol)
4531 DeactivationSymbol =
4533 if (!DeactivationSymbol->getType()->isPointerTy())
4535 "constant ptrauth deactivation symbol must be a pointer");
4549 unsigned Opc = Lex.getUIntVal();
4550 Type *DestTy =
nullptr;
4553 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4554 parseGlobalTypeAndValue(SrcVal) ||
4555 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4556 parseType(DestTy) ||
4557 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4560 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4569 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4571 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4573 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4575 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4577 return error(
ID.Loc,
"urem constexprs are no longer supported");
4579 return error(
ID.Loc,
"srem constexprs are no longer supported");
4581 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4583 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4585 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4587 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4589 return error(
ID.Loc,
"frem constexprs are no longer supported");
4591 return error(
ID.Loc,
"and constexprs are no longer supported");
4593 return error(
ID.Loc,
"or constexprs are no longer supported");
4595 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4597 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4599 return error(
ID.Loc,
"shl constexprs are no longer supported");
4601 return error(
ID.Loc,
"mul constexprs are no longer supported");
4603 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4605 return error(
ID.Loc,
"select constexprs are no longer supported");
4607 return error(
ID.Loc,
"zext constexprs are no longer supported");
4609 return error(
ID.Loc,
"sext constexprs are no longer supported");
4611 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4613 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4615 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4617 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4619 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4621 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4623 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4625 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4633 unsigned Opc = Lex.getUIntVal();
4636 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4637 Opc == Instruction::Mul) {
4646 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4647 parseGlobalTypeAndValue(Val0) ||
4648 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4649 parseGlobalTypeAndValue(Val1) ||
4650 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4653 return error(
ID.Loc,
"operands of constexpr must have same type");
4657 "constexpr requires integer or integer vector operands");
4668 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4671 if (parseGlobalTypeAndValue(
C))
4673 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4685 unsigned Opc = Lex.getUIntVal();
4688 bool HasInRange =
false;
4694 if (
Opc == Instruction::GetElementPtr) {
4710 return tokError(
"expected integer");
4711 InRangeStart = Lex.getAPSIntVal();
4716 return tokError(
"expected integer");
4717 InRangeEnd = Lex.getAPSIntVal();
4725 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4728 if (
Opc == Instruction::GetElementPtr) {
4729 if (parseType(Ty) ||
4730 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4734 if (parseGlobalValueVector(Elts) ||
4738 if (
Opc == Instruction::GetElementPtr) {
4739 if (Elts.
size() == 0 ||
4740 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4741 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4744 std::optional<ConstantRange>
InRange;
4746 unsigned IndexWidth =
4747 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4748 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4749 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4750 if (InRangeStart.
sge(InRangeEnd))
4751 return error(
ID.Loc,
"expected end to be larger than start");
4761 for (Constant *Val : Indices) {
4764 return error(
ID.Loc,
"getelementptr index must be an integer");
4767 if (GEPWidth && (ValNumEl != GEPWidth))
4770 "getelementptr vector index has a wrong number of elements");
4773 GEPWidth = ValNumEl;
4777 SmallPtrSet<Type*, 4> Visited;
4778 if (!Indices.empty() && !Ty->
isSized(&Visited))
4779 return error(
ID.Loc,
"base element of getelementptr must be sized");
4782 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4785 return error(
ID.Loc,
"invalid getelementptr indices");
4789 }
else if (
Opc == Instruction::ShuffleVector) {
4790 if (Elts.
size() != 3)
4791 return error(
ID.Loc,
"expected three operands to shufflevector");
4793 return error(
ID.Loc,
"invalid operands to shufflevector");
4794 SmallVector<int, 16>
Mask;
4797 }
else if (
Opc == Instruction::ExtractElement) {
4798 if (Elts.
size() != 2)
4799 return error(
ID.Loc,
"expected two operands to extractelement");
4801 return error(
ID.Loc,
"invalid extractelement operands");
4804 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4805 if (Elts.
size() != 3)
4806 return error(
ID.Loc,
"expected three operands to insertelement");
4808 return error(
ID.Loc,
"invalid insertelement operands");
4823bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4827 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4828 convertValIDToValue(Ty,
ID, V,
nullptr);
4830 return error(
ID.Loc,
"global values must be constants");
4834bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4836 return parseType(Ty) || parseGlobalValue(Ty, V);
4839bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4842 LocTy KwLoc = Lex.getLoc();
4848 return tokError(
"expected comdat variable");
4849 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4851 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4854 if (GlobalName.
empty())
4855 return tokError(
"comdat cannot be unnamed");
4856 C = getComdat(std::string(GlobalName), KwLoc);
4865bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4879 if (parseGlobalTypeAndValue(
C))
4887bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
4889 if (parseMDNodeVector(Elts))
4900bool LLParser::parseMDNode(MDNode *&
N) {
4902 return parseSpecializedMDNode(
N);
4904 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4907bool LLParser::parseMDNodeTail(MDNode *&
N) {
4910 return parseMDTuple(
N);
4913 return parseMDNodeID(
N);
4919template <
class FieldTy>
struct MDFieldImpl {
4920 typedef MDFieldImpl ImplTy;
4924 void assign(FieldTy Val) {
4926 this->Val = std::move(Val);
4929 explicit MDFieldImpl(FieldTy
Default)
4937template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4938 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4949 void assign(FieldTypeA
A) {
4951 this->
A = std::move(
A);
4955 void assign(FieldTypeB
B) {
4957 this->
B = std::move(
B);
4961 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4963 WhatIs(IsInvalid) {}
4966struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4973struct LineField :
public MDUnsignedField {
4974 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4977struct ColumnField :
public MDUnsignedField {
4978 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4981struct DwarfTagField :
public MDUnsignedField {
4987struct DwarfMacinfoTypeField :
public MDUnsignedField {
4993struct DwarfAttEncodingField :
public MDUnsignedField {
4994 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
4997struct DwarfVirtualityField :
public MDUnsignedField {
5001struct DwarfLangField :
public MDUnsignedField {
5005struct DwarfSourceLangNameField :
public MDUnsignedField {
5006 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5009struct DwarfCCField :
public MDUnsignedField {
5010 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
5013struct DwarfEnumKindField :
public MDUnsignedField {
5014 DwarfEnumKindField()
5019struct EmissionKindField :
public MDUnsignedField {
5020 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5023struct FixedPointKindField :
public MDUnsignedField {
5024 FixedPointKindField()
5025 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5028struct NameTableKindField :
public MDUnsignedField {
5029 NameTableKindField()
5032 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5035struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
5036 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5039struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
5040 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5043struct MDAPSIntField :
public MDFieldImpl<APSInt> {
5044 MDAPSIntField() : ImplTy(
APSInt()) {}
5047struct MDSignedField :
public MDFieldImpl<int64_t> {
5051 MDSignedField(int64_t
Default = 0)
5053 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5057struct MDBoolField :
public MDFieldImpl<bool> {
5061struct MDField :
public MDFieldImpl<Metadata *> {
5064 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5067struct MDStringField :
public MDFieldImpl<MDString *> {
5068 enum class EmptyIs {
5073 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5074 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5077struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5081struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5085struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5086 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5087 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5089 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5090 bool AllowNull =
true)
5091 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5093 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5094 bool isMDField()
const {
return WhatIs == IsTypeB; }
5095 int64_t getMDSignedValue()
const {
5096 assert(isMDSignedField() &&
"Wrong field type");
5099 Metadata *getMDFieldValue()
const {
5100 assert(isMDField() &&
"Wrong field type");
5105struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5106 MDUnsignedOrMDField(uint64_t
Default = 0,
bool AllowNull =
true)
5107 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5109 MDUnsignedOrMDField(uint64_t
Default, uint64_t Max,
bool AllowNull =
true)
5110 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5112 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5113 bool isMDField()
const {
return WhatIs == IsTypeB; }
5114 uint64_t getMDUnsignedValue()
const {
5115 assert(isMDUnsignedField() &&
"Wrong field type");
5118 Metadata *getMDFieldValue()
const {
5119 assert(isMDField() &&
"Wrong field type");
5124 if (isMDUnsignedField())
5126 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5128 return getMDFieldValue();
5140 return tokError(
"expected integer");
5142 Result.assign(Lex.getAPSIntVal());
5149 MDUnsignedField &Result) {
5150 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5151 return tokError(
"expected unsigned integer");
5153 auto &U = Lex.getAPSIntVal();
5154 if (U.ugt(Result.Max))
5155 return tokError(
"value for '" + Name +
"' too large, limit is " +
5157 Result.assign(U.getZExtValue());
5158 assert(Result.Val <= Result.Max &&
"Expected value in range");
5165 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5169 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5175 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5178 return tokError(
"expected DWARF tag");
5182 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5183 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5192 DwarfMacinfoTypeField &Result) {
5194 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5197 return tokError(
"expected DWARF macinfo type");
5201 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5202 Lex.getStrVal() +
"'");
5203 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5205 Result.assign(Macinfo);
5212 DwarfVirtualityField &Result) {
5214 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5217 return tokError(
"expected DWARF virtuality code");
5221 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5222 Lex.getStrVal() +
"'");
5223 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5224 Result.assign(Virtuality);
5231 DwarfEnumKindField &Result) {
5233 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5236 return tokError(
"expected DWARF enum kind code");
5240 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5241 Lex.getStrVal() +
"'");
5242 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5243 Result.assign(EnumKind);
5251 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5254 return tokError(
"expected DWARF language");
5258 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5260 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5261 Result.assign(Lang);
5268 DwarfSourceLangNameField &Result) {
5270 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5273 return tokError(
"expected DWARF source language name");
5277 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5278 Lex.getStrVal() +
"'");
5279 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5280 Result.assign(Lang);
5288 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5291 return tokError(
"expected DWARF calling convention");
5295 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5296 Lex.getStrVal() +
"'");
5297 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
5305 EmissionKindField &Result) {
5307 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5310 return tokError(
"expected emission kind");
5314 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5316 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5317 Result.assign(*Kind);
5324 FixedPointKindField &Result) {
5326 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5329 return tokError(
"expected fixed-point kind");
5333 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5335 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5336 Result.assign(*Kind);
5343 NameTableKindField &Result) {
5345 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5348 return tokError(
"expected nameTable kind");
5352 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5354 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5355 Result.assign((
unsigned)*Kind);
5362 DwarfAttEncodingField &Result) {
5364 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5367 return tokError(
"expected DWARF type attribute encoding");
5371 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5372 Lex.getStrVal() +
"'");
5373 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5374 Result.assign(Encoding);
5388 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5390 bool Res = parseUInt32(TempVal);
5396 return tokError(
"expected debug info flag");
5400 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5415 Result.assign(Combined);
5428 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5430 bool Res = parseUInt32(TempVal);
5436 return tokError(
"expected debug info flag");
5440 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5441 Lex.getStrVal() +
"'");
5455 Result.assign(Combined);
5462 return tokError(
"expected signed integer");
5464 auto &S = Lex.getAPSIntVal();
5466 return tokError(
"value for '" + Name +
"' too small, limit is " +
5469 return tokError(
"value for '" + Name +
"' too large, limit is " +
5471 Result.assign(S.getExtValue());
5472 assert(Result.Val >= Result.Min &&
"Expected value in range");
5473 assert(Result.Val <= Result.Max &&
"Expected value in range");
5480 switch (Lex.getKind()) {
5482 return tokError(
"expected 'true' or 'false'");
5484 Result.assign(
true);
5487 Result.assign(
false);
5497 if (!Result.AllowNull)
5498 return tokError(
"'" + Name +
"' cannot be null");
5500 Result.assign(
nullptr);
5505 if (parseMetadata(MD,
nullptr))
5514 MDSignedOrMDField &Result) {
5517 MDSignedField Res = Result.A;
5518 if (!parseMDField(
Loc, Name, Res)) {
5526 MDField Res = Result.B;
5527 if (!parseMDField(
Loc, Name, Res)) {
5537 MDUnsignedOrMDField &Result) {
5540 MDUnsignedField Res = Result.A;
5541 if (!parseMDField(
Loc, Name, Res)) {
5549 MDField Res = Result.B;
5550 if (!parseMDField(
Loc, Name, Res)) {
5560 LocTy ValueLoc = Lex.getLoc();
5562 if (parseStringConstant(S))
5566 switch (Result.EmptyIs) {
5567 case MDStringField::EmptyIs::Null:
5568 Result.assign(
nullptr);
5570 case MDStringField::EmptyIs::Empty:
5572 case MDStringField::EmptyIs::Error:
5573 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5584 if (parseMDNodeVector(MDs))
5587 Result.assign(std::move(MDs));
5593 ChecksumKindField &Result) {
5594 std::optional<DIFile::ChecksumKind> CSKind =
5598 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5601 Result.assign(*CSKind);
5608template <
class ParserTy>
5609bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5612 return tokError(
"expected field label here");
5621template <
class ParserTy>
5622bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5629 if (parseMDFieldsImplBody(ParseField))
5632 ClosingLoc = Lex.getLoc();
5636template <
class FieldTy>
5637bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5639 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5641 LocTy Loc = Lex.getLoc();
5643 return parseMDField(Loc, Name, Result);
5646bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5649#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5650 if (Lex.getStrVal() == #CLASS) \
5651 return parse##CLASS(N, IsDistinct);
5652#include "llvm/IR/Metadata.def"
5654 return tokError(
"expected metadata type");
5657#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5658#define NOP_FIELD(NAME, TYPE, INIT)
5659#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5661 return error(ClosingLoc, "missing required field '" #NAME "'");
5662#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5663 if (Lex.getStrVal() == #NAME) \
5664 return parseMDField(#NAME, NAME);
5665#define PARSE_MD_FIELDS() \
5666 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5669 if (parseMDFieldsImpl( \
5671 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5672 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5677 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5679#define GET_OR_DISTINCT(CLASS, ARGS) \
5680 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5685bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5686#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5687 OPTIONAL(line, LineField, ); \
5688 OPTIONAL(column, ColumnField, ); \
5689 REQUIRED(scope, MDField, ( false)); \
5690 OPTIONAL(inlinedAt, MDField, ); \
5691 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5692 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5693 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5695#undef VISIT_MD_FIELDS
5698 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5699 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5705bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5707 return tokError(
"missing 'distinct', required for !DIAssignID()");
5723bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5724#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5725 REQUIRED(tag, DwarfTagField, ); \
5726 OPTIONAL(header, MDStringField, ); \
5727 OPTIONAL(operands, MDFieldList, );
5729#undef VISIT_MD_FIELDS
5732 (Context, tag.Val, header.Val, operands.Val));
5741bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5742#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5743 OPTIONAL(name, MDStringField, ); \
5744 OPTIONAL(file, MDField, ); \
5745 OPTIONAL(line, LineField, ); \
5746 OPTIONAL(scope, MDField, ); \
5747 OPTIONAL(baseType, MDField, ); \
5748 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5749 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5750 OPTIONAL(flags, DIFlagField, ); \
5751 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5752 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5753 OPTIONAL(stride, MDSignedOrMDField, ); \
5754 OPTIONAL(bias, MDSignedOrMDField, );
5756#undef VISIT_MD_FIELDS
5758 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5759 if (Bound.isMDSignedField())
5762 if (Bound.isMDField())
5763 return Bound.getMDFieldValue();
5767 Metadata *LowerBound = convToMetadata(lowerBound);
5769 Metadata *Stride = convToMetadata(stride);
5770 Metadata *Bias = convToMetadata(bias);
5773 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5774 size.getValueAsMetadata(Context), align.Val, flags.Val,
5775 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5784bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5785#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5786 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5787 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5788 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5789 OPTIONAL(stride, MDSignedOrMDField, );
5791#undef VISIT_MD_FIELDS
5798 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5799 if (Bound.isMDSignedField())
5802 if (Bound.isMDField())
5803 return Bound.getMDFieldValue();
5808 LowerBound = convToMetadata(lowerBound);
5810 Stride = convToMetadata(stride);
5813 (Context,
Count, LowerBound, UpperBound, Stride));
5821bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5822#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5823 OPTIONAL(count, MDSignedOrMDField, ); \
5824 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5825 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5826 OPTIONAL(stride, MDSignedOrMDField, );
5828#undef VISIT_MD_FIELDS
5830 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5831 if (Bound.isMDSignedField())
5833 Context, {dwarf::DW_OP_consts,
5834 static_cast<uint64_t
>(Bound.getMDSignedValue())});
5835 if (Bound.isMDField())
5836 return Bound.getMDFieldValue();
5841 Metadata *LowerBound = ConvToMetadata(lowerBound);
5843 Metadata *Stride = ConvToMetadata(stride);
5846 (Context,
Count, LowerBound, UpperBound, Stride));
5853bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5854#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5855 REQUIRED(name, MDStringField, ); \
5856 REQUIRED(value, MDAPSIntField, ); \
5857 OPTIONAL(isUnsigned, MDBoolField, (false));
5859#undef VISIT_MD_FIELDS
5861 if (isUnsigned.Val && value.Val.isNegative())
5862 return tokError(
"unsigned enumerator with negative value");
5867 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5879bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5880#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5881 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5882 OPTIONAL(name, MDStringField, ); \
5883 OPTIONAL(file, MDField, ); \
5884 OPTIONAL(line, LineField, ); \
5885 OPTIONAL(scope, MDField, ); \
5886 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5887 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5888 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5889 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5890 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5891 OPTIONAL(flags, DIFlagField, );
5893#undef VISIT_MD_FIELDS
5896 DIBasicType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
5897 size.getValueAsMetadata(Context), align.Val, encoding.Val,
5898 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5907bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
5908#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5909 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5910 OPTIONAL(name, MDStringField, ); \
5911 OPTIONAL(file, MDField, ); \
5912 OPTIONAL(line, LineField, ); \
5913 OPTIONAL(scope, MDField, ); \
5914 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5915 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5916 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5917 OPTIONAL(flags, DIFlagField, ); \
5918 OPTIONAL(kind, FixedPointKindField, ); \
5919 OPTIONAL(factor, MDSignedField, ); \
5920 OPTIONAL(numerator, MDAPSIntField, ); \
5921 OPTIONAL(denominator, MDAPSIntField, );
5923#undef VISIT_MD_FIELDS
5926 (Context, tag.Val,
name.Val,
file.Val, line.Val,
5927 scope.Val,
size.getValueAsMetadata(Context),
5928 align.Val, encoding.Val, flags.Val, kind.Val,
5929 factor.Val, numerator.Val, denominator.Val));
5935bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5936#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5937 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5938 OPTIONAL(name, MDStringField, ); \
5939 OPTIONAL(stringLength, MDField, ); \
5940 OPTIONAL(stringLengthExpression, MDField, ); \
5941 OPTIONAL(stringLocationExpression, MDField, ); \
5942 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5943 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5944 OPTIONAL(encoding, DwarfAttEncodingField, );
5946#undef VISIT_MD_FIELDS
5950 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5951 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
5952 align.Val, encoding.Val));
5965bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
5966#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5967 REQUIRED(tag, DwarfTagField, ); \
5968 OPTIONAL(name, MDStringField, ); \
5969 OPTIONAL(file, MDField, ); \
5970 OPTIONAL(line, LineField, ); \
5971 OPTIONAL(scope, MDField, ); \
5972 REQUIRED(baseType, MDField, ); \
5973 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5974 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5975 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5976 OPTIONAL(flags, DIFlagField, ); \
5977 OPTIONAL(extraData, MDField, ); \
5978 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5979 OPTIONAL(annotations, MDField, ); \
5980 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5981 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5982 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5983 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5984 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5986#undef VISIT_MD_FIELDS
5988 std::optional<unsigned> DWARFAddressSpace;
5989 if (dwarfAddressSpace.Val != UINT32_MAX)
5990 DWARFAddressSpace = dwarfAddressSpace.Val;
5991 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5993 PtrAuthData.emplace(
5994 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5995 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5996 ptrAuthAuthenticatesNullValues.Val);
5999 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6000 baseType.Val,
size.getValueAsMetadata(Context), align.Val,
6001 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6002 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6006bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
6007#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6008 REQUIRED(tag, DwarfTagField, ); \
6009 OPTIONAL(name, MDStringField, ); \
6010 OPTIONAL(file, MDField, ); \
6011 OPTIONAL(line, LineField, ); \
6012 OPTIONAL(scope, MDField, ); \
6013 OPTIONAL(baseType, MDField, ); \
6014 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6015 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6016 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6017 OPTIONAL(flags, DIFlagField, ); \
6018 OPTIONAL(elements, MDField, ); \
6019 OPTIONAL(runtimeLang, DwarfLangField, ); \
6020 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6021 OPTIONAL(vtableHolder, MDField, ); \
6022 OPTIONAL(templateParams, MDField, ); \
6023 OPTIONAL(identifier, MDStringField, ); \
6024 OPTIONAL(discriminator, MDField, ); \
6025 OPTIONAL(dataLocation, MDField, ); \
6026 OPTIONAL(associated, MDField, ); \
6027 OPTIONAL(allocated, MDField, ); \
6028 OPTIONAL(rank, MDSignedOrMDField, ); \
6029 OPTIONAL(annotations, MDField, ); \
6030 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6031 OPTIONAL(specification, MDField, ); \
6032 OPTIONAL(bitStride, MDField, );
6034#undef VISIT_MD_FIELDS
6037 if (rank.isMDSignedField())
6040 else if (rank.isMDField())
6041 Rank = rank.getMDFieldValue();
6043 std::optional<unsigned> EnumKind;
6045 EnumKind = enumKind.Val;
6050 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
6051 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
6052 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6053 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6054 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6055 dataLocation.Val, associated.Val, allocated.Val, Rank,
6056 annotations.Val, bitStride.Val)) {
6065 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6066 size.getValueAsMetadata(Context), align.Val,
6067 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6068 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6069 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6070 allocated.Val, Rank, annotations.Val, specification.Val,
6071 num_extra_inhabitants.Val, bitStride.Val));
6075bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6076#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6077 OPTIONAL(flags, DIFlagField, ); \
6078 OPTIONAL(cc, DwarfCCField, ); \
6079 REQUIRED(types, MDField, );
6081#undef VISIT_MD_FIELDS
6084 (Context, flags.Val, cc.Val, types.Val));
6093bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6097#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6098 REQUIRED(filename, MDStringField, ); \
6099 REQUIRED(directory, MDStringField, ); \
6100 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6101 OPTIONAL(checksum, MDStringField, ); \
6102 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6104#undef VISIT_MD_FIELDS
6106 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6107 if (checksumkind.Seen && checksum.Seen)
6108 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6109 else if (checksumkind.Seen || checksum.Seen)
6110 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6112 MDString *
Source =
nullptr;
6116 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6127bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6129 return tokError(
"missing 'distinct', required for !DICompileUnit");
6131 LocTy Loc = Lex.getLoc();
6133#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6134 REQUIRED(file, MDField, ( false)); \
6135 OPTIONAL(language, DwarfLangField, ); \
6136 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6137 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6138 OPTIONAL(producer, MDStringField, ); \
6139 OPTIONAL(isOptimized, MDBoolField, ); \
6140 OPTIONAL(flags, MDStringField, ); \
6141 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6142 OPTIONAL(splitDebugFilename, MDStringField, ); \
6143 OPTIONAL(emissionKind, EmissionKindField, ); \
6144 OPTIONAL(enums, MDField, ); \
6145 OPTIONAL(retainedTypes, MDField, ); \
6146 OPTIONAL(globals, MDField, ); \
6147 OPTIONAL(imports, MDField, ); \
6148 OPTIONAL(macros, MDField, ); \
6149 OPTIONAL(dwoId, MDUnsignedField, ); \
6150 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6151 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6152 OPTIONAL(nameTableKind, NameTableKindField, ); \
6153 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6154 OPTIONAL(sysroot, MDStringField, ); \
6155 OPTIONAL(sdk, MDStringField, );
6157#undef VISIT_MD_FIELDS
6159 if (!language.Seen && !sourceLanguageName.Seen)
6160 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6161 "required for !DICompileUnit");
6163 if (language.Seen && sourceLanguageName.Seen)
6164 return error(Loc,
"can only specify one of 'language' and "
6165 "'sourceLanguageName' on !DICompileUnit");
6167 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6168 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6169 "'sourceLanguageName' on !DICompileUnit");
6173 language.Seen ? DISourceLanguageName(language.Val)
6174 : DISourceLanguageName(sourceLanguageName.Val,
6175 sourceLanguageVersion.Val),
6176 file.Val, producer.Val, isOptimized.Val, flags.Val, runtimeVersion.Val,
6177 splitDebugFilename.Val, emissionKind.Val, enums.Val, retainedTypes.Val,
6178 globals.Val, imports.Val, macros.Val, dwoId.Val, splitDebugInlining.Val,
6179 debugInfoForProfiling.Val, nameTableKind.Val, rangesBaseAddress.Val,
6180 sysroot.Val, sdk.Val);
6193bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6194 auto Loc = Lex.getLoc();
6195#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6196 OPTIONAL(scope, MDField, ); \
6197 OPTIONAL(name, MDStringField, ); \
6198 OPTIONAL(linkageName, MDStringField, ); \
6199 OPTIONAL(file, MDField, ); \
6200 OPTIONAL(line, LineField, ); \
6201 OPTIONAL(type, MDField, ); \
6202 OPTIONAL(isLocal, MDBoolField, ); \
6203 OPTIONAL(isDefinition, MDBoolField, (true)); \
6204 OPTIONAL(scopeLine, LineField, ); \
6205 OPTIONAL(containingType, MDField, ); \
6206 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6207 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6208 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6209 OPTIONAL(flags, DIFlagField, ); \
6210 OPTIONAL(spFlags, DISPFlagField, ); \
6211 OPTIONAL(isOptimized, MDBoolField, ); \
6212 OPTIONAL(unit, MDField, ); \
6213 OPTIONAL(templateParams, MDField, ); \
6214 OPTIONAL(declaration, MDField, ); \
6215 OPTIONAL(retainedNodes, MDField, ); \
6216 OPTIONAL(thrownTypes, MDField, ); \
6217 OPTIONAL(annotations, MDField, ); \
6218 OPTIONAL(targetFuncName, MDStringField, ); \
6219 OPTIONAL(keyInstructions, MDBoolField, );
6221#undef VISIT_MD_FIELDS
6226 spFlags.Seen ? spFlags.Val
6228 isOptimized.Val, virtuality.Val);
6229 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6232 "missing 'distinct', required for !DISubprogram that is a Definition");
6235 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6236 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6237 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6238 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6239 targetFuncName.Val, keyInstructions.Val));
6249bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6250#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6251 REQUIRED(scope, MDField, ( false)); \
6252 OPTIONAL(file, MDField, ); \
6253 OPTIONAL(line, LineField, ); \
6254 OPTIONAL(column, ColumnField, );
6256#undef VISIT_MD_FIELDS
6259 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6265bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6266#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6267 REQUIRED(scope, MDField, ( false)); \
6268 OPTIONAL(file, MDField, ); \
6269 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6271#undef VISIT_MD_FIELDS
6274 (Context, scope.Val,
file.Val, discriminator.Val));
6280bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6281#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6282 REQUIRED(scope, MDField, ); \
6283 OPTIONAL(declaration, MDField, ); \
6284 OPTIONAL(name, MDStringField, ); \
6285 OPTIONAL(file, MDField, ); \
6286 OPTIONAL(line, LineField, );
6288#undef VISIT_MD_FIELDS
6291 (Context, scope.Val, declaration.Val,
name.Val,
6292 file.Val, line.Val));
6298bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6299#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6300 REQUIRED(scope, MDField, ); \
6301 OPTIONAL(name, MDStringField, ); \
6302 OPTIONAL(exportSymbols, MDBoolField, );
6304#undef VISIT_MD_FIELDS
6307 (Context, scope.Val,
name.Val, exportSymbols.Val));
6314bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6315#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6316 REQUIRED(type, DwarfMacinfoTypeField, ); \
6317 OPTIONAL(line, LineField, ); \
6318 REQUIRED(name, MDStringField, ); \
6319 OPTIONAL(value, MDStringField, );
6321#undef VISIT_MD_FIELDS
6324 (Context, type.Val, line.Val,
name.Val, value.Val));
6330bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6331#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6332 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6333 OPTIONAL(line, LineField, ); \
6334 REQUIRED(file, MDField, ); \
6335 OPTIONAL(nodes, MDField, );
6337#undef VISIT_MD_FIELDS
6340 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6348bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6349#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6350 REQUIRED(scope, MDField, ); \
6351 REQUIRED(name, MDStringField, ); \
6352 OPTIONAL(configMacros, MDStringField, ); \
6353 OPTIONAL(includePath, MDStringField, ); \
6354 OPTIONAL(apinotes, MDStringField, ); \
6355 OPTIONAL(file, MDField, ); \
6356 OPTIONAL(line, LineField, ); \
6357 OPTIONAL(isDecl, MDBoolField, );
6359#undef VISIT_MD_FIELDS
6362 configMacros.Val, includePath.Val,
6363 apinotes.Val, line.Val, isDecl.Val));
6369bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6370#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6371 OPTIONAL(name, MDStringField, ); \
6372 REQUIRED(type, MDField, ); \
6373 OPTIONAL(defaulted, MDBoolField, );
6375#undef VISIT_MD_FIELDS
6378 (Context,
name.Val, type.Val, defaulted.Val));
6386bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6387#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6388 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6389 OPTIONAL(name, MDStringField, ); \
6390 OPTIONAL(type, MDField, ); \
6391 OPTIONAL(defaulted, MDBoolField, ); \
6392 REQUIRED(value, MDField, );
6395#undef VISIT_MD_FIELDS
6398 DITemplateValueParameter,
6399 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6408bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6409#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6410 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6411 OPTIONAL(scope, MDField, ); \
6412 OPTIONAL(linkageName, MDStringField, ); \
6413 OPTIONAL(file, MDField, ); \
6414 OPTIONAL(line, LineField, ); \
6415 OPTIONAL(type, MDField, ); \
6416 OPTIONAL(isLocal, MDBoolField, ); \
6417 OPTIONAL(isDefinition, MDBoolField, (true)); \
6418 OPTIONAL(templateParams, MDField, ); \
6419 OPTIONAL(declaration, MDField, ); \
6420 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6421 OPTIONAL(annotations, MDField, );
6423#undef VISIT_MD_FIELDS
6427 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6428 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6429 declaration.Val, templateParams.Val, align.Val,
6441bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6442#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6443 REQUIRED(scope, MDField, ( false)); \
6444 OPTIONAL(name, MDStringField, ); \
6445 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6446 OPTIONAL(file, MDField, ); \
6447 OPTIONAL(line, LineField, ); \
6448 OPTIONAL(type, MDField, ); \
6449 OPTIONAL(flags, DIFlagField, ); \
6450 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6451 OPTIONAL(annotations, MDField, );
6453#undef VISIT_MD_FIELDS
6456 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6457 type.Val, arg.Val, flags.Val, align.Val,
6464bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6465#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6466 REQUIRED(scope, MDField, ( false)); \
6467 REQUIRED(name, MDStringField, ); \
6468 REQUIRED(file, MDField, ); \
6469 REQUIRED(line, LineField, ); \
6470 OPTIONAL(column, ColumnField, ); \
6471 OPTIONAL(isArtificial, MDBoolField, ); \
6472 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6474#undef VISIT_MD_FIELDS
6476 std::optional<unsigned> CoroSuspendIdx =
6477 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6481 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6482 column.Val, isArtificial.Val, CoroSuspendIdx));
6488bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6501 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6510 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6511 Lex.getStrVal() +
"'");
6514 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6515 return tokError(
"expected unsigned integer");
6517 auto &
U = Lex.getAPSIntVal();
6519 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6533bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6535 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6538 return parseDIExpressionBody(Result, IsDistinct);
6543bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6544 assert(PFS &&
"Expected valid function state");
6555 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6569bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6571#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6572 REQUIRED(var, MDField, ); \
6573 REQUIRED(expr, MDField, );
6575#undef VISIT_MD_FIELDS
6578 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6585bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6586#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6587 OPTIONAL(name, MDStringField, ); \
6588 OPTIONAL(file, MDField, ); \
6589 OPTIONAL(line, LineField, ); \
6590 OPTIONAL(setter, MDStringField, ); \
6591 OPTIONAL(getter, MDStringField, ); \
6592 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6593 OPTIONAL(type, MDField, );
6595#undef VISIT_MD_FIELDS
6598 (Context,
name.Val,
file.Val, line.Val, getter.Val,
6599 setter.Val, attributes.Val, type.Val));
6606bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6607#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6608 REQUIRED(tag, DwarfTagField, ); \
6609 REQUIRED(scope, MDField, ); \
6610 OPTIONAL(entity, MDField, ); \
6611 OPTIONAL(file, MDField, ); \
6612 OPTIONAL(line, LineField, ); \
6613 OPTIONAL(name, MDStringField, ); \
6614 OPTIONAL(elements, MDField, );
6616#undef VISIT_MD_FIELDS
6619 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6620 line.Val,
name.Val, elements.Val));
6624#undef PARSE_MD_FIELD
6636bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6639 if (parseMetadata(MD, &PFS))
6650bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6651 PerFunctionState *PFS) {
6654 if (parseType(Ty, TypeMsg, Loc))
6657 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6660 if (parseValue(Ty, V, PFS))
6675bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6679 if (Lex.getStrVal() ==
"DIArgList") {
6681 if (parseDIArgList(AL, PFS))
6687 if (parseSpecializedMDNode(
N)) {
6697 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6707 if (parseMDString(S))
6717 if (parseMDNodeTail(
N))
6728 PerFunctionState *PFS) {
6730 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6735 return error(
ID.Loc,
"invalid use of function-local name");
6736 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6737 return V ==
nullptr;
6740 return error(
ID.Loc,
"invalid use of function-local name");
6741 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6742 return V ==
nullptr;
6745 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6749 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6754 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6757 return V ==
nullptr;
6759 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6762 return V ==
nullptr;
6765 return error(
ID.Loc,
"integer/byte constant must have integer/byte type");
6768 :
V = ConstantByte::
get(Context,
ID.APSIntVal);
6773 return error(
ID.Loc,
"floating point constant invalid for type");
6779 bool IsSNAN = ID.APFloatVal.isSignaling();
6782 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6784 else if (Ty->isBFloatTy())
6785 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6787 else if (Ty->isFloatTy())
6788 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6794 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6795 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6796 ID.APFloatVal.isNegative(), &Payload);
6799 V = ConstantFP::get(Context,
ID.APFloatVal);
6801 if (
V->getType() != Ty)
6802 return error(
ID.Loc,
"floating point constant does not have type '" +
6808 return error(
ID.Loc,
"null must be a pointer type");
6814 return error(
ID.Loc,
"invalid type for undef constant");
6819 return error(
ID.Loc,
"invalid empty array initializer");
6825 return error(
ID.Loc,
"invalid type for null constant");
6828 return error(
ID.Loc,
"invalid type for null constant");
6833 return error(
ID.Loc,
"invalid type for none constant");
6839 return error(
ID.Loc,
"invalid type for poison constant");
6843 if (
ID.ConstantVal->getType() != Ty)
6844 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6851 return error(
ID.Loc,
"vector constant must have vector type");
6853 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6855 "' but expected '" +
6863 if (
ST->getNumElements() !=
ID.UIntVal)
6865 "initializer with struct type has wrong # elements");
6867 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6870 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6871 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6874 "element " + Twine(i) +
6875 " of struct initializer doesn't match struct element type");
6878 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6880 return error(
ID.Loc,
"constant expression type mismatch");
6889 auto Loc = Lex.getLoc();
6890 if (parseValID(
ID,
nullptr, Ty))
6903 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6913 return error(Loc,
"expected a constant value");
6917bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6921 FileLoc
Start = getTokLineColumnPos();
6922 bool Ret = parseValID(
ID, PFS, Ty) || convertValIDToValue(Ty,
ID, V, PFS);
6923 if (!Ret && ParserContext) {
6924 FileLoc End = getPrevTokEndLineColumnPos();
6925 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
6930bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6932 return parseType(Ty) || parseValue(Ty, V, PFS);
6935bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
6936 PerFunctionState &PFS) {
6939 if (parseTypeAndValue(V, PFS))
6942 return error(Loc,
"expected a basic block");
6951 if (!Name.starts_with(
"llvm.dbg."))
6954 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6955 FnID == Intrinsic::dbg_assign;
6963bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
6964 unsigned &FunctionNumber,
6967 LocTy LinkageLoc = Lex.getLoc();
6969 unsigned Visibility;
6970 unsigned DLLStorageClass;
6972 AttrBuilder RetAttrs(M->getContext());
6975 Type *RetType =
nullptr;
6976 LocTy RetTypeLoc = Lex.getLoc();
6977 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
6979 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6980 parseType(RetType, RetTypeLoc,
true ))
6989 return error(LinkageLoc,
"invalid linkage for function definition");
6999 return error(LinkageLoc,
"invalid linkage for function declaration");
7003 return error(LinkageLoc,
"invalid function linkage type");
7007 return error(LinkageLoc,
7008 "symbol with local linkage must have default visibility");
7011 return error(LinkageLoc,
7012 "symbol with local linkage cannot have a DLL storage class");
7015 return error(RetTypeLoc,
"invalid function return type");
7017 LocTy NameLoc = Lex.getLoc();
7019 std::string FunctionName;
7021 FunctionName = Lex.getStrVal();
7023 FunctionNumber = Lex.getUIntVal();
7024 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
7028 return tokError(
"expected function name");
7034 return tokError(
"expected '(' in function argument list");
7038 AttrBuilder FuncAttrs(M->getContext());
7039 std::vector<unsigned> FwdRefAttrGrps;
7042 std::string Partition;
7043 MaybeAlign Alignment, PrefAlignment;
7046 unsigned AddrSpace = 0;
7052 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7053 parseOptionalUnnamedAddr(UnnamedAddr) ||
7054 parseOptionalProgramAddrSpace(AddrSpace) ||
7055 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7059 parseOptionalComdat(FunctionName,
C) ||
7060 parseOptionalAlignment(Alignment) ||
7061 parseOptionalPrefAlignment(PrefAlignment) ||
7062 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7066 parseGlobalTypeAndValue(PersonalityFn)))
7069 if (FuncAttrs.contains(Attribute::Builtin))
7070 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7073 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7075 FuncAttrs.removeAttribute(Attribute::Alignment);
7080 std::vector<Type*> ParamTypeList;
7083 for (
const ArgInfo &Arg : ArgList) {
7084 ParamTypeList.push_back(Arg.Ty);
7085 Attrs.push_back(Arg.Attrs);
7092 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7093 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7099 GlobalValue *FwdFn =
nullptr;
7100 if (!FunctionName.empty()) {
7103 auto FRVI = ForwardRefVals.find(FunctionName);
7104 if (FRVI != ForwardRefVals.end()) {
7105 FwdFn = FRVI->second.first;
7107 return error(FRVI->second.second,
7108 "invalid forward reference to "
7111 "' with wrong type: "
7115 ForwardRefVals.erase(FRVI);
7116 }
else if ((Fn = M->getFunction(FunctionName))) {
7118 return error(NameLoc,
7119 "invalid redefinition of function '" + FunctionName +
"'");
7120 }
else if (M->getNamedValue(FunctionName)) {
7121 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7127 if (FunctionNumber == (
unsigned)-1)
7128 FunctionNumber = NumberedVals.getNext();
7132 auto I = ForwardRefValIDs.find(FunctionNumber);
7133 if (
I != ForwardRefValIDs.end()) {
7134 FwdFn =
I->second.first;
7136 return error(NameLoc,
"type of definition and forward reference of '@" +
7137 Twine(FunctionNumber) +
7142 ForwardRefValIDs.erase(
I);
7151 if (FunctionName.empty())
7152 NumberedVals.add(FunctionNumber, Fn);
7168 if (!
GC.empty()) Fn->
setGC(GC);
7171 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7175 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7176 if (ParserContext && ArgList[i].IdentLoc)
7177 ParserContext->addInstructionOrArgumentLocation(
7178 &*ArgIt, ArgList[i].IdentLoc.value());
7180 if (ArgList[i].
Name.empty())
continue;
7183 ArgIt->
setName(ArgList[i].Name);
7185 if (ArgIt->
getName() != ArgList[i].Name)
7186 return error(ArgList[i].Loc,
7187 "redefinition of argument '%" + ArgList[i].Name +
"'");
7200 if (FunctionName.empty()) {
7202 ID.UIntVal = FunctionNumber;
7205 ID.StrVal = FunctionName;
7207 auto Blocks = ForwardRefBlockAddresses.find(
ID);
7208 if (Blocks != ForwardRefBlockAddresses.end())
7209 return error(Blocks->first.Loc,
7210 "cannot take blockaddress inside a declaration");
7214bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7216 if (FunctionNumber == -1) {
7218 ID.StrVal = std::string(F.getName());
7221 ID.UIntVal = FunctionNumber;
7224 auto Blocks = P.ForwardRefBlockAddresses.find(
ID);
7225 if (Blocks == P.ForwardRefBlockAddresses.end())
7228 for (
const auto &
I : Blocks->second) {
7229 const ValID &BBID =
I.first;
7230 GlobalValue *GV =
I.second;
7233 "Expected local id or name");
7240 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7243 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7251 P.ForwardRefBlockAddresses.erase(Blocks);
7257bool LLParser::parseFunctionBody(Function &Fn,
unsigned FunctionNumber,
7258 ArrayRef<unsigned> UnnamedArgNums) {
7260 return tokError(
"expected '{' in function body");
7263 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7267 if (PFS.resolveForwardRefBlockAddresses())
7273 return tokError(
"function body requires at least one basic block");
7277 if (parseBasicBlock(PFS))
7281 if (parseUseListOrder(&PFS))
7288 return PFS.finishFunction();
7293bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7294 FileLoc BBStart = getTokLineColumnPos();
7299 LocTy NameLoc = Lex.getLoc();
7301 Name = Lex.getStrVal();
7304 NameID = Lex.getUIntVal();
7308 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7312 std::string NameStr;
7317 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7318 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7325 if (SeenOldDbgInfoFormat)
7326 return error(Lex.getLoc(),
"debug record should not appear in a module "
7327 "containing debug info intrinsics");
7328 SeenNewDbgInfoFormat =
true;
7332 if (parseDebugRecord(DR, PFS))
7334 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7337 FileLoc InstStart = getTokLineColumnPos();
7340 LocTy NameLoc = Lex.getLoc();
7345 NameID = Lex.getUIntVal();
7347 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7350 NameStr = Lex.getStrVal();
7352 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7356 switch (parseInstruction(Inst, BB, PFS)) {
7359 case InstError:
return true;
7366 if (parseInstructionMetadata(*Inst))
7369 case InstExtraComma:
7374 if (parseInstructionMetadata(*Inst))
7380 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7384 for (DbgRecordPtr &DR : TrailingDbgRecord)
7386 TrailingDbgRecord.clear();
7387 if (ParserContext) {
7388 ParserContext->addInstructionOrArgumentLocation(
7389 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7394 ParserContext->addBlockLocation(
7395 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7397 assert(TrailingDbgRecord.empty() &&
7398 "All debug values should have been attached to an instruction.");
7407bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7410 LocTy DVRLoc = Lex.getLoc();
7412 return error(DVRLoc,
"expected debug record type here");
7413 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7414 .Case(
"declare", RecordKind::ValueKind)
7415 .Case(
"value", RecordKind::ValueKind)
7416 .Case(
"assign", RecordKind::ValueKind)
7417 .Case(
"label", RecordKind::LabelKind)
7418 .Case(
"declare_value", RecordKind::ValueKind);
7427 if (parseMDNode(Label))
7432 if (parseMDNode(DbgLoc))
7440 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7441 .Case(
"declare", LocType::Declare)
7442 .Case(
"value", LocType::Value)
7443 .Case(
"assign", LocType::Assign)
7444 .Case(
"declare_value", LocType::DeclareValue);
7452 if (parseMetadata(ValLocMD, &PFS))
7459 if (parseMDNode(Variable))
7466 if (parseMDNode(Expression))
7472 MDNode *AssignID =
nullptr;
7473 Metadata *AddressLocation =
nullptr;
7474 MDNode *AddressExpression =
nullptr;
7477 if (parseMDNode(AssignID))
7483 if (parseMetadata(AddressLocation, &PFS))
7489 if (parseMDNode(AddressExpression))
7503 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7513int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7514 PerFunctionState &PFS) {
7517 return tokError(
"found end of file when expecting more instructions");
7518 LocTy Loc = Lex.getLoc();
7519 unsigned KeywordVal = Lex.getUIntVal();
7524 return error(Loc,
"expected instruction opcode");
7528 return parseRet(Inst, BB, PFS);
7530 return parseBr(Inst, PFS);
7532 return parseSwitch(Inst, PFS);
7534 return parseIndirectBr(Inst, PFS);
7536 return parseInvoke(Inst, PFS);
7538 return parseResume(Inst, PFS);
7540 return parseCleanupRet(Inst, PFS);
7542 return parseCatchRet(Inst, PFS);
7544 return parseCatchSwitch(Inst, PFS);
7546 return parseCatchPad(Inst, PFS);
7548 return parseCleanupPad(Inst, PFS);
7550 return parseCallBr(Inst, PFS);
7553 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7554 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7570 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7582 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7583 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7597 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7605 return parseArithmetic(Inst, PFS, KeywordVal,
7609 if (parseLogical(Inst, PFS, KeywordVal))
7617 return parseLogical(Inst, PFS, KeywordVal);
7620 if (parseCompare(Inst, PFS, KeywordVal))
7627 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7628 int Res = parseCompare(Inst, PFS, KeywordVal);
7640 bool Res = parseCast(Inst, PFS, KeywordVal);
7652 if (parseCast(Inst, PFS, KeywordVal))
7669 return parseCast(Inst, PFS, KeywordVal);
7672 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7673 if (parseCast(Inst, PFS, KeywordVal))
7682 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7683 int Res = parseSelect(Inst, PFS);
7688 return error(Loc,
"fast-math-flags specified for select without "
7689 "floating-point scalar or vector return type");
7695 return parseVAArg(Inst, PFS);
7697 return parseExtractElement(Inst, PFS);
7699 return parseInsertElement(Inst, PFS);
7701 return parseShuffleVector(Inst, PFS);
7703 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7704 int Res = parsePHI(Inst, PFS);
7709 return error(Loc,
"fast-math-flags specified for phi without "
7710 "floating-point scalar or vector return type");
7716 return parseLandingPad(Inst, PFS);
7718 return parseFreeze(Inst, PFS);
7730 return parseAlloc(Inst, PFS);
7732 return parseLoad(Inst, PFS);
7734 return parseStore(Inst, PFS);
7736 return parseCmpXchg(Inst, PFS);
7738 return parseAtomicRMW(Inst, PFS);
7740 return parseFence(Inst, PFS);
7742 return parseGetElementPtr(Inst, PFS);
7744 return parseExtractValue(Inst, PFS);
7746 return parseInsertValue(Inst, PFS);
7751bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7752 if (
Opc == Instruction::FCmp) {
7753 switch (Lex.getKind()) {
7755 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7774 switch (Lex.getKind()) {
7776 return tokError(
"expected icmp predicate (e.g. 'eq')");
7800bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7801 PerFunctionState &PFS) {
7802 SMLoc TypeLoc = Lex.getLoc();
7804 if (parseType(Ty,
true ))
7807 Type *ResType = PFS.getFunction().getReturnType();
7811 return error(TypeLoc,
"value doesn't match function result type '" +
7819 if (parseValue(Ty, RV, PFS))
7823 return error(TypeLoc,
"value doesn't match function result type '" +
7833bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7837 if (parseTypeAndValue(Op0, Loc, PFS))
7846 return error(Loc,
"branch condition must have 'i1' type");
7848 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7849 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7850 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7851 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7863bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7864 LocTy CondLoc, BBLoc;
7867 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7868 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7869 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7873 if (!
Cond->getType()->isIntegerTy())
7874 return error(CondLoc,
"switch condition must have integer type");
7877 SmallPtrSet<Value*, 32> SeenCases;
7883 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7884 parseToken(
lltok::comma,
"expected ',' after case value") ||
7885 parseTypeAndBasicBlock(DestBB, PFS))
7888 if (!SeenCases.
insert(Constant).second)
7889 return error(CondLoc,
"duplicate case value in switch");
7891 return error(CondLoc,
"case value is not a constant integer");
7899 for (
const auto &[OnVal, Dest] : Table)
7900 SI->addCase(OnVal, Dest);
7908bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7911 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7912 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7916 if (!
Address->getType()->isPointerTy())
7917 return error(AddrLoc,
"indirectbr address must have pointer type");
7920 SmallVector<BasicBlock*, 16> DestList;
7924 if (parseTypeAndBasicBlock(DestBB, PFS))
7929 if (parseTypeAndBasicBlock(DestBB, PFS))
7935 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7939 for (BasicBlock *Dest : DestList)
7949 FunctionType *&FuncTy) {
7955 for (
const ParamInfo &Arg : ArgList)
7969bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7970 LocTy CallLoc = Lex.getLoc();
7971 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7972 std::vector<unsigned> FwdRefAttrGrps;
7975 unsigned InvokeAddrSpace;
7976 Type *RetType =
nullptr;
7983 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7984 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7985 parseType(RetType, RetTypeLoc,
true ) ||
7986 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7987 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
7989 parseOptionalOperandBundles(BundleList, PFS) ||
7991 parseTypeAndBasicBlock(NormalBB, PFS) ||
7993 parseTypeAndBasicBlock(UnwindBB, PFS))
8000 if (resolveFunctionType(RetType, ArgList, Ty))
8001 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8007 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
8012 SmallVector<Value *, 8>
Args;
8019 for (
const ParamInfo &Arg : ArgList) {
8020 Type *ExpectedTy =
nullptr;
8023 }
else if (!Ty->isVarArg()) {
8024 return error(Arg.Loc,
"too many arguments specified");
8027 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8028 return error(Arg.Loc,
"argument is not of expected type '" +
8030 Args.push_back(Arg.V);
8035 return error(CallLoc,
"not enough parameters specified for call");
8044 II->setCallingConv(CC);
8045 II->setAttributes(PAL);
8046 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
8053bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8055 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8063bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8064 PerFunctionState &PFS) {
8065 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8070 if (!
Args.empty() &&
8071 parseToken(
lltok::comma,
"expected ',' in argument list"))
8076 Type *ArgTy =
nullptr;
8077 if (parseType(ArgTy, ArgLoc))
8082 if (parseMetadataAsValue(V, PFS))
8085 if (parseValue(ArgTy, V, PFS))
8097bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8098 Value *CleanupPad =
nullptr;
8100 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8115 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8126bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8127 Value *CatchPad =
nullptr;
8129 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8136 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8137 parseTypeAndBasicBlock(BB, PFS))
8146bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8154 return tokError(
"expected scope value for catchswitch");
8159 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8165 if (parseTypeAndBasicBlock(DestBB, PFS))
8170 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8173 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8181 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8187 for (BasicBlock *DestBB : Table)
8188 CatchSwitch->addHandler(DestBB);
8195bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8196 Value *CatchSwitch =
nullptr;
8202 return tokError(
"expected scope value for catchpad");
8207 SmallVector<Value *, 8>
Args;
8208 if (parseExceptionArgs(Args, PFS))
8217bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8218 Value *ParentPad =
nullptr;
8225 return tokError(
"expected scope value for cleanuppad");
8230 SmallVector<Value *, 8>
Args;
8231 if (parseExceptionArgs(Args, PFS))
8247bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8248 unsigned Opc,
bool IsFP) {
8250 if (parseTypeAndValue(
LHS, Loc, PFS))
8257 return error(Loc,
"invalid operand type for instruction");
8267bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8268 LocTy CallLoc = Lex.getLoc();
8269 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8270 std::vector<unsigned> FwdRefAttrGrps;
8273 Type *RetType =
nullptr;
8280 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8281 parseType(RetType, RetTypeLoc,
true ) ||
8282 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8283 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8285 parseOptionalOperandBundles(BundleList, PFS) ||
8287 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8292 SmallVector<BasicBlock *, 16> IndirectDests;
8296 if (parseTypeAndBasicBlock(DestBB, PFS))
8301 if (parseTypeAndBasicBlock(DestBB, PFS))
8307 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8314 if (resolveFunctionType(RetType, ArgList, Ty))
8315 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8326 SmallVector<Value *, 8>
Args;
8333 for (
const ParamInfo &Arg : ArgList) {
8334 Type *ExpectedTy =
nullptr;
8337 }
else if (!Ty->isVarArg()) {
8338 return error(Arg.Loc,
"too many arguments specified");
8341 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8342 return error(Arg.Loc,
"argument is not of expected type '" +
8344 Args.push_back(Arg.V);
8349 return error(CallLoc,
"not enough parameters specified for call");
8361 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8375bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8376 unsigned Opc,
bool IsFP) {
8378 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8379 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8387 return error(Loc,
"invalid operand type for instruction");
8395bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8398 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8399 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8405 "instruction requires integer or integer vector operands");
8414bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8420 if (parseCmpPredicate(Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8421 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8425 if (
Opc == Instruction::FCmp) {
8427 return error(Loc,
"fcmp requires floating point operands");
8430 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8433 return error(Loc,
"icmp requires integer operands");
8445bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8449 Type *DestTy =
nullptr;
8450 if (parseTypeAndValue(
Op, Loc, PFS) ||
8451 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8456 return error(Loc,
"invalid cast opcode for cast from '" +
8465bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8467 Value *Op0, *Op1, *Op2;
8468 if (parseTypeAndValue(Op0, Loc, PFS) ||
8469 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8470 parseTypeAndValue(Op1, PFS) ||
8471 parseToken(
lltok::comma,
"expected ',' after select value") ||
8472 parseTypeAndValue(Op2, PFS))
8476 return error(Loc, Reason);
8484bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8486 Type *EltTy =
nullptr;
8488 if (parseTypeAndValue(
Op, PFS) ||
8489 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8490 parseType(EltTy, TypeLoc))
8494 return error(TypeLoc,
"va_arg requires operand with first class type");
8496 Inst =
new VAArgInst(
Op, EltTy);
8502bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8505 if (parseTypeAndValue(Op0, Loc, PFS) ||
8506 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8507 parseTypeAndValue(Op1, PFS))
8511 return error(Loc,
"invalid extractelement operands");
8519bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8521 Value *Op0, *Op1, *Op2;
8522 if (parseTypeAndValue(Op0, Loc, PFS) ||
8523 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8524 parseTypeAndValue(Op1, PFS) ||
8525 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8526 parseTypeAndValue(Op2, PFS))
8530 return error(Loc,
"invalid insertelement operands");
8538bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8540 Value *Op0, *Op1, *Op2;
8541 if (parseTypeAndValue(Op0, Loc, PFS) ||
8542 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8543 parseTypeAndValue(Op1, PFS) ||
8544 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8545 parseTypeAndValue(Op2, PFS))
8549 return error(Loc,
"invalid shufflevector operands");
8551 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8557int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8561 if (parseType(Ty, TypeLoc))
8565 return error(TypeLoc,
"phi node must have first class type");
8568 bool AteExtraComma =
false;
8580 AteExtraComma =
true;
8584 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8585 parseValue(Ty, Op0, PFS) ||
8586 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8595 for (
const auto &[Val, BB] : PHIVals)
8598 return AteExtraComma ? InstExtraComma : InstNormal;
8607bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8610 if (parseType(Ty, TyLoc))
8623 return tokError(
"expected 'catch' or 'filter' clause type");
8627 if (parseTypeAndValue(V, VLoc, PFS))
8634 return error(VLoc,
"'catch' clause has an invalid type");
8637 return error(VLoc,
"'filter' clause has an invalid type");
8642 return error(VLoc,
"clause argument must be a constant");
8646 Inst = LP.release();
8652bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8655 if (parseTypeAndValue(
Op, Loc, PFS))
8658 Inst =
new FreezeInst(
Op);
8671bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8673 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8674 std::vector<unsigned> FwdRefAttrGrps;
8676 unsigned CallAddrSpace;
8678 Type *RetType =
nullptr;
8683 LocTy CallLoc = Lex.getLoc();
8687 "expected 'tail call', 'musttail call', or 'notail call'"))
8690 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8692 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8693 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8694 parseType(RetType, RetTypeLoc,
true ) ||
8695 parseValID(CalleeID, &PFS) ||
8697 PFS.getFunction().isVarArg()) ||
8698 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8699 parseOptionalOperandBundles(BundleList, PFS))
8706 if (resolveFunctionType(RetType, ArgList, Ty))
8707 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8713 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
8720 SmallVector<Value*, 8>
Args;
8726 for (
const ParamInfo &Arg : ArgList) {
8727 Type *ExpectedTy =
nullptr;
8730 }
else if (!Ty->isVarArg()) {
8731 return error(Arg.Loc,
"too many arguments specified");
8734 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8735 return error(Arg.Loc,
"argument is not of expected type '" +
8737 Args.push_back(Arg.V);
8738 Attrs.push_back(Arg.Attrs);
8742 return error(CallLoc,
"not enough parameters specified for call");
8755 return error(CallLoc,
"fast-math-flags specified for call without "
8756 "floating-point scalar or vector return type");
8763 if (SeenNewDbgInfoFormat) {
8765 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8766 "using non-intrinsic debug info");
8768 SeenOldDbgInfoFormat =
true;
8771 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8783int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8785 LocTy SizeLoc, TyLoc, ASLoc;
8786 MaybeAlign Alignment;
8787 unsigned AddrSpace = 0;
8790 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8791 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8793 if (parseType(Ty, TyLoc))
8797 return error(TyLoc,
"invalid type for alloca");
8799 bool AteExtraComma =
false;
8801 if (Lex.getKind() == lltok::kw_align) {
8802 if (parseOptionalAlignment(Alignment))
8804 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8807 ASLoc = Lex.getLoc();
8808 if (parseOptionalAddrSpace(AddrSpace))
8811 AteExtraComma =
true;
8813 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8816 if (Lex.getKind() == lltok::kw_align) {
8817 if (parseOptionalAlignment(Alignment))
8819 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8822 ASLoc = Lex.getLoc();
8823 if (parseOptionalAddrSpace(AddrSpace))
8826 AteExtraComma =
true;
8832 if (
Size && !
Size->getType()->isIntegerTy())
8833 return error(SizeLoc,
"element count must have integer type");
8835 SmallPtrSet<Type *, 4> Visited;
8836 if (!Alignment && !Ty->
isSized(&Visited))
8837 return error(TyLoc,
"Cannot allocate unsized type");
8839 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8840 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
8844 return AteExtraComma ? InstExtraComma : InstNormal;
8851int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8853 MaybeAlign Alignment;
8854 bool AteExtraComma =
false;
8855 bool isAtomic =
false;
8864 bool isVolatile =
false;
8871 LocTy ExplicitTypeLoc = Lex.getLoc();
8872 if (parseType(Ty) ||
8873 parseToken(
lltok::comma,
"expected comma after load's type") ||
8874 parseTypeAndValue(Val, Loc, PFS) ||
8875 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8876 parseOptionalCommaAlign(Alignment, AteExtraComma))
8880 return error(Loc,
"load operand must be a pointer to a first class type");
8881 if (isAtomic && !Alignment)
8882 return error(Loc,
"atomic load must have explicit non-zero alignment");
8885 return error(Loc,
"atomic load cannot use Release ordering");
8887 SmallPtrSet<Type *, 4> Visited;
8888 if (!Alignment && !Ty->
isSized(&Visited))
8889 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8891 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8892 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8893 return AteExtraComma ? InstExtraComma : InstNormal;
8901int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8903 MaybeAlign Alignment;
8904 bool AteExtraComma =
false;
8905 bool isAtomic =
false;
8914 bool isVolatile =
false;
8920 if (parseTypeAndValue(Val, Loc, PFS) ||
8921 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8922 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8923 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8924 parseOptionalCommaAlign(Alignment, AteExtraComma))
8928 return error(PtrLoc,
"store operand must be a pointer");
8930 return error(Loc,
"store operand must be a first class value");
8931 if (isAtomic && !Alignment)
8932 return error(Loc,
"atomic store must have explicit non-zero alignment");
8935 return error(Loc,
"atomic store cannot use Acquire ordering");
8936 SmallPtrSet<Type *, 4> Visited;
8938 return error(Loc,
"storing unsized types is not allowed");
8940 Alignment = M->getDataLayout().getABITypeAlign(Val->
getType());
8942 Inst =
new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8943 return AteExtraComma ? InstExtraComma : InstNormal;
8950int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8952 bool AteExtraComma =
false;
8956 bool isVolatile =
false;
8957 bool isWeak =
false;
8958 MaybeAlign Alignment;
8966 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8967 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
8968 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8969 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
8970 parseTypeAndValue(New, NewLoc, PFS) ||
8971 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
8972 parseOrdering(FailureOrdering) ||
8973 parseOptionalCommaAlign(Alignment, AteExtraComma))
8977 return tokError(
"invalid cmpxchg success ordering");
8979 return tokError(
"invalid cmpxchg failure ordering");
8981 return error(PtrLoc,
"cmpxchg operand must be a pointer");
8982 if (
Cmp->getType() !=
New->getType())
8983 return error(NewLoc,
"compare value and new value type do not match");
8984 if (!
New->getType()->isFirstClassType())
8985 return error(NewLoc,
"cmpxchg operand must be a first class value");
8987 const Align DefaultAlignment(
8988 PFS.getFunction().getDataLayout().getTypeStoreSize(
8991 AtomicCmpXchgInst *CXI =
8992 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8993 SuccessOrdering, FailureOrdering, SSID);
8998 return AteExtraComma ? InstExtraComma : InstNormal;
9004int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9006 bool AteExtraComma =
false;
9009 bool isVolatile =
false;
9012 MaybeAlign Alignment;
9017 switch (Lex.getKind()) {
9019 return tokError(
"expected binary operation in atomicrmw");
9078 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9079 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9080 parseTypeAndValue(Val, ValLoc, PFS) ||
9081 parseScopeAndOrdering(
true , SSID, Ordering) ||
9082 parseOptionalCommaAlign(Alignment, AteExtraComma))
9086 return tokError(
"atomicrmw cannot be unordered");
9088 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9090 return error(ValLoc,
"atomicrmw operand may not be scalable");
9099 " operand must be an integer, floating point, or pointer type");
9103 return error(ValLoc,
"atomicrmw " +
9105 " operand must be a floating point type");
9109 return error(ValLoc,
"atomicrmw " +
9111 " operand must be an integer");
9116 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
9119 return error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
9121 const Align DefaultAlignment(
9122 PFS.getFunction().getDataLayout().getTypeStoreSize(
9124 AtomicRMWInst *RMWI =
9126 Alignment.value_or(DefaultAlignment), Ordering, SSID);
9129 return AteExtraComma ? InstExtraComma : InstNormal;
9134int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9137 if (parseScopeAndOrdering(
true , SSID, Ordering))
9141 return tokError(
"fence cannot be unordered");
9143 return tokError(
"fence cannot be monotonic");
9145 Inst =
new FenceInst(Context, Ordering, SSID);
9151int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9152 Value *Ptr =
nullptr;
9153 Value *Val =
nullptr;
9169 if (parseType(Ty) ||
9170 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9171 parseTypeAndValue(Ptr, Loc, PFS))
9176 if (!BasePointerType)
9177 return error(Loc,
"base of getelementptr must be a pointer");
9179 SmallVector<Value*, 16> Indices;
9180 bool AteExtraComma =
false;
9183 ElementCount GEPWidth =
BaseType->isVectorTy()
9189 AteExtraComma =
true;
9192 if (parseTypeAndValue(Val, EltLoc, PFS))
9195 return error(EltLoc,
"getelementptr index must be an integer");
9198 ElementCount ValNumEl = ValVTy->getElementCount();
9202 "getelementptr vector index has a wrong number of elements");
9203 GEPWidth = ValNumEl;
9208 SmallPtrSet<Type*, 4> Visited;
9210 return error(Loc,
"base element of getelementptr must be sized");
9214 return error(Loc,
"getelementptr cannot target structure that contains "
9215 "scalable vector type");
9218 return error(Loc,
"invalid getelementptr indices");
9221 GEP->setNoWrapFlags(NW);
9222 return AteExtraComma ? InstExtraComma : InstNormal;
9227int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9229 SmallVector<unsigned, 4> Indices;
9231 if (parseTypeAndValue(Val, Loc, PFS) ||
9232 parseIndexList(Indices, AteExtraComma))
9236 return error(Loc,
"extractvalue operand must be aggregate type");
9239 return error(Loc,
"invalid indices for extractvalue");
9241 return AteExtraComma ? InstExtraComma : InstNormal;
9246int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9248 SmallVector<unsigned, 4> Indices;
9250 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9251 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9252 parseTypeAndValue(Val1, Loc1, PFS) ||
9253 parseIndexList(Indices, AteExtraComma))
9257 return error(Loc0,
"insertvalue operand must be aggregate type");
9261 return error(Loc0,
"invalid indices for insertvalue");
9262 if (IndexedType != Val1->
getType())
9263 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9267 return AteExtraComma ? InstExtraComma : InstNormal;
9278bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9293 if (parseMetadata(MD,
nullptr))
9298 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9304bool LLParser::sortUseListOrder(
Value *V, ArrayRef<unsigned> Indexes,
9306 if (!
V->hasUseList())
9309 return error(Loc,
"value has no uses");
9311 unsigned NumUses = 0;
9312 SmallDenseMap<const Use *, unsigned, 16> Order;
9313 for (
const Use &U :
V->uses()) {
9314 if (++NumUses > Indexes.
size())
9316 Order[&
U] = Indexes[NumUses - 1];
9319 return error(Loc,
"value only has one use");
9320 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9322 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9324 V->sortUseList([&](
const Use &L,
const Use &R) {
9332bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9333 SMLoc Loc = Lex.getLoc();
9337 return tokError(
"expected non-empty list of uselistorder indexes");
9344 bool IsOrdered =
true;
9345 assert(Indexes.
empty() &&
"Expected empty order vector");
9348 if (parseUInt32(Index))
9353 Max = std::max(Max, Index);
9354 IsOrdered &= Index == Indexes.
size();
9362 if (Indexes.
size() < 2)
9363 return error(Loc,
"expected >= 2 uselistorder indexes");
9366 "expected distinct uselistorder indexes in range [0, size)");
9368 return error(Loc,
"expected uselistorder indexes to change the order");
9375bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9376 SMLoc Loc = Lex.getLoc();
9381 SmallVector<unsigned, 16> Indexes;
9382 if (parseTypeAndValue(V, PFS) ||
9383 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9384 parseUseListOrderIndexes(Indexes))
9387 return sortUseListOrder(V, Indexes, Loc);
9392bool LLParser::parseUseListOrderBB() {
9394 SMLoc Loc = Lex.getLoc();
9398 SmallVector<unsigned, 16> Indexes;
9399 if (parseValID(Fn,
nullptr) ||
9400 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
9401 parseValID(Label,
nullptr) ||
9402 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
9403 parseUseListOrderIndexes(Indexes))
9409 GV = M->getNamedValue(Fn.
StrVal);
9411 GV = NumberedVals.get(Fn.
UIntVal);
9413 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
9416 "invalid function forward reference in uselistorder_bb");
9419 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
9420 if (
F->isDeclaration())
9421 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
9425 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
9427 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
9428 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
9430 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
9432 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
9434 return sortUseListOrder(V, Indexes, Loc);
9440bool LLParser::parseModuleEntry(
unsigned ID) {
9449 parseStringConstant(Path) ||
9457 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9458 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9459 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9460 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9461 parseUInt32(Hash[4]))
9468 auto ModuleEntry = Index->addModule(Path, Hash);
9469 ModuleIdMap[
ID] = ModuleEntry->first();
9476bool LLParser::parseTypeIdEntry(
unsigned ID) {
9485 parseStringConstant(Name))
9488 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9490 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9495 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9496 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9497 for (
auto TIDRef : FwdRefTIDs->second) {
9499 "Forward referenced type id GUID expected to be 0");
9502 ForwardRefTypeIds.erase(FwdRefTIDs);
9510bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9514 parseTypeTestResolution(TIS.
TTRes))
9519 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9530 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
9536bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9545 parseStringConstant(Name))
9549 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9556 IdToIndexMapType IdToIndexMap;
9569 if (parseGVReference(VI, GVId))
9576 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9577 TI.push_back({
Offset, VI});
9585 for (
auto I : IdToIndexMap) {
9586 auto &Infos = ForwardRefValueInfos[
I.first];
9587 for (
auto P :
I.second) {
9589 "Forward referenced ValueInfo expected to be empty");
9590 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9600 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9601 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9602 for (
auto TIDRef : FwdRefTIDs->second) {
9604 "Forward referenced type id GUID expected to be 0");
9607 ForwardRefTypeIds.erase(FwdRefTIDs);
9619bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9627 switch (Lex.getKind()) {
9647 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9659 switch (Lex.getKind()) {
9674 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9687 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
9700bool LLParser::parseOptionalWpdResolutions(
9701 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9709 WholeProgramDevirtResolution WPDRes;
9713 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9716 WPDResMap[
Offset] = WPDRes;
9733bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9741 switch (Lex.getKind()) {
9752 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9758 switch (Lex.getKind()) {
9766 if (parseOptionalResByArg(WPDRes.
ResByArg))
9770 return error(Lex.getLoc(),
9771 "expected optional WholeProgramDevirtResolution field");
9788bool LLParser::parseOptionalResByArg(
9789 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9797 std::vector<uint64_t>
Args;
9798 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
9806 WholeProgramDevirtResolution::ByArg ByArg;
9807 switch (Lex.getKind()) {
9821 return error(Lex.getLoc(),
9822 "unexpected WholeProgramDevirtResolution::ByArg kind");
9828 switch (Lex.getKind()) {
9832 parseUInt64(ByArg.
Info))
9838 parseUInt32(ByArg.
Byte))
9844 parseUInt32(ByArg.
Bit))
9848 return error(Lex.getLoc(),
9849 "expected optional whole program devirt field");
9856 ResByArg[
Args] = ByArg;
9867bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9875 if (parseUInt64(Val))
9877 Args.push_back(Val);
9886static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9901bool LLParser::addGlobalValueToIndex(
9903 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
9908 VI = Index->getOrInsertValueInfo(GUID);
9912 auto *GV = M->getNamedValue(Name);
9914 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
9916 VI = Index->getOrInsertValueInfo(GV);
9920 "Need a source_filename to compute GUID for local");
9923 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9928 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9929 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9930 for (
auto VIRef : FwdRefVIs->second) {
9932 "Forward referenced ValueInfo expected to be empty");
9935 ForwardRefValueInfos.erase(FwdRefVIs);
9939 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
9940 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9941 for (
auto AliaseeRef : FwdRefAliasees->second) {
9942 assert(!AliaseeRef.first->hasAliasee() &&
9943 "Forward referencing alias already has aliasee");
9944 assert(Summary &&
"Aliasee must be a definition");
9945 AliaseeRef.first->setAliasee(VI,
Summary.get());
9947 ForwardRefAliasees.erase(FwdRefAliasees);
9952 Index->addGlobalValueSummary(VI, std::move(Summary));
9955 if (
ID == NumberedValueInfos.size())
9956 NumberedValueInfos.push_back(VI);
9959 if (
ID > NumberedValueInfos.size())
9960 NumberedValueInfos.resize(
ID + 1);
9961 NumberedValueInfos[
ID] =
VI;
9969bool LLParser::parseSummaryIndexFlags() {
9976 if (parseUInt64(Flags))
9979 Index->setFlags(Flags);
9985bool LLParser::parseBlockCount() {
9991 uint64_t BlockCount;
9992 if (parseUInt64(BlockCount))
9995 Index->setBlockCount(BlockCount);
10003bool LLParser::parseGVEntry(
unsigned ID) {
10011 LocTy Loc = Lex.getLoc();
10014 switch (Lex.getKind()) {
10018 parseStringConstant(Name))
10024 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
10028 return error(Lex.getLoc(),
"expected name or guid tag");
10051 switch (Lex.getKind()) {
10053 if (parseFunctionSummary(Name, GUID,
ID))
10057 if (parseVariableSummary(Name, GUID,
ID))
10061 if (parseAliasSummary(Name, GUID,
ID))
10065 return error(Lex.getLoc(),
"expected summary type");
10083 LocTy Loc = Lex.getLoc();
10087 StringRef ModulePath;
10088 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10091 false,
false,
false,
10093 unsigned InstCount;
10095 FunctionSummary::TypeIdInfo TypeIdInfo;
10096 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10098 std::vector<CallsiteInfo> Callsites;
10099 std::vector<AllocInfo> Allocs;
10101 FunctionSummary::FFlags FFlags = {};
10104 parseModuleReference(ModulePath) ||
10105 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10108 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10113 switch (Lex.getKind()) {
10115 if (parseOptionalFFlags(FFlags))
10119 if (parseOptionalCalls(Calls))
10123 if (parseOptionalTypeIdInfo(TypeIdInfo))
10127 if (parseOptionalRefs(Refs))
10131 if (parseOptionalParamAccesses(ParamAccesses))
10135 if (parseOptionalAllocs(Allocs))
10139 if (parseOptionalCallsites(Callsites))
10143 return error(Lex.getLoc(),
"expected optional function summary field");
10150 auto FS = std::make_unique<FunctionSummary>(
10151 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10157 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10159 FS->setModulePath(ModulePath);
10161 return addGlobalValueToIndex(Name, GUID,
10163 std::move(FS), Loc);
10171 LocTy Loc = Lex.getLoc();
10175 StringRef ModulePath;
10176 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10179 false,
false,
false,
10181 GlobalVarSummary::GVarFlags GVarFlags(
false,
10189 parseModuleReference(ModulePath) ||
10190 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10192 parseGVarFlags(GVarFlags))
10197 switch (Lex.getKind()) {
10199 if (parseOptionalVTableFuncs(VTableFuncs))
10203 if (parseOptionalRefs(Refs))
10207 return error(Lex.getLoc(),
"expected optional variable summary field");
10215 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10217 GS->setModulePath(ModulePath);
10218 GS->setVTableFuncs(std::move(VTableFuncs));
10220 return addGlobalValueToIndex(Name, GUID,
10222 std::move(GS), Loc);
10231 LocTy Loc = Lex.getLoc();
10234 StringRef ModulePath;
10235 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10238 false,
false,
false,
10242 parseModuleReference(ModulePath) ||
10243 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10249 ValueInfo AliaseeVI;
10251 auto AS = std::make_unique<AliasSummary>(GVFlags);
10252 AS->setModulePath(ModulePath);
10255 if (parseGVReference(AliaseeVI, GVId))
10260 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10262 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10263 assert(Summary &&
"Aliasee must be a definition");
10264 AS->setAliasee(AliaseeVI, Summary);
10271 return addGlobalValueToIndex(Name, GUID,
10273 std::move(AS), Loc);
10278bool LLParser::parseFlag(
unsigned &Val) {
10279 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10280 return tokError(
"expected integer");
10281 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10297bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10301 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10307 switch (Lex.getKind()) {
10310 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10316 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10322 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10328 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10334 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10340 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10346 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10352 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10358 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10364 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10369 return error(Lex.getLoc(),
"expected function flag type");
10373 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10384bool LLParser::parseOptionalCalls(
10385 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10389 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10393 IdToIndexMapType IdToIndexMap;
10402 LocTy Loc = Lex.getLoc();
10404 if (parseGVReference(VI, GVId))
10408 unsigned RelBF = 0;
10409 unsigned HasTailCall =
false;
10413 switch (Lex.getKind()) {
10416 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10422 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10427 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10431 return error(Lex.getLoc(),
"expected hotness, relbf, or tail");
10438 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10448 for (
auto I : IdToIndexMap) {
10449 auto &Infos = ForwardRefValueInfos[
I.first];
10450 for (
auto P :
I.second) {
10452 "Forward referenced ValueInfo expected to be empty");
10453 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10466 switch (Lex.getKind()) {
10470 case lltok::kw_cold:
10476 case lltok::kw_hot:
10483 return error(Lex.getLoc(),
"invalid call edge hotness");
10492bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10496 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10500 IdToIndexMapType IdToIndexMap;
10504 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10509 LocTy Loc = Lex.getLoc();
10511 if (parseGVReference(VI, GVId))
10524 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10525 VTableFuncs.push_back({
VI,
Offset});
10527 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10533 for (
auto I : IdToIndexMap) {
10534 auto &Infos = ForwardRefValueInfos[
I.first];
10535 for (
auto P :
I.second) {
10537 "Forward referenced ValueInfo expected to be empty");
10538 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10542 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10549bool LLParser::parseParamNo(uint64_t &ParamNo) {
10551 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10557bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10560 auto ParseAPSInt = [&](
APSInt &Val) {
10562 return tokError(
"expected integer");
10563 Val = Lex.getAPSIntVal();
10565 Val.setIsSigned(
true);
10587bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10588 IdLocListType &IdLocList) {
10596 LocTy Loc = Lex.getLoc();
10597 if (parseGVReference(VI, GVId))
10601 IdLocList.emplace_back(GVId, Loc);
10604 parseParamNo(
Call.ParamNo) ||
10606 parseParamAccessOffset(
Call.Offsets))
10618bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10619 IdLocListType &IdLocList) {
10621 parseParamNo(
Param.ParamNo) ||
10623 parseParamAccessOffset(
Param.Use))
10632 FunctionSummary::ParamAccess::Call
Call;
10633 if (parseParamAccessCall(
Call, IdLocList))
10650bool LLParser::parseOptionalParamAccesses(
10651 std::vector<FunctionSummary::ParamAccess> &Params) {
10659 IdLocListType VContexts;
10660 size_t CallsNum = 0;
10662 FunctionSummary::ParamAccess ParamAccess;
10663 if (parseParamAccess(ParamAccess, VContexts))
10665 CallsNum += ParamAccess.
Calls.size();
10666 assert(VContexts.size() == CallsNum);
10668 Params.emplace_back(std::move(ParamAccess));
10676 IdLocListType::const_iterator ItContext = VContexts.begin();
10677 for (
auto &PA : Params) {
10678 for (
auto &
C : PA.Calls) {
10680 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10681 ItContext->second);
10685 assert(ItContext == VContexts.end());
10692bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10696 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10700 struct ValueContext {
10705 std::vector<ValueContext> VContexts;
10709 VC.Loc = Lex.getLoc();
10710 if (parseGVReference(
VC.VI,
VC.GVId))
10712 VContexts.push_back(VC);
10718 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10719 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10722 IdToIndexMapType IdToIndexMap;
10723 for (
auto &VC : VContexts) {
10728 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
10734 for (
auto I : IdToIndexMap) {
10735 auto &Infos = ForwardRefValueInfos[
I.first];
10736 for (
auto P :
I.second) {
10738 "Forward referenced ValueInfo expected to be empty");
10739 Infos.emplace_back(&Refs[
P.first],
P.second);
10753bool LLParser::parseOptionalTypeIdInfo(
10754 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10763 switch (Lex.getKind()) {
10765 if (parseTypeTests(TypeIdInfo.
TypeTests))
10789 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
10793 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10802bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10810 IdToIndexMapType IdToIndexMap;
10814 unsigned ID = Lex.getUIntVal();
10815 LocTy Loc = Lex.getLoc();
10819 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
10821 }
else if (parseUInt64(GUID))
10823 TypeTests.push_back(GUID);
10828 for (
auto I : IdToIndexMap) {
10829 auto &Ids = ForwardRefTypeIds[
I.first];
10830 for (
auto P :
I.second) {
10831 assert(TypeTests[
P.first] == 0 &&
10832 "Forward referenced type id GUID expected to be 0");
10833 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10837 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10845bool LLParser::parseVFuncIdList(
10846 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10847 assert(Lex.getKind() == Kind);
10854 IdToIndexMapType IdToIndexMap;
10856 FunctionSummary::VFuncId VFuncId;
10857 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10859 VFuncIdList.push_back(VFuncId);
10867 for (
auto I : IdToIndexMap) {
10868 auto &Ids = ForwardRefTypeIds[
I.first];
10869 for (
auto P :
I.second) {
10870 assert(VFuncIdList[
P.first].GUID == 0 &&
10871 "Forward referenced type id GUID expected to be 0");
10872 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10881bool LLParser::parseConstVCallList(
10883 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10884 assert(Lex.getKind() == Kind);
10891 IdToIndexMapType IdToIndexMap;
10893 FunctionSummary::ConstVCall ConstVCall;
10894 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10896 ConstVCallList.push_back(ConstVCall);
10904 for (
auto I : IdToIndexMap) {
10905 auto &Ids = ForwardRefTypeIds[
I.first];
10906 for (
auto P :
I.second) {
10907 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10908 "Forward referenced type id GUID expected to be 0");
10909 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10918bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10919 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10921 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
10925 if (parseArgs(ConstVCall.
Args))
10937bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10938 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10948 unsigned ID = Lex.getUIntVal();
10949 LocTy Loc = Lex.getLoc();
10953 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
10955 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
10957 parseUInt64(VFuncId.
GUID))
10963 parseUInt64(VFuncId.
Offset) ||
10975bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10985 switch (Lex.getKind()) {
10992 assert(HasLinkage &&
"Linkage not optional in summary entry");
10999 parseOptionalVisibility(Flag);
11004 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11010 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11016 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11022 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11031 if (parseOptionalImportType(Lex.getKind(), IK))
11033 GVFlags.
ImportType =
static_cast<unsigned>(IK);
11038 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11043 return error(Lex.getLoc(),
"expected gv flag type");
11057bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11065 auto ParseRest = [
this](
unsigned int &Val) {
11069 return parseFlag(Val);
11074 switch (Lex.getKind()) {
11075 case lltok::kw_readonly:
11076 if (ParseRest(Flag))
11080 case lltok::kw_writeonly:
11081 if (ParseRest(Flag))
11086 if (ParseRest(Flag))
11091 if (ParseRest(Flag))
11096 return error(Lex.getLoc(),
"expected gvar flag type");
11104bool LLParser::parseModuleReference(StringRef &ModulePath) {
11111 unsigned ModuleID = Lex.getUIntVal();
11112 auto I = ModuleIdMap.find(ModuleID);
11114 assert(
I != ModuleIdMap.end());
11115 ModulePath =
I->second;
11121bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11124 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11128 GVId = Lex.getUIntVal();
11130 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11132 VI = NumberedValueInfos[GVId];
11149bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11153 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11165 SmallVector<uint8_t> Versions;
11168 if (parseAllocType(V))
11173 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11177 std::vector<MIBInfo> MIBs;
11178 if (parseMemProfs(MIBs))
11181 Allocs.push_back({Versions, MIBs});
11198bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11202 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11208 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11217 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11223 SmallVector<unsigned> StackIdIndices;
11227 uint64_t StackId = 0;
11228 if (parseUInt64(StackId))
11230 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11251bool LLParser::parseAllocType(uint8_t &
AllocType) {
11252 switch (Lex.getKind()) {
11259 case lltok::kw_cold:
11262 case lltok::kw_hot:
11266 return error(Lex.getLoc(),
"invalid alloc type");
11279bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11283 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11287 IdToIndexMapType IdToIndexMap;
11290 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11297 LocTy Loc = Lex.getLoc();
11299 if (parseGVReference(VI, GVId))
11303 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11309 SmallVector<unsigned> Clones;
11312 if (parseUInt32(V))
11318 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11324 SmallVector<unsigned> StackIdIndices;
11328 uint64_t StackId = 0;
11329 if (parseUInt64(StackId))
11331 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11342 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11343 Callsites.push_back({
VI, Clones, StackIdIndices});
11351 for (
auto I : IdToIndexMap) {
11352 auto &Infos = ForwardRefValueInfos[
I.first];
11353 for (
auto P :
I.second) {
11355 "Forward referenced ValueInfo expected to be empty");
11356 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11360 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...
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.
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ULT
1 1 0 0 True if unordered or less than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
@ ICMP_SGE
signed greater or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
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, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
static constexpr ElementCount getFixed(ScalarTy MinVal)
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind getKind() const
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
LLVMContext & getContext()
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
static MemoryEffectsBase readOnly()
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static auto targetMemLocations()
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
bool isTargetMemLoc(IRMemLocation Loc) const
Whether location is target memory location.
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
A Module instance is used to store all the information related to an LLVM module.
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
constexpr const char * getPointer() const
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator find(StringRef Key)
StringMapIterBase< Comdat, false > iterator
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - 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 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 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 getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys)
Gets the overload types of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
@ kw_aarch64_sme_preservemost_from_x1
@ kw_no_sanitize_hwaddress
@ kw_cheriot_librarycallcc
@ kw_cheriot_compartmentcalleecc
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_cheriot_compartmentcallcc
@ kw_amdgpu_gfx_whole_wave
@ kw_typeTestAssumeConstVCalls
@ kw_typeidCompatibleVTable
@ kw_typeCheckedLoadVCalls
@ kw_inaccessiblemem_or_argmemonly
@ kw_externally_initialized
@ kw_sanitize_address_dyninit
@ kw_amdgpu_cs_chain_preserve
@ kw_available_externally
@ kw_typeTestAssumeVCalls
@ kw_aarch64_sme_preservemost_from_x0
@ kw_dso_local_equivalent
@ kw_aarch64_sme_preservemost_from_x2
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
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.
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto dyn_cast_or_null(const Y &Val)
@ Async
"Asynchronous" unwind tables (instr precise)
@ Sync
"Synchronous" unwind tables
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
FunctionAddr VTableAddr Count
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
CaptureComponents
Components of the pointer that may be captured.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
IRMemLocation
The locations at which a function might access memory.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
bool capturesNothing(CaptureComponents CC)
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getInvalid()
static constexpr DenormalMode getIEEE()
std::vector< uint64_t > Args
unsigned ReturnDoesNotAlias
unsigned MustBeUnreachable
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned NoRenameOnPromotion
This field is written by the ThinLTO prelink stage to decide whether a particular static global value...
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
std::map< unsigned, Type * > Types
StringMap< Type * > NamedTypes
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
NumberedValues< GlobalValue * > GlobalValues
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.