65 "Allow incomplete IR on a best effort basis (references to unknown "
66 "metadata will be dropped)"));
81 const char *Boundary = BoundaryLoc.
getPointer();
82 const char *BlockCommentStart =
nullptr;
83 bool InLineComment =
false;
85 for (
const char *Ptr = Begin; Ptr <
End;) {
86 if (BlockCommentStart) {
87 if (Ptr + 1 <
End && Ptr[0] ==
'*' && Ptr[1] ==
'/') {
89 if (BlockCommentStart < Boundary && Ptr > Boundary)
91 BlockCommentStart =
nullptr;
99 if (*Ptr ==
'\n' || *Ptr ==
'\r')
100 InLineComment =
false;
106 InLineComment =
true;
110 if (Ptr + 1 <
End && Ptr[0] ==
'/' && Ptr[1] ==
'*') {
111 BlockCommentStart = Ptr;
118 return BlockCommentStart && BlockCommentStart < Boundary && End > Boundary;
127 if (Context.shouldDiscardValueNames())
130 "Can't read textual IR with a Context that discards named Values");
133 if (parseTargetDefinitions(DataLayoutCallback))
137 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
138 validateEndOfIndex();
143 restoreParsingState(Slots);
147 if (parseType(Ty) || parseConstantValue(Ty,
C))
150 return error(Lex.getLoc(),
"expected end of string");
156 restoreParsingState(Slots);
160 SMLoc Start = Lex.getLoc();
165 Read =
End.getPointer() - Start.getPointer();
172 restoreParsingState(Slots);
176 SMLoc Start = Lex.getLoc();
178 bool Status = parseDIExpressionBody(Result,
false);
180 Read =
End.getPointer() - Start.getPointer();
187 restoreParsingState(&Slots);
191 if (Lex.getLoc().getPointer() >=
End.getPointer())
192 return error(
End,
"expected end of metadata definition");
194 return tokError(
"expected a metadata definition");
195 if (parseStandaloneMetadata())
197 if (Lex.getPrevTokEndLoc().getPointer() >
End.getPointer() ||
199 Lex.getLoc().getPointer() <
End.getPointer()) ||
201 return error(
End,
"expected end of metadata definition");
205 return tokError(
"expected end of metadata definitions");
207 if (!ForwardRefMDNodes.empty())
208 return error(ForwardRefMDNodes.begin()->second.second,
209 "use of undefined metadata '!" +
210 Twine(ForwardRefMDNodes.begin()->first) +
"'");
212 for (
auto &[
_, MD] : NumberedMetadata)
213 if (MD && !MD->isResolved())
216 NewDistinctSPs.clear();
218 Slots.MetadataNodes = std::move(NumberedMetadata);
222void LLParser::restoreParsingState(
const SlotMapping *Slots) {
229 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
230 for (
const auto &
I : Slots->
Types)
231 NumberedTypes.insert(
232 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
238 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
245 if (MD->isTemporary())
249 assert(
II->use_empty() &&
"Cannot have uses");
250 II->eraseFromParent();
259void LLParser::dropUnknownMetadataReferences() {
260 auto Pred = [](
unsigned MDKind, MDNode *
Node) {
return Node->isTemporary(); };
262 F.eraseMetadataIf(Pred);
264 I.eraseMetadataIf(Pred);
271 for (GlobalVariable &GV : M->globals())
272 GV.eraseMetadataIf(Pred);
275 [](
const auto &
E) {
return std::get<2>(
E)->isTemporary(); });
277 [](
const auto &
E) {
return std::get<2>(
E)->isTemporary(); });
282 if (
Info.first->getNumTemporaryUses() == 1) {
283 NumberedMetadata.erase(ID);
284 ForwardRefMDNodes.erase(ID);
297 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
298 "Mixed debug intrinsics/records seen without a parsing error?");
301 for (
const auto &RAG : ForwardRefAttrGroups) {
303 const std::vector<unsigned> &
Attrs = RAG.second;
304 AttrBuilder
B(Context);
306 for (
const auto &Attr : Attrs) {
307 auto R = NumberedAttrBuilders.find(Attr);
308 if (R != NumberedAttrBuilders.end())
313 AttributeList AS = Fn->getAttributes();
314 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
315 AS = AS.removeFnAttributes(Context);
321 if (MaybeAlign
A = FnAttrs.getAlignment()) {
322 Fn->setAlignment(*
A);
323 FnAttrs.removeAttribute(Attribute::Alignment);
326 AS = AS.addFnAttributes(Context, FnAttrs);
327 Fn->setAttributes(AS);
329 AttributeList AS = CI->getAttributes();
330 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
331 AS = AS.removeFnAttributes(Context);
333 AS = AS.addFnAttributes(Context, FnAttrs);
334 CI->setAttributes(AS);
336 AttributeList AS =
II->getAttributes();
337 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
338 AS = AS.removeFnAttributes(Context);
340 AS = AS.addFnAttributes(Context, FnAttrs);
341 II->setAttributes(AS);
343 AttributeList AS = CBI->getAttributes();
344 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
345 AS = AS.removeFnAttributes(Context);
347 AS = AS.addFnAttributes(Context, FnAttrs);
348 CBI->setAttributes(AS);
350 AttrBuilder
Attrs(M->getContext(), GV->getAttributes());
360 if (!ForwardRefBlockAddresses.empty())
361 return error(ForwardRefBlockAddresses.begin()->first.Loc,
362 "expected function name in blockaddress");
364 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
365 GlobalValue *FwdRef) {
366 GlobalValue *GV =
nullptr;
368 GV = M->getNamedValue(GVRef.
StrVal);
370 GV = NumberedVals.get(GVRef.
UIntVal);
375 "' referenced by dso_local_equivalent");
379 "expected a function, alias to function, or ifunc "
380 "in dso_local_equivalent");
383 FwdRef->replaceAllUsesWith(Equiv);
384 FwdRef->eraseFromParent();
391 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
392 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
395 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
396 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
399 ForwardRefDSOLocalEquivalentIDs.clear();
400 ForwardRefDSOLocalEquivalentNames.clear();
402 for (
const auto &NT : NumberedTypes)
403 if (
NT.second.second.isValid())
405 "use of undefined type '%" + Twine(
NT.first) +
"'");
407 for (
const auto &[Name, TypeInfo] : NamedTypes)
408 if (TypeInfo.second.isValid())
409 return error(TypeInfo.second,
410 "use of undefined type named '" + Name +
"'");
412 if (!ForwardRefComdats.empty())
413 return error(ForwardRefComdats.begin()->second,
414 "use of undefined comdat '$" +
415 ForwardRefComdats.begin()->first +
"'");
418 dropUnknownMetadataReferences();
420 if (!ForwardRefMDNodes.empty())
421 return error(ForwardRefMDNodes.begin()->second.second,
422 "use of undefined metadata '!" +
423 Twine(ForwardRefMDNodes.begin()->first) +
"'");
426 for (
auto [Loc, DR, MD] : PendingDbgRecords) {
430 return error(Loc,
"invalid debug location");
432 PendingDbgRecords.clear();
433 for (
auto [Loc,
I, MD] : PendingDbgInsts) {
437 return error(Loc,
"invalid !dbg metadata");
439 PendingDbgInsts.clear();
453 if (!CB || !CB->isCallee(&U))
454 return error(
Info.second,
"intrinsic can only be used as callee");
456 std::string ErrorMsg;
457 raw_string_ostream ErrorOS(ErrorMsg);
471 return error(
Info.second,
"unknown intrinsic '" + Name +
"'");
482 Info.first->eraseFromParent();
483 ForwardRefVals.erase(Name);
492 auto GetCommonFunctionType = [](
Value *
V) -> FunctionType * {
493 FunctionType *FTy =
nullptr;
494 for (Use &U :
V->uses()) {
496 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
498 FTy = CB->getFunctionType();
506 Type *Ty = GetCommonFunctionType(
Info.first);
514 GV =
new GlobalVariable(*M, Ty,
false,
517 Info.first->replaceAllUsesWith(GV);
518 Info.first->eraseFromParent();
519 ForwardRefVals.erase(Name);
522 if (!ForwardRefVals.empty())
523 return error(ForwardRefVals.begin()->second.second,
524 "use of undefined value '@" + ForwardRefVals.begin()->first +
527 if (!ForwardRefValIDs.empty())
528 return error(ForwardRefValIDs.begin()->second.second,
529 "use of undefined value '@" +
530 Twine(ForwardRefValIDs.begin()->first) +
"'");
533 for (
auto &
N : NumberedMetadata) {
534 if (
N.second && !
N.second->isResolved())
535 N.second->resolveCycles();
539 NewDistinctSPs.clear();
546 if (UpgradeDebugInfo)
560 Slots->GlobalValues = std::move(NumberedVals);
561 Slots->MetadataNodes = std::move(NumberedMetadata);
562 for (
const auto &
I : NamedTypes)
563 Slots->NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
564 for (
const auto &
I : NumberedTypes)
565 Slots->Types.insert(std::make_pair(
I.first,
I.second.first));
571bool LLParser::validateEndOfIndex() {
575 if (!ForwardRefValueInfos.empty())
576 return error(ForwardRefValueInfos.begin()->second.front().second,
577 "use of undefined summary '^" +
578 Twine(ForwardRefValueInfos.begin()->first) +
"'");
580 if (!ForwardRefAliasees.empty())
581 return error(ForwardRefAliasees.begin()->second.front().second,
582 "use of undefined summary '^" +
583 Twine(ForwardRefAliasees.begin()->first) +
"'");
585 if (!ForwardRefTypeIds.empty())
586 return error(ForwardRefTypeIds.begin()->second.front().second,
587 "use of undefined type id summary '^" +
588 Twine(ForwardRefTypeIds.begin()->first) +
"'");
602 std::string TentativeDLStr = M->getDataLayoutStr();
607 switch (Lex.getKind()) {
609 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
613 if (parseSourceFileName())
622 if (
auto LayoutOverride =
623 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
624 TentativeDLStr = *LayoutOverride;
630 M->setDataLayout(MaybeDL.
get());
634bool LLParser::parseTopLevelEntities() {
638 switch (Lex.getKind()) {
642 if (parseSummaryEntry())
646 if (parseSourceFileName())
656 switch (Lex.getKind()) {
658 return tokError(
"expected top-level entity");
669 if (parseModuleAsm())
673 if (parseUnnamedType())
677 if (parseNamedType())
681 if (parseUnnamedGlobal())
685 if (parseNamedGlobal())
690 if (parseStandaloneMetadata())
694 if (parseSummaryEntry())
698 if (parseNamedMetadata())
702 if (parseUnnamedAttrGrp())
706 if (parseUseListOrder())
718bool LLParser::parseModuleAsm() {
726 Module::GlobalAsmProperties Props;
730 SMLoc Loc = Lex.getLoc();
732 return error(Loc,
"expected property name followed by ':'");
734 Key = Lex.getStrVal();
737 if (parseStringConstant(
Value))
741 return error(Loc,
"unknown property name");
751 std::string AsmStrPart;
752 if (parseStringConstant(AsmStrPart))
754 AsmStr += AsmStrPart +
"\n";
757 M->appendModuleInlineAsm({AsmStr, Props});
764bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
770 return tokError(
"unknown target property");
773 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
774 parseStringConstant(Str))
776 M->setTargetTriple(Triple(std::move(Str)));
780 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
782 DLStrLoc = Lex.getLoc();
783 if (parseStringConstant(TentativeDLStr))
791bool LLParser::parseSourceFileName() {
794 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
795 parseStringConstant(SourceFileName))
798 M->setSourceFileName(SourceFileName);
804bool LLParser::parseUnnamedType() {
805 LocTy TypeLoc = Lex.getLoc();
806 unsigned TypeID = Lex.getUIntVal();
809 if (parseToken(
lltok::equal,
"expected '=' after name") ||
814 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
818 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
820 return error(TypeLoc,
"non-struct types may not be recursive");
822 Entry.second = SMLoc();
830bool LLParser::parseNamedType() {
831 std::string
Name = Lex.getStrVal();
832 LocTy NameLoc = Lex.getLoc();
835 if (parseToken(
lltok::equal,
"expected '=' after name") ||
840 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
844 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
846 return error(NameLoc,
"non-struct types may not be recursive");
848 Entry.second = SMLoc();
856bool LLParser::parseDeclare() {
860 std::vector<std::pair<unsigned, MDNode *>> MDs;
864 if (parseMetadataAttachment(MDK,
N))
866 MDs.push_back({MDK,
N});
870 unsigned FunctionNumber = -1;
871 SmallVector<unsigned> UnnamedArgNums;
872 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
875 F->addMetadata(MD.first, *MD.second);
881bool LLParser::parseDefine() {
884 FileLoc FunctionStart = getTokLineColumnPos();
888 unsigned FunctionNumber = -1;
889 SmallVector<unsigned> UnnamedArgNums;
891 parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
892 parseOptionalFunctionMetadata(*
F) ||
893 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
895 ParserContext->addFunctionLocation(
896 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
904bool LLParser::parseGlobalType(
bool &IsConstant) {
911 return tokError(
"expected 'global' or 'constant'");
917bool LLParser::parseOptionalUnnamedAddr(
938bool LLParser::parseUnnamedGlobal() {
941 LocTy NameLoc = Lex.getLoc();
945 VarID = Lex.getUIntVal();
946 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
950 if (parseToken(
lltok::equal,
"expected '=' after name"))
953 VarID = NumberedVals.getNext();
957 unsigned Linkage, Visibility, DLLStorageClass;
961 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
963 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
966 switch (Lex.getKind()) {
968 return parseGlobal(Name,
VarID, NameLoc,
Linkage, HasLinkage, Visibility,
969 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
972 return parseAliasOrIFunc(Name,
VarID, NameLoc,
Linkage, Visibility,
973 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
982bool LLParser::parseNamedGlobal() {
984 LocTy NameLoc = Lex.getLoc();
985 std::string
Name = Lex.getStrVal();
989 unsigned Linkage, Visibility, DLLStorageClass;
993 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
994 parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
996 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
999 switch (Lex.getKind()) {
1001 return parseGlobal(Name, -1, NameLoc,
Linkage, HasLinkage, Visibility,
1002 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1005 return parseAliasOrIFunc(Name, -1, NameLoc,
Linkage, Visibility,
1006 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1010bool LLParser::parseComdat() {
1012 std::string
Name = Lex.getStrVal();
1013 LocTy NameLoc = Lex.getLoc();
1020 return tokError(
"expected comdat type");
1023 switch (Lex.getKind()) {
1025 return tokError(
"unknown selection kind");
1047 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
1048 return error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
1051 if (
I != ComdatSymTab.
end())
1054 C = M->getOrInsertComdat(Name);
1055 C->setSelectionKind(SK);
1062bool LLParser::parseMDString(
MDString *&Result) {
1064 if (parseStringConstant(Str))
1072bool LLParser::parseMDNodeID(
MDNode *&Result) {
1074 LocTy IDLoc = Lex.getLoc();
1076 if (parseUInt32(MID))
1080 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
1087 auto &FwdRef = ForwardRefMDNodes[MID];
1090 Result = FwdRef.first.get();
1091 It->second.reset(Result);
1097bool LLParser::parseNamedMetadata() {
1099 std::string
Name = Lex.getStrVal();
1107 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1110 MDNode *
N =
nullptr;
1115 Lex.getStrVal() ==
"DIExpression") {
1116 if (parseDIExpression(
N,
false))
1121 Lex.getStrVal() ==
"DIArgList") {
1122 return tokError(
"found DIArgList outside of function");
1130 return parseToken(
lltok::rbrace,
"expected end of metadata node");
1135bool LLParser::parseStandaloneMetadata() {
1138 unsigned MetadataID = 0;
1141 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1146 return tokError(
"unexpected type in metadata definition");
1150 if (parseSpecializedMDNode(Init, IsDistinct))
1153 parseMDTuple(Init, IsDistinct))
1157 auto FI = ForwardRefMDNodes.find(MetadataID);
1158 if (FI != ForwardRefMDNodes.end()) {
1159 auto *ToReplace = FI->second.first.get();
1163 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1164 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1165 "Inst unexpectedly already has DIAssignID attachment");
1166 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1170 ToReplace->replaceAllUsesWith(Init);
1171 ForwardRefMDNodes.erase(FI);
1173 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
1175 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1177 return tokError(
"Metadata id is already used");
1178 It->second.reset(Init);
1185bool LLParser::skipModuleSummaryEntry() {
1195 return tokError(
"Expected 'gv', 'module', 'typeid', "
1196 "'typeidCompatibleVTable', 'flags' or 'blockcount' at the "
1197 "start of summary entry");
1199 return parseSummaryIndexFlags();
1201 return parseBlockCount();
1203 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1204 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1208 unsigned NumOpenParen = 1;
1210 switch (Lex.getKind()) {
1218 return tokError(
"found end of file while parsing summary entry");
1224 }
while (NumOpenParen > 0);
1230bool LLParser::parseSummaryEntry() {
1236 Lex.setIgnoreColonInIdentifiers(
true);
1244 return skipModuleSummaryEntry();
1246 bool result =
false;
1247 switch (Lex.getKind()) {
1249 result = parseGVEntry(SummaryID);
1252 result = parseModuleEntry(SummaryID);
1255 result = parseTypeIdEntry(SummaryID);
1258 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1261 result = parseSummaryIndexFlags();
1264 result = parseBlockCount();
1267 result =
error(Lex.getLoc(),
"unexpected summary kind");
1270 Lex.setIgnoreColonInIdentifiers(
false);
1304bool LLParser::parseAliasOrIFunc(
const std::string &Name,
unsigned NameID,
1305 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1306 unsigned DLLStorageClass,
bool DSOLocal,
1321 return error(NameLoc,
"invalid linkage type for alias");
1324 return error(NameLoc,
1325 "symbol with local linkage must have default visibility");
1328 return error(NameLoc,
1329 "symbol with local linkage cannot have a DLL storage class");
1332 LocTy ExplicitTypeLoc = Lex.getLoc();
1333 if (parseType(Ty) ||
1334 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1338 LocTy AliaseeLoc = Lex.getLoc();
1343 if (parseGlobalTypeAndValue(Aliasee))
1348 if (parseValID(ID,
nullptr))
1351 return error(AliaseeLoc,
"invalid aliasee");
1352 Aliasee =
ID.ConstantVal;
1358 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1359 unsigned AddrSpace = PTy->getAddressSpace();
1361 GlobalValue *GVal =
nullptr;
1365 if (!
Name.empty()) {
1366 auto I = ForwardRefVals.find(Name);
1367 if (
I != ForwardRefVals.end()) {
1368 GVal =
I->second.first;
1369 ForwardRefVals.erase(Name);
1370 }
else if (M->getNamedValue(Name)) {
1371 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1374 auto I = ForwardRefValIDs.find(NameID);
1375 if (
I != ForwardRefValIDs.end()) {
1376 GVal =
I->second.first;
1377 ForwardRefValIDs.erase(
I);
1382 std::unique_ptr<GlobalAlias> GA;
1383 std::unique_ptr<GlobalIFunc> GI;
1411 if (parseGlobalObjectMetadataAttachment(*GI))
1414 return tokError(
"unknown alias or ifunc property!");
1419 NumberedVals.add(NameID, GV);
1426 "forward reference and definition of alias have different types");
1436 M->insertAlias(GA.release());
1438 M->insertIFunc(GI.release());
1439 assert(GV->
getName() == Name &&
"Should not be a name conflict!");
1448 case lltok::kw_sanitize_memtag:
1462 switch (Lex.getKind()) {
1464 Meta.NoAddress =
true;
1467 Meta.NoHWAddress =
true;
1469 case lltok::kw_sanitize_memtag:
1473 Meta.IsDynInit =
true;
1476 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1496bool LLParser::parseGlobal(
const std::string &Name,
unsigned NameID,
1497 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1498 unsigned Visibility,
unsigned DLLStorageClass,
1502 return error(NameLoc,
1503 "symbol with local linkage must have default visibility");
1506 return error(NameLoc,
1507 "symbol with local linkage cannot have a DLL storage class");
1511 LocTy IsExternallyInitializedLoc;
1515 if (parseOptionalAddrSpace(AddrSpace) ||
1517 IsExternallyInitialized,
1518 &IsExternallyInitializedLoc) ||
1519 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1528 if (parseGlobalValue(Ty, Init))
1533 return error(TyLoc,
"invalid type for global variable");
1535 GlobalValue *GVal =
nullptr;
1538 if (!
Name.empty()) {
1539 auto I = ForwardRefVals.find(Name);
1540 if (
I != ForwardRefVals.end()) {
1541 GVal =
I->second.first;
1542 ForwardRefVals.erase(
I);
1543 }
else if (M->getNamedValue(Name)) {
1544 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1549 if (NameID == (
unsigned)-1)
1550 NameID = NumberedVals.getNext();
1552 auto I = ForwardRefValIDs.find(NameID);
1553 if (
I != ForwardRefValIDs.end()) {
1554 GVal =
I->second.first;
1555 ForwardRefValIDs.erase(
I);
1559 GlobalVariable *GV =
new GlobalVariable(
1564 NumberedVals.add(NameID, GV);
1582 "forward reference and definition of global have different types");
1602 }
else if (Lex.getKind() == lltok::kw_align) {
1604 if (parseOptionalAlignment(Alignment))
1610 if (parseOptionalCodeModel(CodeModel))
1614 if (parseGlobalObjectMetadataAttachment(*GV))
1617 if (parseSanitizer(GV))
1621 if (parseOptionalComdat(Name,
C))
1626 return tokError(
"unknown global variable property!");
1630 AttrBuilder
Attrs(M->getContext());
1632 std::vector<unsigned> FwdRefAttrGrps;
1633 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1635 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1637 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1645bool LLParser::parseUnnamedAttrGrp() {
1647 LocTy AttrGrpLoc = Lex.getLoc();
1651 return tokError(
"expected attribute group id");
1653 unsigned VarID = Lex.getUIntVal();
1654 std::vector<unsigned> unused;
1662 auto R = NumberedAttrBuilders.find(
VarID);
1663 if (R == NumberedAttrBuilders.end())
1664 R = NumberedAttrBuilders.emplace(
VarID, AttrBuilder(M->getContext())).first;
1666 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1667 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1670 if (!
R->second.hasAttributes())
1671 return error(AttrGrpLoc,
"attribute group has no attributes");
1678#define GET_ATTR_NAMES
1679#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1680 case lltok::kw_##DISPLAY_NAME: \
1681 return Attribute::ENUM_NAME;
1682#include "llvm/IR/Attributes.inc"
1691 return parseRequiredTypeAttr(
B, Lex.getKind(), Attr);
1694 case Attribute::Alignment: {
1703 if (parseOptionalAlignment(Alignment,
true))
1706 B.addAlignmentAttr(Alignment);
1709 case Attribute::StackAlignment: {
1714 parseUInt32(Alignment))
1717 if (parseOptionalStackAlignment(Alignment))
1720 B.addStackAlignmentAttr(Alignment);
1723 case Attribute::AllocSize: {
1724 unsigned ElemSizeArg;
1725 std::optional<unsigned> NumElemsArg;
1726 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1728 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1731 case Attribute::VScaleRange: {
1732 unsigned MinValue, MaxValue;
1733 if (parseVScaleRangeArguments(MinValue, MaxValue))
1735 B.addVScaleRangeAttr(MinValue,
1736 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1739 case Attribute::Dereferenceable: {
1740 std::optional<uint64_t> Bytes;
1741 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1743 assert(Bytes.has_value());
1744 B.addDereferenceableAttr(Bytes.value());
1747 case Attribute::DeadOnReturn: {
1748 std::optional<uint64_t> Bytes;
1749 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1752 if (Bytes.has_value()) {
1753 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1755 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1759 case Attribute::DereferenceableOrNull: {
1760 std::optional<uint64_t> Bytes;
1761 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1763 assert(Bytes.has_value());
1764 B.addDereferenceableOrNullAttr(Bytes.value());
1767 case Attribute::UWTable: {
1769 if (parseOptionalUWTableKind(Kind))
1771 B.addUWTableAttr(Kind);
1774 case Attribute::AllocKind: {
1776 if (parseAllocKind(Kind))
1778 B.addAllocKindAttr(Kind);
1781 case Attribute::Memory: {
1782 std::optional<MemoryEffects> ME = parseMemoryAttr();
1785 B.addMemoryAttr(*ME);
1788 case Attribute::DenormalFPEnv: {
1789 std::optional<DenormalFPEnv>
Mode = parseDenormalFPEnvAttr();
1793 B.addDenormalFPEnvAttr(*
Mode);
1796 case Attribute::NoFPClass: {
1799 B.addNoFPClassAttr(NoFPClass);
1805 case Attribute::Range:
1806 return parseRangeAttr(
B);
1807 case Attribute::Initializes:
1808 return parseInitializesAttr(
B);
1809 case Attribute::Captures:
1810 return parseCapturesAttr(
B);
1812 B.addAttribute(Attr);
1820 case lltok::kw_readnone:
1823 case lltok::kw_readonly:
1826 case lltok::kw_writeonly:
1845bool LLParser::parseFnAttributeValuePairs(AttrBuilder &
B,
1846 std::vector<unsigned> &FwdRefAttrGrps,
1847 bool InAttrGrp, LocTy &BuiltinLoc) {
1848 bool HaveError =
false;
1859 if (parseStringAttribute(
B))
1871 "cannot have an attribute group reference in an attribute group");
1874 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1880 SMLoc Loc = Lex.getLoc();
1881 if (Token == lltok::kw_builtin)
1893 return error(Lex.getLoc(),
"unterminated attribute group");
1896 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1903 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1907 B.addMemoryAttr(ME);
1921 PTy->getAddressSpace());
1930 error(Loc,
"'" + Name +
"' is not a basic block");
1932 error(Loc,
"'" + Name +
"' defined with type '" +
1945 error(Loc,
"global variable reference must have pointer type");
1956 auto I = ForwardRefVals.find(Name);
1957 if (
I != ForwardRefVals.end())
1958 Val =
I->second.first;
1964 checkValidVariableType(Loc,
"@" + Name, Ty, Val));
1968 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1975 error(Loc,
"global variable reference must have pointer type");
1979 GlobalValue *Val = NumberedVals.get(ID);
1984 auto I = ForwardRefValIDs.find(ID);
1985 if (
I != ForwardRefValIDs.end())
1986 Val =
I->second.first;
1992 checkValidVariableType(Loc,
"@" + Twine(ID), Ty, Val));
1996 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
2004Comdat *LLParser::getComdat(
const std::string &Name, LocTy
Loc) {
2008 if (
I != ComdatSymTab.
end())
2012 Comdat *
C = M->getOrInsertComdat(Name);
2013 ForwardRefComdats[
Name] = Loc;
2023bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
2024 if (Lex.getKind() !=
T)
2025 return tokError(ErrMsg);
2032bool LLParser::parseStringConstant(std::string &Result) {
2034 return tokError(
"expected string constant");
2035 Result = Lex.getStrVal();
2042bool LLParser::parseUInt32(uint32_t &Val) {
2043 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
2044 return tokError(
"expected integer");
2045 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
2046 if (Val64 !=
unsigned(Val64))
2047 return tokError(
"expected 32-bit integer (too large)");
2055bool LLParser::parseUInt64(
uint64_t &Val) {
2056 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
2057 return tokError(
"expected integer");
2058 Val = Lex.getAPSIntVal().getLimitedValue();
2068 switch (Lex.getKind()) {
2070 return tokError(
"expected localdynamic, initialexec or localexec");
2098 return parseTLSModel(TLM) ||
2099 parseToken(
lltok::rparen,
"expected ')' after thread local model");
2107bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
2108 AddrSpace = DefaultAS;
2112 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
2114 const std::string &AddrSpaceStr = Lex.getStrVal();
2115 if (AddrSpaceStr ==
"A") {
2116 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2117 }
else if (AddrSpaceStr ==
"G") {
2118 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2119 }
else if (AddrSpaceStr ==
"P") {
2120 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2121 }
else if (std::optional<unsigned> AS =
2122 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2125 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
2131 return tokError(
"expected integer or string constant");
2132 SMLoc Loc = Lex.getLoc();
2133 if (parseUInt32(AddrSpace))
2136 return error(Loc,
"invalid address space, must be a 24-bit integer");
2140 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
2141 ParseAddrspaceValue(AddrSpace) ||
2148bool LLParser::parseStringAttribute(AttrBuilder &
B) {
2149 std::string Attr = Lex.getStrVal();
2152 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
2154 B.addAttribute(Attr, Val);
2159bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &
B,
bool IsParam) {
2160 bool HaveError =
false;
2167 if (parseStringAttribute(
B))
2178 SMLoc Loc = Lex.getLoc();
2183 if (parseEnumAttribute(Attr,
B,
false))
2187 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2189 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2237bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2238 unsigned &Visibility,
2239 unsigned &DLLStorageClass,
bool &DSOLocal) {
2243 parseOptionalDSOLocal(DSOLocal);
2244 parseOptionalVisibility(Visibility);
2245 parseOptionalDLLStorageClass(DLLStorageClass);
2248 return error(Lex.getLoc(),
"dso_location and DLL-StorageClass mismatch");
2254void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2255 switch (Lex.getKind()) {
2276void LLParser::parseOptionalVisibility(
unsigned &Res) {
2277 switch (Lex.getKind()) {
2294bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2298 return tokError(
"unknown import kind. Expect definition or declaration.");
2313void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2314 switch (Lex.getKind()) {
2385bool LLParser::parseOptionalCallingConv(
unsigned &CC) {
2386 switch (Lex.getKind()) {
2476 return tokError(
"unknown RISC-V ABI VLEN");
2477#define CC_VLS_CASE(ABIVlen) \
2479 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2507 return parseUInt32(CC);
2517bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2520 std::string
Name = Lex.getStrVal();
2521 Kind = M->getMDKindID(Name);
2524 return parseMDNode(MD);
2529bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2532 return tokError(
"expected metadata after comma");
2536 auto Loc = Lex.getLoc();
2537 if (parseMetadataAttachment(MDK,
N))
2540 if (MDK == LLVMContext::MD_DIAssignID)
2541 TempDIAssignIDAttachments[
N].push_back(&Inst);
2542 else if (MDK == LLVMContext::MD_dbg)
2543 PendingDbgInsts.emplace_back(Loc, &Inst,
N);
2554bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2557 if (parseMetadataAttachment(MDK,
N))
2566bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2568 if (parseGlobalObjectMetadataAttachment(
F))
2576bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2578 if (!EatIfPresent(lltok::kw_align))
2580 LocTy AlignLoc = Lex.getLoc();
2583 LocTy ParenLoc = Lex.getLoc();
2584 bool HaveParens =
false;
2590 if (parseUInt64(
Value))
2594 return error(ParenLoc,
"expected ')'");
2597 return error(AlignLoc,
"alignment is not a power of two");
2599 return error(AlignLoc,
"huge alignments are not supported yet");
2607bool LLParser::parseOptionalPrefAlignment(
MaybeAlign &Alignment) {
2611 LocTy AlignLoc = Lex.getLoc();
2614 LocTy ParenLoc = Lex.getLoc();
2616 return error(ParenLoc,
"expected '('");
2618 if (parseUInt64(
Value))
2621 ParenLoc = Lex.getLoc();
2623 return error(ParenLoc,
"expected ')'");
2626 return error(AlignLoc,
"alignment is not a power of two");
2628 return error(AlignLoc,
"huge alignments are not supported yet");
2638 auto StrVal = Lex.getStrVal();
2639 auto ErrMsg =
"expected global code model string";
2640 if (StrVal ==
"tiny")
2642 else if (StrVal ==
"small")
2644 else if (StrVal ==
"kernel")
2646 else if (StrVal ==
"medium")
2648 else if (StrVal ==
"large")
2651 return tokError(ErrMsg);
2663bool LLParser::parseOptionalAttrBytes(
lltok::Kind AttrKind,
2664 std::optional<uint64_t> &Bytes,
2665 bool ErrorNoBytes) {
2666 assert((AttrKind == lltok::kw_dereferenceable ||
2667 AttrKind == lltok::kw_dereferenceable_or_null ||
2668 AttrKind == lltok::kw_dead_on_return) &&
2672 if (!EatIfPresent(AttrKind))
2674 LocTy ParenLoc = Lex.getLoc();
2677 return error(ParenLoc,
"expected '('");
2678 Bytes = std::nullopt;
2681 LocTy DerefLoc = Lex.getLoc();
2682 if (parseUInt64(Bytes.value()))
2684 ParenLoc = Lex.getLoc();
2686 return error(ParenLoc,
"expected ')'");
2688 return error(DerefLoc,
"byte count specified must be non-zero");
2692bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2697 LocTy KindLoc = Lex.getLoc();
2703 return error(KindLoc,
"expected unwind table kind");
2710 LocTy ParenLoc = Lex.getLoc();
2712 return error(ParenLoc,
"expected '('");
2713 LocTy KindLoc = Lex.getLoc();
2715 if (parseStringConstant(Arg))
2716 return error(KindLoc,
"expected allockind value");
2720 }
else if (
A ==
"realloc") {
2722 }
else if (
A ==
"free") {
2724 }
else if (
A ==
"uninitialized") {
2726 }
else if (
A ==
"zeroed") {
2728 }
else if (
A ==
"aligned") {
2731 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2734 ParenLoc = Lex.getLoc();
2736 return error(ParenLoc,
"expected ')'");
2738 return error(KindLoc,
"expected allockind value");
2747 return {Loc::ArgMem};
2749 return {Loc::InaccessibleMem};
2751 return {Loc::ErrnoMem};
2753 return {Loc::TargetMem0};
2755 return {Loc::TargetMem1};
2778 return std::nullopt;
2782static std::optional<DenormalMode::DenormalModeKind>
2794 return std::nullopt;
2798std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2803 Lex.setIgnoreColonInIdentifiers(
true);
2808 tokError(
"expected '('");
2809 return std::nullopt;
2812 bool SeenLoc =
false;
2813 bool SeenTargetLoc =
false;
2816 if (!Locs.
empty()) {
2819 tokError(
"expected ':' after location");
2820 return std::nullopt;
2827 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2828 "or access kind (none, read, write, readwrite)");
2830 tokError(
"expected access kind (none, read, write, readwrite)");
2831 return std::nullopt;
2835 if (!Locs.
empty()) {
2840 SeenTargetLoc =
true;
2842 if (Locs.size() > 1 && SeenTargetLoc) {
2843 tokError(
"target memory default access kind must be specified first");
2844 return std::nullopt;
2849 tokError(
"default access kind must be specified first");
2850 return std::nullopt;
2859 tokError(
"unterminated memory attribute");
2860 return std::nullopt;
2863std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2864 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2867 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2868 "positivezero, dynamic)");
2874 std::optional<DenormalMode::DenormalModeKind> InputMode;
2878 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2879 "positivezero, dynamic)");
2886 InputMode = OutputMode;
2889 return DenormalMode(*OutputMode, *InputMode);
2892std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2895 Lex.setIgnoreColonInIdentifiers(
true);
2906 bool HasDefaultSection =
false;
2908 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2909 if (!ParsedDefaultMode)
2911 DefaultMode = *ParsedDefaultMode;
2912 HasDefaultSection =
true;
2917 if (HasDefaultSection && !HasComma) {
2918 tokError(
"expected ',' before float:");
2923 if (parseType(Ty) || !Ty->
isFloatTy()) {
2924 tokError(
"expected float:");
2928 if (parseToken(
lltok::colon,
"expected ':' before float denormal_fpenv"))
2931 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2935 F32Mode = *ParsedF32Mode;
2938 if (parseToken(
lltok::rparen,
"unterminated denormal_fpenv"))
2941 return DenormalFPEnv(DefaultMode, F32Mode);
2983unsigned LLParser::parseNoFPClassAttr() {
2988 tokError(
"expected '('");
2995 if (TestMask != 0) {
2999 !parseUInt64(
Value)) {
3001 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
3006 error(Lex.getLoc(),
"expected ')'");
3012 error(Lex.getLoc(),
"expected nofpclass test mask");
3030bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
3031 bool &AteExtraComma) {
3032 AteExtraComma =
false;
3036 AteExtraComma =
true;
3040 if (Lex.getKind() != lltok::kw_align)
3041 return error(Lex.getLoc(),
"expected metadata or 'align'");
3043 if (parseOptionalAlignment(Alignment))
3056bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
3057 bool &AteExtraComma) {
3058 AteExtraComma =
false;
3062 AteExtraComma =
true;
3068 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
3070 if (parseOptionalAddrSpace(AddrSpace))
3077bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
3078 std::optional<unsigned> &HowManyArg) {
3081 auto StartParen = Lex.getLoc();
3083 return error(StartParen,
"expected '('");
3085 if (parseUInt32(BaseSizeArg))
3089 auto HowManyAt = Lex.getLoc();
3091 if (parseUInt32(HowMany))
3093 if (HowMany == BaseSizeArg)
3094 return error(HowManyAt,
3095 "'allocsize' indices can't refer to the same parameter");
3096 HowManyArg = HowMany;
3098 HowManyArg = std::nullopt;
3100 auto EndParen = Lex.getLoc();
3102 return error(EndParen,
"expected ')'");
3106bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
3107 unsigned &MaxValue) {
3110 auto StartParen = Lex.getLoc();
3112 return error(StartParen,
"expected '('");
3114 if (parseUInt32(MinValue))
3118 if (parseUInt32(MaxValue))
3121 MaxValue = MinValue;
3123 auto EndParen = Lex.getLoc();
3125 return error(EndParen,
"expected ')'");
3134bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
3139 return parseScope(SSID) || parseOrdering(Ordering);
3149 auto StartParenAt = Lex.getLoc();
3151 return error(StartParenAt,
"Expected '(' in syncscope");
3154 auto SSNAt = Lex.getLoc();
3155 if (parseStringConstant(SSN))
3156 return error(SSNAt,
"Expected synchronization scope name");
3158 auto EndParenAt = Lex.getLoc();
3160 return error(EndParenAt,
"Expected ')' in syncscope");
3162 SSID = Context.getOrInsertSyncScopeID(SSN);
3173 switch (Lex.getKind()) {
3175 return tokError(
"Expected ordering on atomic instruction");
3194bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
3196 if (!EatIfPresent(lltok::kw_alignstack))
3198 LocTy ParenLoc = Lex.getLoc();
3200 return error(ParenLoc,
"expected '('");
3201 LocTy AlignLoc = Lex.getLoc();
3202 if (parseUInt32(Alignment))
3204 ParenLoc = Lex.getLoc();
3206 return error(ParenLoc,
"expected ')'");
3208 return error(AlignLoc,
"stack alignment is not a power of two");
3222 bool &AteExtraComma) {
3223 AteExtraComma =
false;
3226 return tokError(
"expected ',' as start of index list");
3230 if (Indices.
empty())
3231 return tokError(
"expected index");
3232 AteExtraComma =
true;
3236 if (parseUInt32(Idx))
3249bool LLParser::parseType(
Type *&Result,
const Twine &
Msg,
bool AllowVoid) {
3250 SMLoc TypeLoc = Lex.getLoc();
3251 switch (Lex.getKind()) {
3253 return tokError(
Msg);
3262 if (
Result->isPointerTy()) {
3264 if (parseOptionalAddrSpace(AddrSpace))
3270 return tokError(
"ptr* is invalid - use ptr instead");
3281 if (parseTargetExtType(Result))
3287 if (parseAnonStructType(Result,
false))
3293 if (parseArrayVectorType(Result,
false))
3300 if (parseAnonStructType(Result,
true) ||
3301 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
3303 }
else if (parseArrayVectorType(Result,
true))
3308 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
3314 Entry.second = Lex.getLoc();
3323 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
3329 Entry.second = Lex.getLoc();
3339 switch (Lex.getKind()) {
3342 if (!AllowVoid &&
Result->isVoidTy())
3343 return error(TypeLoc,
"void type only allowed for function results");
3349 return tokError(
"basic block pointers are invalid");
3351 return tokError(
"pointers to void are invalid - use i8* instead");
3353 return tokError(
"pointer to this type is invalid");
3361 return tokError(
"basic block pointers are invalid");
3363 return tokError(
"pointers to void are invalid; use i8* instead");
3365 return tokError(
"pointer to this type is invalid");
3367 if (parseOptionalAddrSpace(AddrSpace) ||
3368 parseToken(
lltok::star,
"expected '*' in address space"))
3377 if (parseFunctionType(Result))
3390 PerFunctionState &PFS,
bool IsMustTailCall,
3391 bool InVarArgsFunc) {
3397 if (!ArgList.
empty() &&
3398 parseToken(
lltok::comma,
"expected ',' in argument list"))
3403 const char *
Msg =
"unexpected ellipsis in argument list for ";
3404 if (!IsMustTailCall)
3405 return tokError(Twine(
Msg) +
"non-musttail call");
3407 return tokError(Twine(
Msg) +
"musttail call in non-varargs function");
3409 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3414 Type *ArgTy =
nullptr;
3416 if (parseType(ArgTy, ArgLoc))
3419 return error(ArgLoc,
"invalid type for function argument");
3421 AttrBuilder ArgAttrs(M->getContext());
3424 if (parseMetadataAsValue(V, PFS))
3428 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3435 if (IsMustTailCall && InVarArgsFunc)
3436 return tokError(
"expected '...' at end of argument list for musttail call "
3437 "in varargs function");
3445bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3448 if (!EatIfPresent(AttrToken))
3451 return error(Lex.getLoc(),
"expected '('");
3455 return error(Lex.getLoc(),
"expected ')'");
3457 B.addTypeAttr(AttrKind, Ty);
3463bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3471 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3473 return tokError(
"expected integer");
3474 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3476 "integer is too large for the bit width of specified type");
3477 Val = Lex.getAPSIntVal().extend(
BitWidth);
3482 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3485 return error(TyLoc,
"the range must have integer type!");
3493 return tokError(
"the range represent the empty set but limits aren't 0!");
3504bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3507 auto ParseAPSInt = [&](APInt &Val) {
3509 return tokError(
"expected integer");
3510 Val = Lex.getAPSIntVal().extend(64);
3530 return tokError(
"the range should not represent the full or empty set!");
3542 if (!CRLOrNull.has_value())
3543 return tokError(
"Invalid (unordered or overlapping) range list");
3544 B.addInitializesAttr(*CRLOrNull);
3548bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3550 std::optional<CaptureComponents> Ret;
3554 Lex.setIgnoreColonInIdentifiers(
true);
3562 bool SeenComponent =
false;
3568 return tokError(
"duplicate 'ret' location");
3571 SeenComponent =
false;
3576 return tokError(
"cannot use 'none' with other component");
3580 return tokError(
"cannot use 'none' with other component");
3591 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3592 "'provenance' or 'read_provenance'");
3595 SeenComponent =
true;
3603 B.addCapturesAttr(CaptureInfo(
Other, Ret.value_or(
Other)));
3616bool LLParser::parseOptionalOperandBundles(
3618 LocTy BeginLoc = Lex.getLoc();
3624 if (!BundleList.
empty() &&
3625 parseToken(
lltok::comma,
"expected ',' in input list"))
3629 if (parseStringConstant(
Tag))
3632 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3635 std::vector<Value *> Inputs;
3638 if (!Inputs.empty() &&
3639 parseToken(
lltok::comma,
"expected ',' in input list"))
3643 Value *Input =
nullptr;
3647 if (parseMetadataAsValue(Input, PFS))
3649 }
else if (parseValue(Ty, Input, PFS)) {
3652 Inputs.push_back(Input);
3660 if (BundleList.
empty())
3661 return error(BeginLoc,
"operand bundle set must not be empty");
3668 unsigned NextID,
unsigned ID) {
3670 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3671 Twine(NextID) +
"' or greater");
3688 unsigned CurValID = 0;
3702 LocTy TypeLoc = Lex.getLoc();
3703 Type *ArgTy =
nullptr;
3704 AttrBuilder
Attrs(M->getContext());
3705 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3709 return error(TypeLoc,
"argument can not have void type");
3714 bool Unnamed =
false;
3716 Name = Lex.getStrVal();
3717 IdentStart = getTokLineColumnPos();
3719 IdentEnd = getPrevTokEndLineColumnPos();
3723 ArgID = Lex.getUIntVal();
3724 IdentStart = getTokLineColumnPos();
3725 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3728 IdentEnd = getPrevTokEndLineColumnPos();
3734 CurValID = ArgID + 1;
3738 return error(TypeLoc,
"invalid type for function argument");
3742 Unnamed ? std::nullopt
3743 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3748 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3753bool LLParser::parseFunctionType(
Type *&Result) {
3757 return tokError(
"invalid function return type");
3761 SmallVector<unsigned> UnnamedArgNums;
3762 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3766 for (
const ArgInfo &Arg : ArgList) {
3767 if (!Arg.Name.empty())
3768 return error(Arg.Loc,
"argument name invalid in function type");
3769 if (Arg.Attrs.hasAttributes())
3770 return error(Arg.Loc,
"argument attributes invalid in function type");
3774 for (
const ArgInfo &Arg : ArgList)
3783bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3785 if (parseStructBody(Elts))
3793bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3794 std::pair<Type *, LocTy> &Entry,
3798 return error(TypeLoc,
"redefinition of type");
3804 Entry.second = SMLoc();
3809 ResultTy =
Entry.first;
3821 return error(TypeLoc,
"forward references to non-struct type");
3825 return parseArrayVectorType(ResultTy,
true);
3826 return parseType(ResultTy);
3830 Entry.second = SMLoc();
3839 if (parseStructBody(Body) ||
3840 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3844 return tokError(
toString(std::move(
E)));
3864 LocTy EltTyLoc = Lex.getLoc();
3871 return error(EltTyLoc,
"invalid element type for struct");
3874 EltTyLoc = Lex.getLoc();
3879 return error(EltTyLoc,
"invalid element type for struct");
3884 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3893bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3894 bool Scalable =
false;
3898 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3904 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3905 Lex.getAPSIntVal().getBitWidth() > 64)
3906 return tokError(
"expected number in address space");
3908 LocTy SizeLoc = Lex.getLoc();
3912 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3915 LocTy TypeLoc = Lex.getLoc();
3916 Type *EltTy =
nullptr;
3917 if (parseType(EltTy))
3921 "expected end of sequential type"))
3926 return error(SizeLoc,
"zero element vector is illegal");
3928 return error(SizeLoc,
"size too large for vector");
3930 return error(TypeLoc,
"invalid vector element type");
3934 return error(TypeLoc,
"invalid array element type");
3951bool LLParser::parseTargetExtType(
Type *&Result) {
3956 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3957 parseStringConstant(TypeName))
3964 SmallVector<unsigned> IntParams;
3965 bool SeenInt =
false;
3972 if (parseUInt32(IntVal))
3975 }
else if (SeenInt) {
3978 return tokError(
"expected uint32 param");
3981 if (parseType(TypeParam,
true))
3987 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3992 if (
auto E = TTy.takeError())
3993 return tokError(
toString(std::move(
E)));
4006 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
4009 auto It = UnnamedArgNums.
begin();
4012 unsigned ArgNum = *It++;
4013 NumberedVals.add(ArgNum, &A);
4018LLParser::PerFunctionState::~PerFunctionState() {
4021 for (
const auto &P : ForwardRefVals) {
4024 P.second.first->replaceAllUsesWith(
4026 P.second.first->deleteValue();
4029 for (
const auto &P : ForwardRefValIDs) {
4032 P.second.first->replaceAllUsesWith(
4034 P.second.first->deleteValue();
4038bool LLParser::PerFunctionState::finishFunction() {
4039 if (!ForwardRefVals.empty())
4040 return P.error(ForwardRefVals.begin()->second.second,
4041 "use of undefined value '%" + ForwardRefVals.begin()->first +
4043 if (!ForwardRefValIDs.empty())
4044 return P.error(ForwardRefValIDs.begin()->second.second,
4045 "use of undefined value '%" +
4046 Twine(ForwardRefValIDs.begin()->first) +
"'");
4053Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
4056 Value *Val =
F.getValueSymbolTable()->lookup(Name);
4061 auto I = ForwardRefVals.find(Name);
4062 if (
I != ForwardRefVals.end())
4063 Val =
I->second.first;
4068 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
4072 P.error(Loc,
"invalid use of a non-first-class type");
4083 if (FwdVal->
getName() != Name) {
4084 P.error(Loc,
"name is too long which can result in name collisions, "
4085 "consider making the name shorter or "
4086 "increasing -non-global-value-max-name-size");
4090 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
4094Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
4096 Value *Val = NumberedVals.get(ID);
4101 auto I = ForwardRefValIDs.find(ID);
4102 if (
I != ForwardRefValIDs.end())
4103 Val =
I->second.first;
4108 return P.checkValidVariableType(Loc,
"%" + Twine(ID), Ty, Val);
4111 P.error(Loc,
"invalid use of a non-first-class type");
4123 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
4129bool LLParser::PerFunctionState::setInstName(
int NameID,
4130 const std::string &NameStr,
4131 LocTy NameLoc, Instruction *Inst) {
4134 if (NameID != -1 || !NameStr.empty())
4135 return P.error(NameLoc,
"instructions returning void cannot have a name");
4141 if (NameStr.empty()) {
4144 NameID = NumberedVals.getNext();
4146 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
4150 auto FI = ForwardRefValIDs.find(NameID);
4151 if (FI != ForwardRefValIDs.end()) {
4154 return P.error(NameLoc,
"instruction forward referenced with type '" +
4158 Sentinel->replaceAllUsesWith(Inst);
4160 ForwardRefValIDs.erase(FI);
4163 NumberedVals.add(NameID, Inst);
4168 auto FI = ForwardRefVals.find(NameStr);
4169 if (FI != ForwardRefVals.end()) {
4172 return P.error(NameLoc,
"instruction forward referenced with type '" +
4176 Sentinel->replaceAllUsesWith(Inst);
4178 ForwardRefVals.erase(FI);
4184 if (Inst->
getName() != NameStr)
4185 return P.error(NameLoc,
"multiple definition of local value named '" +
4192BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
4198BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID,
LocTy Loc) {
4206BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
4207 int NameID,
LocTy Loc) {
4211 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
4214 NameID = NumberedVals.getNext();
4216 BB = getBB(NameID, Loc);
4218 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
4222 BB = getBB(Name, Loc);
4224 P.error(Loc,
"unable to create block named '" + Name +
"'");
4235 ForwardRefValIDs.erase(NameID);
4236 NumberedVals.add(NameID, BB);
4239 ForwardRefVals.erase(Name);
4256bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS,
Type *ExpectedTy) {
4257 ID.Loc = Lex.getLoc();
4258 switch (Lex.getKind()) {
4260 return tokError(
"expected value token");
4262 ID.UIntVal = Lex.getUIntVal();
4266 ID.StrVal = Lex.getStrVal();
4270 ID.UIntVal = Lex.getUIntVal();
4274 ID.StrVal = Lex.getStrVal();
4278 ID.APSIntVal = Lex.getAPSIntVal();
4282 ID.APFloatVal = Lex.getAPFloatVal();
4288 return error(
ID.Loc,
"unexpected floating-point literal");
4290 return error(
ID.Loc,
"floating-point constant invalid for type");
4295 "Invalid float strings should be caught by the lexer");
4300 return error(
ID.Loc,
"floating-point constant overflowed type");
4302 return error(
ID.Loc,
"floating-point constant underflowed type");
4308 return error(
ID.Loc,
"unexpected floating-point literal");
4310 const APInt &
Bits = Lex.getAPSIntVal();
4312 return error(
ID.Loc,
"float hex literal has incorrect number of bits");
4313 ID.APFloatVal =
APFloat(Semantics, Bits);
4335 if (parseGlobalValueVector(Elts) ||
4336 parseToken(
lltok::rbrace,
"expected end of struct constant"))
4339 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4340 ID.UIntVal = Elts.
size();
4341 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4342 Elts.
size() *
sizeof(Elts[0]));
4353 LocTy FirstEltLoc = Lex.getLoc();
4354 if (parseGlobalValueVector(Elts) ||
4356 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
4360 if (isPackedStruct) {
4361 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4362 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4363 Elts.
size() *
sizeof(Elts[0]));
4364 ID.UIntVal = Elts.
size();
4370 return error(
ID.Loc,
"constant vector must not be empty");
4372 if (!Elts[0]->
getType()->isIntegerTy() && !Elts[0]->
getType()->isByteTy() &&
4373 !Elts[0]->
getType()->isFloatingPointTy() &&
4377 "vector elements must have integer, byte, pointer or floating point "
4381 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
4383 return error(FirstEltLoc,
"vector element #" + Twine(i) +
4384 " is not of type '" +
4394 LocTy FirstEltLoc = Lex.getLoc();
4395 if (parseGlobalValueVector(Elts) ||
4407 if (!Elts[0]->
getType()->isFirstClassType())
4408 return error(FirstEltLoc,
"invalid array element type: " +
4414 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4416 return error(FirstEltLoc,
"array element #" + Twine(i) +
4417 " is not of type '" +
4429 Context, Lex.getStrVal(),
false, ATy->getElementType()->isByteTy());
4438 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4441 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4444 parseStringConstant(
ID.StrVal) ||
4445 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4448 ID.StrVal2 = Lex.getStrVal();
4449 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4450 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4461 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4462 parseValID(Fn, PFS) ||
4464 "expected comma in block address expression") ||
4465 parseValID(Label, PFS) ||
4466 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4470 return error(Fn.
Loc,
"expected function name in blockaddress");
4472 return error(
Label.Loc,
"expected basic block name in blockaddress");
4475 GlobalValue *GV =
nullptr;
4477 GV = NumberedVals.get(Fn.
UIntVal);
4478 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4479 GV = M->getNamedValue(Fn.
StrVal);
4485 return error(Fn.
Loc,
"expected function name in blockaddress");
4487 if (
F->isDeclaration())
4488 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4493 GlobalValue *&FwdRef =
4494 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4502 "type of blockaddress must be a pointer and not '" +
4507 FwdDeclAS = PFS->getFunction().getAddressSpace();
4511 FwdRef =
new GlobalVariable(
4516 ID.ConstantVal = FwdRef;
4524 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4526 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4528 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4530 return error(
Label.Loc,
"referenced value is not a basic block");
4533 return error(
Label.Loc,
"cannot take address of numeric label after "
4534 "the function is defined");
4536 F->getValueSymbolTable()->lookup(
Label.StrVal));
4538 return error(
Label.Loc,
"referenced value is not a basic block");
4552 if (parseValID(Fn, PFS))
4557 "expected global value name in dso_local_equivalent");
4560 GlobalValue *GV =
nullptr;
4562 GV = NumberedVals.get(Fn.
UIntVal);
4563 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4564 GV = M->getNamedValue(Fn.
StrVal);
4570 ? ForwardRefDSOLocalEquivalentIDs
4571 : ForwardRefDSOLocalEquivalentNames;
4572 GlobalValue *&FwdRef = FwdRefMap[Fn];
4579 ID.ConstantVal = FwdRef;
4585 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4586 "in dso_local_equivalent");
4597 if (parseValID(ID, PFS))
4601 return error(
ID.Loc,
"expected global value name in no_cfi");
4613 Constant *Disc =
nullptr, *AddrDisc =
nullptr,
4614 *DeactivationSymbol =
nullptr;
4617 "expected '(' in constant ptrauth expression") ||
4618 parseGlobalTypeAndValue(Ptr) ||
4620 "expected comma in constant ptrauth expression") ||
4621 parseGlobalTypeAndValue(
Key))
4624 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(Disc))
4626 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4629 parseGlobalTypeAndValue(DeactivationSymbol))
4632 "expected ')' in constant ptrauth expression"))
4636 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4639 if (!KeyC || KeyC->getBitWidth() != 32)
4640 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4642 ConstantInt *DiscC =
nullptr;
4648 "constant ptrauth integer discriminator must be i64 constant");
4654 if (!AddrDisc->getType()->isPointerTy())
4656 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4661 if (!DeactivationSymbol)
4662 DeactivationSymbol =
4664 if (!DeactivationSymbol->getType()->isPointerTy())
4666 "constant ptrauth deactivation symbol must be a pointer");
4680 unsigned Opc = Lex.getUIntVal();
4681 Type *DestTy =
nullptr;
4684 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4685 parseGlobalTypeAndValue(SrcVal) ||
4686 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4687 parseType(DestTy) ||
4688 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4691 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4700 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4702 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4704 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4706 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4708 return error(
ID.Loc,
"urem constexprs are no longer supported");
4710 return error(
ID.Loc,
"srem constexprs are no longer supported");
4712 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4714 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4716 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4718 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4720 return error(
ID.Loc,
"frem constexprs are no longer supported");
4722 return error(
ID.Loc,
"and constexprs are no longer supported");
4724 return error(
ID.Loc,
"or constexprs are no longer supported");
4726 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4728 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4730 return error(
ID.Loc,
"shl constexprs are no longer supported");
4732 return error(
ID.Loc,
"mul constexprs are no longer supported");
4734 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4736 return error(
ID.Loc,
"select constexprs are no longer supported");
4738 return error(
ID.Loc,
"zext constexprs are no longer supported");
4740 return error(
ID.Loc,
"sext constexprs are no longer supported");
4742 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4744 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4746 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4748 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4750 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4752 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4754 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4756 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4764 unsigned Opc = Lex.getUIntVal();
4767 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4768 Opc == Instruction::Mul) {
4777 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4778 parseGlobalTypeAndValue(Val0) ||
4779 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4780 parseGlobalTypeAndValue(Val1) ||
4781 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4784 return error(
ID.Loc,
"operands of constexpr must have same type");
4788 "constexpr requires integer or integer vector operands");
4799 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4802 if (parseGlobalTypeAndValue(
C))
4804 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4816 unsigned Opc = Lex.getUIntVal();
4819 bool HasInRange =
false;
4825 if (
Opc == Instruction::GetElementPtr) {
4841 return tokError(
"expected integer");
4842 InRangeStart = Lex.getAPSIntVal();
4847 return tokError(
"expected integer");
4848 InRangeEnd = Lex.getAPSIntVal();
4856 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4859 if (
Opc == Instruction::GetElementPtr) {
4860 if (parseType(Ty) ||
4861 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4865 if (parseGlobalValueVector(Elts) ||
4869 if (
Opc == Instruction::GetElementPtr) {
4870 if (Elts.
size() == 0 ||
4871 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4872 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4875 std::optional<ConstantRange>
InRange;
4877 unsigned IndexWidth =
4878 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4879 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4880 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4881 if (InRangeStart.
sge(InRangeEnd))
4882 return error(
ID.Loc,
"expected end to be larger than start");
4892 for (Constant *Val : Indices) {
4895 return error(
ID.Loc,
"getelementptr index must be an integer");
4898 if (GEPWidth && (ValNumEl != GEPWidth))
4901 "getelementptr vector index has a wrong number of elements");
4904 GEPWidth = ValNumEl;
4908 if (!Indices.empty() && !Ty->
isSized())
4909 return error(
ID.Loc,
"base element of getelementptr must be sized");
4912 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4915 return error(
ID.Loc,
"invalid getelementptr indices");
4921 }
else if (
Opc == Instruction::ShuffleVector) {
4922 if (Elts.
size() != 3)
4923 return error(
ID.Loc,
"expected three operands to shufflevector");
4925 return error(
ID.Loc,
"invalid operands to shufflevector");
4926 SmallVector<int, 16>
Mask;
4929 }
else if (
Opc == Instruction::ExtractElement) {
4930 if (Elts.
size() != 2)
4931 return error(
ID.Loc,
"expected two operands to extractelement");
4933 return error(
ID.Loc,
"invalid extractelement operands");
4936 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4937 if (Elts.
size() != 3)
4938 return error(
ID.Loc,
"expected three operands to insertelement");
4940 return error(
ID.Loc,
"invalid insertelement operands");
4955bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4959 bool Parsed = parseValID(ID,
nullptr, Ty) ||
4960 convertValIDToValue(Ty, ID, V,
nullptr);
4962 return error(
ID.Loc,
"global values must be constants");
4966bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4968 return parseType(Ty) || parseGlobalValue(Ty, V);
4971bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4974 LocTy KwLoc = Lex.getLoc();
4980 return tokError(
"expected comdat variable");
4981 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4983 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4986 if (GlobalName.
empty())
4987 return tokError(
"comdat cannot be unnamed");
4988 C = getComdat(std::string(GlobalName), KwLoc);
4997bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
5011 if (parseGlobalTypeAndValue(
C))
5019bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
5021 if (parseMDNodeVector(Elts))
5032bool LLParser::parseMDNode(MDNode *&
N) {
5034 return parseSpecializedMDNode(
N);
5036 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
5039bool LLParser::parseMDNodeTail(MDNode *&
N) {
5042 return parseMDTuple(
N);
5045 return parseMDNodeID(
N);
5051template <
class FieldTy>
struct MDFieldImpl {
5052 typedef MDFieldImpl ImplTy;
5056 void assign(FieldTy Val) {
5058 this->Val = std::move(Val);
5061 explicit MDFieldImpl(FieldTy
Default)
5069template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
5070 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5083 this->
A = std::move(
A);
5089 this->
B = std::move(
B);
5093 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5095 WhatIs(IsInvalid) {}
5098struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
5105struct LineField :
public MDUnsignedField {
5106 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5109struct ColumnField :
public MDUnsignedField {
5110 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5113struct DwarfTagField :
public MDUnsignedField {
5119struct DwarfMacinfoTypeField :
public MDUnsignedField {
5125struct DwarfAttEncodingField :
public MDUnsignedField {
5126 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
5129struct DwarfVirtualityField :
public MDUnsignedField {
5133struct DwarfLangField :
public MDUnsignedField {
5137struct DwarfSourceLangNameField :
public MDUnsignedField {
5138 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5141struct DwarfLangDialectField :
public MDUnsignedField {
5142 DwarfLangDialectField()
5146struct DwarfCCField :
public MDUnsignedField {
5147 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
5150struct DwarfEnumKindField :
public MDUnsignedField {
5151 DwarfEnumKindField()
5156struct EmissionKindField :
public MDUnsignedField {
5157 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5160struct FixedPointKindField :
public MDUnsignedField {
5161 FixedPointKindField()
5162 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5165struct NameTableKindField :
public MDUnsignedField {
5166 NameTableKindField()
5169 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5172struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
5173 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5176struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
5177 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5180struct MDAPSIntField :
public MDFieldImpl<APSInt> {
5181 MDAPSIntField() : ImplTy(
APSInt()) {}
5184struct MDSignedField :
public MDFieldImpl<int64_t> {
5188 MDSignedField(int64_t
Default = 0)
5190 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5194struct MDBoolField :
public MDFieldImpl<bool> {
5198struct MDField :
public MDFieldImpl<Metadata *> {
5201 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5204struct MDStringField :
public MDFieldImpl<MDString *> {
5205 enum class EmptyIs {
5210 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5211 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5214struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5218struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5222struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5223 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5224 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5226 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5227 bool AllowNull =
true)
5228 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5230 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5231 bool isMDField()
const {
return WhatIs == IsTypeB; }
5232 int64_t getMDSignedValue()
const {
5233 assert(isMDSignedField() &&
"Wrong field type");
5236 Metadata *getMDFieldValue()
const {
5237 assert(isMDField() &&
"Wrong field type");
5242struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5244 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5247 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5249 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5250 bool isMDField()
const {
return WhatIs == IsTypeB; }
5251 uint64_t getMDUnsignedValue()
const {
5252 assert(isMDUnsignedField() &&
"Wrong field type");
5255 Metadata *getMDFieldValue()
const {
5256 assert(isMDField() &&
"Wrong field type");
5261 if (isMDUnsignedField())
5263 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5265 return getMDFieldValue();
5277 return tokError(
"expected integer");
5279 Result.assign(Lex.getAPSIntVal());
5286 MDUnsignedField &Result) {
5287 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5288 return tokError(
"expected unsigned integer");
5290 auto &U = Lex.getAPSIntVal();
5291 if (U.ugt(Result.Max))
5292 return tokError(
"value for '" + Name +
"' too large, limit is " +
5294 Result.assign(U.getZExtValue());
5295 assert(Result.Val <= Result.Max &&
"Expected value in range");
5302 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5306 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5312 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5315 return tokError(
"expected DWARF tag");
5319 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5320 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5329 DwarfMacinfoTypeField &Result) {
5331 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5334 return tokError(
"expected DWARF macinfo type");
5338 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5339 Lex.getStrVal() +
"'");
5340 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5342 Result.assign(Macinfo);
5349 DwarfVirtualityField &Result) {
5351 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5354 return tokError(
"expected DWARF virtuality code");
5358 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5359 Lex.getStrVal() +
"'");
5360 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5361 Result.assign(Virtuality);
5368 DwarfEnumKindField &Result) {
5370 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5373 return tokError(
"expected DWARF enum kind code");
5377 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5378 Lex.getStrVal() +
"'");
5379 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5380 Result.assign(EnumKind);
5388 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5391 return tokError(
"expected DWARF language");
5395 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5397 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5398 Result.assign(Lang);
5405 DwarfSourceLangNameField &Result) {
5407 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5410 return tokError(
"expected DWARF source language name");
5414 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5415 Lex.getStrVal() +
"'");
5416 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5417 Result.assign(Lang);
5424 DwarfLangDialectField &Result) {
5429 if (Lex.getAPSIntVal() == 0)
5430 return tokError(
"value for 'dialect' must be a known DWARF language "
5431 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5432 "DW_LLVM_LANG_DIALECT_tile)");
5433 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5437 return tokError(
"expected DWARF language dialect");
5439 StringRef DialectString = Lex.getStrVal();
5444 if (Dialect > Result.Max)
5445 return tokError(
"invalid DWARF language dialect" +
Twine(
" '") +
5446 DialectString +
"'");
5447 Result.assign(Dialect);
5455 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5458 return tokError(
"expected DWARF calling convention");
5462 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5463 Lex.getStrVal() +
"'");
5464 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
5472 EmissionKindField &Result) {
5474 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5477 return tokError(
"expected emission kind");
5481 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5483 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5484 Result.assign(*Kind);
5491 FixedPointKindField &Result) {
5493 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5496 return tokError(
"expected fixed-point kind");
5500 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5502 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5503 Result.assign(*Kind);
5510 NameTableKindField &Result) {
5512 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5515 return tokError(
"expected nameTable kind");
5519 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5521 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5522 Result.assign((
unsigned)*Kind);
5529 DwarfAttEncodingField &Result) {
5531 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5534 return tokError(
"expected DWARF type attribute encoding");
5538 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5539 Lex.getStrVal() +
"'");
5540 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5541 Result.assign(Encoding);
5555 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5557 bool Res = parseUInt32(TempVal);
5563 return tokError(
"expected debug info flag");
5567 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5582 Result.assign(Combined);
5595 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5597 bool Res = parseUInt32(TempVal);
5603 return tokError(
"expected debug info flag");
5607 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5608 Lex.getStrVal() +
"'");
5622 Result.assign(Combined);
5629 return tokError(
"expected signed integer");
5631 auto &S = Lex.getAPSIntVal();
5633 return tokError(
"value for '" + Name +
"' too small, limit is " +
5636 return tokError(
"value for '" + Name +
"' too large, limit is " +
5638 Result.assign(S.getExtValue());
5639 assert(Result.Val >= Result.Min &&
"Expected value in range");
5640 assert(Result.Val <= Result.Max &&
"Expected value in range");
5647 switch (Lex.getKind()) {
5649 return tokError(
"expected 'true' or 'false'");
5651 Result.assign(
true);
5654 Result.assign(
false);
5664 if (!Result.AllowNull)
5665 return tokError(
"'" + Name +
"' cannot be null");
5667 Result.assign(
nullptr);
5672 if (parseMetadata(MD,
nullptr))
5681 MDSignedOrMDField &Result) {
5684 MDSignedField Res = Result.A;
5685 if (!parseMDField(
Loc, Name, Res)) {
5693 MDField Res = Result.B;
5694 if (!parseMDField(
Loc, Name, Res)) {
5704 MDUnsignedOrMDField &Result) {
5707 MDUnsignedField Res = Result.A;
5708 if (!parseMDField(
Loc, Name, Res)) {
5716 MDField Res = Result.B;
5717 if (!parseMDField(
Loc, Name, Res)) {
5727 LocTy ValueLoc = Lex.getLoc();
5729 if (parseStringConstant(S))
5733 switch (Result.EmptyIs) {
5734 case MDStringField::EmptyIs::Null:
5735 Result.assign(
nullptr);
5737 case MDStringField::EmptyIs::Empty:
5739 case MDStringField::EmptyIs::Error:
5740 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5751 if (parseMDNodeVector(MDs))
5754 Result.assign(std::move(MDs));
5760 ChecksumKindField &Result) {
5761 std::optional<DIFile::ChecksumKind> CSKind =
5765 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5768 Result.assign(*CSKind);
5775template <
class ParserTy>
5776bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5779 return tokError(
"expected field label here");
5788template <
class ParserTy>
5789bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5796 if (parseMDFieldsImplBody(ParseField))
5799 ClosingLoc = Lex.getLoc();
5803template <
class FieldTy>
5804bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5806 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5808 LocTy Loc = Lex.getLoc();
5810 return parseMDField(Loc, Name, Result);
5813bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5816#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5817 if (Lex.getStrVal() == #CLASS) \
5818 return parse##CLASS(N, IsDistinct);
5819#include "llvm/IR/Metadata.def"
5821 return tokError(
"expected metadata type");
5824#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5825#define NOP_FIELD(NAME, TYPE, INIT)
5826#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5828 return error(ClosingLoc, "missing required field '" #NAME "'");
5829#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5830 if (Lex.getStrVal() == #NAME) \
5831 return parseMDField(#NAME, NAME);
5832#define PARSE_MD_FIELDS() \
5833 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5836 if (parseMDFieldsImpl( \
5838 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5839 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5844 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5846#define GET_OR_DISTINCT(CLASS, ARGS) \
5847 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5852bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5853#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5854 OPTIONAL(line, LineField, ); \
5855 OPTIONAL(column, ColumnField, ); \
5856 REQUIRED(scope, MDField, ( false)); \
5857 OPTIONAL(inlinedAt, MDField, ); \
5858 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5859 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5860 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX)); \
5861 OPTIONAL(irlayers, MDField, );
5863#undef VISIT_MD_FIELDS
5867 inlinedAt.Val, isImplicitCode.Val,
5868 atomGroup.Val, atomRank.Val, irlayers.Val));
5872bool LLParser::parseDILayerLoc(
MDNode *&Result,
bool IsDistinct) {
5873#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5874 OPTIONAL(line, LineField, ); \
5875 OPTIONAL(column, ColumnField, ); \
5876 REQUIRED(file, MDField, ( false)); \
5877 REQUIRED(kind, MDStringField, );
5879#undef VISIT_MD_FIELDS
5882 (Context, kind.Val,
file.Val, line.Val, column.Val));
5886bool LLParser::parseDILayerLocList(
MDNode *&Result,
bool IsDistinct) {
5895 if (parseMetadata(MD,
nullptr))
5908bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5910 return tokError(
"missing 'distinct', required for !DIAssignID()");
5926bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5927#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5928 REQUIRED(tag, DwarfTagField, ); \
5929 OPTIONAL(header, MDStringField, ); \
5930 OPTIONAL(operands, MDFieldList, );
5932#undef VISIT_MD_FIELDS
5935 (Context, tag.Val, header.Val, operands.Val));
5944bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5945#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5946 OPTIONAL(name, MDStringField, ); \
5947 OPTIONAL(file, MDField, ); \
5948 OPTIONAL(line, LineField, ); \
5949 OPTIONAL(scope, MDField, ); \
5950 OPTIONAL(baseType, MDField, ); \
5951 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5952 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5953 OPTIONAL(flags, DIFlagField, ); \
5954 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5955 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5956 OPTIONAL(stride, MDSignedOrMDField, ); \
5957 OPTIONAL(bias, MDSignedOrMDField, );
5959#undef VISIT_MD_FIELDS
5961 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5962 if (Bound.isMDSignedField())
5965 if (Bound.isMDField())
5966 return Bound.getMDFieldValue();
5972 Metadata *Stride = convToMetadata(stride);
5973 Metadata *Bias = convToMetadata(bias);
5976 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5977 size.getValueAsMetadata(Context),
align.Val, flags.Val,
5978 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5987bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5988#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5989 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5990 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5991 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5992 OPTIONAL(stride, MDSignedOrMDField, );
5994#undef VISIT_MD_FIELDS
6001 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
6002 if (Bound.isMDSignedField())
6005 if (Bound.isMDField())
6006 return Bound.getMDFieldValue();
6013 Stride = convToMetadata(stride);
6016 (Context,
Count, LowerBound, UpperBound, Stride));
6024bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
6025#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6026 OPTIONAL(count, MDSignedOrMDField, ); \
6027 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6028 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6029 OPTIONAL(stride, MDSignedOrMDField, );
6031#undef VISIT_MD_FIELDS
6033 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
6034 if (Bound.isMDSignedField())
6036 Context, {dwarf::DW_OP_consts,
6037 static_cast<uint64_t>(Bound.getMDSignedValue())});
6038 if (Bound.isMDField())
6039 return Bound.getMDFieldValue();
6046 Metadata *Stride = ConvToMetadata(stride);
6049 (Context,
Count, LowerBound, UpperBound, Stride));
6056bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
6057#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6058 REQUIRED(name, MDStringField, ); \
6059 REQUIRED(value, MDAPSIntField, ); \
6060 OPTIONAL(isUnsigned, MDBoolField, (false));
6062#undef VISIT_MD_FIELDS
6064 if (isUnsigned.Val && value.Val.isNegative())
6065 return tokError(
"unsigned enumerator with negative value");
6070 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
6082bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
6083#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6084 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6085 OPTIONAL(name, MDStringField, ); \
6086 OPTIONAL(file, MDField, ); \
6087 OPTIONAL(line, LineField, ); \
6088 OPTIONAL(scope, MDField, ); \
6089 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6090 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6091 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
6092 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6093 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6094 OPTIONAL(flags, DIFlagField, );
6096#undef VISIT_MD_FIELDS
6099 DIBasicType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6100 size.getValueAsMetadata(Context),
align.Val, encoding.Val,
6101 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6110bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
6111#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6112 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6113 OPTIONAL(name, MDStringField, ); \
6114 OPTIONAL(file, MDField, ); \
6115 OPTIONAL(line, LineField, ); \
6116 OPTIONAL(scope, MDField, ); \
6117 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6118 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6119 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6120 OPTIONAL(flags, DIFlagField, ); \
6121 OPTIONAL(kind, FixedPointKindField, ); \
6122 OPTIONAL(factor, MDSignedField, ); \
6123 OPTIONAL(numerator, MDAPSIntField, ); \
6124 OPTIONAL(denominator, MDAPSIntField, );
6126#undef VISIT_MD_FIELDS
6129 (Context, tag.Val,
name.Val,
file.Val, line.Val,
6130 scope.Val,
size.getValueAsMetadata(Context),
6131 align.Val, encoding.Val, flags.Val, kind.Val,
6132 factor.Val, numerator.Val, denominator.Val));
6138bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
6139#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6140 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6141 OPTIONAL(name, MDStringField, ); \
6142 OPTIONAL(stringLength, MDField, ); \
6143 OPTIONAL(stringLengthExpression, MDField, ); \
6144 OPTIONAL(stringLocationExpression, MDField, ); \
6145 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6146 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6147 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6148 OPTIONAL(charType, MDField, );
6150#undef VISIT_MD_FIELDS
6154 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
6155 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
6156 align.Val, encoding.Val, charType.Val));
6169bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
6170#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6171 REQUIRED(tag, DwarfTagField, ); \
6172 OPTIONAL(name, MDStringField, ); \
6173 OPTIONAL(file, MDField, ); \
6174 OPTIONAL(line, LineField, ); \
6175 OPTIONAL(scope, MDField, ); \
6176 REQUIRED(baseType, MDField, ); \
6177 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6178 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6179 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6180 OPTIONAL(flags, DIFlagField, ); \
6181 OPTIONAL(extraData, MDField, ); \
6182 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6183 OPTIONAL(annotations, MDField, ); \
6184 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6185 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6186 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6187 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6188 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6190#undef VISIT_MD_FIELDS
6192 std::optional<unsigned> DWARFAddressSpace;
6193 if (dwarfAddressSpace.Val != UINT32_MAX)
6194 DWARFAddressSpace = dwarfAddressSpace.Val;
6195 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6197 PtrAuthData.emplace(
6198 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6199 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6200 ptrAuthAuthenticatesNullValues.Val);
6203 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6204 baseType.Val,
size.getValueAsMetadata(Context),
align.Val,
6205 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6206 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6210bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
6211#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6212 REQUIRED(tag, DwarfTagField, ); \
6213 OPTIONAL(name, MDStringField, ); \
6214 OPTIONAL(file, MDField, ); \
6215 OPTIONAL(line, LineField, ); \
6216 OPTIONAL(scope, MDField, ); \
6217 OPTIONAL(baseType, MDField, ); \
6218 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6219 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6220 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6221 OPTIONAL(flags, DIFlagField, ); \
6222 OPTIONAL(elements, MDField, ); \
6223 OPTIONAL(runtimeLang, DwarfLangField, ); \
6224 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6225 OPTIONAL(vtableHolder, MDField, ); \
6226 OPTIONAL(templateParams, MDField, ); \
6227 OPTIONAL(identifier, MDStringField, ); \
6228 OPTIONAL(discriminator, MDField, ); \
6229 OPTIONAL(dataLocation, MDField, ); \
6230 OPTIONAL(associated, MDField, ); \
6231 OPTIONAL(allocated, MDField, ); \
6232 OPTIONAL(rank, MDSignedOrMDField, ); \
6233 OPTIONAL(annotations, MDField, ); \
6234 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6235 OPTIONAL(specification, MDField, ); \
6236 OPTIONAL(bitStride, MDField, );
6238#undef VISIT_MD_FIELDS
6241 if (rank.isMDSignedField())
6244 else if (rank.isMDField())
6245 Rank = rank.getMDFieldValue();
6247 std::optional<unsigned> EnumKind;
6249 EnumKind = enumKind.Val;
6254 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
6255 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
6256 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6257 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6258 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6259 dataLocation.Val, associated.Val, allocated.Val, Rank,
6260 annotations.Val, bitStride.Val)) {
6269 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6270 size.getValueAsMetadata(Context),
align.Val,
6271 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6272 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6273 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6274 allocated.Val, Rank, annotations.Val, specification.Val,
6275 num_extra_inhabitants.Val, bitStride.Val));
6279bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6280#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6281 OPTIONAL(flags, DIFlagField, ); \
6282 OPTIONAL(cc, DwarfCCField, ); \
6283 REQUIRED(types, MDField, );
6285#undef VISIT_MD_FIELDS
6288 (Context, flags.Val, cc.Val, types.Val));
6297bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6301#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6302 REQUIRED(filename, MDStringField, ); \
6303 REQUIRED(directory, MDStringField, ); \
6304 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6305 OPTIONAL(checksum, MDStringField, ); \
6306 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6308#undef VISIT_MD_FIELDS
6310 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6311 if (checksumkind.Seen && checksum.Seen)
6312 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6313 else if (checksumkind.Seen || checksum.Seen)
6314 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6316 MDString *
Source =
nullptr;
6320 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6332bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6334 return tokError(
"missing 'distinct', required for !DICompileUnit");
6336 LocTy Loc = Lex.getLoc();
6338#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6339 REQUIRED(file, MDField, ( false)); \
6340 OPTIONAL(language, DwarfLangField, ); \
6341 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6342 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6343 OPTIONAL(producer, MDStringField, ); \
6344 OPTIONAL(isOptimized, MDBoolField, ); \
6345 OPTIONAL(flags, MDStringField, ); \
6346 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6347 OPTIONAL(splitDebugFilename, MDStringField, ); \
6348 OPTIONAL(emissionKind, EmissionKindField, ); \
6349 OPTIONAL(enums, MDField, ); \
6350 OPTIONAL(retainedTypes, MDField, ); \
6351 OPTIONAL(globals, MDField, ); \
6352 OPTIONAL(imports, MDField, ); \
6353 OPTIONAL(macros, MDField, ); \
6354 OPTIONAL(dwoId, MDUnsignedField, ); \
6355 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6356 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6357 OPTIONAL(nameTableKind, NameTableKindField, ); \
6358 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6359 OPTIONAL(sysroot, MDStringField, ); \
6360 OPTIONAL(sdk, MDStringField, ); \
6361 OPTIONAL(dialect, DwarfLangDialectField, );
6363#undef VISIT_MD_FIELDS
6365 if (!language.Seen && !sourceLanguageName.Seen)
6366 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6367 "required for !DICompileUnit");
6369 if (language.Seen && sourceLanguageName.Seen)
6370 return error(Loc,
"can only specify one of 'language' and "
6371 "'sourceLanguageName' on !DICompileUnit");
6373 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6374 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6375 "'sourceLanguageName' on !DICompileUnit");
6377 uint16_t Dialect =
static_cast<uint16_t
>(dialect.Val);
6380 ? DISourceLanguageName(
static_cast<uint16_t
>(language.Val), Dialect)
6381 : DISourceLanguageName(
6382 static_cast<uint16_t>(sourceLanguageName.Val),
6383 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6386 Context, SourceLanguage,
file.Val, producer.Val, isOptimized.Val,
6387 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6388 enums.Val, retainedTypes.Val,
globals.Val, imports.Val, macros.Val,
6389 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6390 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6403bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6404 auto Loc = Lex.getLoc();
6405#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6406 OPTIONAL(scope, MDField, ); \
6407 OPTIONAL(name, MDStringField, ); \
6408 OPTIONAL(linkageName, MDStringField, ); \
6409 OPTIONAL(file, MDField, ); \
6410 OPTIONAL(line, LineField, ); \
6411 REQUIRED(type, MDField, ( false)); \
6412 OPTIONAL(isLocal, MDBoolField, ); \
6413 OPTIONAL(isDefinition, MDBoolField, (true)); \
6414 OPTIONAL(scopeLine, LineField, ); \
6415 OPTIONAL(containingType, MDField, ); \
6416 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6417 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6418 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6419 OPTIONAL(flags, DIFlagField, ); \
6420 OPTIONAL(spFlags, DISPFlagField, ); \
6421 OPTIONAL(isOptimized, MDBoolField, ); \
6422 OPTIONAL(unit, MDField, ); \
6423 OPTIONAL(templateParams, MDField, ); \
6424 OPTIONAL(declaration, MDField, ); \
6425 OPTIONAL(retainedNodes, MDField, ); \
6426 OPTIONAL(thrownTypes, MDField, ); \
6427 OPTIONAL(annotations, MDField, ); \
6428 OPTIONAL(targetFuncName, MDStringField, ); \
6429 OPTIONAL(keyInstructions, MDBoolField, );
6431#undef VISIT_MD_FIELDS
6436 spFlags.Seen ? spFlags.Val
6438 isOptimized.Val, virtuality.Val);
6439 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6442 "missing 'distinct', required for !DISubprogram that is a Definition");
6445 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6446 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6447 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6448 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6449 targetFuncName.Val, keyInstructions.Val));
6459bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6460#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6461 REQUIRED(scope, MDField, ( false)); \
6462 OPTIONAL(file, MDField, ); \
6463 OPTIONAL(line, LineField, ); \
6464 OPTIONAL(column, ColumnField, );
6466#undef VISIT_MD_FIELDS
6469 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6475bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6476#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6477 REQUIRED(scope, MDField, ( false)); \
6478 OPTIONAL(file, MDField, ); \
6479 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6481#undef VISIT_MD_FIELDS
6484 (Context, scope.Val,
file.Val, discriminator.Val));
6490bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6491#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6492 REQUIRED(scope, MDField, ); \
6493 OPTIONAL(declaration, MDField, ); \
6494 OPTIONAL(name, MDStringField, ); \
6495 OPTIONAL(file, MDField, ); \
6496 OPTIONAL(line, LineField, );
6498#undef VISIT_MD_FIELDS
6501 (Context, scope.Val, declaration.Val,
name.Val,
6502 file.Val, line.Val));
6508bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6509#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6510 REQUIRED(scope, MDField, ); \
6511 OPTIONAL(name, MDStringField, ); \
6512 OPTIONAL(exportSymbols, MDBoolField, );
6514#undef VISIT_MD_FIELDS
6517 (Context, scope.Val,
name.Val, exportSymbols.Val));
6524bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6525#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6526 REQUIRED(type, DwarfMacinfoTypeField, ); \
6527 OPTIONAL(line, LineField, ); \
6528 REQUIRED(name, MDStringField, ); \
6529 OPTIONAL(value, MDStringField, );
6531#undef VISIT_MD_FIELDS
6534 (Context, type.Val, line.Val,
name.Val, value.Val));
6540bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6541#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6542 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6543 OPTIONAL(line, LineField, ); \
6544 REQUIRED(file, MDField, ); \
6545 OPTIONAL(nodes, MDField, );
6547#undef VISIT_MD_FIELDS
6550 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6558bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6559#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6560 REQUIRED(scope, MDField, ); \
6561 REQUIRED(name, MDStringField, ); \
6562 OPTIONAL(configMacros, MDStringField, ); \
6563 OPTIONAL(includePath, MDStringField, ); \
6564 OPTIONAL(apinotes, MDStringField, ); \
6565 OPTIONAL(file, MDField, ); \
6566 OPTIONAL(line, LineField, ); \
6567 OPTIONAL(isDecl, MDBoolField, );
6569#undef VISIT_MD_FIELDS
6572 configMacros.Val, includePath.Val,
6573 apinotes.Val, line.Val, isDecl.Val));
6579bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6580#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6581 OPTIONAL(name, MDStringField, ); \
6582 REQUIRED(type, MDField, ); \
6583 OPTIONAL(defaulted, MDBoolField, );
6585#undef VISIT_MD_FIELDS
6588 (Context,
name.Val, type.Val, defaulted.Val));
6596bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6597#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6598 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6599 OPTIONAL(name, MDStringField, ); \
6600 OPTIONAL(type, MDField, ); \
6601 OPTIONAL(defaulted, MDBoolField, ); \
6602 REQUIRED(value, MDField, );
6605#undef VISIT_MD_FIELDS
6608 DITemplateValueParameter,
6609 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6618bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6619#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6620 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6621 OPTIONAL(scope, MDField, ); \
6622 OPTIONAL(linkageName, MDStringField, ); \
6623 OPTIONAL(file, MDField, ); \
6624 OPTIONAL(line, LineField, ); \
6625 OPTIONAL(type, MDField, ); \
6626 OPTIONAL(isLocal, MDBoolField, ); \
6627 OPTIONAL(isDefinition, MDBoolField, (true)); \
6628 OPTIONAL(templateParams, MDField, ); \
6629 OPTIONAL(declaration, MDField, ); \
6630 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6631 OPTIONAL(annotations, MDField, );
6633#undef VISIT_MD_FIELDS
6637 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6638 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6639 declaration.Val, templateParams.Val,
align.Val,
6651bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6652#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6653 REQUIRED(scope, MDField, ( false)); \
6654 OPTIONAL(name, MDStringField, ); \
6655 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6656 OPTIONAL(file, MDField, ); \
6657 OPTIONAL(line, LineField, ); \
6658 OPTIONAL(type, MDField, ); \
6659 OPTIONAL(flags, DIFlagField, ); \
6660 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6661 OPTIONAL(annotations, MDField, );
6663#undef VISIT_MD_FIELDS
6666 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6667 type.Val, arg.Val, flags.Val,
align.Val,
6674bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6675#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6676 REQUIRED(scope, MDField, ( false)); \
6677 REQUIRED(name, MDStringField, ); \
6678 REQUIRED(file, MDField, ); \
6679 REQUIRED(line, LineField, ); \
6680 OPTIONAL(column, ColumnField, ); \
6681 OPTIONAL(isArtificial, MDBoolField, ); \
6682 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6684#undef VISIT_MD_FIELDS
6686 std::optional<unsigned> CoroSuspendIdx =
6687 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6691 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6692 column.Val, isArtificial.Val, CoroSuspendIdx));
6698bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6711 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6720 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6721 Lex.getStrVal() +
"'");
6724 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6725 return tokError(
"expected unsigned integer");
6727 auto &
U = Lex.getAPSIntVal();
6729 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6743bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6745 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6748 return parseDIExpressionBody(Result, IsDistinct);
6753bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6754 assert(PFS &&
"Expected valid function state");
6765 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6779bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6781#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6782 REQUIRED(var, MDField, ); \
6783 REQUIRED(expr, MDField, );
6785#undef VISIT_MD_FIELDS
6788 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6795bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6796#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6797 OPTIONAL(name, MDStringField, ); \
6798 OPTIONAL(file, MDField, ); \
6799 OPTIONAL(line, LineField, ); \
6800 OPTIONAL(setter, MDStringField, ); \
6801 OPTIONAL(getter, MDStringField, ); \
6802 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6803 OPTIONAL(type, MDField, );
6805#undef VISIT_MD_FIELDS
6808 (Context,
name.Val,
file.Val, line.Val, getter.Val,
6809 setter.Val, attributes.Val, type.Val));
6816bool LLParser::parseDIProperty(
MDNode *&Result,
bool IsDistinct) {
6817#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6818 OPTIONAL(name, MDStringField, ); \
6819 OPTIONAL(file, MDField, ); \
6820 OPTIONAL(line, LineField, ); \
6821 OPTIONAL(type, MDField, ); \
6822 OPTIONAL(backing_storage, MDField, );
6824#undef VISIT_MD_FIELDS
6827 type.Val, backing_storage.Val));
6834bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6835#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6836 REQUIRED(tag, DwarfTagField, ); \
6837 REQUIRED(scope, MDField, ); \
6838 OPTIONAL(entity, MDField, ); \
6839 OPTIONAL(file, MDField, ); \
6840 OPTIONAL(line, LineField, ); \
6841 OPTIONAL(name, MDStringField, ); \
6842 OPTIONAL(elements, MDField, );
6844#undef VISIT_MD_FIELDS
6847 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6848 line.Val,
name.Val, elements.Val));
6852#undef PARSE_MD_FIELD
6864bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6867 if (parseMetadata(MD, &PFS))
6878bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6879 PerFunctionState *PFS) {
6882 if (parseType(Ty, TypeMsg, Loc))
6885 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6888 if (parseValue(Ty, V, PFS))
6903bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6907 if (Lex.getStrVal() ==
"DIArgList") {
6909 if (parseDIArgList(AL, PFS))
6915 if (parseSpecializedMDNode(
N)) {
6925 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6935 if (parseMDString(S))
6945 if (parseMDNodeTail(
N))
6955bool LLParser::convertValIDToValue(
Type *Ty,
ValID &ID,
Value *&V,
6956 PerFunctionState *PFS) {
6958 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6963 return error(
ID.Loc,
"invalid use of function-local name");
6964 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6965 return V ==
nullptr;
6968 return error(
ID.Loc,
"invalid use of function-local name");
6969 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6970 return V ==
nullptr;
6973 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6977 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6982 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6985 return V ==
nullptr;
6987 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6990 return V ==
nullptr;
6993 return error(
ID.Loc,
"integer/byte constant must have integer/byte type");
6996 :
V = ConstantByte::
get(Context,
ID.APSIntVal);
7001 return error(
ID.Loc,
"floating point constant invalid for type");
7007 bool IsSNAN = ID.APFloatVal.isSignaling();
7010 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
7012 else if (Ty->isBFloatTy())
7013 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
7015 else if (Ty->isFloatTy())
7016 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
7022 APInt Payload = ID.APFloatVal.bitcastToAPInt();
7023 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
7024 ID.APFloatVal.isNegative(), &Payload);
7027 V = ConstantFP::get(Context,
ID.APFloatVal);
7029 if (
V->getType() != Ty)
7030 return error(
ID.Loc,
"floating point constant does not have type '" +
7036 return error(
ID.Loc,
"null must be a pointer type");
7042 return error(
ID.Loc,
"invalid type for undef constant");
7047 return error(
ID.Loc,
"invalid empty array initializer");
7053 return error(
ID.Loc,
"invalid type for null constant");
7056 return error(
ID.Loc,
"invalid type for null constant");
7061 return error(
ID.Loc,
"invalid type for none constant");
7067 return error(
ID.Loc,
"invalid type for poison constant");
7071 if (
ID.ConstantVal->getType() != Ty)
7072 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7079 return error(
ID.Loc,
"vector constant must have vector type");
7081 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7083 "' but expected '" +
7091 if (
ST->getNumElements() !=
ID.UIntVal)
7093 "initializer with struct type has wrong # elements");
7095 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
7098 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
7099 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
7102 "element " + Twine(i) +
7103 " of struct initializer doesn't match struct element type");
7106 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
7108 return error(
ID.Loc,
"constant expression type mismatch");
7117 auto Loc = Lex.getLoc();
7118 if (parseValID(ID,
nullptr, Ty))
7131 if (convertValIDToValue(Ty, ID, V,
nullptr))
7141 return error(Loc,
"expected a constant value");
7145bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
7149 FileLoc
Start = getTokLineColumnPos();
7150 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
7151 if (!Ret && ParserContext) {
7152 FileLoc
End = getPrevTokEndLineColumnPos();
7153 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start,
End));
7158bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
7160 return parseType(Ty) || parseValue(Ty, V, PFS);
7163bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
7164 PerFunctionState &PFS) {
7167 if (parseTypeAndValue(V, PFS))
7170 return error(Loc,
"expected a basic block");
7179 if (!Name.starts_with(
"llvm.dbg."))
7182 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7183 FnID == Intrinsic::dbg_assign;
7191bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
7192 unsigned &FunctionNumber,
7195 LocTy LinkageLoc = Lex.getLoc();
7197 unsigned Visibility;
7198 unsigned DLLStorageClass;
7200 AttrBuilder RetAttrs(M->getContext());
7203 Type *RetType =
nullptr;
7204 LocTy RetTypeLoc = Lex.getLoc();
7205 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
7207 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7208 parseType(RetType, RetTypeLoc,
true ))
7217 return error(LinkageLoc,
"invalid linkage for function definition");
7227 return error(LinkageLoc,
"invalid linkage for function declaration");
7231 return error(LinkageLoc,
"invalid function linkage type");
7235 return error(LinkageLoc,
7236 "symbol with local linkage must have default visibility");
7239 return error(LinkageLoc,
7240 "symbol with local linkage cannot have a DLL storage class");
7243 return error(RetTypeLoc,
"invalid function return type");
7245 LocTy NameLoc = Lex.getLoc();
7247 std::string FunctionName;
7249 FunctionName = Lex.getStrVal();
7251 FunctionNumber = Lex.getUIntVal();
7252 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
7256 return tokError(
"expected function name");
7262 return tokError(
"expected '(' in function argument list");
7266 AttrBuilder FuncAttrs(M->getContext());
7267 std::vector<unsigned> FwdRefAttrGrps;
7270 std::string Partition;
7274 unsigned AddrSpace = 0;
7280 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7281 parseOptionalUnnamedAddr(UnnamedAddr) ||
7282 parseOptionalProgramAddrSpace(AddrSpace) ||
7283 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7287 parseOptionalComdat(FunctionName,
C) ||
7288 parseOptionalAlignment(Alignment) ||
7289 parseOptionalPrefAlignment(PrefAlignment) ||
7290 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7294 parseGlobalTypeAndValue(PersonalityFn)))
7297 if (FuncAttrs.contains(Attribute::Builtin))
7298 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7301 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7303 FuncAttrs.removeAttribute(Attribute::Alignment);
7308 std::vector<Type*> ParamTypeList;
7311 for (
const ArgInfo &Arg : ArgList) {
7312 ParamTypeList.push_back(Arg.Ty);
7313 Attrs.push_back(Arg.Attrs);
7320 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7321 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7327 GlobalValue *FwdFn =
nullptr;
7328 if (!FunctionName.empty()) {
7331 auto FRVI = ForwardRefVals.find(FunctionName);
7332 if (FRVI != ForwardRefVals.end()) {
7333 FwdFn = FRVI->second.first;
7335 return error(FRVI->second.second,
7336 "invalid forward reference to "
7339 "' with wrong type: "
7343 ForwardRefVals.erase(FRVI);
7344 }
else if ((Fn = M->getFunction(FunctionName))) {
7346 return error(NameLoc,
7347 "invalid redefinition of function '" + FunctionName +
"'");
7348 }
else if (M->getNamedValue(FunctionName)) {
7349 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7355 if (FunctionNumber == (
unsigned)-1)
7356 FunctionNumber = NumberedVals.getNext();
7360 auto I = ForwardRefValIDs.find(FunctionNumber);
7361 if (
I != ForwardRefValIDs.end()) {
7362 FwdFn =
I->second.first;
7364 return error(NameLoc,
"type of definition and forward reference of '@" +
7365 Twine(FunctionNumber) +
7370 ForwardRefValIDs.erase(
I);
7379 if (FunctionName.empty())
7380 NumberedVals.add(FunctionNumber, Fn);
7396 if (!
GC.empty()) Fn->
setGC(GC);
7399 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7403 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7404 if (ParserContext && ArgList[i].IdentLoc)
7405 ParserContext->addInstructionOrArgumentLocation(
7406 &*ArgIt, ArgList[i].IdentLoc.value());
7408 if (ArgList[i].
Name.empty())
continue;
7411 ArgIt->
setName(ArgList[i].Name);
7413 if (ArgIt->
getName() != ArgList[i].Name)
7414 return error(ArgList[i].Loc,
7415 "redefinition of argument '%" + ArgList[i].Name +
"'");
7428 if (FunctionName.empty()) {
7430 ID.UIntVal = FunctionNumber;
7433 ID.StrVal = FunctionName;
7435 auto Blocks = ForwardRefBlockAddresses.find(ID);
7436 if (Blocks != ForwardRefBlockAddresses.end())
7437 return error(Blocks->first.Loc,
7438 "cannot take blockaddress inside a declaration");
7442bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7444 if (FunctionNumber == -1) {
7446 ID.StrVal = std::string(F.getName());
7449 ID.UIntVal = FunctionNumber;
7452 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7453 if (Blocks == P.ForwardRefBlockAddresses.end())
7456 for (
const auto &
I : Blocks->second) {
7457 const ValID &BBID =
I.first;
7458 GlobalValue *GV =
I.second;
7461 "Expected local id or name");
7468 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7471 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7479 P.ForwardRefBlockAddresses.erase(Blocks);
7485bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
7486 ArrayRef<unsigned> UnnamedArgNums) {
7488 return tokError(
"expected '{' in function body");
7491 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7495 if (PFS.resolveForwardRefBlockAddresses())
7501 return tokError(
"function body requires at least one basic block");
7505 if (parseBasicBlock(PFS))
7509 if (parseUseListOrder(&PFS))
7516 return PFS.finishFunction();
7521bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7522 FileLoc BBStart = getTokLineColumnPos();
7527 LocTy NameLoc = Lex.getLoc();
7529 Name = Lex.getStrVal();
7532 NameID = Lex.getUIntVal();
7536 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7540 std::string NameStr;
7545 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7546 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7553 if (SeenOldDbgInfoFormat)
7554 return error(Lex.getLoc(),
"debug record should not appear in a module "
7555 "containing debug info intrinsics");
7556 SeenNewDbgInfoFormat =
true;
7560 if (parseDebugRecord(DR, PFS))
7562 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7565 FileLoc InstStart = getTokLineColumnPos();
7568 LocTy NameLoc = Lex.getLoc();
7573 NameID = Lex.getUIntVal();
7575 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7578 NameStr = Lex.getStrVal();
7580 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7584 switch (parseInstruction(Inst, BB, PFS)) {
7587 case InstError:
return true;
7594 if (parseInstructionMetadata(*Inst))
7597 case InstExtraComma:
7602 if (parseInstructionMetadata(*Inst))
7608 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7612 for (DbgRecordPtr &DR : TrailingDbgRecord)
7614 TrailingDbgRecord.clear();
7615 if (ParserContext) {
7616 ParserContext->addInstructionOrArgumentLocation(
7617 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7622 ParserContext->addBlockLocation(
7623 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7625 assert(TrailingDbgRecord.empty() &&
7626 "All debug values should have been attached to an instruction.");
7635bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7638 LocTy DVRLoc = Lex.getLoc();
7640 return error(DVRLoc,
"expected debug record type here");
7641 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7642 .Case(
"declare", RecordKind::ValueKind)
7643 .Case(
"value", RecordKind::ValueKind)
7644 .Case(
"assign", RecordKind::ValueKind)
7645 .Case(
"label", RecordKind::LabelKind)
7646 .Case(
"declare_value", RecordKind::ValueKind);
7655 if (parseMDNode(Label))
7660 if (parseMDNode(DbgLoc))
7665 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7669 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7670 .Case(
"declare", LocType::Declare)
7671 .Case(
"value", LocType::Value)
7672 .Case(
"assign", LocType::Assign)
7673 .Case(
"declare_value", LocType::DeclareValue);
7681 if (parseMetadata(ValLocMD, &PFS))
7688 if (parseMDNode(Variable))
7695 if (parseMDNode(Expression))
7701 MDNode *AssignID =
nullptr;
7702 Metadata *AddressLocation =
nullptr;
7703 MDNode *AddressExpression =
nullptr;
7706 if (parseMDNode(AssignID))
7712 if (parseMetadata(AddressLocation, &PFS))
7718 if (parseMDNode(AddressExpression))
7732 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7734 PendingDbgRecords.emplace_back(DVRLoc, DR,
DebugLoc);
7743int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7744 PerFunctionState &PFS) {
7747 return tokError(
"found end of file when expecting more instructions");
7748 LocTy Loc = Lex.getLoc();
7749 unsigned KeywordVal = Lex.getUIntVal();
7754 return error(Loc,
"expected instruction opcode");
7758 return parseRet(Inst, BB, PFS);
7760 return parseBr(Inst, PFS);
7762 return parseSwitch(Inst, PFS);
7764 return parseIndirectBr(Inst, PFS);
7766 return parseInvoke(Inst, PFS);
7768 return parseResume(Inst, PFS);
7770 return parseCleanupRet(Inst, PFS);
7772 return parseCatchRet(Inst, PFS);
7774 return parseCatchSwitch(Inst, PFS);
7776 return parseCatchPad(Inst, PFS);
7778 return parseCleanupPad(Inst, PFS);
7780 return parseCallBr(Inst, PFS);
7783 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7784 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7800 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7812 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7813 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7827 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7835 return parseArithmetic(Inst, PFS, KeywordVal,
7839 if (parseLogical(Inst, PFS, KeywordVal))
7847 return parseLogical(Inst, PFS, KeywordVal);
7850 if (parseCompare(Inst, PFS, KeywordVal))
7857 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7858 int Res = parseCompare(Inst, PFS, KeywordVal);
7868 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7870 bool Res = parseCast(Inst, PFS, KeywordVal);
7880 bool Res = parseCast(Inst, PFS, KeywordVal);
7892 if (parseCast(Inst, PFS, KeywordVal))
7901 bool NonNull = EatIfPresent(lltok::kw_nonnull);
7902 if (parseCast(Inst, PFS, KeywordVal))
7915 return parseCast(Inst, PFS, KeywordVal);
7919 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7920 if (parseCast(Inst, PFS, KeywordVal))
7929 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7930 int Res = parseSelect(Inst, PFS);
7936 return error(Loc,
"fast-math-flags specified for select without "
7937 "floating-point scalar or vector return type");
7944 return parseVAArg(Inst, PFS);
7946 return parseExtractElement(Inst, PFS);
7948 return parseInsertElement(Inst, PFS);
7950 return parseShuffleVector(Inst, PFS);
7952 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7953 int Res = parsePHI(Inst, PFS);
7959 return error(Loc,
"fast-math-flags specified for phi without "
7960 "floating-point scalar or vector return type");
7967 return parseLandingPad(Inst, PFS);
7969 return parseFreeze(Inst, PFS);
7971 return parseBitInsert(Inst, PFS);
7973 return parseBitExtract(Inst, PFS);
7985 return parseAlloc(Inst, PFS);
7987 return parseLoad(Inst, PFS);
7989 return parseStore(Inst, PFS);
7991 return parseCmpXchg(Inst, PFS);
7993 return parseAtomicRMW(Inst, PFS);
7995 return parseFence(Inst, PFS);
7997 return parseGetElementPtr(Inst, PFS);
7999 return parseExtractValue(Inst, PFS);
8001 return parseInsertValue(Inst, PFS);
8006bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
8007 if (
Opc == Instruction::FCmp) {
8008 switch (Lex.getKind()) {
8010 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
8029 switch (Lex.getKind()) {
8031 return tokError(
"expected icmp predicate (e.g. 'eq')");
8055bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
8056 PerFunctionState &PFS) {
8057 SMLoc TypeLoc = Lex.getLoc();
8059 if (parseType(Ty,
true ))
8062 Type *ResType = PFS.getFunction().getReturnType();
8066 return error(TypeLoc,
"value doesn't match function result type '" +
8074 if (parseValue(Ty, RV, PFS))
8078 return error(TypeLoc,
"value doesn't match function result type '" +
8088bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
8092 if (parseTypeAndValue(Op0, Loc, PFS))
8101 return error(Loc,
"branch condition must have 'i1' type");
8103 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
8104 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
8105 parseToken(
lltok::comma,
"expected ',' after true destination") ||
8106 parseTypeAndBasicBlock(Op2, Loc2, PFS))
8118bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8119 LocTy CondLoc, BBLoc;
8122 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
8123 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
8124 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8128 if (!
Cond->getType()->isIntegerTy())
8129 return error(CondLoc,
"switch condition must have integer type");
8132 SmallPtrSet<Value*, 32> SeenCases;
8138 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8139 parseToken(
lltok::comma,
"expected ',' after case value") ||
8140 parseTypeAndBasicBlock(DestBB, PFS))
8143 if (!SeenCases.
insert(Constant).second)
8144 return error(CondLoc,
"duplicate case value in switch");
8146 return error(CondLoc,
"case value is not a constant integer");
8154 for (
const auto &[OnVal, Dest] :
Table)
8155 SI->addCase(OnVal, Dest);
8163bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8166 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
8167 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
8171 if (!
Address->getType()->isPointerTy())
8172 return error(AddrLoc,
"indirectbr address must have pointer type");
8175 SmallVector<BasicBlock*, 16> DestList;
8179 if (parseTypeAndBasicBlock(DestBB, PFS))
8184 if (parseTypeAndBasicBlock(DestBB, PFS))
8190 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8194 for (BasicBlock *Dest : DestList)
8204 FunctionType *&FuncTy) {
8210 for (
const ParamInfo &Arg : ArgList)
8224bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8225 LocTy CallLoc = Lex.getLoc();
8226 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8227 std::vector<unsigned> FwdRefAttrGrps;
8230 unsigned InvokeAddrSpace;
8231 Type *RetType =
nullptr;
8238 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8239 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8240 parseType(RetType, RetTypeLoc,
true ) ||
8241 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8242 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8244 parseOptionalOperandBundles(BundleList, PFS) ||
8246 parseTypeAndBasicBlock(NormalBB, PFS) ||
8248 parseTypeAndBasicBlock(UnwindBB, PFS))
8255 if (resolveFunctionType(RetType, ArgList, Ty))
8256 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8262 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
8267 SmallVector<Value *, 8>
Args;
8274 for (
const ParamInfo &Arg : ArgList) {
8275 Type *ExpectedTy =
nullptr;
8278 }
else if (!Ty->isVarArg()) {
8279 return error(Arg.Loc,
"too many arguments specified");
8282 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8283 return error(Arg.Loc,
"argument is not of expected type '" +
8285 Args.push_back(Arg.V);
8290 return error(CallLoc,
"not enough parameters specified for call");
8299 II->setCallingConv(CC);
8300 II->setAttributes(PAL);
8301 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
8308bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8310 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8318bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8319 PerFunctionState &PFS) {
8320 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8325 if (!
Args.empty() &&
8326 parseToken(
lltok::comma,
"expected ',' in argument list"))
8331 Type *ArgTy =
nullptr;
8332 if (parseType(ArgTy, ArgLoc))
8337 if (parseMetadataAsValue(V, PFS))
8340 if (parseValue(ArgTy, V, PFS))
8352bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8353 Value *CleanupPad =
nullptr;
8355 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8370 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8381bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8382 Value *CatchPad =
nullptr;
8384 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8391 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8392 parseTypeAndBasicBlock(BB, PFS))
8401bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8409 return tokError(
"expected scope value for catchswitch");
8414 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8420 if (parseTypeAndBasicBlock(DestBB, PFS))
8422 Table.push_back(DestBB);
8425 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8428 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8436 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8442 for (BasicBlock *DestBB :
Table)
8443 CatchSwitch->addHandler(DestBB);
8450bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8451 Value *CatchSwitch =
nullptr;
8457 return tokError(
"expected scope value for catchpad");
8462 SmallVector<Value *, 8>
Args;
8463 if (parseExceptionArgs(Args, PFS))
8472bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8473 Value *ParentPad =
nullptr;
8480 return tokError(
"expected scope value for cleanuppad");
8485 SmallVector<Value *, 8>
Args;
8486 if (parseExceptionArgs(Args, PFS))
8502bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8503 unsigned Opc,
bool IsFP) {
8505 if (parseTypeAndValue(
LHS, Loc, PFS))
8512 return error(Loc,
"invalid operand type for instruction");
8522bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8523 LocTy CallLoc = Lex.getLoc();
8524 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8525 std::vector<unsigned> FwdRefAttrGrps;
8528 Type *RetType =
nullptr;
8535 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8536 parseType(RetType, RetTypeLoc,
true ) ||
8537 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8538 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8540 parseOptionalOperandBundles(BundleList, PFS) ||
8542 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8547 SmallVector<BasicBlock *, 16> IndirectDests;
8551 if (parseTypeAndBasicBlock(DestBB, PFS))
8556 if (parseTypeAndBasicBlock(DestBB, PFS))
8562 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8569 if (resolveFunctionType(RetType, ArgList, Ty))
8570 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8581 SmallVector<Value *, 8>
Args;
8588 for (
const ParamInfo &Arg : ArgList) {
8589 Type *ExpectedTy =
nullptr;
8592 }
else if (!Ty->isVarArg()) {
8593 return error(Arg.Loc,
"too many arguments specified");
8596 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8597 return error(Arg.Loc,
"argument is not of expected type '" +
8599 Args.push_back(Arg.V);
8604 return error(CallLoc,
"not enough parameters specified for call");
8616 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8630bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8631 unsigned Opc,
bool IsFP) {
8633 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8634 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8642 return error(Loc,
"invalid operand type for instruction");
8650bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8653 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8654 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8660 "instruction requires integer or integer vector operands");
8669bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8675 if (parseCmpPredicate(Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8676 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8680 if (
Opc == Instruction::FCmp) {
8682 return error(Loc,
"fcmp requires floating point operands");
8685 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8688 return error(Loc,
"icmp requires integer operands");
8700bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8704 Type *DestTy =
nullptr;
8705 if (parseTypeAndValue(
Op, Loc, PFS) ||
8706 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8711 return error(Loc,
"invalid cast opcode for cast from '" +
8720bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8722 Value *Op0, *Op1, *Op2;
8723 if (parseTypeAndValue(Op0, Loc, PFS) ||
8724 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8725 parseTypeAndValue(Op1, PFS) ||
8726 parseToken(
lltok::comma,
"expected ',' after select value") ||
8727 parseTypeAndValue(Op2, PFS))
8731 return error(Loc, Reason);
8739bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8741 Type *EltTy =
nullptr;
8743 if (parseTypeAndValue(
Op, PFS) ||
8744 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8745 parseType(EltTy, TypeLoc))
8749 return error(TypeLoc,
"va_arg requires operand with first class type");
8751 Inst =
new VAArgInst(
Op, EltTy);
8757bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8760 if (parseTypeAndValue(Op0, Loc, PFS) ||
8761 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8762 parseTypeAndValue(Op1, PFS))
8766 return error(Loc,
"invalid extractelement operands");
8774bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8776 Value *Op0, *Op1, *Op2;
8777 if (parseTypeAndValue(Op0, Loc, PFS) ||
8778 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8779 parseTypeAndValue(Op1, PFS) ||
8780 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8781 parseTypeAndValue(Op2, PFS))
8785 return error(Loc,
"invalid insertelement operands");
8793bool LLParser::parseBitExtract(Instruction *&Inst, PerFunctionState &PFS) {
8797 if (parseType(Ty, Loc) ||
8798 parseToken(
lltok::comma,
"expected ',' after bitextract type") ||
8799 parseTypeAndValue(Op0, Loc, PFS) ||
8800 parseToken(
lltok::comma,
"expected ',' after bitextract source value") ||
8801 parseTypeAndValue(Op1, PFS))
8805 return error(Loc, Reason);
8813bool LLParser::parseBitInsert(Instruction *&Inst, PerFunctionState &PFS) {
8815 Value *Op0, *Op1, *Op2;
8816 if (parseTypeAndValue(Op0, Loc, PFS) ||
8817 parseToken(
lltok::comma,
"expected ',' after bitinsert source value") ||
8818 parseTypeAndValue(Op1, PFS) ||
8819 parseToken(
lltok::comma,
"expected ',' after bitinsert insert value") ||
8820 parseTypeAndValue(Op2, PFS))
8824 return error(Loc, Reason);
8832bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8834 Value *Op0, *Op1, *Op2;
8835 if (parseTypeAndValue(Op0, Loc, PFS) ||
8836 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8837 parseTypeAndValue(Op1, PFS) ||
8838 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8839 parseTypeAndValue(Op2, PFS))
8843 return error(Loc,
"invalid shufflevector operands");
8845 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8851int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8855 if (parseType(Ty, TypeLoc))
8859 return error(TypeLoc,
"phi node must have first class type");
8862 bool AteExtraComma =
false;
8874 AteExtraComma =
true;
8878 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8879 parseValue(Ty, Op0, PFS) ||
8880 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8889 for (
const auto &[Val, BB] : PHIVals)
8892 return AteExtraComma ? InstExtraComma : InstNormal;
8901bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8904 if (parseType(Ty, TyLoc))
8917 return tokError(
"expected 'catch' or 'filter' clause type");
8921 if (parseTypeAndValue(V, VLoc, PFS))
8928 return error(VLoc,
"'catch' clause has an invalid type");
8931 return error(VLoc,
"'filter' clause has an invalid type");
8936 return error(VLoc,
"clause argument must be a constant");
8940 Inst = LP.release();
8946bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8949 if (parseTypeAndValue(
Op, Loc, PFS))
8952 Inst =
new FreezeInst(
Op);
8965bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8967 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8968 std::vector<unsigned> FwdRefAttrGrps;
8970 unsigned CallAddrSpace;
8972 Type *RetType =
nullptr;
8977 LocTy CallLoc = Lex.getLoc();
8981 "expected 'tail call', 'musttail call', or 'notail call'"))
8984 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8986 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8987 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8988 parseType(RetType, RetTypeLoc,
true ) ||
8989 parseValID(CalleeID, &PFS) ||
8991 PFS.getFunction().isVarArg()) ||
8992 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8993 parseOptionalOperandBundles(BundleList, PFS))
9000 if (resolveFunctionType(RetType, ArgList, Ty))
9001 return error(RetTypeLoc,
"Invalid result type for LLVM function");
9007 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
9014 SmallVector<Value*, 8>
Args;
9020 for (
const ParamInfo &Arg : ArgList) {
9021 Type *ExpectedTy =
nullptr;
9024 }
else if (!Ty->isVarArg()) {
9025 return error(Arg.Loc,
"too many arguments specified");
9028 if (ExpectedTy && ExpectedTy != Arg.V->getType())
9029 return error(Arg.Loc,
"argument is not of expected type '" +
9031 Args.push_back(Arg.V);
9032 Attrs.push_back(Arg.Attrs);
9036 return error(CallLoc,
"not enough parameters specified for call");
9049 return error(CallLoc,
"fast-math-flags specified for call without "
9050 "floating-point scalar or vector return type");
9057 if (SeenNewDbgInfoFormat) {
9059 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
9060 "using non-intrinsic debug info");
9062 SeenOldDbgInfoFormat =
true;
9065 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
9077int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
9079 LocTy SizeLoc, TyLoc, ASLoc;
9081 unsigned AddrSpace = 0;
9084 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
9085 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
9087 if (parseType(Ty, TyLoc))
9091 return error(TyLoc,
"invalid type for alloca");
9093 bool AteExtraComma =
false;
9095 if (Lex.getKind() == lltok::kw_align) {
9096 if (parseOptionalAlignment(Alignment))
9098 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9101 ASLoc = Lex.getLoc();
9102 if (parseOptionalAddrSpace(AddrSpace))
9105 AteExtraComma =
true;
9107 if (parseTypeAndValue(
Size, SizeLoc, PFS))
9110 if (Lex.getKind() == lltok::kw_align) {
9111 if (parseOptionalAlignment(Alignment))
9113 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9116 ASLoc = Lex.getLoc();
9117 if (parseOptionalAddrSpace(AddrSpace))
9120 AteExtraComma =
true;
9126 if (
Size && !
Size->getType()->isIntegerTy())
9127 return error(SizeLoc,
"element count must have integer type");
9129 if (!Alignment && !Ty->
isSized())
9130 return error(TyLoc,
"Cannot allocate unsized type");
9132 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
9133 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
9137 return AteExtraComma ? InstExtraComma : InstNormal;
9144int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
9147 bool AteExtraComma =
false;
9157 bool isVolatile =
false;
9163 bool IsElementwise =
false;
9165 IsElementwise =
true;
9170 LocTy ExplicitTypeLoc = Lex.getLoc();
9171 if (parseType(Ty) ||
9172 parseToken(
lltok::comma,
"expected comma after load's type") ||
9173 parseTypeAndValue(Val, Loc, PFS) ||
9174 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9175 parseOptionalCommaAlign(Alignment, AteExtraComma))
9179 return error(Loc,
"load operand must be a pointer to a first class type");
9181 if (IsElementwise && !isAtomic)
9182 return error(Loc,
"elementwise load must be atomic");
9185 return error(ExplicitTypeLoc,
9186 "atomic elementwise load operand must have fixed vector type");
9188 if (isAtomic && !Alignment)
9189 return error(Loc,
"atomic load must have explicit non-zero alignment");
9193 return error(Loc,
"atomic load cannot use Release ordering");
9196 "atomic elementwise load cannot be sequentially consistent");
9198 if (!Alignment && !Ty->
isSized())
9199 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
9201 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9202 Inst =
new LoadInst(Ty, Val,
"",
9204 SSID, IsElementwise},
9206 return AteExtraComma ? InstExtraComma : InstNormal;
9214int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9218 bool AteExtraComma =
false;
9228 bool isVolatile =
false;
9234 bool IsElementwise =
false;
9236 IsElementwise =
true;
9240 if (parseTypeAndValue(Val, Loc, PFS) ||
9241 parseToken(
lltok::comma,
"expected ',' after store operand") ||
9242 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9243 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9244 parseOptionalCommaAlign(Alignment, AteExtraComma))
9248 return error(PtrLoc,
"store operand must be a pointer");
9250 return error(Loc,
"store operand must be a first class value");
9251 if (isAtomic && !Alignment)
9252 return error(Loc,
"atomic store must have explicit non-zero alignment");
9255 return error(Loc,
"atomic store cannot use Acquire ordering");
9257 if (IsElementwise && !isAtomic)
9258 return error(Loc,
"elementwise store must be atomic");
9262 Loc,
"atomic elementwise store operand must have fixed vector type");
9266 "atomic elementwise store cannot be sequentially consistent");
9269 return error(Loc,
"storing unsized types is not allowed");
9273 Inst =
new StoreInst(Val, Ptr,
9275 SSID, IsElementwise},
9277 return AteExtraComma ? InstExtraComma : InstNormal;
9284int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9286 bool AteExtraComma =
false;
9290 bool isVolatile =
false;
9291 bool isWeak =
false;
9300 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9301 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
9302 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9303 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
9304 parseTypeAndValue(New, NewLoc, PFS) ||
9305 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
9306 parseOrdering(FailureOrdering) ||
9307 parseOptionalCommaAlign(Alignment, AteExtraComma))
9311 return tokError(
"invalid cmpxchg success ordering");
9313 return tokError(
"invalid cmpxchg failure ordering");
9315 return error(PtrLoc,
"cmpxchg operand must be a pointer");
9316 if (
Cmp->getType() !=
New->getType())
9317 return error(NewLoc,
"compare value and new value type do not match");
9318 if (!
New->getType()->isFirstClassType())
9319 return error(NewLoc,
"cmpxchg operand must be a first class value");
9321 const Align DefaultAlignment(
9322 PFS.getFunction().getDataLayout().getTypeStoreSize(
9325 AtomicCmpXchgInst *CXI =
9326 new AtomicCmpXchgInst(Ptr, Cmp, New,
Alignment.value_or(DefaultAlignment),
9327 SuccessOrdering, FailureOrdering, SSID);
9332 return AteExtraComma ? InstExtraComma : InstNormal;
9339int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9341 bool AteExtraComma =
false;
9345 bool IsElementwise =
false;
9353 IsElementwise =
true;
9355 switch (Lex.getKind()) {
9357 return tokError(
"expected binary operation in atomicrmw");
9416 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9417 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9418 parseTypeAndValue(Val, ValLoc, PFS) ||
9419 parseScopeAndOrdering(
true , SSID, Ordering) ||
9420 parseOptionalCommaAlign(Alignment, AteExtraComma))
9424 return tokError(
"atomicrmw cannot be unordered");
9426 return tokError(
"atomicrmw elementwise cannot be sequentially consistent");
9428 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9430 return error(ValLoc,
"atomicrmw operand may not be scalable");
9433 if (IsElementwise) {
9435 return error(ValLoc,
9436 "atomicrmw elementwise operand must be a fixed vector type");
9445 " operand must be an integer type, a floating-point type, a "
9446 "pointer type, or a fixed vector of any of these types");
9450 return error(ValLoc,
"atomicrmw " +
9452 " operand must be a floating point or fixed "
9453 "vector of floating point type");
9460 " operand must be an integer or fixed vector of integer type");
9465 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9467 return error(ValLoc,
9468 "atomicrmw operand must have a power-of-two byte size");
9469 const Align DefaultAlignment(
9470 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->
getType()));
9471 AtomicRMWInst *RMWI =
new AtomicRMWInst(
Operation, Ptr, Val,
9473 Ordering, SSID, IsElementwise);
9476 return AteExtraComma ? InstExtraComma : InstNormal;
9481int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9484 if (parseScopeAndOrdering(
true , SSID, Ordering))
9488 return tokError(
"fence cannot be unordered");
9490 return tokError(
"fence cannot be monotonic");
9492 Inst =
new FenceInst(Context, Ordering, SSID);
9498int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9499 Value *Ptr =
nullptr;
9500 Value *Val =
nullptr;
9516 if (parseType(Ty) ||
9517 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9518 parseTypeAndValue(Ptr, Loc, PFS))
9523 if (!BasePointerType)
9524 return error(Loc,
"base of getelementptr must be a pointer");
9526 SmallVector<Value*, 16> Indices;
9527 bool AteExtraComma =
false;
9530 ElementCount GEPWidth =
BaseType->isVectorTy()
9536 AteExtraComma =
true;
9539 if (parseTypeAndValue(Val, EltLoc, PFS))
9542 return error(EltLoc,
"getelementptr index must be an integer");
9545 ElementCount ValNumEl = ValVTy->getElementCount();
9549 "getelementptr vector index has a wrong number of elements");
9550 GEPWidth = ValNumEl;
9556 return error(Loc,
"base element of getelementptr must be sized");
9560 return error(Loc,
"getelementptr cannot target structure that contains "
9561 "scalable vector type");
9564 return error(Loc,
"invalid getelementptr indices");
9567 GEP->setNoWrapFlags(NW);
9568 return AteExtraComma ? InstExtraComma : InstNormal;
9573int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9575 SmallVector<unsigned, 4> Indices;
9577 if (parseTypeAndValue(Val, Loc, PFS) ||
9578 parseIndexList(Indices, AteExtraComma))
9582 return error(Loc,
"extractvalue operand must be aggregate type");
9585 return error(Loc,
"invalid indices for extractvalue");
9587 return AteExtraComma ? InstExtraComma : InstNormal;
9592int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9594 SmallVector<unsigned, 4> Indices;
9596 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9597 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9598 parseTypeAndValue(Val1, Loc1, PFS) ||
9599 parseIndexList(Indices, AteExtraComma))
9603 return error(Loc0,
"insertvalue operand must be aggregate type");
9607 return error(Loc0,
"invalid indices for insertvalue");
9608 if (IndexedType != Val1->
getType())
9609 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9613 return AteExtraComma ? InstExtraComma : InstNormal;
9624bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9639 if (parseMetadata(MD,
nullptr))
9644 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9650bool LLParser::sortUseListOrder(
Value *V, ArrayRef<unsigned> Indexes,
9652 if (!
V->hasUseList())
9655 return error(Loc,
"value has no uses");
9657 unsigned NumUses = 0;
9658 SmallDenseMap<const Use *, unsigned, 16> Order;
9659 for (
const Use &U :
V->uses()) {
9660 if (++NumUses > Indexes.
size())
9662 Order[&
U] = Indexes[NumUses - 1];
9665 return error(Loc,
"value only has one use");
9666 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9668 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9670 V->sortUseList([&](
const Use &L,
const Use &R) {
9678bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9679 SMLoc Loc = Lex.getLoc();
9683 return tokError(
"expected non-empty list of uselistorder indexes");
9690 bool IsOrdered =
true;
9691 assert(Indexes.
empty() &&
"Expected empty order vector");
9694 if (parseUInt32(Index))
9699 Max = std::max(Max, Index);
9700 IsOrdered &= Index == Indexes.
size();
9708 if (Indexes.
size() < 2)
9709 return error(Loc,
"expected >= 2 uselistorder indexes");
9712 "expected distinct uselistorder indexes in range [0, size)");
9714 return error(Loc,
"expected uselistorder indexes to change the order");
9721bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9722 SMLoc Loc = Lex.getLoc();
9727 SmallVector<unsigned, 16> Indexes;
9728 if (parseTypeAndValue(V, PFS) ||
9729 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9730 parseUseListOrderIndexes(Indexes))
9733 return sortUseListOrder(V, Indexes, Loc);
9739bool LLParser::parseModuleEntry(
unsigned ID) {
9748 parseStringConstant(Path) ||
9756 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9757 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9758 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9759 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9760 parseUInt32(Hash[4]))
9767 auto ModuleEntry = Index->addModule(Path, Hash);
9768 ModuleIdMap[
ID] = ModuleEntry->first();
9775bool LLParser::parseTypeIdEntry(
unsigned ID) {
9784 parseStringConstant(Name))
9787 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9789 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9794 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9795 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9796 for (
auto TIDRef : FwdRefTIDs->second) {
9798 "Forward referenced type id GUID expected to be 0");
9801 ForwardRefTypeIds.erase(FwdRefTIDs);
9809bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9813 parseTypeTestResolution(TIS.
TTRes))
9818 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9835bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9844 parseStringConstant(Name))
9848 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9855 IdToIndexMapType IdToIndexMap;
9868 if (parseGVReference(VI, GVId))
9875 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9876 TI.push_back({
Offset, VI});
9884 for (
auto I : IdToIndexMap) {
9885 auto &Infos = ForwardRefValueInfos[
I.first];
9886 for (
auto P :
I.second) {
9888 "Forward referenced ValueInfo expected to be empty");
9889 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9899 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9900 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9901 for (
auto TIDRef : FwdRefTIDs->second) {
9903 "Forward referenced type id GUID expected to be 0");
9906 ForwardRefTypeIds.erase(FwdRefTIDs);
9918bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9926 switch (Lex.getKind()) {
9946 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9958 switch (Lex.getKind()) {
9973 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9986 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
9999bool LLParser::parseOptionalWpdResolutions(
10000 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
10008 WholeProgramDevirtResolution WPDRes;
10012 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
10015 WPDResMap[
Offset] = WPDRes;
10032bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
10040 switch (Lex.getKind()) {
10051 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
10057 switch (Lex.getKind()) {
10065 if (parseOptionalResByArg(WPDRes.
ResByArg))
10069 return error(Lex.getLoc(),
10070 "expected optional WholeProgramDevirtResolution field");
10087bool LLParser::parseOptionalResByArg(
10088 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
10096 std::vector<uint64_t>
Args;
10097 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
10105 WholeProgramDevirtResolution::ByArg ByArg;
10106 switch (Lex.getKind()) {
10120 return error(Lex.getLoc(),
10121 "unexpected WholeProgramDevirtResolution::ByArg kind");
10127 switch (Lex.getKind()) {
10131 parseUInt64(ByArg.
Info))
10137 parseUInt32(ByArg.
Byte))
10143 parseUInt32(ByArg.
Bit))
10147 return error(Lex.getLoc(),
10148 "expected optional whole program devirt field");
10155 ResByArg[
Args] = ByArg;
10166bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10174 if (parseUInt64(Val))
10176 Args.push_back(Val);
10200bool LLParser::addGlobalValueToIndex(
10202 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
10207 VI = Index->getOrInsertValueInfo(GUID);
10211 auto *GV = M->getNamedValue(Name);
10213 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
10219 VI = Index->getOrInsertValueInfo(GV, GUID);
10223 "Need a source_filename to compute GUID for local");
10226 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10231 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10232 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10233 for (
auto VIRef : FwdRefVIs->second) {
10235 "Forward referenced ValueInfo expected to be empty");
10238 ForwardRefValueInfos.erase(FwdRefVIs);
10242 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10243 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10244 for (
auto AliaseeRef : FwdRefAliasees->second) {
10245 assert(!AliaseeRef.first->hasAliasee() &&
10246 "Forward referencing alias already has aliasee");
10247 assert(Summary &&
"Aliasee must be a definition");
10248 AliaseeRef.first->setAliasee(VI,
Summary.get());
10250 ForwardRefAliasees.erase(FwdRefAliasees);
10255 Index->addGlobalValueSummary(VI, std::move(Summary));
10258 if (ID == NumberedValueInfos.size())
10259 NumberedValueInfos.push_back(VI);
10262 if (ID > NumberedValueInfos.size())
10263 NumberedValueInfos.resize(ID + 1);
10264 NumberedValueInfos[
ID] =
VI;
10272bool LLParser::parseSummaryIndexFlags() {
10279 if (parseUInt64(Flags))
10282 Index->setFlags(Flags);
10288bool LLParser::parseBlockCount() {
10295 if (parseUInt64(BlockCount))
10298 Index->setBlockCount(BlockCount);
10306bool LLParser::parseGVEntry(
unsigned ID) {
10314 LocTy Loc = Lex.getLoc();
10317 switch (Lex.getKind()) {
10321 parseStringConstant(Name))
10327 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
10331 return error(Lex.getLoc(),
"expected name or guid tag");
10354 switch (Lex.getKind()) {
10356 if (parseFunctionSummary(Name, GUID, ID))
10360 if (parseVariableSummary(Name, GUID, ID))
10364 if (parseAliasSummary(Name, GUID, ID))
10368 return error(Lex.getLoc(),
"expected summary type");
10386 LocTy Loc = Lex.getLoc();
10390 StringRef ModulePath;
10391 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10394 false,
false,
false,
10396 unsigned InstCount;
10398 FunctionSummary::TypeIdInfo TypeIdInfo;
10399 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10401 std::vector<CallsiteInfo> Callsites;
10402 std::vector<AllocInfo> Allocs;
10404 FunctionSummary::FFlags FFlags = {};
10407 parseModuleReference(ModulePath) ||
10408 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10411 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10416 switch (Lex.getKind()) {
10418 if (parseOptionalFFlags(FFlags))
10422 if (parseOptionalCalls(Calls))
10426 if (parseOptionalTypeIdInfo(TypeIdInfo))
10430 if (parseOptionalRefs(Refs))
10434 if (parseOptionalParamAccesses(ParamAccesses))
10438 if (parseOptionalAllocs(Allocs))
10442 if (parseOptionalCallsites(Callsites))
10446 return error(Lex.getLoc(),
"expected optional function summary field");
10453 auto FS = std::make_unique<FunctionSummary>(
10454 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10460 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10462 FS->setModulePath(ModulePath);
10464 return addGlobalValueToIndex(Name, GUID,
10466 std::move(FS), Loc);
10474 LocTy Loc = Lex.getLoc();
10478 StringRef ModulePath;
10479 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10482 false,
false,
false,
10484 GlobalVarSummary::GVarFlags GVarFlags(
false,
10492 parseModuleReference(ModulePath) ||
10493 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10495 parseGVarFlags(GVarFlags))
10500 switch (Lex.getKind()) {
10502 if (parseOptionalVTableFuncs(VTableFuncs))
10506 if (parseOptionalRefs(Refs))
10510 return error(Lex.getLoc(),
"expected optional variable summary field");
10518 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10520 GS->setModulePath(ModulePath);
10521 GS->setVTableFuncs(std::move(VTableFuncs));
10523 return addGlobalValueToIndex(Name, GUID,
10525 std::move(GS), Loc);
10534 LocTy Loc = Lex.getLoc();
10537 StringRef ModulePath;
10538 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10541 false,
false,
false,
10545 parseModuleReference(ModulePath) ||
10546 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10552 ValueInfo AliaseeVI;
10554 auto AS = std::make_unique<AliasSummary>(GVFlags);
10555 AS->setModulePath(ModulePath);
10558 if (parseGVReference(AliaseeVI, GVId))
10563 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10565 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10566 assert(Summary &&
"Aliasee must be a definition");
10567 AS->setAliasee(AliaseeVI, Summary);
10574 return addGlobalValueToIndex(Name, GUID,
10576 std::move(AS), Loc);
10581bool LLParser::parseFlag(
unsigned &Val) {
10582 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10583 return tokError(
"expected integer");
10584 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10600bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10604 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10610 switch (Lex.getKind()) {
10613 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10619 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10625 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10631 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10637 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10643 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10649 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10655 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10661 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10667 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10672 return error(Lex.getLoc(),
"expected function flag type");
10676 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10687bool LLParser::parseOptionalCalls(
10688 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10692 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10696 IdToIndexMapType IdToIndexMap;
10705 LocTy Loc = Lex.getLoc();
10707 if (parseGVReference(VI, GVId))
10711 unsigned RelBF = 0;
10712 unsigned HasTailCall =
false;
10716 switch (Lex.getKind()) {
10719 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10725 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10730 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10734 return error(Lex.getLoc(),
"expected hotness, relbf, or tail");
10741 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10751 for (
auto I : IdToIndexMap) {
10752 auto &Infos = ForwardRefValueInfos[
I.first];
10753 for (
auto P :
I.second) {
10755 "Forward referenced ValueInfo expected to be empty");
10756 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10769 switch (Lex.getKind()) {
10773 case lltok::kw_cold:
10779 case lltok::kw_hot:
10786 return error(Lex.getLoc(),
"invalid call edge hotness");
10795bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10799 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10803 IdToIndexMapType IdToIndexMap;
10807 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10812 LocTy Loc = Lex.getLoc();
10814 if (parseGVReference(VI, GVId))
10827 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10828 VTableFuncs.push_back({
VI,
Offset});
10830 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10836 for (
auto I : IdToIndexMap) {
10837 auto &Infos = ForwardRefValueInfos[
I.first];
10838 for (
auto P :
I.second) {
10840 "Forward referenced ValueInfo expected to be empty");
10841 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10845 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10852bool LLParser::parseParamNo(
uint64_t &ParamNo) {
10854 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10860bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10863 auto ParseAPSInt = [&](
APSInt &Val) {
10865 return tokError(
"expected integer");
10866 Val = Lex.getAPSIntVal();
10868 Val.setIsSigned(
true);
10890bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10891 IdLocListType &IdLocList) {
10899 LocTy Loc = Lex.getLoc();
10900 if (parseGVReference(VI, GVId))
10904 IdLocList.emplace_back(GVId, Loc);
10907 parseParamNo(
Call.ParamNo) ||
10909 parseParamAccessOffset(
Call.Offsets))
10921bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10922 IdLocListType &IdLocList) {
10924 parseParamNo(
Param.ParamNo) ||
10926 parseParamAccessOffset(
Param.Use))
10935 FunctionSummary::ParamAccess::Call
Call;
10936 if (parseParamAccessCall(
Call, IdLocList))
10953bool LLParser::parseOptionalParamAccesses(
10954 std::vector<FunctionSummary::ParamAccess> &Params) {
10962 IdLocListType VContexts;
10963 size_t CallsNum = 0;
10965 FunctionSummary::ParamAccess ParamAccess;
10966 if (parseParamAccess(ParamAccess, VContexts))
10968 CallsNum += ParamAccess.
Calls.size();
10969 assert(VContexts.size() == CallsNum);
10971 Params.emplace_back(std::move(ParamAccess));
10979 IdLocListType::const_iterator ItContext = VContexts.begin();
10980 for (
auto &PA : Params) {
10981 for (
auto &
C : PA.Calls) {
10983 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10984 ItContext->second);
10988 assert(ItContext == VContexts.end());
10995bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10999 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
11003 struct ValueContext {
11008 std::vector<ValueContext> VContexts;
11012 VC.Loc = Lex.getLoc();
11013 if (parseGVReference(
VC.VI,
VC.GVId))
11015 VContexts.push_back(VC);
11021 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
11022 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
11025 IdToIndexMapType IdToIndexMap;
11026 for (
auto &VC : VContexts) {
11031 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
11037 for (
auto I : IdToIndexMap) {
11038 auto &Infos = ForwardRefValueInfos[
I.first];
11039 for (
auto P :
I.second) {
11041 "Forward referenced ValueInfo expected to be empty");
11042 Infos.emplace_back(&Refs[
P.first],
P.second);
11056bool LLParser::parseOptionalTypeIdInfo(
11057 FunctionSummary::TypeIdInfo &TypeIdInfo) {
11066 switch (Lex.getKind()) {
11068 if (parseTypeTests(TypeIdInfo.
TypeTests))
11092 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
11096 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11105bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
11113 IdToIndexMapType IdToIndexMap;
11117 unsigned ID = Lex.getUIntVal();
11118 LocTy Loc = Lex.getLoc();
11122 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
11124 }
else if (parseUInt64(GUID))
11126 TypeTests.push_back(GUID);
11131 for (
auto I : IdToIndexMap) {
11132 auto &Ids = ForwardRefTypeIds[
I.first];
11133 for (
auto P :
I.second) {
11134 assert(TypeTests[
P.first] == 0 &&
11135 "Forward referenced type id GUID expected to be 0");
11136 Ids.emplace_back(&TypeTests[
P.first],
P.second);
11140 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11148bool LLParser::parseVFuncIdList(
11149 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
11150 assert(Lex.getKind() == Kind);
11157 IdToIndexMapType IdToIndexMap;
11159 FunctionSummary::VFuncId VFuncId;
11160 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11162 VFuncIdList.push_back(VFuncId);
11170 for (
auto I : IdToIndexMap) {
11171 auto &Ids = ForwardRefTypeIds[
I.first];
11172 for (
auto P :
I.second) {
11173 assert(VFuncIdList[
P.first].GUID == 0 &&
11174 "Forward referenced type id GUID expected to be 0");
11175 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
11184bool LLParser::parseConstVCallList(
11186 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11187 assert(Lex.getKind() == Kind);
11194 IdToIndexMapType IdToIndexMap;
11196 FunctionSummary::ConstVCall ConstVCall;
11197 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11199 ConstVCallList.push_back(ConstVCall);
11207 for (
auto I : IdToIndexMap) {
11208 auto &Ids = ForwardRefTypeIds[
I.first];
11209 for (
auto P :
I.second) {
11210 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
11211 "Forward referenced type id GUID expected to be 0");
11212 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
11221bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11222 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11224 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
11228 if (parseArgs(ConstVCall.
Args))
11240bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11241 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11251 unsigned ID = Lex.getUIntVal();
11252 LocTy Loc = Lex.getLoc();
11256 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
11258 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
11260 parseUInt64(VFuncId.
GUID))
11266 parseUInt64(VFuncId.
Offset) ||
11278bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11288 switch (Lex.getKind()) {
11295 assert(HasLinkage &&
"Linkage not optional in summary entry");
11302 parseOptionalVisibility(Flag);
11307 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11313 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11319 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11325 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11334 if (parseOptionalImportType(Lex.getKind(), IK))
11336 GVFlags.
ImportType =
static_cast<unsigned>(IK);
11341 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11346 return error(Lex.getLoc(),
"expected gv flag type");
11360bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11368 auto ParseRest = [
this](
unsigned int &Val) {
11372 return parseFlag(Val);
11377 switch (Lex.getKind()) {
11378 case lltok::kw_readonly:
11379 if (ParseRest(Flag))
11383 case lltok::kw_writeonly:
11384 if (ParseRest(Flag))
11389 if (ParseRest(Flag))
11394 if (ParseRest(Flag))
11399 return error(Lex.getLoc(),
"expected gvar flag type");
11407bool LLParser::parseModuleReference(StringRef &ModulePath) {
11414 unsigned ModuleID = Lex.getUIntVal();
11415 auto I = ModuleIdMap.find(ModuleID);
11417 assert(
I != ModuleIdMap.end());
11418 ModulePath =
I->second;
11424bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11427 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11431 GVId = Lex.getUIntVal();
11433 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11435 VI = NumberedValueInfos[GVId];
11452bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11456 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11468 SmallVector<uint8_t> Versions;
11471 if (parseAllocType(V))
11476 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11480 std::vector<MIBInfo> MIBs;
11481 if (parseMemProfs(MIBs))
11484 Allocs.push_back({Versions, MIBs});
11501bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11505 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11511 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11520 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11526 SmallVector<unsigned> StackIdIndices;
11531 if (parseUInt64(StackId))
11533 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11554bool LLParser::parseAllocType(uint8_t &
AllocType) {
11555 switch (Lex.getKind()) {
11562 case lltok::kw_cold:
11565 case lltok::kw_hot:
11569 return error(Lex.getLoc(),
"invalid alloc type");
11582bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11586 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11590 IdToIndexMapType IdToIndexMap;
11593 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11600 LocTy Loc = Lex.getLoc();
11602 if (parseGVReference(VI, GVId))
11606 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11612 SmallVector<unsigned> Clones;
11615 if (parseUInt32(V))
11621 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11627 SmallVector<unsigned> StackIdIndices;
11632 if (parseUInt64(StackId))
11634 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11645 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11646 Callsites.push_back({
VI, Clones, StackIdIndices});
11654 for (
auto I : IdToIndexMap) {
11655 auto &Infos = ForwardRefValueInfos[
I.first];
11656 for (
auto P :
I.second) {
11658 "Forward referenced ValueInfo expected to be empty");
11659 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11663 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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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")
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static uint64_t align(uint64_t Size)
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static bool blockCommentCrossesBoundary(SMLoc BeginLoc, SMLoc EndLoc, SMLoc BoundaryLoc)
Return whether skipped trivia contains a block comment that crosses the boundary between two metadata...
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 scope_exit class, which executes user-defined cleanup logic at scope exit.
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 const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
static BitInsertInst * Create(Value *Base, Value *Val, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
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_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH 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 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 LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
LLVM_ABI void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
std::pair< key_type, mapped_type > value_type
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind getKind() const
LLVM_ABI bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
LLVMContext & getContext()
LLVM_ABI bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
LLVM_ABI bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
LLVM_ABI bool parseMetadataDefinitions(SlotMapping &Slots, ArrayRef< SMLoc > DefinitionEnds)
LLVM_ABI bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
static MemoryEffectsBase readOnly()
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static auto targetMemLocations()
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
bool isTargetMemLoc(IRMemLocation Loc) const
Whether location is target memory location.
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
A Module instance is used to store all the information related to an LLVM module.
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
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() 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)
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.
bool isSized() const
Return true if it makes sense to take the size of this 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 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.
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
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.
@ 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.
@ WASM_EmscriptenInvoke
For emscripten __invoke_* functions.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
@ X86_StdCall
stdcall is mostly used by the Win32 API.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
constexpr bool isAtomic(const T &...O)
constexpr bool isPacked(const T &...O)
@ System
Synchronized with respect to all concurrently executing threads.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_LLVM_LANG_DIALECT_max
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
@ kw_aarch64_sme_preservemost_from_x1
@ kw_wasm_emscripten_invokecc
@ kw_no_sanitize_hwaddress
@ kw_cheriot_librarycallcc
@ kw_cheriot_compartmentcalleecc
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_cheriot_compartmentcallcc
@ kw_amdgpu_gfx_whole_wave
@ kw_typeTestAssumeConstVCalls
@ kw_typeidCompatibleVTable
@ kw_typeCheckedLoadVCalls
@ kw_inaccessiblemem_or_argmemonly
@ kw_externally_initialized
@ kw_sanitize_address_dyninit
@ kw_amdgpu_cs_chain_preserve
@ kw_available_externally
@ kw_typeTestAssumeVCalls
@ kw_aarch64_sme_preservemost_from_x0
@ kw_dso_local_equivalent
@ kw_aarch64_sme_preservemost_from_x2
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
static void assign(DXContainerYAML::SourceInfo::SectionHeader &Dst, const dxbc::SourceInfo::SectionHeader &Src)
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
@ Async
"Asynchronous" unwind tables (instr precise)
@ Sync
"Synchronous" unwind tables
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
CaptureComponents
Components of the pointer that may be captured.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
IRMemLocation
The locations at which a function might access memory.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
@ End
Run the machine verifier once, at the end of the pipeline.
bool capturesNothing(CaptureComponents CC)
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getInvalid()
static constexpr DenormalMode getIEEE()
std::vector< uint64_t > Args
unsigned ReturnDoesNotAlias
unsigned MustBeUnreachable
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned NoRenameOnPromotion
This field is written by the ThinLTO prelink stage to decide whether a particular static global value...
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
LLVM_ABI bool set(StringRef Name, std::string Value)
Set a property using a string name.
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
std::map< unsigned, Type * > Types
StringMap< Type * > NamedTypes
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
NumberedValues< GlobalValue * > GlobalValues
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.