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");
344 std::string ErrorMsg;
345 raw_string_ostream ErrorOS(ErrorMsg);
359 return error(
Info.second,
"unknown intrinsic '" + Name +
"'");
370 Info.first->eraseFromParent();
371 ForwardRefVals.erase(Name);
380 auto GetCommonFunctionType = [](
Value *
V) -> FunctionType * {
381 FunctionType *FTy =
nullptr;
382 for (Use &U :
V->uses()) {
384 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
386 FTy = CB->getFunctionType();
394 Type *Ty = GetCommonFunctionType(
Info.first);
402 GV =
new GlobalVariable(*M, Ty,
false,
405 Info.first->replaceAllUsesWith(GV);
406 Info.first->eraseFromParent();
407 ForwardRefVals.erase(Name);
410 if (!ForwardRefVals.empty())
411 return error(ForwardRefVals.begin()->second.second,
412 "use of undefined value '@" + ForwardRefVals.begin()->first +
415 if (!ForwardRefValIDs.empty())
416 return error(ForwardRefValIDs.begin()->second.second,
417 "use of undefined value '@" +
418 Twine(ForwardRefValIDs.begin()->first) +
"'");
421 dropUnknownMetadataReferences();
423 if (!ForwardRefMDNodes.empty())
424 return error(ForwardRefMDNodes.begin()->second.second,
425 "use of undefined metadata '!" +
426 Twine(ForwardRefMDNodes.begin()->first) +
"'");
429 for (
auto &
N : NumberedMetadata) {
430 if (
N.second && !
N.second->isResolved())
431 N.second->resolveCycles();
435 NewDistinctSPs.clear();
437 for (
auto *Inst : InstsWithTBAATag) {
438 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
441 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
444 if (MD != UpgradedMD)
445 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
454 if (UpgradeDebugInfo)
467 Slots->GlobalValues = std::move(NumberedVals);
468 Slots->MetadataNodes = std::move(NumberedMetadata);
469 for (
const auto &
I : NamedTypes)
470 Slots->NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
471 for (
const auto &
I : NumberedTypes)
472 Slots->Types.insert(std::make_pair(
I.first,
I.second.first));
478bool LLParser::validateEndOfIndex() {
482 if (!ForwardRefValueInfos.empty())
483 return error(ForwardRefValueInfos.begin()->second.front().second,
484 "use of undefined summary '^" +
485 Twine(ForwardRefValueInfos.begin()->first) +
"'");
487 if (!ForwardRefAliasees.empty())
488 return error(ForwardRefAliasees.begin()->second.front().second,
489 "use of undefined summary '^" +
490 Twine(ForwardRefAliasees.begin()->first) +
"'");
492 if (!ForwardRefTypeIds.empty())
493 return error(ForwardRefTypeIds.begin()->second.front().second,
494 "use of undefined type id summary '^" +
495 Twine(ForwardRefTypeIds.begin()->first) +
"'");
509 std::string TentativeDLStr = M->getDataLayoutStr();
514 switch (Lex.getKind()) {
516 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
520 if (parseSourceFileName())
529 if (
auto LayoutOverride =
530 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
531 TentativeDLStr = *LayoutOverride;
537 M->setDataLayout(MaybeDL.
get());
541bool LLParser::parseTopLevelEntities() {
545 switch (Lex.getKind()) {
549 if (parseSummaryEntry())
553 if (parseSourceFileName())
563 switch (Lex.getKind()) {
565 return tokError(
"expected top-level entity");
576 if (parseModuleAsm())
580 if (parseUnnamedType())
584 if (parseNamedType())
588 if (parseUnnamedGlobal())
592 if (parseNamedGlobal())
597 if (parseStandaloneMetadata())
601 if (parseSummaryEntry())
605 if (parseNamedMetadata())
609 if (parseUnnamedAttrGrp())
613 if (parseUseListOrder())
617 if (parseUseListOrderBB())
626bool LLParser::parseModuleAsm() {
632 parseStringConstant(AsmStr))
635 M->appendModuleInlineAsm(AsmStr);
642bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
648 return tokError(
"unknown target property");
651 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
652 parseStringConstant(Str))
654 M->setTargetTriple(Triple(std::move(Str)));
658 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
660 DLStrLoc = Lex.getLoc();
661 if (parseStringConstant(TentativeDLStr))
669bool LLParser::parseSourceFileName() {
672 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
673 parseStringConstant(SourceFileName))
676 M->setSourceFileName(SourceFileName);
682bool LLParser::parseUnnamedType() {
683 LocTy TypeLoc = Lex.getLoc();
684 unsigned TypeID = Lex.getUIntVal();
687 if (parseToken(
lltok::equal,
"expected '=' after name") ||
692 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
696 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
698 return error(TypeLoc,
"non-struct types may not be recursive");
700 Entry.second = SMLoc();
708bool LLParser::parseNamedType() {
709 std::string
Name = Lex.getStrVal();
710 LocTy NameLoc = Lex.getLoc();
713 if (parseToken(
lltok::equal,
"expected '=' after name") ||
718 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
722 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
724 return error(NameLoc,
"non-struct types may not be recursive");
726 Entry.second = SMLoc();
734bool LLParser::parseDeclare() {
738 std::vector<std::pair<unsigned, MDNode *>> MDs;
742 if (parseMetadataAttachment(MDK,
N))
744 MDs.push_back({MDK,
N});
748 unsigned FunctionNumber = -1;
749 SmallVector<unsigned> UnnamedArgNums;
750 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
753 F->addMetadata(MD.first, *MD.second);
759bool LLParser::parseDefine() {
762 FileLoc FunctionStart = getTokLineColumnPos();
766 unsigned FunctionNumber = -1;
767 SmallVector<unsigned> UnnamedArgNums;
769 parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
770 parseOptionalFunctionMetadata(*
F) ||
771 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
773 ParserContext->addFunctionLocation(
774 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
782bool LLParser::parseGlobalType(
bool &IsConstant) {
789 return tokError(
"expected 'global' or 'constant'");
795bool LLParser::parseOptionalUnnamedAddr(
816bool LLParser::parseUnnamedGlobal() {
819 LocTy NameLoc = Lex.getLoc();
823 VarID = Lex.getUIntVal();
824 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
828 if (parseToken(
lltok::equal,
"expected '=' after name"))
831 VarID = NumberedVals.getNext();
835 unsigned Linkage, Visibility, DLLStorageClass;
839 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
841 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
844 switch (Lex.getKind()) {
846 return parseGlobal(Name,
VarID, NameLoc,
Linkage, HasLinkage, Visibility,
847 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
850 return parseAliasOrIFunc(Name,
VarID, NameLoc,
Linkage, Visibility,
851 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
860bool LLParser::parseNamedGlobal() {
862 LocTy NameLoc = Lex.getLoc();
863 std::string
Name = Lex.getStrVal();
867 unsigned Linkage, Visibility, DLLStorageClass;
871 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
872 parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
874 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
877 switch (Lex.getKind()) {
879 return parseGlobal(Name, -1, NameLoc,
Linkage, HasLinkage, Visibility,
880 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
883 return parseAliasOrIFunc(Name, -1, NameLoc,
Linkage, Visibility,
884 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
888bool LLParser::parseComdat() {
890 std::string
Name = Lex.getStrVal();
891 LocTy NameLoc = Lex.getLoc();
898 return tokError(
"expected comdat type");
901 switch (Lex.getKind()) {
903 return tokError(
"unknown selection kind");
925 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
926 return error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
929 if (
I != ComdatSymTab.
end())
932 C = M->getOrInsertComdat(Name);
933 C->setSelectionKind(SK);
940bool LLParser::parseMDString(
MDString *&Result) {
942 if (parseStringConstant(Str))
950bool LLParser::parseMDNodeID(
MDNode *&Result) {
952 LocTy IDLoc = Lex.getLoc();
954 if (parseUInt32(MID))
958 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
965 auto &FwdRef = ForwardRefMDNodes[MID];
968 Result = FwdRef.first.get();
969 It->second.reset(Result);
975bool LLParser::parseNamedMetadata() {
977 std::string
Name = Lex.getStrVal();
985 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
993 Lex.getStrVal() ==
"DIExpression") {
994 if (parseDIExpression(
N,
false))
999 Lex.getStrVal() ==
"DIArgList") {
1000 return tokError(
"found DIArgList outside of function");
1008 return parseToken(
lltok::rbrace,
"expected end of metadata node");
1013bool LLParser::parseStandaloneMetadata() {
1016 unsigned MetadataID = 0;
1019 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1024 return tokError(
"unexpected type in metadata definition");
1028 if (parseSpecializedMDNode(Init, IsDistinct))
1031 parseMDTuple(Init, IsDistinct))
1035 auto FI = ForwardRefMDNodes.find(MetadataID);
1036 if (FI != ForwardRefMDNodes.end()) {
1037 auto *ToReplace = FI->second.first.get();
1041 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1042 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1043 "Inst unexpectedly already has DIAssignID attachment");
1044 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1048 ToReplace->replaceAllUsesWith(Init);
1049 ForwardRefMDNodes.erase(FI);
1051 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
1053 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1055 return tokError(
"Metadata id is already used");
1056 It->second.reset(Init);
1063bool LLParser::skipModuleSummaryEntry() {
1073 return tokError(
"Expected 'gv', 'module', 'typeid', "
1074 "'typeidCompatibleVTable', 'flags' or 'blockcount' at the "
1075 "start of summary entry");
1077 return parseSummaryIndexFlags();
1079 return parseBlockCount();
1081 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1082 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1086 unsigned NumOpenParen = 1;
1088 switch (Lex.getKind()) {
1096 return tokError(
"found end of file while parsing summary entry");
1102 }
while (NumOpenParen > 0);
1108bool LLParser::parseSummaryEntry() {
1114 Lex.setIgnoreColonInIdentifiers(
true);
1122 return skipModuleSummaryEntry();
1124 bool result =
false;
1125 switch (Lex.getKind()) {
1127 result = parseGVEntry(SummaryID);
1130 result = parseModuleEntry(SummaryID);
1133 result = parseTypeIdEntry(SummaryID);
1136 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1139 result = parseSummaryIndexFlags();
1142 result = parseBlockCount();
1145 result =
error(Lex.getLoc(),
"unexpected summary kind");
1148 Lex.setIgnoreColonInIdentifiers(
false);
1182bool LLParser::parseAliasOrIFunc(
const std::string &Name,
unsigned NameID,
1183 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1184 unsigned DLLStorageClass,
bool DSOLocal,
1199 return error(NameLoc,
"invalid linkage type for alias");
1202 return error(NameLoc,
1203 "symbol with local linkage must have default visibility");
1206 return error(NameLoc,
1207 "symbol with local linkage cannot have a DLL storage class");
1210 LocTy ExplicitTypeLoc = Lex.getLoc();
1211 if (parseType(Ty) ||
1212 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1216 LocTy AliaseeLoc = Lex.getLoc();
1221 if (parseGlobalTypeAndValue(Aliasee))
1226 if (parseValID(
ID,
nullptr))
1229 return error(AliaseeLoc,
"invalid aliasee");
1230 Aliasee =
ID.ConstantVal;
1236 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1237 unsigned AddrSpace = PTy->getAddressSpace();
1239 GlobalValue *GVal =
nullptr;
1243 if (!
Name.empty()) {
1244 auto I = ForwardRefVals.find(Name);
1245 if (
I != ForwardRefVals.end()) {
1246 GVal =
I->second.first;
1247 ForwardRefVals.erase(Name);
1248 }
else if (M->getNamedValue(Name)) {
1249 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1252 auto I = ForwardRefValIDs.find(NameID);
1253 if (
I != ForwardRefValIDs.end()) {
1254 GVal =
I->second.first;
1255 ForwardRefValIDs.erase(
I);
1260 std::unique_ptr<GlobalAlias> GA;
1261 std::unique_ptr<GlobalIFunc> GI;
1289 if (parseGlobalObjectMetadataAttachment(*GI))
1292 return tokError(
"unknown alias or ifunc property!");
1297 NumberedVals.add(NameID, GV);
1304 "forward reference and definition of alias have different types");
1314 M->insertAlias(GA.release());
1316 M->insertIFunc(GI.release());
1317 assert(GV->
getName() == Name &&
"Should not be a name conflict!");
1326 case lltok::kw_sanitize_memtag:
1340 switch (Lex.getKind()) {
1342 Meta.NoAddress =
true;
1345 Meta.NoHWAddress =
true;
1347 case lltok::kw_sanitize_memtag:
1351 Meta.IsDynInit =
true;
1354 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1374bool LLParser::parseGlobal(
const std::string &Name,
unsigned NameID,
1375 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1376 unsigned Visibility,
unsigned DLLStorageClass,
1380 return error(NameLoc,
1381 "symbol with local linkage must have default visibility");
1384 return error(NameLoc,
1385 "symbol with local linkage cannot have a DLL storage class");
1389 LocTy IsExternallyInitializedLoc;
1393 if (parseOptionalAddrSpace(AddrSpace) ||
1395 IsExternallyInitialized,
1396 &IsExternallyInitializedLoc) ||
1397 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1406 if (parseGlobalValue(Ty, Init))
1411 return error(TyLoc,
"invalid type for global variable");
1413 GlobalValue *GVal =
nullptr;
1416 if (!
Name.empty()) {
1417 auto I = ForwardRefVals.find(Name);
1418 if (
I != ForwardRefVals.end()) {
1419 GVal =
I->second.first;
1420 ForwardRefVals.erase(
I);
1421 }
else if (M->getNamedValue(Name)) {
1422 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1427 if (NameID == (
unsigned)-1)
1428 NameID = NumberedVals.getNext();
1430 auto I = ForwardRefValIDs.find(NameID);
1431 if (
I != ForwardRefValIDs.end()) {
1432 GVal =
I->second.first;
1433 ForwardRefValIDs.erase(
I);
1437 GlobalVariable *GV =
new GlobalVariable(
1442 NumberedVals.add(NameID, GV);
1460 "forward reference and definition of global have different types");
1480 }
else if (Lex.getKind() == lltok::kw_align) {
1481 MaybeAlign Alignment;
1482 if (parseOptionalAlignment(Alignment))
1488 if (parseOptionalCodeModel(CodeModel))
1492 if (parseGlobalObjectMetadataAttachment(*GV))
1495 if (parseSanitizer(GV))
1499 if (parseOptionalComdat(Name,
C))
1504 return tokError(
"unknown global variable property!");
1508 AttrBuilder
Attrs(M->getContext());
1510 std::vector<unsigned> FwdRefAttrGrps;
1511 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1513 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1515 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1523bool LLParser::parseUnnamedAttrGrp() {
1525 LocTy AttrGrpLoc = Lex.getLoc();
1529 return tokError(
"expected attribute group id");
1531 unsigned VarID = Lex.getUIntVal();
1532 std::vector<unsigned> unused;
1540 auto R = NumberedAttrBuilders.find(
VarID);
1541 if (R == NumberedAttrBuilders.end())
1542 R = NumberedAttrBuilders.emplace(
VarID, AttrBuilder(M->getContext())).first;
1544 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1545 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1548 if (!
R->second.hasAttributes())
1549 return error(AttrGrpLoc,
"attribute group has no attributes");
1556#define GET_ATTR_NAMES
1557#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1558 case lltok::kw_##DISPLAY_NAME: \
1559 return Attribute::ENUM_NAME;
1560#include "llvm/IR/Attributes.inc"
1569 return parseRequiredTypeAttr(
B, Lex.getKind(), Attr);
1572 case Attribute::Alignment: {
1573 MaybeAlign Alignment;
1581 if (parseOptionalAlignment(Alignment,
true))
1584 B.addAlignmentAttr(Alignment);
1587 case Attribute::StackAlignment: {
1592 parseUInt32(Alignment))
1595 if (parseOptionalStackAlignment(Alignment))
1598 B.addStackAlignmentAttr(Alignment);
1601 case Attribute::AllocSize: {
1602 unsigned ElemSizeArg;
1603 std::optional<unsigned> NumElemsArg;
1604 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1606 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1609 case Attribute::VScaleRange: {
1610 unsigned MinValue, MaxValue;
1611 if (parseVScaleRangeArguments(MinValue, MaxValue))
1613 B.addVScaleRangeAttr(MinValue,
1614 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1617 case Attribute::Dereferenceable: {
1618 std::optional<uint64_t> Bytes;
1619 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1621 assert(Bytes.has_value());
1622 B.addDereferenceableAttr(Bytes.value());
1625 case Attribute::DeadOnReturn: {
1626 std::optional<uint64_t> Bytes;
1627 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1630 if (Bytes.has_value()) {
1631 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1633 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1637 case Attribute::DereferenceableOrNull: {
1638 std::optional<uint64_t> Bytes;
1639 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1641 assert(Bytes.has_value());
1642 B.addDereferenceableOrNullAttr(Bytes.value());
1645 case Attribute::UWTable: {
1647 if (parseOptionalUWTableKind(Kind))
1649 B.addUWTableAttr(Kind);
1652 case Attribute::AllocKind: {
1654 if (parseAllocKind(Kind))
1656 B.addAllocKindAttr(Kind);
1659 case Attribute::Memory: {
1660 std::optional<MemoryEffects> ME = parseMemoryAttr();
1663 B.addMemoryAttr(*ME);
1666 case Attribute::DenormalFPEnv: {
1667 std::optional<DenormalFPEnv>
Mode = parseDenormalFPEnvAttr();
1671 B.addDenormalFPEnvAttr(*
Mode);
1674 case Attribute::NoFPClass: {
1677 B.addNoFPClassAttr(NoFPClass);
1683 case Attribute::Range:
1684 return parseRangeAttr(
B);
1685 case Attribute::Initializes:
1686 return parseInitializesAttr(
B);
1687 case Attribute::Captures:
1688 return parseCapturesAttr(
B);
1690 B.addAttribute(Attr);
1698 case lltok::kw_readnone:
1701 case lltok::kw_readonly:
1704 case lltok::kw_writeonly:
1723bool LLParser::parseFnAttributeValuePairs(AttrBuilder &
B,
1724 std::vector<unsigned> &FwdRefAttrGrps,
1725 bool InAttrGrp, LocTy &BuiltinLoc) {
1726 bool HaveError =
false;
1737 if (parseStringAttribute(
B))
1749 "cannot have an attribute group reference in an attribute group");
1752 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1758 SMLoc Loc = Lex.getLoc();
1759 if (Token == lltok::kw_builtin)
1771 return error(Lex.getLoc(),
"unterminated attribute group");
1774 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1781 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1785 B.addMemoryAttr(ME);
1799 PTy->getAddressSpace());
1808 error(Loc,
"'" + Name +
"' is not a basic block");
1810 error(Loc,
"'" + Name +
"' defined with type '" +
1823 error(Loc,
"global variable reference must have pointer type");
1834 auto I = ForwardRefVals.find(Name);
1835 if (
I != ForwardRefVals.end())
1836 Val =
I->second.first;
1842 checkValidVariableType(Loc,
"@" + Name, Ty, Val));
1846 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1853 error(Loc,
"global variable reference must have pointer type");
1857 GlobalValue *Val = NumberedVals.get(
ID);
1862 auto I = ForwardRefValIDs.find(
ID);
1863 if (
I != ForwardRefValIDs.end())
1864 Val =
I->second.first;
1870 checkValidVariableType(Loc,
"@" + Twine(
ID), Ty, Val));
1874 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1882Comdat *LLParser::getComdat(
const std::string &Name, LocTy
Loc) {
1886 if (
I != ComdatSymTab.
end())
1890 Comdat *
C = M->getOrInsertComdat(Name);
1891 ForwardRefComdats[
Name] = Loc;
1901bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
1902 if (Lex.getKind() !=
T)
1903 return tokError(ErrMsg);
1910bool LLParser::parseStringConstant(std::string &Result) {
1912 return tokError(
"expected string constant");
1913 Result = Lex.getStrVal();
1920bool LLParser::parseUInt32(uint32_t &Val) {
1921 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1922 return tokError(
"expected integer");
1923 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1924 if (Val64 !=
unsigned(Val64))
1925 return tokError(
"expected 32-bit integer (too large)");
1933bool LLParser::parseUInt64(uint64_t &Val) {
1934 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
1935 return tokError(
"expected integer");
1936 Val = Lex.getAPSIntVal().getLimitedValue();
1946 switch (Lex.getKind()) {
1948 return tokError(
"expected localdynamic, initialexec or localexec");
1976 return parseTLSModel(TLM) ||
1977 parseToken(
lltok::rparen,
"expected ')' after thread local model");
1985bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
1986 AddrSpace = DefaultAS;
1990 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
1992 const std::string &AddrSpaceStr = Lex.getStrVal();
1993 if (AddrSpaceStr ==
"A") {
1994 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1995 }
else if (AddrSpaceStr ==
"G") {
1996 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1997 }
else if (AddrSpaceStr ==
"P") {
1998 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1999 }
else if (std::optional<unsigned> AS =
2000 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2003 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
2009 return tokError(
"expected integer or string constant");
2010 SMLoc Loc = Lex.getLoc();
2011 if (parseUInt32(AddrSpace))
2014 return error(Loc,
"invalid address space, must be a 24-bit integer");
2018 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
2019 ParseAddrspaceValue(AddrSpace) ||
2026bool LLParser::parseStringAttribute(AttrBuilder &
B) {
2027 std::string Attr = Lex.getStrVal();
2030 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
2032 B.addAttribute(Attr, Val);
2037bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &
B,
bool IsParam) {
2038 bool HaveError =
false;
2045 if (parseStringAttribute(
B))
2056 SMLoc Loc = Lex.getLoc();
2061 if (parseEnumAttribute(Attr,
B,
false))
2065 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2067 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2115bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2116 unsigned &Visibility,
2117 unsigned &DLLStorageClass,
bool &DSOLocal) {
2121 parseOptionalDSOLocal(DSOLocal);
2122 parseOptionalVisibility(Visibility);
2123 parseOptionalDLLStorageClass(DLLStorageClass);
2126 return error(Lex.getLoc(),
"dso_location and DLL-StorageClass mismatch");
2132void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2133 switch (Lex.getKind()) {
2154void LLParser::parseOptionalVisibility(
unsigned &Res) {
2155 switch (Lex.getKind()) {
2172bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2176 return tokError(
"unknown import kind. Expect definition or declaration.");
2191void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2192 switch (Lex.getKind()) {
2262bool LLParser::parseOptionalCallingConv(
unsigned &CC) {
2263 switch (Lex.getKind()) {
2350 return tokError(
"unknown RISC-V ABI VLEN");
2351#define CC_VLS_CASE(ABIVlen) \
2353 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2381 return parseUInt32(CC);
2391bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2394 std::string
Name = Lex.getStrVal();
2395 Kind = M->getMDKindID(Name);
2398 return parseMDNode(MD);
2403bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2406 return tokError(
"expected metadata after comma");
2410 if (parseMetadataAttachment(MDK,
N))
2413 if (MDK == LLVMContext::MD_DIAssignID)
2414 TempDIAssignIDAttachments[
N].push_back(&Inst);
2418 if (MDK == LLVMContext::MD_tbaa)
2419 InstsWithTBAATag.push_back(&Inst);
2428bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2431 if (parseMetadataAttachment(MDK,
N))
2440bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2442 if (parseGlobalObjectMetadataAttachment(
F))
2450bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2451 Alignment = std::nullopt;
2452 if (!EatIfPresent(lltok::kw_align))
2454 LocTy AlignLoc = Lex.getLoc();
2457 LocTy ParenLoc = Lex.getLoc();
2458 bool HaveParens =
false;
2464 if (parseUInt64(
Value))
2468 return error(ParenLoc,
"expected ')'");
2471 return error(AlignLoc,
"alignment is not a power of two");
2473 return error(AlignLoc,
"huge alignments are not supported yet");
2481bool LLParser::parseOptionalPrefAlignment(
MaybeAlign &Alignment) {
2482 Alignment = std::nullopt;
2485 LocTy AlignLoc = Lex.getLoc();
2488 LocTy ParenLoc = Lex.getLoc();
2490 return error(ParenLoc,
"expected '('");
2492 if (parseUInt64(
Value))
2495 ParenLoc = Lex.getLoc();
2497 return error(ParenLoc,
"expected ')'");
2500 return error(AlignLoc,
"alignment is not a power of two");
2502 return error(AlignLoc,
"huge alignments are not supported yet");
2512 auto StrVal = Lex.getStrVal();
2513 auto ErrMsg =
"expected global code model string";
2514 if (StrVal ==
"tiny")
2516 else if (StrVal ==
"small")
2518 else if (StrVal ==
"kernel")
2520 else if (StrVal ==
"medium")
2522 else if (StrVal ==
"large")
2525 return tokError(ErrMsg);
2537bool LLParser::parseOptionalAttrBytes(
lltok::Kind AttrKind,
2538 std::optional<uint64_t> &Bytes,
2539 bool ErrorNoBytes) {
2540 assert((AttrKind == lltok::kw_dereferenceable ||
2541 AttrKind == lltok::kw_dereferenceable_or_null ||
2542 AttrKind == lltok::kw_dead_on_return) &&
2546 if (!EatIfPresent(AttrKind))
2548 LocTy ParenLoc = Lex.getLoc();
2551 return error(ParenLoc,
"expected '('");
2552 Bytes = std::nullopt;
2555 LocTy DerefLoc = Lex.getLoc();
2556 if (parseUInt64(Bytes.value()))
2558 ParenLoc = Lex.getLoc();
2560 return error(ParenLoc,
"expected ')'");
2562 return error(DerefLoc,
"byte count specified must be non-zero");
2566bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2571 LocTy KindLoc = Lex.getLoc();
2577 return error(KindLoc,
"expected unwind table kind");
2584 LocTy ParenLoc = Lex.getLoc();
2586 return error(ParenLoc,
"expected '('");
2587 LocTy KindLoc = Lex.getLoc();
2589 if (parseStringConstant(Arg))
2590 return error(KindLoc,
"expected allockind value");
2594 }
else if (
A ==
"realloc") {
2596 }
else if (
A ==
"free") {
2598 }
else if (
A ==
"uninitialized") {
2600 }
else if (
A ==
"zeroed") {
2602 }
else if (
A ==
"aligned") {
2605 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2608 ParenLoc = Lex.getLoc();
2610 return error(ParenLoc,
"expected ')'");
2612 return error(KindLoc,
"expected allockind value");
2621 return {Loc::ArgMem};
2623 return {Loc::InaccessibleMem};
2625 return {Loc::ErrnoMem};
2627 return {Loc::TargetMem0};
2629 return {Loc::TargetMem1};
2652 return std::nullopt;
2656static std::optional<DenormalMode::DenormalModeKind>
2668 return std::nullopt;
2672std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2677 Lex.setIgnoreColonInIdentifiers(
true);
2682 tokError(
"expected '('");
2683 return std::nullopt;
2686 bool SeenLoc =
false;
2687 bool SeenTargetLoc =
false;
2690 if (!Locs.
empty()) {
2693 tokError(
"expected ':' after location");
2694 return std::nullopt;
2701 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2702 "or access kind (none, read, write, readwrite)");
2704 tokError(
"expected access kind (none, read, write, readwrite)");
2705 return std::nullopt;
2709 if (!Locs.
empty()) {
2714 SeenTargetLoc =
true;
2716 if (Locs.size() > 1 && SeenTargetLoc) {
2717 tokError(
"target memory default access kind must be specified first");
2718 return std::nullopt;
2723 tokError(
"default access kind must be specified first");
2724 return std::nullopt;
2733 tokError(
"unterminated memory attribute");
2734 return std::nullopt;
2737std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2738 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2741 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2742 "positivezero, dynamic)");
2748 std::optional<DenormalMode::DenormalModeKind> InputMode;
2752 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2753 "positivezero, dynamic)");
2760 InputMode = OutputMode;
2763 return DenormalMode(*OutputMode, *InputMode);
2766std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2769 Lex.setIgnoreColonInIdentifiers(
true);
2780 bool HasDefaultSection =
false;
2782 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2783 if (!ParsedDefaultMode)
2785 DefaultMode = *ParsedDefaultMode;
2786 HasDefaultSection =
true;
2791 if (HasDefaultSection && !HasComma) {
2792 tokError(
"expected ',' before float:");
2797 if (parseType(Ty) || !Ty->
isFloatTy()) {
2798 tokError(
"expected float:");
2802 if (parseToken(
lltok::colon,
"expected ':' before float denormal_fpenv"))
2805 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2809 F32Mode = *ParsedF32Mode;
2812 if (parseToken(
lltok::rparen,
"unterminated denormal_fpenv"))
2815 return DenormalFPEnv(DefaultMode, F32Mode);
2857unsigned LLParser::parseNoFPClassAttr() {
2862 tokError(
"expected '('");
2869 if (TestMask != 0) {
2873 !parseUInt64(
Value)) {
2875 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
2880 error(Lex.getLoc(),
"expected ')'");
2886 error(Lex.getLoc(),
"expected nofpclass test mask");
2904bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
2905 bool &AteExtraComma) {
2906 AteExtraComma =
false;
2910 AteExtraComma =
true;
2914 if (Lex.getKind() != lltok::kw_align)
2915 return error(Lex.getLoc(),
"expected metadata or 'align'");
2917 if (parseOptionalAlignment(Alignment))
2930bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
2931 bool &AteExtraComma) {
2932 AteExtraComma =
false;
2936 AteExtraComma =
true;
2942 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
2944 if (parseOptionalAddrSpace(AddrSpace))
2951bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
2952 std::optional<unsigned> &HowManyArg) {
2955 auto StartParen = Lex.getLoc();
2957 return error(StartParen,
"expected '('");
2959 if (parseUInt32(BaseSizeArg))
2963 auto HowManyAt = Lex.getLoc();
2965 if (parseUInt32(HowMany))
2967 if (HowMany == BaseSizeArg)
2968 return error(HowManyAt,
2969 "'allocsize' indices can't refer to the same parameter");
2970 HowManyArg = HowMany;
2972 HowManyArg = std::nullopt;
2974 auto EndParen = Lex.getLoc();
2976 return error(EndParen,
"expected ')'");
2980bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
2981 unsigned &MaxValue) {
2984 auto StartParen = Lex.getLoc();
2986 return error(StartParen,
"expected '('");
2988 if (parseUInt32(MinValue))
2992 if (parseUInt32(MaxValue))
2995 MaxValue = MinValue;
2997 auto EndParen = Lex.getLoc();
2999 return error(EndParen,
"expected ')'");
3008bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
3013 return parseScope(SSID) || parseOrdering(Ordering);
3023 auto StartParenAt = Lex.getLoc();
3025 return error(StartParenAt,
"Expected '(' in syncscope");
3028 auto SSNAt = Lex.getLoc();
3029 if (parseStringConstant(SSN))
3030 return error(SSNAt,
"Expected synchronization scope name");
3032 auto EndParenAt = Lex.getLoc();
3034 return error(EndParenAt,
"Expected ')' in syncscope");
3036 SSID = Context.getOrInsertSyncScopeID(SSN);
3047 switch (Lex.getKind()) {
3049 return tokError(
"Expected ordering on atomic instruction");
3068bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
3070 if (!EatIfPresent(lltok::kw_alignstack))
3072 LocTy ParenLoc = Lex.getLoc();
3074 return error(ParenLoc,
"expected '('");
3075 LocTy AlignLoc = Lex.getLoc();
3076 if (parseUInt32(Alignment))
3078 ParenLoc = Lex.getLoc();
3080 return error(ParenLoc,
"expected ')'");
3082 return error(AlignLoc,
"stack alignment is not a power of two");
3096 bool &AteExtraComma) {
3097 AteExtraComma =
false;
3100 return tokError(
"expected ',' as start of index list");
3104 if (Indices.
empty())
3105 return tokError(
"expected index");
3106 AteExtraComma =
true;
3110 if (parseUInt32(Idx))
3123bool LLParser::parseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
3124 SMLoc TypeLoc = Lex.getLoc();
3125 switch (Lex.getKind()) {
3127 return tokError(Msg);
3136 if (
Result->isPointerTy()) {
3138 if (parseOptionalAddrSpace(AddrSpace))
3144 return tokError(
"ptr* is invalid - use ptr instead");
3155 if (parseTargetExtType(Result))
3161 if (parseAnonStructType(Result,
false))
3167 if (parseArrayVectorType(Result,
false))
3174 if (parseAnonStructType(Result,
true) ||
3175 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
3177 }
else if (parseArrayVectorType(Result,
true))
3182 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
3188 Entry.second = Lex.getLoc();
3197 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
3203 Entry.second = Lex.getLoc();
3213 switch (Lex.getKind()) {
3216 if (!AllowVoid &&
Result->isVoidTy())
3217 return error(TypeLoc,
"void type only allowed for function results");
3223 return tokError(
"basic block pointers are invalid");
3225 return tokError(
"pointers to void are invalid - use i8* instead");
3227 return tokError(
"pointer to this type is invalid");
3235 return tokError(
"basic block pointers are invalid");
3237 return tokError(
"pointers to void are invalid; use i8* instead");
3239 return tokError(
"pointer to this type is invalid");
3241 if (parseOptionalAddrSpace(AddrSpace) ||
3242 parseToken(
lltok::star,
"expected '*' in address space"))
3251 if (parseFunctionType(Result))
3264 PerFunctionState &PFS,
bool IsMustTailCall,
3265 bool InVarArgsFunc) {
3271 if (!ArgList.
empty() &&
3272 parseToken(
lltok::comma,
"expected ',' in argument list"))
3277 const char *Msg =
"unexpected ellipsis in argument list for ";
3278 if (!IsMustTailCall)
3279 return tokError(Twine(Msg) +
"non-musttail call");
3281 return tokError(Twine(Msg) +
"musttail call in non-varargs function");
3283 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3288 Type *ArgTy =
nullptr;
3290 if (parseType(ArgTy, ArgLoc))
3293 return error(ArgLoc,
"invalid type for function argument");
3295 AttrBuilder ArgAttrs(M->getContext());
3298 if (parseMetadataAsValue(V, PFS))
3302 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3309 if (IsMustTailCall && InVarArgsFunc)
3310 return tokError(
"expected '...' at end of argument list for musttail call "
3311 "in varargs function");
3319bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3322 if (!EatIfPresent(AttrToken))
3325 return error(Lex.getLoc(),
"expected '('");
3329 return error(Lex.getLoc(),
"expected ')'");
3331 B.addTypeAttr(AttrKind, Ty);
3337bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3345 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3347 return tokError(
"expected integer");
3348 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3350 "integer is too large for the bit width of specified type");
3351 Val = Lex.getAPSIntVal().extend(
BitWidth);
3356 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3359 return error(TyLoc,
"the range must have integer type!");
3367 return tokError(
"the range represent the empty set but limits aren't 0!");
3378bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3381 auto ParseAPSInt = [&](APInt &Val) {
3383 return tokError(
"expected integer");
3384 Val = Lex.getAPSIntVal().extend(64);
3404 return tokError(
"the range should not represent the full or empty set!");
3416 if (!CRLOrNull.has_value())
3417 return tokError(
"Invalid (unordered or overlapping) range list");
3418 B.addInitializesAttr(*CRLOrNull);
3422bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3424 std::optional<CaptureComponents> Ret;
3428 Lex.setIgnoreColonInIdentifiers(
true);
3436 bool SeenComponent =
false;
3442 return tokError(
"duplicate 'ret' location");
3445 SeenComponent =
false;
3450 return tokError(
"cannot use 'none' with other component");
3454 return tokError(
"cannot use 'none' with other component");
3465 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3466 "'provenance' or 'read_provenance'");
3469 SeenComponent =
true;
3477 B.addCapturesAttr(CaptureInfo(
Other, Ret.value_or(
Other)));
3490bool LLParser::parseOptionalOperandBundles(
3492 LocTy BeginLoc = Lex.getLoc();
3498 if (!BundleList.
empty() &&
3499 parseToken(
lltok::comma,
"expected ',' in input list"))
3503 if (parseStringConstant(
Tag))
3506 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3509 std::vector<Value *> Inputs;
3512 if (!Inputs.empty() &&
3513 parseToken(
lltok::comma,
"expected ',' in input list"))
3517 Value *Input =
nullptr;
3521 if (parseMetadataAsValue(Input, PFS))
3523 }
else if (parseValue(Ty, Input, PFS)) {
3526 Inputs.push_back(Input);
3534 if (BundleList.
empty())
3535 return error(BeginLoc,
"operand bundle set must not be empty");
3542 unsigned NextID,
unsigned ID) {
3544 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3545 Twine(NextID) +
"' or greater");
3562 unsigned CurValID = 0;
3576 LocTy TypeLoc = Lex.getLoc();
3577 Type *ArgTy =
nullptr;
3578 AttrBuilder
Attrs(M->getContext());
3579 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3583 return error(TypeLoc,
"argument can not have void type");
3588 bool Unnamed =
false;
3590 Name = Lex.getStrVal();
3591 IdentStart = getTokLineColumnPos();
3593 IdentEnd = getPrevTokEndLineColumnPos();
3597 ArgID = Lex.getUIntVal();
3598 IdentStart = getTokLineColumnPos();
3599 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3602 IdentEnd = getPrevTokEndLineColumnPos();
3608 CurValID = ArgID + 1;
3612 return error(TypeLoc,
"invalid type for function argument");
3616 Unnamed ? std::nullopt
3617 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3622 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3627bool LLParser::parseFunctionType(
Type *&Result) {
3631 return tokError(
"invalid function return type");
3635 SmallVector<unsigned> UnnamedArgNums;
3636 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3640 for (
const ArgInfo &Arg : ArgList) {
3641 if (!Arg.Name.empty())
3642 return error(Arg.Loc,
"argument name invalid in function type");
3643 if (Arg.Attrs.hasAttributes())
3644 return error(Arg.Loc,
"argument attributes invalid in function type");
3648 for (
const ArgInfo &Arg : ArgList)
3657bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3659 if (parseStructBody(Elts))
3667bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3668 std::pair<Type *, LocTy> &Entry,
3672 return error(TypeLoc,
"redefinition of type");
3678 Entry.second = SMLoc();
3683 ResultTy =
Entry.first;
3695 return error(TypeLoc,
"forward references to non-struct type");
3699 return parseArrayVectorType(ResultTy,
true);
3700 return parseType(ResultTy);
3704 Entry.second = SMLoc();
3713 if (parseStructBody(Body) ||
3714 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3718 return tokError(
toString(std::move(
E)));
3738 LocTy EltTyLoc = Lex.getLoc();
3745 return error(EltTyLoc,
"invalid element type for struct");
3748 EltTyLoc = Lex.getLoc();
3753 return error(EltTyLoc,
"invalid element type for struct");
3758 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3767bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3768 bool Scalable =
false;
3772 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3778 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3779 Lex.getAPSIntVal().getBitWidth() > 64)
3780 return tokError(
"expected number in address space");
3782 LocTy SizeLoc = Lex.getLoc();
3783 uint64_t
Size = Lex.getAPSIntVal().getZExtValue();
3786 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3789 LocTy TypeLoc = Lex.getLoc();
3790 Type *EltTy =
nullptr;
3791 if (parseType(EltTy))
3795 "expected end of sequential type"))
3800 return error(SizeLoc,
"zero element vector is illegal");
3802 return error(SizeLoc,
"size too large for vector");
3804 return error(TypeLoc,
"invalid vector element type");
3808 return error(TypeLoc,
"invalid array element type");
3825bool LLParser::parseTargetExtType(
Type *&Result) {
3830 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3831 parseStringConstant(TypeName))
3838 SmallVector<unsigned> IntParams;
3839 bool SeenInt =
false;
3846 if (parseUInt32(IntVal))
3849 }
else if (SeenInt) {
3852 return tokError(
"expected uint32 param");
3855 if (parseType(TypeParam,
true))
3861 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3866 if (
auto E = TTy.takeError())
3867 return tokError(
toString(std::move(
E)));
3880 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
3883 auto It = UnnamedArgNums.
begin();
3886 unsigned ArgNum = *It++;
3887 NumberedVals.add(ArgNum, &A);
3892LLParser::PerFunctionState::~PerFunctionState() {
3895 for (
const auto &P : ForwardRefVals) {
3898 P.second.first->replaceAllUsesWith(
3900 P.second.first->deleteValue();
3903 for (
const auto &P : ForwardRefValIDs) {
3906 P.second.first->replaceAllUsesWith(
3908 P.second.first->deleteValue();
3912bool LLParser::PerFunctionState::finishFunction() {
3913 if (!ForwardRefVals.empty())
3914 return P.error(ForwardRefVals.begin()->second.second,
3915 "use of undefined value '%" + ForwardRefVals.begin()->first +
3917 if (!ForwardRefValIDs.empty())
3918 return P.error(ForwardRefValIDs.begin()->second.second,
3919 "use of undefined value '%" +
3920 Twine(ForwardRefValIDs.begin()->first) +
"'");
3927Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
3930 Value *Val =
F.getValueSymbolTable()->lookup(Name);
3935 auto I = ForwardRefVals.find(Name);
3936 if (
I != ForwardRefVals.end())
3937 Val =
I->second.first;
3942 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
3946 P.error(Loc,
"invalid use of a non-first-class type");
3957 if (FwdVal->
getName() != Name) {
3958 P.error(Loc,
"name is too long which can result in name collisions, "
3959 "consider making the name shorter or "
3960 "increasing -non-global-value-max-name-size");
3964 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
3968Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
3970 Value *Val = NumberedVals.get(
ID);
3975 auto I = ForwardRefValIDs.find(
ID);
3976 if (
I != ForwardRefValIDs.end())
3977 Val =
I->second.first;
3982 return P.checkValidVariableType(Loc,
"%" + Twine(
ID), Ty, Val);
3985 P.error(Loc,
"invalid use of a non-first-class type");
3997 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
4003bool LLParser::PerFunctionState::setInstName(
int NameID,
4004 const std::string &NameStr,
4005 LocTy NameLoc, Instruction *Inst) {
4008 if (NameID != -1 || !NameStr.empty())
4009 return P.error(NameLoc,
"instructions returning void cannot have a name");
4015 if (NameStr.empty()) {
4018 NameID = NumberedVals.getNext();
4020 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
4024 auto FI = ForwardRefValIDs.find(NameID);
4025 if (FI != ForwardRefValIDs.end()) {
4028 return P.error(NameLoc,
"instruction forward referenced with type '" +
4032 Sentinel->replaceAllUsesWith(Inst);
4034 ForwardRefValIDs.erase(FI);
4037 NumberedVals.add(NameID, Inst);
4042 auto FI = ForwardRefVals.find(NameStr);
4043 if (FI != ForwardRefVals.end()) {
4046 return P.error(NameLoc,
"instruction forward referenced with type '" +
4050 Sentinel->replaceAllUsesWith(Inst);
4052 ForwardRefVals.erase(FI);
4058 if (Inst->
getName() != NameStr)
4059 return P.error(NameLoc,
"multiple definition of local value named '" +
4066BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
4080BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
4081 int NameID,
LocTy Loc) {
4085 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
4088 NameID = NumberedVals.getNext();
4090 BB = getBB(NameID, Loc);
4092 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
4096 BB = getBB(Name, Loc);
4098 P.error(Loc,
"unable to create block named '" + Name +
"'");
4109 ForwardRefValIDs.erase(NameID);
4110 NumberedVals.add(NameID, BB);
4113 ForwardRefVals.erase(Name);
4130bool LLParser::parseValID(ValID &
ID, PerFunctionState *PFS,
Type *ExpectedTy) {
4131 ID.Loc = Lex.getLoc();
4132 switch (Lex.getKind()) {
4134 return tokError(
"expected value token");
4136 ID.UIntVal = Lex.getUIntVal();
4140 ID.StrVal = Lex.getStrVal();
4144 ID.UIntVal = Lex.getUIntVal();
4148 ID.StrVal = Lex.getStrVal();
4152 ID.APSIntVal = Lex.getAPSIntVal();
4156 ID.APFloatVal = Lex.getAPFloatVal();
4162 return error(
ID.Loc,
"unexpected floating-point literal");
4164 return error(
ID.Loc,
"floating-point constant invalid for type");
4169 "Invalid float strings should be caught by the lexer");
4174 return error(
ID.Loc,
"floating-point constant overflowed type");
4176 return error(
ID.Loc,
"floating-point constant underflowed type");
4182 return error(
ID.Loc,
"unexpected floating-point literal");
4184 const APInt &
Bits = Lex.getAPSIntVal();
4186 return error(
ID.Loc,
"float hex literal has incorrect number of bits");
4187 ID.APFloatVal =
APFloat(Semantics, Bits);
4209 if (parseGlobalValueVector(Elts) ||
4210 parseToken(
lltok::rbrace,
"expected end of struct constant"))
4213 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4214 ID.UIntVal = Elts.
size();
4215 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4216 Elts.
size() *
sizeof(Elts[0]));
4227 LocTy FirstEltLoc = Lex.getLoc();
4228 if (parseGlobalValueVector(Elts) ||
4230 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
4234 if (isPackedStruct) {
4235 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4236 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4237 Elts.
size() *
sizeof(Elts[0]));
4238 ID.UIntVal = Elts.
size();
4244 return error(
ID.Loc,
"constant vector must not be empty");
4246 if (!Elts[0]->
getType()->isIntegerTy() && !Elts[0]->
getType()->isByteTy() &&
4247 !Elts[0]->
getType()->isFloatingPointTy() &&
4251 "vector elements must have integer, byte, pointer or floating point "
4255 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
4257 return error(FirstEltLoc,
"vector element #" + Twine(i) +
4258 " is not of type '" +
4268 LocTy FirstEltLoc = Lex.getLoc();
4269 if (parseGlobalValueVector(Elts) ||
4281 if (!Elts[0]->
getType()->isFirstClassType())
4282 return error(FirstEltLoc,
"invalid array element type: " +
4288 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4290 return error(FirstEltLoc,
"array element #" + Twine(i) +
4291 " is not of type '" +
4303 Context, Lex.getStrVal(),
false, ATy->getElementType()->isByteTy());
4312 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4315 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4318 parseStringConstant(
ID.StrVal) ||
4319 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4322 ID.StrVal2 = Lex.getStrVal();
4323 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4324 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4335 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4336 parseValID(Fn, PFS) ||
4338 "expected comma in block address expression") ||
4339 parseValID(Label, PFS) ||
4340 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4344 return error(Fn.
Loc,
"expected function name in blockaddress");
4346 return error(
Label.Loc,
"expected basic block name in blockaddress");
4349 GlobalValue *GV =
nullptr;
4351 GV = NumberedVals.get(Fn.
UIntVal);
4352 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4353 GV = M->getNamedValue(Fn.
StrVal);
4359 return error(Fn.
Loc,
"expected function name in blockaddress");
4361 if (
F->isDeclaration())
4362 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4367 GlobalValue *&FwdRef =
4368 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4376 "type of blockaddress must be a pointer and not '" +
4381 FwdDeclAS = PFS->getFunction().getAddressSpace();
4385 FwdRef =
new GlobalVariable(
4390 ID.ConstantVal = FwdRef;
4398 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4400 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4402 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4404 return error(
Label.Loc,
"referenced value is not a basic block");
4407 return error(
Label.Loc,
"cannot take address of numeric label after "
4408 "the function is defined");
4410 F->getValueSymbolTable()->lookup(
Label.StrVal));
4412 return error(
Label.Loc,
"referenced value is not a basic block");
4426 if (parseValID(Fn, PFS))
4431 "expected global value name in dso_local_equivalent");
4434 GlobalValue *GV =
nullptr;
4436 GV = NumberedVals.get(Fn.
UIntVal);
4437 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4438 GV = M->getNamedValue(Fn.
StrVal);
4444 ? ForwardRefDSOLocalEquivalentIDs
4445 : ForwardRefDSOLocalEquivalentNames;
4446 GlobalValue *&FwdRef = FwdRefMap[Fn];
4453 ID.ConstantVal = FwdRef;
4459 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4460 "in dso_local_equivalent");
4471 if (parseValID(
ID, PFS))
4475 return error(
ID.Loc,
"expected global value name in no_cfi");
4487 Constant *Disc =
nullptr, *AddrDisc =
nullptr,
4488 *DeactivationSymbol =
nullptr;
4491 "expected '(' in constant ptrauth expression") ||
4492 parseGlobalTypeAndValue(Ptr) ||
4494 "expected comma in constant ptrauth expression") ||
4495 parseGlobalTypeAndValue(
Key))
4498 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(Disc))
4500 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4503 parseGlobalTypeAndValue(DeactivationSymbol))
4506 "expected ')' in constant ptrauth expression"))
4510 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4513 if (!KeyC || KeyC->getBitWidth() != 32)
4514 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4516 ConstantInt *DiscC =
nullptr;
4522 "constant ptrauth integer discriminator must be i64 constant");
4528 if (!AddrDisc->getType()->isPointerTy())
4530 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4535 if (!DeactivationSymbol)
4536 DeactivationSymbol =
4538 if (!DeactivationSymbol->getType()->isPointerTy())
4540 "constant ptrauth deactivation symbol must be a pointer");
4554 unsigned Opc = Lex.getUIntVal();
4555 Type *DestTy =
nullptr;
4558 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4559 parseGlobalTypeAndValue(SrcVal) ||
4560 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4561 parseType(DestTy) ||
4562 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4565 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4574 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4576 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4578 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4580 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4582 return error(
ID.Loc,
"urem constexprs are no longer supported");
4584 return error(
ID.Loc,
"srem constexprs are no longer supported");
4586 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4588 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4590 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4592 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4594 return error(
ID.Loc,
"frem constexprs are no longer supported");
4596 return error(
ID.Loc,
"and constexprs are no longer supported");
4598 return error(
ID.Loc,
"or constexprs are no longer supported");
4600 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4602 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4604 return error(
ID.Loc,
"shl constexprs are no longer supported");
4606 return error(
ID.Loc,
"mul constexprs are no longer supported");
4608 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4610 return error(
ID.Loc,
"select constexprs are no longer supported");
4612 return error(
ID.Loc,
"zext constexprs are no longer supported");
4614 return error(
ID.Loc,
"sext constexprs are no longer supported");
4616 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4618 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4620 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4622 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4624 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4626 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4628 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4630 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4638 unsigned Opc = Lex.getUIntVal();
4641 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4642 Opc == Instruction::Mul) {
4651 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4652 parseGlobalTypeAndValue(Val0) ||
4653 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4654 parseGlobalTypeAndValue(Val1) ||
4655 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4658 return error(
ID.Loc,
"operands of constexpr must have same type");
4662 "constexpr requires integer or integer vector operands");
4673 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4676 if (parseGlobalTypeAndValue(
C))
4678 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4690 unsigned Opc = Lex.getUIntVal();
4693 bool HasInRange =
false;
4699 if (
Opc == Instruction::GetElementPtr) {
4715 return tokError(
"expected integer");
4716 InRangeStart = Lex.getAPSIntVal();
4721 return tokError(
"expected integer");
4722 InRangeEnd = Lex.getAPSIntVal();
4730 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4733 if (
Opc == Instruction::GetElementPtr) {
4734 if (parseType(Ty) ||
4735 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4739 if (parseGlobalValueVector(Elts) ||
4743 if (
Opc == Instruction::GetElementPtr) {
4744 if (Elts.
size() == 0 ||
4745 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4746 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4749 std::optional<ConstantRange>
InRange;
4751 unsigned IndexWidth =
4752 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4753 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4754 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4755 if (InRangeStart.
sge(InRangeEnd))
4756 return error(
ID.Loc,
"expected end to be larger than start");
4766 for (Constant *Val : Indices) {
4769 return error(
ID.Loc,
"getelementptr index must be an integer");
4772 if (GEPWidth && (ValNumEl != GEPWidth))
4775 "getelementptr vector index has a wrong number of elements");
4778 GEPWidth = ValNumEl;
4782 SmallPtrSet<Type*, 4> Visited;
4783 if (!Indices.empty() && !Ty->
isSized(&Visited))
4784 return error(
ID.Loc,
"base element of getelementptr must be sized");
4787 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4790 return error(
ID.Loc,
"invalid getelementptr indices");
4794 }
else if (
Opc == Instruction::ShuffleVector) {
4795 if (Elts.
size() != 3)
4796 return error(
ID.Loc,
"expected three operands to shufflevector");
4798 return error(
ID.Loc,
"invalid operands to shufflevector");
4799 SmallVector<int, 16>
Mask;
4802 }
else if (
Opc == Instruction::ExtractElement) {
4803 if (Elts.
size() != 2)
4804 return error(
ID.Loc,
"expected two operands to extractelement");
4806 return error(
ID.Loc,
"invalid extractelement operands");
4809 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4810 if (Elts.
size() != 3)
4811 return error(
ID.Loc,
"expected three operands to insertelement");
4813 return error(
ID.Loc,
"invalid insertelement operands");
4828bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4832 bool Parsed = parseValID(
ID,
nullptr, Ty) ||
4833 convertValIDToValue(Ty,
ID, V,
nullptr);
4835 return error(
ID.Loc,
"global values must be constants");
4839bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4841 return parseType(Ty) || parseGlobalValue(Ty, V);
4844bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4847 LocTy KwLoc = Lex.getLoc();
4853 return tokError(
"expected comdat variable");
4854 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4856 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4859 if (GlobalName.
empty())
4860 return tokError(
"comdat cannot be unnamed");
4861 C = getComdat(std::string(GlobalName), KwLoc);
4870bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4884 if (parseGlobalTypeAndValue(
C))
4892bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
4894 if (parseMDNodeVector(Elts))
4905bool LLParser::parseMDNode(MDNode *&
N) {
4907 return parseSpecializedMDNode(
N);
4909 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
4912bool LLParser::parseMDNodeTail(MDNode *&
N) {
4915 return parseMDTuple(
N);
4918 return parseMDNodeID(
N);
4924template <
class FieldTy>
struct MDFieldImpl {
4925 typedef MDFieldImpl ImplTy;
4929 void assign(FieldTy Val) {
4931 this->Val = std::move(Val);
4934 explicit MDFieldImpl(FieldTy
Default)
4942template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
4943 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4954 void assign(FieldTypeA
A) {
4956 this->
A = std::move(
A);
4960 void assign(FieldTypeB
B) {
4962 this->
B = std::move(
B);
4966 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4968 WhatIs(IsInvalid) {}
4971struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
4978struct LineField :
public MDUnsignedField {
4979 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4982struct ColumnField :
public MDUnsignedField {
4983 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4986struct DwarfTagField :
public MDUnsignedField {
4992struct DwarfMacinfoTypeField :
public MDUnsignedField {
4998struct DwarfAttEncodingField :
public MDUnsignedField {
4999 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
5002struct DwarfVirtualityField :
public MDUnsignedField {
5006struct DwarfLangField :
public MDUnsignedField {
5010struct DwarfSourceLangNameField :
public MDUnsignedField {
5011 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5014struct DwarfLangDialectField :
public MDUnsignedField {
5015 DwarfLangDialectField()
5019struct DwarfCCField :
public MDUnsignedField {
5020 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
5023struct DwarfEnumKindField :
public MDUnsignedField {
5024 DwarfEnumKindField()
5029struct EmissionKindField :
public MDUnsignedField {
5030 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5033struct FixedPointKindField :
public MDUnsignedField {
5034 FixedPointKindField()
5035 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5038struct NameTableKindField :
public MDUnsignedField {
5039 NameTableKindField()
5042 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5045struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
5046 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5049struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
5050 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5053struct MDAPSIntField :
public MDFieldImpl<APSInt> {
5054 MDAPSIntField() : ImplTy(
APSInt()) {}
5057struct MDSignedField :
public MDFieldImpl<int64_t> {
5061 MDSignedField(int64_t
Default = 0)
5063 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5067struct MDBoolField :
public MDFieldImpl<bool> {
5071struct MDField :
public MDFieldImpl<Metadata *> {
5074 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5077struct MDStringField :
public MDFieldImpl<MDString *> {
5078 enum class EmptyIs {
5083 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5084 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5087struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5091struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5095struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5096 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5097 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5099 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5100 bool AllowNull =
true)
5101 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5103 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5104 bool isMDField()
const {
return WhatIs == IsTypeB; }
5105 int64_t getMDSignedValue()
const {
5106 assert(isMDSignedField() &&
"Wrong field type");
5109 Metadata *getMDFieldValue()
const {
5110 assert(isMDField() &&
"Wrong field type");
5115struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5116 MDUnsignedOrMDField(uint64_t
Default = 0,
bool AllowNull =
true)
5117 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5119 MDUnsignedOrMDField(uint64_t
Default, uint64_t Max,
bool AllowNull =
true)
5120 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5122 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5123 bool isMDField()
const {
return WhatIs == IsTypeB; }
5124 uint64_t getMDUnsignedValue()
const {
5125 assert(isMDUnsignedField() &&
"Wrong field type");
5128 Metadata *getMDFieldValue()
const {
5129 assert(isMDField() &&
"Wrong field type");
5134 if (isMDUnsignedField())
5136 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5138 return getMDFieldValue();
5150 return tokError(
"expected integer");
5152 Result.assign(Lex.getAPSIntVal());
5159 MDUnsignedField &Result) {
5160 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5161 return tokError(
"expected unsigned integer");
5163 auto &U = Lex.getAPSIntVal();
5164 if (U.ugt(Result.Max))
5165 return tokError(
"value for '" + Name +
"' too large, limit is " +
5167 Result.assign(U.getZExtValue());
5168 assert(Result.Val <= Result.Max &&
"Expected value in range");
5175 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5179 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5185 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5188 return tokError(
"expected DWARF tag");
5192 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5193 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5202 DwarfMacinfoTypeField &Result) {
5204 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5207 return tokError(
"expected DWARF macinfo type");
5211 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5212 Lex.getStrVal() +
"'");
5213 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5215 Result.assign(Macinfo);
5222 DwarfVirtualityField &Result) {
5224 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5227 return tokError(
"expected DWARF virtuality code");
5231 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5232 Lex.getStrVal() +
"'");
5233 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5234 Result.assign(Virtuality);
5241 DwarfEnumKindField &Result) {
5243 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5246 return tokError(
"expected DWARF enum kind code");
5250 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5251 Lex.getStrVal() +
"'");
5252 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5253 Result.assign(EnumKind);
5261 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5264 return tokError(
"expected DWARF language");
5268 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5270 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5271 Result.assign(Lang);
5278 DwarfSourceLangNameField &Result) {
5280 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5283 return tokError(
"expected DWARF source language name");
5287 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5288 Lex.getStrVal() +
"'");
5289 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5290 Result.assign(Lang);
5297 DwarfLangDialectField &Result) {
5302 if (Lex.getAPSIntVal() == 0)
5303 return tokError(
"value for 'dialect' must be a known DWARF language "
5304 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5305 "DW_LLVM_LANG_DIALECT_tile)");
5306 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5310 return tokError(
"expected DWARF language dialect");
5312 StringRef DialectString = Lex.getStrVal();
5317 if (Dialect > Result.Max)
5318 return tokError(
"invalid DWARF language dialect" +
Twine(
" '") +
5319 DialectString +
"'");
5320 Result.assign(Dialect);
5328 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5331 return tokError(
"expected DWARF calling convention");
5335 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5336 Lex.getStrVal() +
"'");
5337 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
5345 EmissionKindField &Result) {
5347 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5350 return tokError(
"expected emission kind");
5354 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5356 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5357 Result.assign(*Kind);
5364 FixedPointKindField &Result) {
5366 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5369 return tokError(
"expected fixed-point kind");
5373 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5375 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5376 Result.assign(*Kind);
5383 NameTableKindField &Result) {
5385 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5388 return tokError(
"expected nameTable kind");
5392 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5394 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5395 Result.assign((
unsigned)*Kind);
5402 DwarfAttEncodingField &Result) {
5404 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5407 return tokError(
"expected DWARF type attribute encoding");
5411 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5412 Lex.getStrVal() +
"'");
5413 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5414 Result.assign(Encoding);
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 debug info flag '") + Lex.getStrVal() +
5455 Result.assign(Combined);
5468 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5470 bool Res = parseUInt32(TempVal);
5476 return tokError(
"expected debug info flag");
5480 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5481 Lex.getStrVal() +
"'");
5495 Result.assign(Combined);
5502 return tokError(
"expected signed integer");
5504 auto &S = Lex.getAPSIntVal();
5506 return tokError(
"value for '" + Name +
"' too small, limit is " +
5509 return tokError(
"value for '" + Name +
"' too large, limit is " +
5511 Result.assign(S.getExtValue());
5512 assert(Result.Val >= Result.Min &&
"Expected value in range");
5513 assert(Result.Val <= Result.Max &&
"Expected value in range");
5520 switch (Lex.getKind()) {
5522 return tokError(
"expected 'true' or 'false'");
5524 Result.assign(
true);
5527 Result.assign(
false);
5537 if (!Result.AllowNull)
5538 return tokError(
"'" + Name +
"' cannot be null");
5540 Result.assign(
nullptr);
5545 if (parseMetadata(MD,
nullptr))
5554 MDSignedOrMDField &Result) {
5557 MDSignedField Res = Result.A;
5558 if (!parseMDField(
Loc, Name, Res)) {
5566 MDField Res = Result.B;
5567 if (!parseMDField(
Loc, Name, Res)) {
5577 MDUnsignedOrMDField &Result) {
5580 MDUnsignedField Res = Result.A;
5581 if (!parseMDField(
Loc, Name, Res)) {
5589 MDField Res = Result.B;
5590 if (!parseMDField(
Loc, Name, Res)) {
5600 LocTy ValueLoc = Lex.getLoc();
5602 if (parseStringConstant(S))
5606 switch (Result.EmptyIs) {
5607 case MDStringField::EmptyIs::Null:
5608 Result.assign(
nullptr);
5610 case MDStringField::EmptyIs::Empty:
5612 case MDStringField::EmptyIs::Error:
5613 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5624 if (parseMDNodeVector(MDs))
5627 Result.assign(std::move(MDs));
5633 ChecksumKindField &Result) {
5634 std::optional<DIFile::ChecksumKind> CSKind =
5638 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5641 Result.assign(*CSKind);
5648template <
class ParserTy>
5649bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5652 return tokError(
"expected field label here");
5661template <
class ParserTy>
5662bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5669 if (parseMDFieldsImplBody(ParseField))
5672 ClosingLoc = Lex.getLoc();
5676template <
class FieldTy>
5677bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5679 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5681 LocTy Loc = Lex.getLoc();
5683 return parseMDField(Loc, Name, Result);
5686bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5689#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5690 if (Lex.getStrVal() == #CLASS) \
5691 return parse##CLASS(N, IsDistinct);
5692#include "llvm/IR/Metadata.def"
5694 return tokError(
"expected metadata type");
5697#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5698#define NOP_FIELD(NAME, TYPE, INIT)
5699#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5701 return error(ClosingLoc, "missing required field '" #NAME "'");
5702#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5703 if (Lex.getStrVal() == #NAME) \
5704 return parseMDField(#NAME, NAME);
5705#define PARSE_MD_FIELDS() \
5706 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5709 if (parseMDFieldsImpl( \
5711 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5712 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5717 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5719#define GET_OR_DISTINCT(CLASS, ARGS) \
5720 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5725bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5726#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5727 OPTIONAL(line, LineField, ); \
5728 OPTIONAL(column, ColumnField, ); \
5729 REQUIRED(scope, MDField, ( false)); \
5730 OPTIONAL(inlinedAt, MDField, ); \
5731 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5732 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5733 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5735#undef VISIT_MD_FIELDS
5738 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5739 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5745bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5747 return tokError(
"missing 'distinct', required for !DIAssignID()");
5763bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5764#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5765 REQUIRED(tag, DwarfTagField, ); \
5766 OPTIONAL(header, MDStringField, ); \
5767 OPTIONAL(operands, MDFieldList, );
5769#undef VISIT_MD_FIELDS
5772 (Context, tag.Val, header.Val, operands.Val));
5781bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5782#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5783 OPTIONAL(name, MDStringField, ); \
5784 OPTIONAL(file, MDField, ); \
5785 OPTIONAL(line, LineField, ); \
5786 OPTIONAL(scope, MDField, ); \
5787 OPTIONAL(baseType, MDField, ); \
5788 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5789 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5790 OPTIONAL(flags, DIFlagField, ); \
5791 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5792 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5793 OPTIONAL(stride, MDSignedOrMDField, ); \
5794 OPTIONAL(bias, MDSignedOrMDField, );
5796#undef VISIT_MD_FIELDS
5798 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5799 if (Bound.isMDSignedField())
5802 if (Bound.isMDField())
5803 return Bound.getMDFieldValue();
5807 Metadata *LowerBound = convToMetadata(lowerBound);
5809 Metadata *Stride = convToMetadata(stride);
5810 Metadata *Bias = convToMetadata(bias);
5813 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5814 size.getValueAsMetadata(Context), align.Val, flags.Val,
5815 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5824bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5826 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5827 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5828 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5829 OPTIONAL(stride, MDSignedOrMDField, );
5831#undef VISIT_MD_FIELDS
5838 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5839 if (Bound.isMDSignedField())
5842 if (Bound.isMDField())
5843 return Bound.getMDFieldValue();
5848 LowerBound = convToMetadata(lowerBound);
5850 Stride = convToMetadata(stride);
5853 (Context,
Count, LowerBound, UpperBound, Stride));
5861bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
5862#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5863 OPTIONAL(count, MDSignedOrMDField, ); \
5864 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5865 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5866 OPTIONAL(stride, MDSignedOrMDField, );
5868#undef VISIT_MD_FIELDS
5870 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5871 if (Bound.isMDSignedField())
5873 Context, {dwarf::DW_OP_consts,
5874 static_cast<uint64_t
>(Bound.getMDSignedValue())});
5875 if (Bound.isMDField())
5876 return Bound.getMDFieldValue();
5881 Metadata *LowerBound = ConvToMetadata(lowerBound);
5883 Metadata *Stride = ConvToMetadata(stride);
5886 (Context,
Count, LowerBound, UpperBound, Stride));
5893bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
5894#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5895 REQUIRED(name, MDStringField, ); \
5896 REQUIRED(value, MDAPSIntField, ); \
5897 OPTIONAL(isUnsigned, MDBoolField, (false));
5899#undef VISIT_MD_FIELDS
5901 if (isUnsigned.Val && value.Val.isNegative())
5902 return tokError(
"unsigned enumerator with negative value");
5907 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5919bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
5920#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5921 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5922 OPTIONAL(name, MDStringField, ); \
5923 OPTIONAL(file, MDField, ); \
5924 OPTIONAL(line, LineField, ); \
5925 OPTIONAL(scope, MDField, ); \
5926 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5927 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5928 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5929 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5930 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5931 OPTIONAL(flags, DIFlagField, );
5933#undef VISIT_MD_FIELDS
5936 DIBasicType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
5937 size.getValueAsMetadata(Context), align.Val, encoding.Val,
5938 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5947bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
5948#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5949 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5950 OPTIONAL(name, MDStringField, ); \
5951 OPTIONAL(file, MDField, ); \
5952 OPTIONAL(line, LineField, ); \
5953 OPTIONAL(scope, MDField, ); \
5954 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5955 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5956 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5957 OPTIONAL(flags, DIFlagField, ); \
5958 OPTIONAL(kind, FixedPointKindField, ); \
5959 OPTIONAL(factor, MDSignedField, ); \
5960 OPTIONAL(numerator, MDAPSIntField, ); \
5961 OPTIONAL(denominator, MDAPSIntField, );
5963#undef VISIT_MD_FIELDS
5966 (Context, tag.Val,
name.Val,
file.Val, line.Val,
5967 scope.Val,
size.getValueAsMetadata(Context),
5968 align.Val, encoding.Val, flags.Val, kind.Val,
5969 factor.Val, numerator.Val, denominator.Val));
5975bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
5976#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5977 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5978 OPTIONAL(name, MDStringField, ); \
5979 OPTIONAL(stringLength, MDField, ); \
5980 OPTIONAL(stringLengthExpression, MDField, ); \
5981 OPTIONAL(stringLocationExpression, MDField, ); \
5982 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5983 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5984 OPTIONAL(encoding, DwarfAttEncodingField, );
5986#undef VISIT_MD_FIELDS
5990 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
5991 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
5992 align.Val, encoding.Val));
6005bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
6006#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6007 REQUIRED(tag, DwarfTagField, ); \
6008 OPTIONAL(name, MDStringField, ); \
6009 OPTIONAL(file, MDField, ); \
6010 OPTIONAL(line, LineField, ); \
6011 OPTIONAL(scope, MDField, ); \
6012 REQUIRED(baseType, MDField, ); \
6013 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6014 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6015 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6016 OPTIONAL(flags, DIFlagField, ); \
6017 OPTIONAL(extraData, MDField, ); \
6018 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6019 OPTIONAL(annotations, MDField, ); \
6020 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6021 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6022 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6023 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6024 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6026#undef VISIT_MD_FIELDS
6028 std::optional<unsigned> DWARFAddressSpace;
6029 if (dwarfAddressSpace.Val != UINT32_MAX)
6030 DWARFAddressSpace = dwarfAddressSpace.Val;
6031 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6033 PtrAuthData.emplace(
6034 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6035 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6036 ptrAuthAuthenticatesNullValues.Val);
6039 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6040 baseType.Val,
size.getValueAsMetadata(Context), align.Val,
6041 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6042 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6046bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
6047#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6048 REQUIRED(tag, DwarfTagField, ); \
6049 OPTIONAL(name, MDStringField, ); \
6050 OPTIONAL(file, MDField, ); \
6051 OPTIONAL(line, LineField, ); \
6052 OPTIONAL(scope, MDField, ); \
6053 OPTIONAL(baseType, MDField, ); \
6054 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6055 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6056 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6057 OPTIONAL(flags, DIFlagField, ); \
6058 OPTIONAL(elements, MDField, ); \
6059 OPTIONAL(runtimeLang, DwarfLangField, ); \
6060 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6061 OPTIONAL(vtableHolder, MDField, ); \
6062 OPTIONAL(templateParams, MDField, ); \
6063 OPTIONAL(identifier, MDStringField, ); \
6064 OPTIONAL(discriminator, MDField, ); \
6065 OPTIONAL(dataLocation, MDField, ); \
6066 OPTIONAL(associated, MDField, ); \
6067 OPTIONAL(allocated, MDField, ); \
6068 OPTIONAL(rank, MDSignedOrMDField, ); \
6069 OPTIONAL(annotations, MDField, ); \
6070 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6071 OPTIONAL(specification, MDField, ); \
6072 OPTIONAL(bitStride, MDField, );
6074#undef VISIT_MD_FIELDS
6077 if (rank.isMDSignedField())
6080 else if (rank.isMDField())
6081 Rank = rank.getMDFieldValue();
6083 std::optional<unsigned> EnumKind;
6085 EnumKind = enumKind.Val;
6090 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
6091 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
6092 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6093 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6094 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6095 dataLocation.Val, associated.Val, allocated.Val, Rank,
6096 annotations.Val, bitStride.Val)) {
6105 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6106 size.getValueAsMetadata(Context), align.Val,
6107 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6108 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6109 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6110 allocated.Val, Rank, annotations.Val, specification.Val,
6111 num_extra_inhabitants.Val, bitStride.Val));
6115bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6116#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6117 OPTIONAL(flags, DIFlagField, ); \
6118 OPTIONAL(cc, DwarfCCField, ); \
6119 REQUIRED(types, MDField, );
6121#undef VISIT_MD_FIELDS
6124 (Context, flags.Val, cc.Val, types.Val));
6133bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6137#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6138 REQUIRED(filename, MDStringField, ); \
6139 REQUIRED(directory, MDStringField, ); \
6140 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6141 OPTIONAL(checksum, MDStringField, ); \
6142 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6144#undef VISIT_MD_FIELDS
6146 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6147 if (checksumkind.Seen && checksum.Seen)
6148 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6149 else if (checksumkind.Seen || checksum.Seen)
6150 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6152 MDString *
Source =
nullptr;
6156 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6168bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6170 return tokError(
"missing 'distinct', required for !DICompileUnit");
6172 LocTy Loc = Lex.getLoc();
6174#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6175 REQUIRED(file, MDField, ( false)); \
6176 OPTIONAL(language, DwarfLangField, ); \
6177 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6178 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6179 OPTIONAL(producer, MDStringField, ); \
6180 OPTIONAL(isOptimized, MDBoolField, ); \
6181 OPTIONAL(flags, MDStringField, ); \
6182 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6183 OPTIONAL(splitDebugFilename, MDStringField, ); \
6184 OPTIONAL(emissionKind, EmissionKindField, ); \
6185 OPTIONAL(enums, MDField, ); \
6186 OPTIONAL(retainedTypes, MDField, ); \
6187 OPTIONAL(globals, MDField, ); \
6188 OPTIONAL(imports, MDField, ); \
6189 OPTIONAL(macros, MDField, ); \
6190 OPTIONAL(dwoId, MDUnsignedField, ); \
6191 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6192 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6193 OPTIONAL(nameTableKind, NameTableKindField, ); \
6194 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6195 OPTIONAL(sysroot, MDStringField, ); \
6196 OPTIONAL(sdk, MDStringField, ); \
6197 OPTIONAL(dialect, DwarfLangDialectField, );
6199#undef VISIT_MD_FIELDS
6201 if (!language.Seen && !sourceLanguageName.Seen)
6202 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6203 "required for !DICompileUnit");
6205 if (language.Seen && sourceLanguageName.Seen)
6206 return error(Loc,
"can only specify one of 'language' and "
6207 "'sourceLanguageName' on !DICompileUnit");
6209 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6210 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6211 "'sourceLanguageName' on !DICompileUnit");
6213 uint16_t Dialect =
static_cast<uint16_t
>(dialect.Val);
6216 ? DISourceLanguageName(
static_cast<uint16_t
>(language.Val), Dialect)
6217 : DISourceLanguageName(
6218 static_cast<uint16_t>(sourceLanguageName.Val),
6219 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6222 Context, SourceLanguage,
file.Val, producer.Val, isOptimized.Val,
6223 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6224 enums.Val, retainedTypes.Val,
globals.Val, imports.Val, macros.Val,
6225 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6226 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6239bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6240 auto Loc = Lex.getLoc();
6241#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6242 OPTIONAL(scope, MDField, ); \
6243 OPTIONAL(name, MDStringField, ); \
6244 OPTIONAL(linkageName, MDStringField, ); \
6245 OPTIONAL(file, MDField, ); \
6246 OPTIONAL(line, LineField, ); \
6247 REQUIRED(type, MDField, ( false)); \
6248 OPTIONAL(isLocal, MDBoolField, ); \
6249 OPTIONAL(isDefinition, MDBoolField, (true)); \
6250 OPTIONAL(scopeLine, LineField, ); \
6251 OPTIONAL(containingType, MDField, ); \
6252 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6253 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6254 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6255 OPTIONAL(flags, DIFlagField, ); \
6256 OPTIONAL(spFlags, DISPFlagField, ); \
6257 OPTIONAL(isOptimized, MDBoolField, ); \
6258 OPTIONAL(unit, MDField, ); \
6259 OPTIONAL(templateParams, MDField, ); \
6260 OPTIONAL(declaration, MDField, ); \
6261 OPTIONAL(retainedNodes, MDField, ); \
6262 OPTIONAL(thrownTypes, MDField, ); \
6263 OPTIONAL(annotations, MDField, ); \
6264 OPTIONAL(targetFuncName, MDStringField, ); \
6265 OPTIONAL(keyInstructions, MDBoolField, );
6267#undef VISIT_MD_FIELDS
6272 spFlags.Seen ? spFlags.Val
6274 isOptimized.Val, virtuality.Val);
6275 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6278 "missing 'distinct', required for !DISubprogram that is a Definition");
6281 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6282 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6283 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6284 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6285 targetFuncName.Val, keyInstructions.Val));
6295bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6296#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6297 REQUIRED(scope, MDField, ( false)); \
6298 OPTIONAL(file, MDField, ); \
6299 OPTIONAL(line, LineField, ); \
6300 OPTIONAL(column, ColumnField, );
6302#undef VISIT_MD_FIELDS
6305 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6311bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6312#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6313 REQUIRED(scope, MDField, ( false)); \
6314 OPTIONAL(file, MDField, ); \
6315 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6317#undef VISIT_MD_FIELDS
6320 (Context, scope.Val,
file.Val, discriminator.Val));
6326bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6327#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6328 REQUIRED(scope, MDField, ); \
6329 OPTIONAL(declaration, MDField, ); \
6330 OPTIONAL(name, MDStringField, ); \
6331 OPTIONAL(file, MDField, ); \
6332 OPTIONAL(line, LineField, );
6334#undef VISIT_MD_FIELDS
6337 (Context, scope.Val, declaration.Val,
name.Val,
6338 file.Val, line.Val));
6344bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6345#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6346 REQUIRED(scope, MDField, ); \
6347 OPTIONAL(name, MDStringField, ); \
6348 OPTIONAL(exportSymbols, MDBoolField, );
6350#undef VISIT_MD_FIELDS
6353 (Context, scope.Val,
name.Val, exportSymbols.Val));
6360bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6361#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6362 REQUIRED(type, DwarfMacinfoTypeField, ); \
6363 OPTIONAL(line, LineField, ); \
6364 REQUIRED(name, MDStringField, ); \
6365 OPTIONAL(value, MDStringField, );
6367#undef VISIT_MD_FIELDS
6370 (Context, type.Val, line.Val,
name.Val, value.Val));
6376bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6377#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6378 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6379 OPTIONAL(line, LineField, ); \
6380 REQUIRED(file, MDField, ); \
6381 OPTIONAL(nodes, MDField, );
6383#undef VISIT_MD_FIELDS
6386 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6394bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6395#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6396 REQUIRED(scope, MDField, ); \
6397 REQUIRED(name, MDStringField, ); \
6398 OPTIONAL(configMacros, MDStringField, ); \
6399 OPTIONAL(includePath, MDStringField, ); \
6400 OPTIONAL(apinotes, MDStringField, ); \
6401 OPTIONAL(file, MDField, ); \
6402 OPTIONAL(line, LineField, ); \
6403 OPTIONAL(isDecl, MDBoolField, );
6405#undef VISIT_MD_FIELDS
6408 configMacros.Val, includePath.Val,
6409 apinotes.Val, line.Val, isDecl.Val));
6415bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6416#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6417 OPTIONAL(name, MDStringField, ); \
6418 REQUIRED(type, MDField, ); \
6419 OPTIONAL(defaulted, MDBoolField, );
6421#undef VISIT_MD_FIELDS
6424 (Context,
name.Val, type.Val, defaulted.Val));
6432bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6433#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6434 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6435 OPTIONAL(name, MDStringField, ); \
6436 OPTIONAL(type, MDField, ); \
6437 OPTIONAL(defaulted, MDBoolField, ); \
6438 REQUIRED(value, MDField, );
6441#undef VISIT_MD_FIELDS
6444 DITemplateValueParameter,
6445 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6454bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6455#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6456 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6457 OPTIONAL(scope, MDField, ); \
6458 OPTIONAL(linkageName, MDStringField, ); \
6459 OPTIONAL(file, MDField, ); \
6460 OPTIONAL(line, LineField, ); \
6461 OPTIONAL(type, MDField, ); \
6462 OPTIONAL(isLocal, MDBoolField, ); \
6463 OPTIONAL(isDefinition, MDBoolField, (true)); \
6464 OPTIONAL(templateParams, MDField, ); \
6465 OPTIONAL(declaration, MDField, ); \
6466 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6467 OPTIONAL(annotations, MDField, );
6469#undef VISIT_MD_FIELDS
6473 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6474 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6475 declaration.Val, templateParams.Val, align.Val,
6487bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6488#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6489 REQUIRED(scope, MDField, ( false)); \
6490 OPTIONAL(name, MDStringField, ); \
6491 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6492 OPTIONAL(file, MDField, ); \
6493 OPTIONAL(line, LineField, ); \
6494 OPTIONAL(type, MDField, ); \
6495 OPTIONAL(flags, DIFlagField, ); \
6496 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6497 OPTIONAL(annotations, MDField, );
6499#undef VISIT_MD_FIELDS
6502 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6503 type.Val, arg.Val, flags.Val, align.Val,
6510bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6511#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6512 REQUIRED(scope, MDField, ( false)); \
6513 REQUIRED(name, MDStringField, ); \
6514 REQUIRED(file, MDField, ); \
6515 REQUIRED(line, LineField, ); \
6516 OPTIONAL(column, ColumnField, ); \
6517 OPTIONAL(isArtificial, MDBoolField, ); \
6518 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6520#undef VISIT_MD_FIELDS
6522 std::optional<unsigned> CoroSuspendIdx =
6523 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6527 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6528 column.Val, isArtificial.Val, CoroSuspendIdx));
6534bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6547 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6556 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6557 Lex.getStrVal() +
"'");
6560 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6561 return tokError(
"expected unsigned integer");
6563 auto &
U = Lex.getAPSIntVal();
6565 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6579bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6581 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6584 return parseDIExpressionBody(Result, IsDistinct);
6589bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6590 assert(PFS &&
"Expected valid function state");
6601 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6615bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6617#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6618 REQUIRED(var, MDField, ); \
6619 REQUIRED(expr, MDField, );
6621#undef VISIT_MD_FIELDS
6624 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6631bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6632#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6633 OPTIONAL(name, MDStringField, ); \
6634 OPTIONAL(file, MDField, ); \
6635 OPTIONAL(line, LineField, ); \
6636 OPTIONAL(setter, MDStringField, ); \
6637 OPTIONAL(getter, MDStringField, ); \
6638 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6639 OPTIONAL(type, MDField, );
6641#undef VISIT_MD_FIELDS
6644 (Context,
name.Val,
file.Val, line.Val, getter.Val,
6645 setter.Val, attributes.Val, type.Val));
6652bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6653#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6654 REQUIRED(tag, DwarfTagField, ); \
6655 REQUIRED(scope, MDField, ); \
6656 OPTIONAL(entity, MDField, ); \
6657 OPTIONAL(file, MDField, ); \
6658 OPTIONAL(line, LineField, ); \
6659 OPTIONAL(name, MDStringField, ); \
6660 OPTIONAL(elements, MDField, );
6662#undef VISIT_MD_FIELDS
6665 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6666 line.Val,
name.Val, elements.Val));
6670#undef PARSE_MD_FIELD
6682bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6685 if (parseMetadata(MD, &PFS))
6696bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6697 PerFunctionState *PFS) {
6700 if (parseType(Ty, TypeMsg, Loc))
6703 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6706 if (parseValue(Ty, V, PFS))
6721bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6725 if (Lex.getStrVal() ==
"DIArgList") {
6727 if (parseDIArgList(AL, PFS))
6733 if (parseSpecializedMDNode(
N)) {
6743 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6753 if (parseMDString(S))
6763 if (parseMDNodeTail(
N))
6774 PerFunctionState *PFS) {
6776 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6781 return error(
ID.Loc,
"invalid use of function-local name");
6782 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6783 return V ==
nullptr;
6786 return error(
ID.Loc,
"invalid use of function-local name");
6787 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6788 return V ==
nullptr;
6791 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6795 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6800 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6803 return V ==
nullptr;
6805 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6808 return V ==
nullptr;
6811 return error(
ID.Loc,
"integer/byte constant must have integer/byte type");
6814 :
V = ConstantByte::
get(Context,
ID.APSIntVal);
6819 return error(
ID.Loc,
"floating point constant invalid for type");
6825 bool IsSNAN = ID.APFloatVal.isSignaling();
6828 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6830 else if (Ty->isBFloatTy())
6831 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6833 else if (Ty->isFloatTy())
6834 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6840 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6841 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6842 ID.APFloatVal.isNegative(), &Payload);
6845 V = ConstantFP::get(Context,
ID.APFloatVal);
6847 if (
V->getType() != Ty)
6848 return error(
ID.Loc,
"floating point constant does not have type '" +
6854 return error(
ID.Loc,
"null must be a pointer type");
6860 return error(
ID.Loc,
"invalid type for undef constant");
6865 return error(
ID.Loc,
"invalid empty array initializer");
6871 return error(
ID.Loc,
"invalid type for null constant");
6874 return error(
ID.Loc,
"invalid type for null constant");
6879 return error(
ID.Loc,
"invalid type for none constant");
6885 return error(
ID.Loc,
"invalid type for poison constant");
6889 if (
ID.ConstantVal->getType() != Ty)
6890 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6897 return error(
ID.Loc,
"vector constant must have vector type");
6899 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
6901 "' but expected '" +
6909 if (
ST->getNumElements() !=
ID.UIntVal)
6911 "initializer with struct type has wrong # elements");
6913 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
6916 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
6917 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
6920 "element " + Twine(i) +
6921 " of struct initializer doesn't match struct element type");
6924 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
6926 return error(
ID.Loc,
"constant expression type mismatch");
6935 auto Loc = Lex.getLoc();
6936 if (parseValID(
ID,
nullptr, Ty))
6949 if (convertValIDToValue(Ty,
ID, V,
nullptr))
6959 return error(Loc,
"expected a constant value");
6963bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
6967 FileLoc
Start = getTokLineColumnPos();
6968 bool Ret = parseValID(
ID, PFS, Ty) || convertValIDToValue(Ty,
ID, V, PFS);
6969 if (!Ret && ParserContext) {
6970 FileLoc End = getPrevTokEndLineColumnPos();
6971 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
6976bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
6978 return parseType(Ty) || parseValue(Ty, V, PFS);
6981bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
6982 PerFunctionState &PFS) {
6985 if (parseTypeAndValue(V, PFS))
6988 return error(Loc,
"expected a basic block");
6997 if (!Name.starts_with(
"llvm.dbg."))
7000 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7001 FnID == Intrinsic::dbg_assign;
7009bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
7010 unsigned &FunctionNumber,
7013 LocTy LinkageLoc = Lex.getLoc();
7015 unsigned Visibility;
7016 unsigned DLLStorageClass;
7018 AttrBuilder RetAttrs(M->getContext());
7021 Type *RetType =
nullptr;
7022 LocTy RetTypeLoc = Lex.getLoc();
7023 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
7025 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7026 parseType(RetType, RetTypeLoc,
true ))
7035 return error(LinkageLoc,
"invalid linkage for function definition");
7045 return error(LinkageLoc,
"invalid linkage for function declaration");
7049 return error(LinkageLoc,
"invalid function linkage type");
7053 return error(LinkageLoc,
7054 "symbol with local linkage must have default visibility");
7057 return error(LinkageLoc,
7058 "symbol with local linkage cannot have a DLL storage class");
7061 return error(RetTypeLoc,
"invalid function return type");
7063 LocTy NameLoc = Lex.getLoc();
7065 std::string FunctionName;
7067 FunctionName = Lex.getStrVal();
7069 FunctionNumber = Lex.getUIntVal();
7070 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
7074 return tokError(
"expected function name");
7080 return tokError(
"expected '(' in function argument list");
7084 AttrBuilder FuncAttrs(M->getContext());
7085 std::vector<unsigned> FwdRefAttrGrps;
7088 std::string Partition;
7089 MaybeAlign Alignment, PrefAlignment;
7092 unsigned AddrSpace = 0;
7098 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7099 parseOptionalUnnamedAddr(UnnamedAddr) ||
7100 parseOptionalProgramAddrSpace(AddrSpace) ||
7101 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7105 parseOptionalComdat(FunctionName,
C) ||
7106 parseOptionalAlignment(Alignment) ||
7107 parseOptionalPrefAlignment(PrefAlignment) ||
7108 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7112 parseGlobalTypeAndValue(PersonalityFn)))
7115 if (FuncAttrs.contains(Attribute::Builtin))
7116 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7119 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7121 FuncAttrs.removeAttribute(Attribute::Alignment);
7126 std::vector<Type*> ParamTypeList;
7129 for (
const ArgInfo &Arg : ArgList) {
7130 ParamTypeList.push_back(Arg.Ty);
7131 Attrs.push_back(Arg.Attrs);
7138 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7139 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7145 GlobalValue *FwdFn =
nullptr;
7146 if (!FunctionName.empty()) {
7149 auto FRVI = ForwardRefVals.find(FunctionName);
7150 if (FRVI != ForwardRefVals.end()) {
7151 FwdFn = FRVI->second.first;
7153 return error(FRVI->second.second,
7154 "invalid forward reference to "
7157 "' with wrong type: "
7161 ForwardRefVals.erase(FRVI);
7162 }
else if ((Fn = M->getFunction(FunctionName))) {
7164 return error(NameLoc,
7165 "invalid redefinition of function '" + FunctionName +
"'");
7166 }
else if (M->getNamedValue(FunctionName)) {
7167 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7173 if (FunctionNumber == (
unsigned)-1)
7174 FunctionNumber = NumberedVals.getNext();
7178 auto I = ForwardRefValIDs.find(FunctionNumber);
7179 if (
I != ForwardRefValIDs.end()) {
7180 FwdFn =
I->second.first;
7182 return error(NameLoc,
"type of definition and forward reference of '@" +
7183 Twine(FunctionNumber) +
7188 ForwardRefValIDs.erase(
I);
7197 if (FunctionName.empty())
7198 NumberedVals.add(FunctionNumber, Fn);
7214 if (!
GC.empty()) Fn->
setGC(GC);
7217 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7221 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7222 if (ParserContext && ArgList[i].IdentLoc)
7223 ParserContext->addInstructionOrArgumentLocation(
7224 &*ArgIt, ArgList[i].IdentLoc.value());
7226 if (ArgList[i].
Name.empty())
continue;
7229 ArgIt->
setName(ArgList[i].Name);
7231 if (ArgIt->
getName() != ArgList[i].Name)
7232 return error(ArgList[i].Loc,
7233 "redefinition of argument '%" + ArgList[i].Name +
"'");
7246 if (FunctionName.empty()) {
7248 ID.UIntVal = FunctionNumber;
7251 ID.StrVal = FunctionName;
7253 auto Blocks = ForwardRefBlockAddresses.find(
ID);
7254 if (Blocks != ForwardRefBlockAddresses.end())
7255 return error(Blocks->first.Loc,
7256 "cannot take blockaddress inside a declaration");
7260bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7262 if (FunctionNumber == -1) {
7264 ID.StrVal = std::string(F.getName());
7267 ID.UIntVal = FunctionNumber;
7270 auto Blocks = P.ForwardRefBlockAddresses.find(
ID);
7271 if (Blocks == P.ForwardRefBlockAddresses.end())
7274 for (
const auto &
I : Blocks->second) {
7275 const ValID &BBID =
I.first;
7276 GlobalValue *GV =
I.second;
7279 "Expected local id or name");
7286 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7289 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7297 P.ForwardRefBlockAddresses.erase(Blocks);
7303bool LLParser::parseFunctionBody(Function &Fn,
unsigned FunctionNumber,
7304 ArrayRef<unsigned> UnnamedArgNums) {
7306 return tokError(
"expected '{' in function body");
7309 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7313 if (PFS.resolveForwardRefBlockAddresses())
7319 return tokError(
"function body requires at least one basic block");
7323 if (parseBasicBlock(PFS))
7327 if (parseUseListOrder(&PFS))
7334 return PFS.finishFunction();
7339bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7340 FileLoc BBStart = getTokLineColumnPos();
7345 LocTy NameLoc = Lex.getLoc();
7347 Name = Lex.getStrVal();
7350 NameID = Lex.getUIntVal();
7354 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7358 std::string NameStr;
7363 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7364 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7371 if (SeenOldDbgInfoFormat)
7372 return error(Lex.getLoc(),
"debug record should not appear in a module "
7373 "containing debug info intrinsics");
7374 SeenNewDbgInfoFormat =
true;
7378 if (parseDebugRecord(DR, PFS))
7380 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7383 FileLoc InstStart = getTokLineColumnPos();
7386 LocTy NameLoc = Lex.getLoc();
7391 NameID = Lex.getUIntVal();
7393 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7396 NameStr = Lex.getStrVal();
7398 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7402 switch (parseInstruction(Inst, BB, PFS)) {
7405 case InstError:
return true;
7412 if (parseInstructionMetadata(*Inst))
7415 case InstExtraComma:
7420 if (parseInstructionMetadata(*Inst))
7426 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7430 for (DbgRecordPtr &DR : TrailingDbgRecord)
7432 TrailingDbgRecord.clear();
7433 if (ParserContext) {
7434 ParserContext->addInstructionOrArgumentLocation(
7435 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7440 ParserContext->addBlockLocation(
7441 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7443 assert(TrailingDbgRecord.empty() &&
7444 "All debug values should have been attached to an instruction.");
7453bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7456 LocTy DVRLoc = Lex.getLoc();
7458 return error(DVRLoc,
"expected debug record type here");
7459 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7460 .Case(
"declare", RecordKind::ValueKind)
7461 .Case(
"value", RecordKind::ValueKind)
7462 .Case(
"assign", RecordKind::ValueKind)
7463 .Case(
"label", RecordKind::LabelKind)
7464 .Case(
"declare_value", RecordKind::ValueKind);
7473 if (parseMDNode(Label))
7478 if (parseMDNode(DbgLoc))
7486 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7487 .Case(
"declare", LocType::Declare)
7488 .Case(
"value", LocType::Value)
7489 .Case(
"assign", LocType::Assign)
7490 .Case(
"declare_value", LocType::DeclareValue);
7498 if (parseMetadata(ValLocMD, &PFS))
7505 if (parseMDNode(Variable))
7512 if (parseMDNode(Expression))
7518 MDNode *AssignID =
nullptr;
7519 Metadata *AddressLocation =
nullptr;
7520 MDNode *AddressExpression =
nullptr;
7523 if (parseMDNode(AssignID))
7529 if (parseMetadata(AddressLocation, &PFS))
7535 if (parseMDNode(AddressExpression))
7549 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7559int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7560 PerFunctionState &PFS) {
7563 return tokError(
"found end of file when expecting more instructions");
7564 LocTy Loc = Lex.getLoc();
7565 unsigned KeywordVal = Lex.getUIntVal();
7570 return error(Loc,
"expected instruction opcode");
7574 return parseRet(Inst, BB, PFS);
7576 return parseBr(Inst, PFS);
7578 return parseSwitch(Inst, PFS);
7580 return parseIndirectBr(Inst, PFS);
7582 return parseInvoke(Inst, PFS);
7584 return parseResume(Inst, PFS);
7586 return parseCleanupRet(Inst, PFS);
7588 return parseCatchRet(Inst, PFS);
7590 return parseCatchSwitch(Inst, PFS);
7592 return parseCatchPad(Inst, PFS);
7594 return parseCleanupPad(Inst, PFS);
7596 return parseCallBr(Inst, PFS);
7599 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7600 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7616 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7628 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7629 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7643 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7651 return parseArithmetic(Inst, PFS, KeywordVal,
7655 if (parseLogical(Inst, PFS, KeywordVal))
7663 return parseLogical(Inst, PFS, KeywordVal);
7666 if (parseCompare(Inst, PFS, KeywordVal))
7673 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7674 int Res = parseCompare(Inst, PFS, KeywordVal);
7686 bool Res = parseCast(Inst, PFS, KeywordVal);
7698 if (parseCast(Inst, PFS, KeywordVal))
7715 return parseCast(Inst, PFS, KeywordVal);
7718 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7719 if (parseCast(Inst, PFS, KeywordVal))
7728 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7729 int Res = parseSelect(Inst, PFS);
7734 return error(Loc,
"fast-math-flags specified for select without "
7735 "floating-point scalar or vector return type");
7741 return parseVAArg(Inst, PFS);
7743 return parseExtractElement(Inst, PFS);
7745 return parseInsertElement(Inst, PFS);
7747 return parseShuffleVector(Inst, PFS);
7749 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7750 int Res = parsePHI(Inst, PFS);
7755 return error(Loc,
"fast-math-flags specified for phi without "
7756 "floating-point scalar or vector return type");
7762 return parseLandingPad(Inst, PFS);
7764 return parseFreeze(Inst, PFS);
7776 return parseAlloc(Inst, PFS);
7778 return parseLoad(Inst, PFS);
7780 return parseStore(Inst, PFS);
7782 return parseCmpXchg(Inst, PFS);
7784 return parseAtomicRMW(Inst, PFS);
7786 return parseFence(Inst, PFS);
7788 return parseGetElementPtr(Inst, PFS);
7790 return parseExtractValue(Inst, PFS);
7792 return parseInsertValue(Inst, PFS);
7797bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
7798 if (
Opc == Instruction::FCmp) {
7799 switch (Lex.getKind()) {
7801 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
7820 switch (Lex.getKind()) {
7822 return tokError(
"expected icmp predicate (e.g. 'eq')");
7846bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7847 PerFunctionState &PFS) {
7848 SMLoc TypeLoc = Lex.getLoc();
7850 if (parseType(Ty,
true ))
7853 Type *ResType = PFS.getFunction().getReturnType();
7857 return error(TypeLoc,
"value doesn't match function result type '" +
7865 if (parseValue(Ty, RV, PFS))
7869 return error(TypeLoc,
"value doesn't match function result type '" +
7879bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7883 if (parseTypeAndValue(Op0, Loc, PFS))
7892 return error(Loc,
"branch condition must have 'i1' type");
7894 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
7895 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7896 parseToken(
lltok::comma,
"expected ',' after true destination") ||
7897 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7909bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7910 LocTy CondLoc, BBLoc;
7913 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
7914 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
7915 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7919 if (!
Cond->getType()->isIntegerTy())
7920 return error(CondLoc,
"switch condition must have integer type");
7923 SmallPtrSet<Value*, 32> SeenCases;
7929 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7930 parseToken(
lltok::comma,
"expected ',' after case value") ||
7931 parseTypeAndBasicBlock(DestBB, PFS))
7934 if (!SeenCases.
insert(Constant).second)
7935 return error(CondLoc,
"duplicate case value in switch");
7937 return error(CondLoc,
"case value is not a constant integer");
7945 for (
const auto &[OnVal, Dest] : Table)
7946 SI->addCase(OnVal, Dest);
7954bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7957 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
7958 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
7962 if (!
Address->getType()->isPointerTy())
7963 return error(AddrLoc,
"indirectbr address must have pointer type");
7966 SmallVector<BasicBlock*, 16> DestList;
7970 if (parseTypeAndBasicBlock(DestBB, PFS))
7975 if (parseTypeAndBasicBlock(DestBB, PFS))
7981 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
7985 for (BasicBlock *Dest : DestList)
7995 FunctionType *&FuncTy) {
8001 for (
const ParamInfo &Arg : ArgList)
8015bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8016 LocTy CallLoc = Lex.getLoc();
8017 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8018 std::vector<unsigned> FwdRefAttrGrps;
8021 unsigned InvokeAddrSpace;
8022 Type *RetType =
nullptr;
8029 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8030 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8031 parseType(RetType, RetTypeLoc,
true ) ||
8032 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8033 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8035 parseOptionalOperandBundles(BundleList, PFS) ||
8037 parseTypeAndBasicBlock(NormalBB, PFS) ||
8039 parseTypeAndBasicBlock(UnwindBB, PFS))
8046 if (resolveFunctionType(RetType, ArgList, Ty))
8047 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8053 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
8058 SmallVector<Value *, 8>
Args;
8065 for (
const ParamInfo &Arg : ArgList) {
8066 Type *ExpectedTy =
nullptr;
8069 }
else if (!Ty->isVarArg()) {
8070 return error(Arg.Loc,
"too many arguments specified");
8073 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8074 return error(Arg.Loc,
"argument is not of expected type '" +
8076 Args.push_back(Arg.V);
8081 return error(CallLoc,
"not enough parameters specified for call");
8090 II->setCallingConv(CC);
8091 II->setAttributes(PAL);
8092 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
8099bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8101 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8109bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8110 PerFunctionState &PFS) {
8111 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8116 if (!
Args.empty() &&
8117 parseToken(
lltok::comma,
"expected ',' in argument list"))
8122 Type *ArgTy =
nullptr;
8123 if (parseType(ArgTy, ArgLoc))
8128 if (parseMetadataAsValue(V, PFS))
8131 if (parseValue(ArgTy, V, PFS))
8143bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8144 Value *CleanupPad =
nullptr;
8146 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8161 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8172bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8173 Value *CatchPad =
nullptr;
8175 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8182 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8183 parseTypeAndBasicBlock(BB, PFS))
8192bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8200 return tokError(
"expected scope value for catchswitch");
8205 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8211 if (parseTypeAndBasicBlock(DestBB, PFS))
8216 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8219 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8227 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8233 for (BasicBlock *DestBB : Table)
8234 CatchSwitch->addHandler(DestBB);
8241bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8242 Value *CatchSwitch =
nullptr;
8248 return tokError(
"expected scope value for catchpad");
8253 SmallVector<Value *, 8>
Args;
8254 if (parseExceptionArgs(Args, PFS))
8263bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8264 Value *ParentPad =
nullptr;
8271 return tokError(
"expected scope value for cleanuppad");
8276 SmallVector<Value *, 8>
Args;
8277 if (parseExceptionArgs(Args, PFS))
8293bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8294 unsigned Opc,
bool IsFP) {
8296 if (parseTypeAndValue(
LHS, Loc, PFS))
8303 return error(Loc,
"invalid operand type for instruction");
8313bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8314 LocTy CallLoc = Lex.getLoc();
8315 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8316 std::vector<unsigned> FwdRefAttrGrps;
8319 Type *RetType =
nullptr;
8326 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8327 parseType(RetType, RetTypeLoc,
true ) ||
8328 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8329 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8331 parseOptionalOperandBundles(BundleList, PFS) ||
8333 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8338 SmallVector<BasicBlock *, 16> IndirectDests;
8342 if (parseTypeAndBasicBlock(DestBB, PFS))
8347 if (parseTypeAndBasicBlock(DestBB, PFS))
8353 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8360 if (resolveFunctionType(RetType, ArgList, Ty))
8361 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8372 SmallVector<Value *, 8>
Args;
8379 for (
const ParamInfo &Arg : ArgList) {
8380 Type *ExpectedTy =
nullptr;
8383 }
else if (!Ty->isVarArg()) {
8384 return error(Arg.Loc,
"too many arguments specified");
8387 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8388 return error(Arg.Loc,
"argument is not of expected type '" +
8390 Args.push_back(Arg.V);
8395 return error(CallLoc,
"not enough parameters specified for call");
8407 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8421bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8422 unsigned Opc,
bool IsFP) {
8424 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8425 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8433 return error(Loc,
"invalid operand type for instruction");
8441bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8444 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8445 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8451 "instruction requires integer or integer vector operands");
8460bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8466 if (parseCmpPredicate(Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8467 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8471 if (
Opc == Instruction::FCmp) {
8473 return error(Loc,
"fcmp requires floating point operands");
8476 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8479 return error(Loc,
"icmp requires integer operands");
8491bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8495 Type *DestTy =
nullptr;
8496 if (parseTypeAndValue(
Op, Loc, PFS) ||
8497 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8502 return error(Loc,
"invalid cast opcode for cast from '" +
8511bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8513 Value *Op0, *Op1, *Op2;
8514 if (parseTypeAndValue(Op0, Loc, PFS) ||
8515 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8516 parseTypeAndValue(Op1, PFS) ||
8517 parseToken(
lltok::comma,
"expected ',' after select value") ||
8518 parseTypeAndValue(Op2, PFS))
8522 return error(Loc, Reason);
8530bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8532 Type *EltTy =
nullptr;
8534 if (parseTypeAndValue(
Op, PFS) ||
8535 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8536 parseType(EltTy, TypeLoc))
8540 return error(TypeLoc,
"va_arg requires operand with first class type");
8542 Inst =
new VAArgInst(
Op, EltTy);
8548bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8551 if (parseTypeAndValue(Op0, Loc, PFS) ||
8552 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8553 parseTypeAndValue(Op1, PFS))
8557 return error(Loc,
"invalid extractelement operands");
8565bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8567 Value *Op0, *Op1, *Op2;
8568 if (parseTypeAndValue(Op0, Loc, PFS) ||
8569 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8570 parseTypeAndValue(Op1, PFS) ||
8571 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8572 parseTypeAndValue(Op2, PFS))
8576 return error(Loc,
"invalid insertelement operands");
8584bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8586 Value *Op0, *Op1, *Op2;
8587 if (parseTypeAndValue(Op0, Loc, PFS) ||
8588 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8589 parseTypeAndValue(Op1, PFS) ||
8590 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8591 parseTypeAndValue(Op2, PFS))
8595 return error(Loc,
"invalid shufflevector operands");
8597 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8603int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8607 if (parseType(Ty, TypeLoc))
8611 return error(TypeLoc,
"phi node must have first class type");
8614 bool AteExtraComma =
false;
8626 AteExtraComma =
true;
8630 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8631 parseValue(Ty, Op0, PFS) ||
8632 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8641 for (
const auto &[Val, BB] : PHIVals)
8644 return AteExtraComma ? InstExtraComma : InstNormal;
8653bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8656 if (parseType(Ty, TyLoc))
8669 return tokError(
"expected 'catch' or 'filter' clause type");
8673 if (parseTypeAndValue(V, VLoc, PFS))
8680 return error(VLoc,
"'catch' clause has an invalid type");
8683 return error(VLoc,
"'filter' clause has an invalid type");
8688 return error(VLoc,
"clause argument must be a constant");
8692 Inst = LP.release();
8698bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8701 if (parseTypeAndValue(
Op, Loc, PFS))
8704 Inst =
new FreezeInst(
Op);
8717bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8719 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8720 std::vector<unsigned> FwdRefAttrGrps;
8722 unsigned CallAddrSpace;
8724 Type *RetType =
nullptr;
8729 LocTy CallLoc = Lex.getLoc();
8733 "expected 'tail call', 'musttail call', or 'notail call'"))
8736 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8738 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8739 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8740 parseType(RetType, RetTypeLoc,
true ) ||
8741 parseValID(CalleeID, &PFS) ||
8743 PFS.getFunction().isVarArg()) ||
8744 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8745 parseOptionalOperandBundles(BundleList, PFS))
8752 if (resolveFunctionType(RetType, ArgList, Ty))
8753 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8759 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
8766 SmallVector<Value*, 8>
Args;
8772 for (
const ParamInfo &Arg : ArgList) {
8773 Type *ExpectedTy =
nullptr;
8776 }
else if (!Ty->isVarArg()) {
8777 return error(Arg.Loc,
"too many arguments specified");
8780 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8781 return error(Arg.Loc,
"argument is not of expected type '" +
8783 Args.push_back(Arg.V);
8784 Attrs.push_back(Arg.Attrs);
8788 return error(CallLoc,
"not enough parameters specified for call");
8801 return error(CallLoc,
"fast-math-flags specified for call without "
8802 "floating-point scalar or vector return type");
8809 if (SeenNewDbgInfoFormat) {
8811 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
8812 "using non-intrinsic debug info");
8814 SeenOldDbgInfoFormat =
true;
8817 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8829int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8831 LocTy SizeLoc, TyLoc, ASLoc;
8832 MaybeAlign Alignment;
8833 unsigned AddrSpace = 0;
8836 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8837 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8839 if (parseType(Ty, TyLoc))
8843 return error(TyLoc,
"invalid type for alloca");
8845 bool AteExtraComma =
false;
8847 if (Lex.getKind() == lltok::kw_align) {
8848 if (parseOptionalAlignment(Alignment))
8850 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8853 ASLoc = Lex.getLoc();
8854 if (parseOptionalAddrSpace(AddrSpace))
8857 AteExtraComma =
true;
8859 if (parseTypeAndValue(
Size, SizeLoc, PFS))
8862 if (Lex.getKind() == lltok::kw_align) {
8863 if (parseOptionalAlignment(Alignment))
8865 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8868 ASLoc = Lex.getLoc();
8869 if (parseOptionalAddrSpace(AddrSpace))
8872 AteExtraComma =
true;
8878 if (
Size && !
Size->getType()->isIntegerTy())
8879 return error(SizeLoc,
"element count must have integer type");
8881 SmallPtrSet<Type *, 4> Visited;
8882 if (!Alignment && !Ty->
isSized(&Visited))
8883 return error(TyLoc,
"Cannot allocate unsized type");
8885 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8886 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
8890 return AteExtraComma ? InstExtraComma : InstNormal;
8897int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8899 MaybeAlign Alignment;
8900 bool AteExtraComma =
false;
8901 bool isAtomic =
false;
8910 bool isVolatile =
false;
8917 LocTy ExplicitTypeLoc = Lex.getLoc();
8918 if (parseType(Ty) ||
8919 parseToken(
lltok::comma,
"expected comma after load's type") ||
8920 parseTypeAndValue(Val, Loc, PFS) ||
8921 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8922 parseOptionalCommaAlign(Alignment, AteExtraComma))
8926 return error(Loc,
"load operand must be a pointer to a first class type");
8927 if (isAtomic && !Alignment)
8928 return error(Loc,
"atomic load must have explicit non-zero alignment");
8931 return error(Loc,
"atomic load cannot use Release ordering");
8933 SmallPtrSet<Type *, 4> Visited;
8934 if (!Alignment && !Ty->
isSized(&Visited))
8935 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
8937 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8938 Inst =
new LoadInst(Ty, Val,
"", isVolatile, *Alignment, Ordering, SSID);
8939 return AteExtraComma ? InstExtraComma : InstNormal;
8947int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8949 MaybeAlign Alignment;
8950 bool AteExtraComma =
false;
8951 bool isAtomic =
false;
8960 bool isVolatile =
false;
8966 if (parseTypeAndValue(Val, Loc, PFS) ||
8967 parseToken(
lltok::comma,
"expected ',' after store operand") ||
8968 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8969 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8970 parseOptionalCommaAlign(Alignment, AteExtraComma))
8974 return error(PtrLoc,
"store operand must be a pointer");
8976 return error(Loc,
"store operand must be a first class value");
8977 if (isAtomic && !Alignment)
8978 return error(Loc,
"atomic store must have explicit non-zero alignment");
8981 return error(Loc,
"atomic store cannot use Acquire ordering");
8982 SmallPtrSet<Type *, 4> Visited;
8984 return error(Loc,
"storing unsized types is not allowed");
8986 Alignment = M->getDataLayout().getABITypeAlign(Val->
getType());
8988 Inst =
new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8989 return AteExtraComma ? InstExtraComma : InstNormal;
8996int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8998 bool AteExtraComma =
false;
9002 bool isVolatile =
false;
9003 bool isWeak =
false;
9004 MaybeAlign Alignment;
9012 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9013 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
9014 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9015 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
9016 parseTypeAndValue(New, NewLoc, PFS) ||
9017 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
9018 parseOrdering(FailureOrdering) ||
9019 parseOptionalCommaAlign(Alignment, AteExtraComma))
9023 return tokError(
"invalid cmpxchg success ordering");
9025 return tokError(
"invalid cmpxchg failure ordering");
9027 return error(PtrLoc,
"cmpxchg operand must be a pointer");
9028 if (
Cmp->getType() !=
New->getType())
9029 return error(NewLoc,
"compare value and new value type do not match");
9030 if (!
New->getType()->isFirstClassType())
9031 return error(NewLoc,
"cmpxchg operand must be a first class value");
9033 const Align DefaultAlignment(
9034 PFS.getFunction().getDataLayout().getTypeStoreSize(
9037 AtomicCmpXchgInst *CXI =
9038 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9039 SuccessOrdering, FailureOrdering, SSID);
9044 return AteExtraComma ? InstExtraComma : InstNormal;
9051int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9053 bool AteExtraComma =
false;
9057 bool IsElementwise =
false;
9060 MaybeAlign Alignment;
9065 IsElementwise =
true;
9067 switch (Lex.getKind()) {
9069 return tokError(
"expected binary operation in atomicrmw");
9128 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9129 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9130 parseTypeAndValue(Val, ValLoc, PFS) ||
9131 parseScopeAndOrdering(
true , SSID, Ordering) ||
9132 parseOptionalCommaAlign(Alignment, AteExtraComma))
9136 return tokError(
"atomicrmw cannot be unordered");
9138 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9140 return error(ValLoc,
"atomicrmw operand may not be scalable");
9146 if (IsElementwise) {
9149 return error(ValLoc,
9150 "atomicrmw elementwise operand must be a fixed vector type");
9151 ScalarTy = VecTy->getElementType();
9160 " operand must be an integer, floating point, or pointer type");
9164 return error(ValLoc,
"atomicrmw " +
9166 " operand must be a floating point type");
9170 return error(ValLoc,
"atomicrmw " +
9172 " operand must be an integer");
9177 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(Val->
getType());
9179 return error(ValLoc,
9180 "atomicrmw operand must have a power-of-two byte size");
9181 const Align DefaultAlignment(
9182 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->
getType()));
9183 AtomicRMWInst *RMWI =
new AtomicRMWInst(
Operation, Ptr, Val,
9184 Alignment.value_or(DefaultAlignment),
9185 Ordering, SSID, IsElementwise);
9188 return AteExtraComma ? InstExtraComma : InstNormal;
9193int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9196 if (parseScopeAndOrdering(
true , SSID, Ordering))
9200 return tokError(
"fence cannot be unordered");
9202 return tokError(
"fence cannot be monotonic");
9204 Inst =
new FenceInst(Context, Ordering, SSID);
9210int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9211 Value *Ptr =
nullptr;
9212 Value *Val =
nullptr;
9228 if (parseType(Ty) ||
9229 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9230 parseTypeAndValue(Ptr, Loc, PFS))
9235 if (!BasePointerType)
9236 return error(Loc,
"base of getelementptr must be a pointer");
9238 SmallVector<Value*, 16> Indices;
9239 bool AteExtraComma =
false;
9242 ElementCount GEPWidth =
BaseType->isVectorTy()
9248 AteExtraComma =
true;
9251 if (parseTypeAndValue(Val, EltLoc, PFS))
9254 return error(EltLoc,
"getelementptr index must be an integer");
9257 ElementCount ValNumEl = ValVTy->getElementCount();
9261 "getelementptr vector index has a wrong number of elements");
9262 GEPWidth = ValNumEl;
9267 SmallPtrSet<Type*, 4> Visited;
9269 return error(Loc,
"base element of getelementptr must be sized");
9273 return error(Loc,
"getelementptr cannot target structure that contains "
9274 "scalable vector type");
9277 return error(Loc,
"invalid getelementptr indices");
9280 GEP->setNoWrapFlags(NW);
9281 return AteExtraComma ? InstExtraComma : InstNormal;
9286int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9288 SmallVector<unsigned, 4> Indices;
9290 if (parseTypeAndValue(Val, Loc, PFS) ||
9291 parseIndexList(Indices, AteExtraComma))
9295 return error(Loc,
"extractvalue operand must be aggregate type");
9298 return error(Loc,
"invalid indices for extractvalue");
9300 return AteExtraComma ? InstExtraComma : InstNormal;
9305int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9307 SmallVector<unsigned, 4> Indices;
9309 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9310 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9311 parseTypeAndValue(Val1, Loc1, PFS) ||
9312 parseIndexList(Indices, AteExtraComma))
9316 return error(Loc0,
"insertvalue operand must be aggregate type");
9320 return error(Loc0,
"invalid indices for insertvalue");
9321 if (IndexedType != Val1->
getType())
9322 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9326 return AteExtraComma ? InstExtraComma : InstNormal;
9337bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9352 if (parseMetadata(MD,
nullptr))
9357 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9363bool LLParser::sortUseListOrder(
Value *V, ArrayRef<unsigned> Indexes,
9365 if (!
V->hasUseList())
9368 return error(Loc,
"value has no uses");
9370 unsigned NumUses = 0;
9371 SmallDenseMap<const Use *, unsigned, 16> Order;
9372 for (
const Use &U :
V->uses()) {
9373 if (++NumUses > Indexes.
size())
9375 Order[&
U] = Indexes[NumUses - 1];
9378 return error(Loc,
"value only has one use");
9379 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9381 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9383 V->sortUseList([&](
const Use &L,
const Use &R) {
9391bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9392 SMLoc Loc = Lex.getLoc();
9396 return tokError(
"expected non-empty list of uselistorder indexes");
9403 bool IsOrdered =
true;
9404 assert(Indexes.
empty() &&
"Expected empty order vector");
9407 if (parseUInt32(Index))
9412 Max = std::max(Max, Index);
9413 IsOrdered &= Index == Indexes.
size();
9421 if (Indexes.
size() < 2)
9422 return error(Loc,
"expected >= 2 uselistorder indexes");
9425 "expected distinct uselistorder indexes in range [0, size)");
9427 return error(Loc,
"expected uselistorder indexes to change the order");
9434bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9435 SMLoc Loc = Lex.getLoc();
9440 SmallVector<unsigned, 16> Indexes;
9441 if (parseTypeAndValue(V, PFS) ||
9442 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9443 parseUseListOrderIndexes(Indexes))
9446 return sortUseListOrder(V, Indexes, Loc);
9451bool LLParser::parseUseListOrderBB() {
9453 SMLoc Loc = Lex.getLoc();
9457 SmallVector<unsigned, 16> Indexes;
9458 if (parseValID(Fn,
nullptr) ||
9459 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
9460 parseValID(Label,
nullptr) ||
9461 parseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
9462 parseUseListOrderIndexes(Indexes))
9468 GV = M->getNamedValue(Fn.
StrVal);
9470 GV = NumberedVals.get(Fn.
UIntVal);
9472 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
9475 "invalid function forward reference in uselistorder_bb");
9478 return error(Fn.
Loc,
"expected function name in uselistorder_bb");
9479 if (
F->isDeclaration())
9480 return error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
9484 return error(
Label.Loc,
"invalid numeric label in uselistorder_bb");
9486 return error(
Label.Loc,
"expected basic block name in uselistorder_bb");
9487 Value *
V =
F->getValueSymbolTable()->lookup(
Label.StrVal);
9489 return error(
Label.Loc,
"invalid basic block in uselistorder_bb");
9491 return error(
Label.Loc,
"expected basic block in uselistorder_bb");
9493 return sortUseListOrder(V, Indexes, Loc);
9499bool LLParser::parseModuleEntry(
unsigned ID) {
9508 parseStringConstant(Path) ||
9516 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9517 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9518 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9519 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9520 parseUInt32(Hash[4]))
9527 auto ModuleEntry = Index->addModule(Path, Hash);
9528 ModuleIdMap[
ID] = ModuleEntry->first();
9535bool LLParser::parseTypeIdEntry(
unsigned ID) {
9544 parseStringConstant(Name))
9547 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9549 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9554 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9555 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9556 for (
auto TIDRef : FwdRefTIDs->second) {
9558 "Forward referenced type id GUID expected to be 0");
9561 ForwardRefTypeIds.erase(FwdRefTIDs);
9569bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9573 parseTypeTestResolution(TIS.
TTRes))
9578 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9589 ValueInfo(
false, (GlobalValueSummaryMapTy::value_type *)-8);
9595bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9604 parseStringConstant(Name))
9608 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9615 IdToIndexMapType IdToIndexMap;
9628 if (parseGVReference(VI, GVId))
9635 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9636 TI.push_back({
Offset, VI});
9644 for (
auto I : IdToIndexMap) {
9645 auto &Infos = ForwardRefValueInfos[
I.first];
9646 for (
auto P :
I.second) {
9648 "Forward referenced ValueInfo expected to be empty");
9649 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9659 auto FwdRefTIDs = ForwardRefTypeIds.find(
ID);
9660 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9661 for (
auto TIDRef : FwdRefTIDs->second) {
9663 "Forward referenced type id GUID expected to be 0");
9666 ForwardRefTypeIds.erase(FwdRefTIDs);
9678bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9686 switch (Lex.getKind()) {
9706 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9718 switch (Lex.getKind()) {
9733 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9746 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
9759bool LLParser::parseOptionalWpdResolutions(
9760 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9768 WholeProgramDevirtResolution WPDRes;
9772 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
9775 WPDResMap[
Offset] = WPDRes;
9792bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9800 switch (Lex.getKind()) {
9811 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
9817 switch (Lex.getKind()) {
9825 if (parseOptionalResByArg(WPDRes.
ResByArg))
9829 return error(Lex.getLoc(),
9830 "expected optional WholeProgramDevirtResolution field");
9847bool LLParser::parseOptionalResByArg(
9848 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9856 std::vector<uint64_t>
Args;
9857 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
9865 WholeProgramDevirtResolution::ByArg ByArg;
9866 switch (Lex.getKind()) {
9880 return error(Lex.getLoc(),
9881 "unexpected WholeProgramDevirtResolution::ByArg kind");
9887 switch (Lex.getKind()) {
9891 parseUInt64(ByArg.
Info))
9897 parseUInt32(ByArg.
Byte))
9903 parseUInt32(ByArg.
Bit))
9907 return error(Lex.getLoc(),
9908 "expected optional whole program devirt field");
9915 ResByArg[
Args] = ByArg;
9926bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9934 if (parseUInt64(Val))
9936 Args.push_back(Val);
9945static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9960bool LLParser::addGlobalValueToIndex(
9962 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
9967 VI = Index->getOrInsertValueInfo(GUID);
9971 auto *GV = M->getNamedValue(Name);
9973 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
9979 VI = Index->getOrInsertValueInfo(GV, GUID);
9983 "Need a source_filename to compute GUID for local");
9986 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9991 auto FwdRefVIs = ForwardRefValueInfos.find(
ID);
9992 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9993 for (
auto VIRef : FwdRefVIs->second) {
9995 "Forward referenced ValueInfo expected to be empty");
9998 ForwardRefValueInfos.erase(FwdRefVIs);
10002 auto FwdRefAliasees = ForwardRefAliasees.find(
ID);
10003 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10004 for (
auto AliaseeRef : FwdRefAliasees->second) {
10005 assert(!AliaseeRef.first->hasAliasee() &&
10006 "Forward referencing alias already has aliasee");
10007 assert(Summary &&
"Aliasee must be a definition");
10008 AliaseeRef.first->setAliasee(VI,
Summary.get());
10010 ForwardRefAliasees.erase(FwdRefAliasees);
10015 Index->addGlobalValueSummary(VI, std::move(Summary));
10018 if (
ID == NumberedValueInfos.size())
10019 NumberedValueInfos.push_back(VI);
10022 if (
ID > NumberedValueInfos.size())
10023 NumberedValueInfos.resize(
ID + 1);
10024 NumberedValueInfos[
ID] =
VI;
10032bool LLParser::parseSummaryIndexFlags() {
10039 if (parseUInt64(Flags))
10042 Index->setFlags(Flags);
10048bool LLParser::parseBlockCount() {
10054 uint64_t BlockCount;
10055 if (parseUInt64(BlockCount))
10058 Index->setBlockCount(BlockCount);
10066bool LLParser::parseGVEntry(
unsigned ID) {
10074 LocTy Loc = Lex.getLoc();
10077 switch (Lex.getKind()) {
10081 parseStringConstant(Name))
10087 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
10091 return error(Lex.getLoc(),
"expected name or guid tag");
10114 switch (Lex.getKind()) {
10116 if (parseFunctionSummary(Name, GUID,
ID))
10120 if (parseVariableSummary(Name, GUID,
ID))
10124 if (parseAliasSummary(Name, GUID,
ID))
10128 return error(Lex.getLoc(),
"expected summary type");
10146 LocTy Loc = Lex.getLoc();
10150 StringRef ModulePath;
10151 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10154 false,
false,
false,
10156 unsigned InstCount;
10158 FunctionSummary::TypeIdInfo TypeIdInfo;
10159 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10161 std::vector<CallsiteInfo> Callsites;
10162 std::vector<AllocInfo> Allocs;
10164 FunctionSummary::FFlags FFlags = {};
10167 parseModuleReference(ModulePath) ||
10168 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10171 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10176 switch (Lex.getKind()) {
10178 if (parseOptionalFFlags(FFlags))
10182 if (parseOptionalCalls(Calls))
10186 if (parseOptionalTypeIdInfo(TypeIdInfo))
10190 if (parseOptionalRefs(Refs))
10194 if (parseOptionalParamAccesses(ParamAccesses))
10198 if (parseOptionalAllocs(Allocs))
10202 if (parseOptionalCallsites(Callsites))
10206 return error(Lex.getLoc(),
"expected optional function summary field");
10213 auto FS = std::make_unique<FunctionSummary>(
10214 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10220 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10222 FS->setModulePath(ModulePath);
10224 return addGlobalValueToIndex(Name, GUID,
10226 std::move(FS), Loc);
10234 LocTy Loc = Lex.getLoc();
10238 StringRef ModulePath;
10239 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10242 false,
false,
false,
10244 GlobalVarSummary::GVarFlags GVarFlags(
false,
10252 parseModuleReference(ModulePath) ||
10253 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10255 parseGVarFlags(GVarFlags))
10260 switch (Lex.getKind()) {
10262 if (parseOptionalVTableFuncs(VTableFuncs))
10266 if (parseOptionalRefs(Refs))
10270 return error(Lex.getLoc(),
"expected optional variable summary field");
10278 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10280 GS->setModulePath(ModulePath);
10281 GS->setVTableFuncs(std::move(VTableFuncs));
10283 return addGlobalValueToIndex(Name, GUID,
10285 std::move(GS), Loc);
10294 LocTy Loc = Lex.getLoc();
10297 StringRef ModulePath;
10298 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10301 false,
false,
false,
10305 parseModuleReference(ModulePath) ||
10306 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10312 ValueInfo AliaseeVI;
10314 auto AS = std::make_unique<AliasSummary>(GVFlags);
10315 AS->setModulePath(ModulePath);
10318 if (parseGVReference(AliaseeVI, GVId))
10323 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10325 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10326 assert(Summary &&
"Aliasee must be a definition");
10327 AS->setAliasee(AliaseeVI, Summary);
10334 return addGlobalValueToIndex(Name, GUID,
10336 std::move(AS), Loc);
10341bool LLParser::parseFlag(
unsigned &Val) {
10342 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10343 return tokError(
"expected integer");
10344 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10360bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10364 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10370 switch (Lex.getKind()) {
10373 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10379 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10385 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10391 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10397 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10403 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10409 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10415 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10421 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10427 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10432 return error(Lex.getLoc(),
"expected function flag type");
10436 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10447bool LLParser::parseOptionalCalls(
10448 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10452 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10456 IdToIndexMapType IdToIndexMap;
10465 LocTy Loc = Lex.getLoc();
10467 if (parseGVReference(VI, GVId))
10471 unsigned RelBF = 0;
10472 unsigned HasTailCall =
false;
10476 switch (Lex.getKind()) {
10479 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10485 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10490 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10494 return error(Lex.getLoc(),
"expected hotness, relbf, or tail");
10501 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10511 for (
auto I : IdToIndexMap) {
10512 auto &Infos = ForwardRefValueInfos[
I.first];
10513 for (
auto P :
I.second) {
10515 "Forward referenced ValueInfo expected to be empty");
10516 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10529 switch (Lex.getKind()) {
10533 case lltok::kw_cold:
10539 case lltok::kw_hot:
10546 return error(Lex.getLoc(),
"invalid call edge hotness");
10555bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10559 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10563 IdToIndexMapType IdToIndexMap;
10567 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10572 LocTy Loc = Lex.getLoc();
10574 if (parseGVReference(VI, GVId))
10587 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10588 VTableFuncs.push_back({
VI,
Offset});
10590 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10596 for (
auto I : IdToIndexMap) {
10597 auto &Infos = ForwardRefValueInfos[
I.first];
10598 for (
auto P :
I.second) {
10600 "Forward referenced ValueInfo expected to be empty");
10601 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10605 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10612bool LLParser::parseParamNo(uint64_t &ParamNo) {
10614 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10620bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10623 auto ParseAPSInt = [&](
APSInt &Val) {
10625 return tokError(
"expected integer");
10626 Val = Lex.getAPSIntVal();
10628 Val.setIsSigned(
true);
10650bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10651 IdLocListType &IdLocList) {
10659 LocTy Loc = Lex.getLoc();
10660 if (parseGVReference(VI, GVId))
10664 IdLocList.emplace_back(GVId, Loc);
10667 parseParamNo(
Call.ParamNo) ||
10669 parseParamAccessOffset(
Call.Offsets))
10681bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10682 IdLocListType &IdLocList) {
10684 parseParamNo(
Param.ParamNo) ||
10686 parseParamAccessOffset(
Param.Use))
10695 FunctionSummary::ParamAccess::Call
Call;
10696 if (parseParamAccessCall(
Call, IdLocList))
10713bool LLParser::parseOptionalParamAccesses(
10714 std::vector<FunctionSummary::ParamAccess> &Params) {
10722 IdLocListType VContexts;
10723 size_t CallsNum = 0;
10725 FunctionSummary::ParamAccess ParamAccess;
10726 if (parseParamAccess(ParamAccess, VContexts))
10728 CallsNum += ParamAccess.
Calls.size();
10729 assert(VContexts.size() == CallsNum);
10731 Params.emplace_back(std::move(ParamAccess));
10739 IdLocListType::const_iterator ItContext = VContexts.begin();
10740 for (
auto &PA : Params) {
10741 for (
auto &
C : PA.Calls) {
10743 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10744 ItContext->second);
10748 assert(ItContext == VContexts.end());
10755bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10759 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10763 struct ValueContext {
10768 std::vector<ValueContext> VContexts;
10772 VC.Loc = Lex.getLoc();
10773 if (parseGVReference(
VC.VI,
VC.GVId))
10775 VContexts.push_back(VC);
10781 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
10782 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10785 IdToIndexMapType IdToIndexMap;
10786 for (
auto &VC : VContexts) {
10791 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
10797 for (
auto I : IdToIndexMap) {
10798 auto &Infos = ForwardRefValueInfos[
I.first];
10799 for (
auto P :
I.second) {
10801 "Forward referenced ValueInfo expected to be empty");
10802 Infos.emplace_back(&Refs[
P.first],
P.second);
10816bool LLParser::parseOptionalTypeIdInfo(
10817 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10826 switch (Lex.getKind()) {
10828 if (parseTypeTests(TypeIdInfo.
TypeTests))
10852 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
10856 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10865bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10873 IdToIndexMapType IdToIndexMap;
10877 unsigned ID = Lex.getUIntVal();
10878 LocTy Loc = Lex.getLoc();
10882 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
10884 }
else if (parseUInt64(GUID))
10886 TypeTests.push_back(GUID);
10891 for (
auto I : IdToIndexMap) {
10892 auto &Ids = ForwardRefTypeIds[
I.first];
10893 for (
auto P :
I.second) {
10894 assert(TypeTests[
P.first] == 0 &&
10895 "Forward referenced type id GUID expected to be 0");
10896 Ids.emplace_back(&TypeTests[
P.first],
P.second);
10900 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
10908bool LLParser::parseVFuncIdList(
10909 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10910 assert(Lex.getKind() == Kind);
10917 IdToIndexMapType IdToIndexMap;
10919 FunctionSummary::VFuncId VFuncId;
10920 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10922 VFuncIdList.push_back(VFuncId);
10930 for (
auto I : IdToIndexMap) {
10931 auto &Ids = ForwardRefTypeIds[
I.first];
10932 for (
auto P :
I.second) {
10933 assert(VFuncIdList[
P.first].GUID == 0 &&
10934 "Forward referenced type id GUID expected to be 0");
10935 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
10944bool LLParser::parseConstVCallList(
10946 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10947 assert(Lex.getKind() == Kind);
10954 IdToIndexMapType IdToIndexMap;
10956 FunctionSummary::ConstVCall ConstVCall;
10957 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10959 ConstVCallList.push_back(ConstVCall);
10967 for (
auto I : IdToIndexMap) {
10968 auto &Ids = ForwardRefTypeIds[
I.first];
10969 for (
auto P :
I.second) {
10970 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
10971 "Forward referenced type id GUID expected to be 0");
10972 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
10981bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10982 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
10984 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
10988 if (parseArgs(ConstVCall.
Args))
11000bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11001 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11011 unsigned ID = Lex.getUIntVal();
11012 LocTy Loc = Lex.getLoc();
11016 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
11018 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
11020 parseUInt64(VFuncId.
GUID))
11026 parseUInt64(VFuncId.
Offset) ||
11038bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11048 switch (Lex.getKind()) {
11055 assert(HasLinkage &&
"Linkage not optional in summary entry");
11062 parseOptionalVisibility(Flag);
11067 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11073 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11079 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11085 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11094 if (parseOptionalImportType(Lex.getKind(), IK))
11096 GVFlags.
ImportType =
static_cast<unsigned>(IK);
11101 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11106 return error(Lex.getLoc(),
"expected gv flag type");
11120bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11128 auto ParseRest = [
this](
unsigned int &Val) {
11132 return parseFlag(Val);
11137 switch (Lex.getKind()) {
11138 case lltok::kw_readonly:
11139 if (ParseRest(Flag))
11143 case lltok::kw_writeonly:
11144 if (ParseRest(Flag))
11149 if (ParseRest(Flag))
11154 if (ParseRest(Flag))
11159 return error(Lex.getLoc(),
"expected gvar flag type");
11167bool LLParser::parseModuleReference(StringRef &ModulePath) {
11174 unsigned ModuleID = Lex.getUIntVal();
11175 auto I = ModuleIdMap.find(ModuleID);
11177 assert(
I != ModuleIdMap.end());
11178 ModulePath =
I->second;
11184bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11187 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11191 GVId = Lex.getUIntVal();
11193 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11195 VI = NumberedValueInfos[GVId];
11212bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11216 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11228 SmallVector<uint8_t> Versions;
11231 if (parseAllocType(V))
11236 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11240 std::vector<MIBInfo> MIBs;
11241 if (parseMemProfs(MIBs))
11244 Allocs.push_back({Versions, MIBs});
11261bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11265 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11271 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11280 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11286 SmallVector<unsigned> StackIdIndices;
11290 uint64_t StackId = 0;
11291 if (parseUInt64(StackId))
11293 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11314bool LLParser::parseAllocType(uint8_t &
AllocType) {
11315 switch (Lex.getKind()) {
11322 case lltok::kw_cold:
11325 case lltok::kw_hot:
11329 return error(Lex.getLoc(),
"invalid alloc type");
11342bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11346 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11350 IdToIndexMapType IdToIndexMap;
11353 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11360 LocTy Loc = Lex.getLoc();
11362 if (parseGVReference(VI, GVId))
11366 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11372 SmallVector<unsigned> Clones;
11375 if (parseUInt32(V))
11381 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11387 SmallVector<unsigned> StackIdIndices;
11391 uint64_t StackId = 0;
11392 if (parseUInt64(StackId))
11394 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11405 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11406 Callsites.push_back({
VI, Clones, StackIdIndices});
11414 for (
auto I : IdToIndexMap) {
11415 auto &Infos = ForwardRefValueInfos[
I.first];
11416 for (
auto P :
I.second) {
11418 "Forward referenced ValueInfo expected to be empty");
11419 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11423 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.
opStatus
IEEE-754R 7: Default exception handling.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
APSInt extOrTrunc(uint32_t width) const
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ FCMP_OLT
0 1 0 0 True if ordered and less than
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ FCMP_ULT
1 1 0 0 True if unordered or less than
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ ICMP_ULT
unsigned less than
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
@ ICMP_SGE
signed greater or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
@ ICMP_ULE
unsigned less or equal
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, 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
Return the entry for the specified key, or a default constructed value if no such entry exists.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind getKind() const
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
LLVMContext & getContext()
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
static MemoryEffectsBase readOnly()
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static auto targetMemLocations()
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
bool isTargetMemLoc(IRMemLocation Loc) const
Whether location is target memory location.
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
A Module instance is used to store all the information related to an LLVM module.
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
constexpr const char * getPointer() const
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator find(StringRef Key)
StringMapIterBase< Comdat, false > iterator
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
bool isByteTy() const
True if this is an instance of ByteType.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
bool isAggregateType() const
Return true if the type is an aggregate type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isTokenTy() const
Return true if this is 'token'.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
LLVM_ABI const fltSemantics & getFltSemantics() const
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
static constexpr uint64_t MaximumAlignment
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
LLVM_ABI unsigned getLanguageDialect(StringRef LanguageDialectString)
LLVM_ABI unsigned getTag(StringRef TagString)
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
@ X86_StdCall
stdcall is mostly used by the Win32 API.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_LLVM_LANG_DIALECT_max
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
@ kw_aarch64_sme_preservemost_from_x1
@ kw_no_sanitize_hwaddress
@ kw_cheriot_librarycallcc
@ kw_cheriot_compartmentcalleecc
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_cheriot_compartmentcallcc
@ kw_amdgpu_gfx_whole_wave
@ kw_typeTestAssumeConstVCalls
@ kw_typeidCompatibleVTable
@ kw_typeCheckedLoadVCalls
@ kw_inaccessiblemem_or_argmemonly
@ kw_externally_initialized
@ kw_sanitize_address_dyninit
@ kw_amdgpu_cs_chain_preserve
@ kw_available_externally
@ kw_typeTestAssumeVCalls
@ kw_aarch64_sme_preservemost_from_x0
@ kw_dso_local_equivalent
@ kw_aarch64_sme_preservemost_from_x2
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
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.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
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.