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();
164 SMLoc End = Lex.getLoc();
172 restoreParsingState(Slots);
176 SMLoc Start = Lex.getLoc();
178 bool Status = parseDIExpressionBody(Result,
false);
179 SMLoc End = Lex.getLoc();
187 restoreParsingState(&Slots);
190 for (
SMLoc End : DefinitionEnds) {
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()) {
2384bool LLParser::parseOptionalCallingConv(
unsigned &CC) {
2385 switch (Lex.getKind()) {
2472 return tokError(
"unknown RISC-V ABI VLEN");
2473#define CC_VLS_CASE(ABIVlen) \
2475 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2503 return parseUInt32(CC);
2513bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2516 std::string
Name = Lex.getStrVal();
2517 Kind = M->getMDKindID(Name);
2520 return parseMDNode(MD);
2525bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2528 return tokError(
"expected metadata after comma");
2532 auto Loc = Lex.getLoc();
2533 if (parseMetadataAttachment(MDK,
N))
2536 if (MDK == LLVMContext::MD_DIAssignID)
2537 TempDIAssignIDAttachments[
N].push_back(&Inst);
2538 else if (MDK == LLVMContext::MD_dbg)
2539 PendingDbgInsts.emplace_back(Loc, &Inst,
N);
2550bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2553 if (parseMetadataAttachment(MDK,
N))
2562bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2564 if (parseGlobalObjectMetadataAttachment(
F))
2572bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2574 if (!EatIfPresent(lltok::kw_align))
2576 LocTy AlignLoc = Lex.getLoc();
2579 LocTy ParenLoc = Lex.getLoc();
2580 bool HaveParens =
false;
2586 if (parseUInt64(
Value))
2590 return error(ParenLoc,
"expected ')'");
2593 return error(AlignLoc,
"alignment is not a power of two");
2595 return error(AlignLoc,
"huge alignments are not supported yet");
2603bool LLParser::parseOptionalPrefAlignment(
MaybeAlign &Alignment) {
2607 LocTy AlignLoc = Lex.getLoc();
2610 LocTy ParenLoc = Lex.getLoc();
2612 return error(ParenLoc,
"expected '('");
2614 if (parseUInt64(
Value))
2617 ParenLoc = Lex.getLoc();
2619 return error(ParenLoc,
"expected ')'");
2622 return error(AlignLoc,
"alignment is not a power of two");
2624 return error(AlignLoc,
"huge alignments are not supported yet");
2634 auto StrVal = Lex.getStrVal();
2635 auto ErrMsg =
"expected global code model string";
2636 if (StrVal ==
"tiny")
2638 else if (StrVal ==
"small")
2640 else if (StrVal ==
"kernel")
2642 else if (StrVal ==
"medium")
2644 else if (StrVal ==
"large")
2647 return tokError(ErrMsg);
2659bool LLParser::parseOptionalAttrBytes(
lltok::Kind AttrKind,
2660 std::optional<uint64_t> &Bytes,
2661 bool ErrorNoBytes) {
2662 assert((AttrKind == lltok::kw_dereferenceable ||
2663 AttrKind == lltok::kw_dereferenceable_or_null ||
2664 AttrKind == lltok::kw_dead_on_return) &&
2668 if (!EatIfPresent(AttrKind))
2670 LocTy ParenLoc = Lex.getLoc();
2673 return error(ParenLoc,
"expected '('");
2674 Bytes = std::nullopt;
2677 LocTy DerefLoc = Lex.getLoc();
2678 if (parseUInt64(Bytes.value()))
2680 ParenLoc = Lex.getLoc();
2682 return error(ParenLoc,
"expected ')'");
2684 return error(DerefLoc,
"byte count specified must be non-zero");
2688bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2693 LocTy KindLoc = Lex.getLoc();
2699 return error(KindLoc,
"expected unwind table kind");
2706 LocTy ParenLoc = Lex.getLoc();
2708 return error(ParenLoc,
"expected '('");
2709 LocTy KindLoc = Lex.getLoc();
2711 if (parseStringConstant(Arg))
2712 return error(KindLoc,
"expected allockind value");
2716 }
else if (
A ==
"realloc") {
2718 }
else if (
A ==
"free") {
2720 }
else if (
A ==
"uninitialized") {
2722 }
else if (
A ==
"zeroed") {
2724 }
else if (
A ==
"aligned") {
2727 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2730 ParenLoc = Lex.getLoc();
2732 return error(ParenLoc,
"expected ')'");
2734 return error(KindLoc,
"expected allockind value");
2743 return {Loc::ArgMem};
2745 return {Loc::InaccessibleMem};
2747 return {Loc::ErrnoMem};
2749 return {Loc::TargetMem0};
2751 return {Loc::TargetMem1};
2774 return std::nullopt;
2778static std::optional<DenormalMode::DenormalModeKind>
2790 return std::nullopt;
2794std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2799 Lex.setIgnoreColonInIdentifiers(
true);
2804 tokError(
"expected '('");
2805 return std::nullopt;
2808 bool SeenLoc =
false;
2809 bool SeenTargetLoc =
false;
2812 if (!Locs.
empty()) {
2815 tokError(
"expected ':' after location");
2816 return std::nullopt;
2823 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2824 "or access kind (none, read, write, readwrite)");
2826 tokError(
"expected access kind (none, read, write, readwrite)");
2827 return std::nullopt;
2831 if (!Locs.
empty()) {
2836 SeenTargetLoc =
true;
2838 if (Locs.size() > 1 && SeenTargetLoc) {
2839 tokError(
"target memory default access kind must be specified first");
2840 return std::nullopt;
2845 tokError(
"default access kind must be specified first");
2846 return std::nullopt;
2855 tokError(
"unterminated memory attribute");
2856 return std::nullopt;
2859std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2860 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2863 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2864 "positivezero, dynamic)");
2870 std::optional<DenormalMode::DenormalModeKind> InputMode;
2874 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2875 "positivezero, dynamic)");
2882 InputMode = OutputMode;
2885 return DenormalMode(*OutputMode, *InputMode);
2888std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2891 Lex.setIgnoreColonInIdentifiers(
true);
2902 bool HasDefaultSection =
false;
2904 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2905 if (!ParsedDefaultMode)
2907 DefaultMode = *ParsedDefaultMode;
2908 HasDefaultSection =
true;
2913 if (HasDefaultSection && !HasComma) {
2914 tokError(
"expected ',' before float:");
2919 if (parseType(Ty) || !Ty->
isFloatTy()) {
2920 tokError(
"expected float:");
2924 if (parseToken(
lltok::colon,
"expected ':' before float denormal_fpenv"))
2927 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2931 F32Mode = *ParsedF32Mode;
2934 if (parseToken(
lltok::rparen,
"unterminated denormal_fpenv"))
2937 return DenormalFPEnv(DefaultMode, F32Mode);
2979unsigned LLParser::parseNoFPClassAttr() {
2984 tokError(
"expected '('");
2991 if (TestMask != 0) {
2995 !parseUInt64(
Value)) {
2997 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
3002 error(Lex.getLoc(),
"expected ')'");
3008 error(Lex.getLoc(),
"expected nofpclass test mask");
3026bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
3027 bool &AteExtraComma) {
3028 AteExtraComma =
false;
3032 AteExtraComma =
true;
3036 if (Lex.getKind() != lltok::kw_align)
3037 return error(Lex.getLoc(),
"expected metadata or 'align'");
3039 if (parseOptionalAlignment(Alignment))
3052bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
3053 bool &AteExtraComma) {
3054 AteExtraComma =
false;
3058 AteExtraComma =
true;
3064 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
3066 if (parseOptionalAddrSpace(AddrSpace))
3073bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
3074 std::optional<unsigned> &HowManyArg) {
3077 auto StartParen = Lex.getLoc();
3079 return error(StartParen,
"expected '('");
3081 if (parseUInt32(BaseSizeArg))
3085 auto HowManyAt = Lex.getLoc();
3087 if (parseUInt32(HowMany))
3089 if (HowMany == BaseSizeArg)
3090 return error(HowManyAt,
3091 "'allocsize' indices can't refer to the same parameter");
3092 HowManyArg = HowMany;
3094 HowManyArg = std::nullopt;
3096 auto EndParen = Lex.getLoc();
3098 return error(EndParen,
"expected ')'");
3102bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
3103 unsigned &MaxValue) {
3106 auto StartParen = Lex.getLoc();
3108 return error(StartParen,
"expected '('");
3110 if (parseUInt32(MinValue))
3114 if (parseUInt32(MaxValue))
3117 MaxValue = MinValue;
3119 auto EndParen = Lex.getLoc();
3121 return error(EndParen,
"expected ')'");
3130bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
3135 return parseScope(SSID) || parseOrdering(Ordering);
3145 auto StartParenAt = Lex.getLoc();
3147 return error(StartParenAt,
"Expected '(' in syncscope");
3150 auto SSNAt = Lex.getLoc();
3151 if (parseStringConstant(SSN))
3152 return error(SSNAt,
"Expected synchronization scope name");
3154 auto EndParenAt = Lex.getLoc();
3156 return error(EndParenAt,
"Expected ')' in syncscope");
3158 SSID = Context.getOrInsertSyncScopeID(SSN);
3169 switch (Lex.getKind()) {
3171 return tokError(
"Expected ordering on atomic instruction");
3190bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
3192 if (!EatIfPresent(lltok::kw_alignstack))
3194 LocTy ParenLoc = Lex.getLoc();
3196 return error(ParenLoc,
"expected '('");
3197 LocTy AlignLoc = Lex.getLoc();
3198 if (parseUInt32(Alignment))
3200 ParenLoc = Lex.getLoc();
3202 return error(ParenLoc,
"expected ')'");
3204 return error(AlignLoc,
"stack alignment is not a power of two");
3218 bool &AteExtraComma) {
3219 AteExtraComma =
false;
3222 return tokError(
"expected ',' as start of index list");
3226 if (Indices.
empty())
3227 return tokError(
"expected index");
3228 AteExtraComma =
true;
3232 if (parseUInt32(Idx))
3245bool LLParser::parseType(
Type *&Result,
const Twine &
Msg,
bool AllowVoid) {
3246 SMLoc TypeLoc = Lex.getLoc();
3247 switch (Lex.getKind()) {
3249 return tokError(
Msg);
3258 if (
Result->isPointerTy()) {
3260 if (parseOptionalAddrSpace(AddrSpace))
3266 return tokError(
"ptr* is invalid - use ptr instead");
3277 if (parseTargetExtType(Result))
3283 if (parseAnonStructType(Result,
false))
3289 if (parseArrayVectorType(Result,
false))
3296 if (parseAnonStructType(Result,
true) ||
3297 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
3299 }
else if (parseArrayVectorType(Result,
true))
3304 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
3310 Entry.second = Lex.getLoc();
3319 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
3325 Entry.second = Lex.getLoc();
3335 switch (Lex.getKind()) {
3338 if (!AllowVoid &&
Result->isVoidTy())
3339 return error(TypeLoc,
"void type only allowed for function results");
3345 return tokError(
"basic block pointers are invalid");
3347 return tokError(
"pointers to void are invalid - use i8* instead");
3349 return tokError(
"pointer to this type is invalid");
3357 return tokError(
"basic block pointers are invalid");
3359 return tokError(
"pointers to void are invalid; use i8* instead");
3361 return tokError(
"pointer to this type is invalid");
3363 if (parseOptionalAddrSpace(AddrSpace) ||
3364 parseToken(
lltok::star,
"expected '*' in address space"))
3373 if (parseFunctionType(Result))
3386 PerFunctionState &PFS,
bool IsMustTailCall,
3387 bool InVarArgsFunc) {
3393 if (!ArgList.
empty() &&
3394 parseToken(
lltok::comma,
"expected ',' in argument list"))
3399 const char *
Msg =
"unexpected ellipsis in argument list for ";
3400 if (!IsMustTailCall)
3401 return tokError(Twine(
Msg) +
"non-musttail call");
3403 return tokError(Twine(
Msg) +
"musttail call in non-varargs function");
3405 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3410 Type *ArgTy =
nullptr;
3412 if (parseType(ArgTy, ArgLoc))
3415 return error(ArgLoc,
"invalid type for function argument");
3417 AttrBuilder ArgAttrs(M->getContext());
3420 if (parseMetadataAsValue(V, PFS))
3424 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3431 if (IsMustTailCall && InVarArgsFunc)
3432 return tokError(
"expected '...' at end of argument list for musttail call "
3433 "in varargs function");
3441bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3444 if (!EatIfPresent(AttrToken))
3447 return error(Lex.getLoc(),
"expected '('");
3451 return error(Lex.getLoc(),
"expected ')'");
3453 B.addTypeAttr(AttrKind, Ty);
3459bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3467 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3469 return tokError(
"expected integer");
3470 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3472 "integer is too large for the bit width of specified type");
3473 Val = Lex.getAPSIntVal().extend(
BitWidth);
3478 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3481 return error(TyLoc,
"the range must have integer type!");
3489 return tokError(
"the range represent the empty set but limits aren't 0!");
3500bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3503 auto ParseAPSInt = [&](APInt &Val) {
3505 return tokError(
"expected integer");
3506 Val = Lex.getAPSIntVal().extend(64);
3526 return tokError(
"the range should not represent the full or empty set!");
3538 if (!CRLOrNull.has_value())
3539 return tokError(
"Invalid (unordered or overlapping) range list");
3540 B.addInitializesAttr(*CRLOrNull);
3544bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3546 std::optional<CaptureComponents> Ret;
3550 Lex.setIgnoreColonInIdentifiers(
true);
3558 bool SeenComponent =
false;
3564 return tokError(
"duplicate 'ret' location");
3567 SeenComponent =
false;
3572 return tokError(
"cannot use 'none' with other component");
3576 return tokError(
"cannot use 'none' with other component");
3587 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3588 "'provenance' or 'read_provenance'");
3591 SeenComponent =
true;
3599 B.addCapturesAttr(CaptureInfo(
Other, Ret.value_or(
Other)));
3612bool LLParser::parseOptionalOperandBundles(
3614 LocTy BeginLoc = Lex.getLoc();
3620 if (!BundleList.
empty() &&
3621 parseToken(
lltok::comma,
"expected ',' in input list"))
3625 if (parseStringConstant(
Tag))
3628 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3631 std::vector<Value *> Inputs;
3634 if (!Inputs.empty() &&
3635 parseToken(
lltok::comma,
"expected ',' in input list"))
3639 Value *Input =
nullptr;
3643 if (parseMetadataAsValue(Input, PFS))
3645 }
else if (parseValue(Ty, Input, PFS)) {
3648 Inputs.push_back(Input);
3656 if (BundleList.
empty())
3657 return error(BeginLoc,
"operand bundle set must not be empty");
3664 unsigned NextID,
unsigned ID) {
3666 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3667 Twine(NextID) +
"' or greater");
3684 unsigned CurValID = 0;
3698 LocTy TypeLoc = Lex.getLoc();
3699 Type *ArgTy =
nullptr;
3700 AttrBuilder
Attrs(M->getContext());
3701 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3705 return error(TypeLoc,
"argument can not have void type");
3710 bool Unnamed =
false;
3712 Name = Lex.getStrVal();
3713 IdentStart = getTokLineColumnPos();
3715 IdentEnd = getPrevTokEndLineColumnPos();
3719 ArgID = Lex.getUIntVal();
3720 IdentStart = getTokLineColumnPos();
3721 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3724 IdentEnd = getPrevTokEndLineColumnPos();
3730 CurValID = ArgID + 1;
3734 return error(TypeLoc,
"invalid type for function argument");
3738 Unnamed ? std::nullopt
3739 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3744 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3749bool LLParser::parseFunctionType(
Type *&Result) {
3753 return tokError(
"invalid function return type");
3757 SmallVector<unsigned> UnnamedArgNums;
3758 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3762 for (
const ArgInfo &Arg : ArgList) {
3763 if (!Arg.Name.empty())
3764 return error(Arg.Loc,
"argument name invalid in function type");
3765 if (Arg.Attrs.hasAttributes())
3766 return error(Arg.Loc,
"argument attributes invalid in function type");
3770 for (
const ArgInfo &Arg : ArgList)
3779bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3781 if (parseStructBody(Elts))
3789bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3790 std::pair<Type *, LocTy> &Entry,
3794 return error(TypeLoc,
"redefinition of type");
3800 Entry.second = SMLoc();
3805 ResultTy =
Entry.first;
3817 return error(TypeLoc,
"forward references to non-struct type");
3821 return parseArrayVectorType(ResultTy,
true);
3822 return parseType(ResultTy);
3826 Entry.second = SMLoc();
3835 if (parseStructBody(Body) ||
3836 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3840 return tokError(
toString(std::move(
E)));
3860 LocTy EltTyLoc = Lex.getLoc();
3867 return error(EltTyLoc,
"invalid element type for struct");
3870 EltTyLoc = Lex.getLoc();
3875 return error(EltTyLoc,
"invalid element type for struct");
3880 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3889bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3890 bool Scalable =
false;
3894 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3900 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3901 Lex.getAPSIntVal().getBitWidth() > 64)
3902 return tokError(
"expected number in address space");
3904 LocTy SizeLoc = Lex.getLoc();
3908 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3911 LocTy TypeLoc = Lex.getLoc();
3912 Type *EltTy =
nullptr;
3913 if (parseType(EltTy))
3917 "expected end of sequential type"))
3922 return error(SizeLoc,
"zero element vector is illegal");
3924 return error(SizeLoc,
"size too large for vector");
3926 return error(TypeLoc,
"invalid vector element type");
3930 return error(TypeLoc,
"invalid array element type");
3947bool LLParser::parseTargetExtType(
Type *&Result) {
3952 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3953 parseStringConstant(TypeName))
3960 SmallVector<unsigned> IntParams;
3961 bool SeenInt =
false;
3968 if (parseUInt32(IntVal))
3971 }
else if (SeenInt) {
3974 return tokError(
"expected uint32 param");
3977 if (parseType(TypeParam,
true))
3983 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
3988 if (
auto E = TTy.takeError())
3989 return tokError(
toString(std::move(
E)));
4002 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
4005 auto It = UnnamedArgNums.
begin();
4008 unsigned ArgNum = *It++;
4009 NumberedVals.add(ArgNum, &A);
4014LLParser::PerFunctionState::~PerFunctionState() {
4017 for (
const auto &P : ForwardRefVals) {
4020 P.second.first->replaceAllUsesWith(
4022 P.second.first->deleteValue();
4025 for (
const auto &P : ForwardRefValIDs) {
4028 P.second.first->replaceAllUsesWith(
4030 P.second.first->deleteValue();
4034bool LLParser::PerFunctionState::finishFunction() {
4035 if (!ForwardRefVals.empty())
4036 return P.error(ForwardRefVals.begin()->second.second,
4037 "use of undefined value '%" + ForwardRefVals.begin()->first +
4039 if (!ForwardRefValIDs.empty())
4040 return P.error(ForwardRefValIDs.begin()->second.second,
4041 "use of undefined value '%" +
4042 Twine(ForwardRefValIDs.begin()->first) +
"'");
4049Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
4052 Value *Val =
F.getValueSymbolTable()->lookup(Name);
4057 auto I = ForwardRefVals.find(Name);
4058 if (
I != ForwardRefVals.end())
4059 Val =
I->second.first;
4064 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
4068 P.error(Loc,
"invalid use of a non-first-class type");
4079 if (FwdVal->
getName() != Name) {
4080 P.error(Loc,
"name is too long which can result in name collisions, "
4081 "consider making the name shorter or "
4082 "increasing -non-global-value-max-name-size");
4086 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
4090Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
4092 Value *Val = NumberedVals.get(ID);
4097 auto I = ForwardRefValIDs.find(ID);
4098 if (
I != ForwardRefValIDs.end())
4099 Val =
I->second.first;
4104 return P.checkValidVariableType(Loc,
"%" + Twine(ID), Ty, Val);
4107 P.error(Loc,
"invalid use of a non-first-class type");
4119 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
4125bool LLParser::PerFunctionState::setInstName(
int NameID,
4126 const std::string &NameStr,
4127 LocTy NameLoc, Instruction *Inst) {
4130 if (NameID != -1 || !NameStr.empty())
4131 return P.error(NameLoc,
"instructions returning void cannot have a name");
4137 if (NameStr.empty()) {
4140 NameID = NumberedVals.getNext();
4142 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
4146 auto FI = ForwardRefValIDs.find(NameID);
4147 if (FI != ForwardRefValIDs.end()) {
4150 return P.error(NameLoc,
"instruction forward referenced with type '" +
4154 Sentinel->replaceAllUsesWith(Inst);
4156 ForwardRefValIDs.erase(FI);
4159 NumberedVals.add(NameID, Inst);
4164 auto FI = ForwardRefVals.find(NameStr);
4165 if (FI != ForwardRefVals.end()) {
4168 return P.error(NameLoc,
"instruction forward referenced with type '" +
4172 Sentinel->replaceAllUsesWith(Inst);
4174 ForwardRefVals.erase(FI);
4180 if (Inst->
getName() != NameStr)
4181 return P.error(NameLoc,
"multiple definition of local value named '" +
4188BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
4194BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID,
LocTy Loc) {
4202BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
4203 int NameID,
LocTy Loc) {
4207 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
4210 NameID = NumberedVals.getNext();
4212 BB = getBB(NameID, Loc);
4214 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
4218 BB = getBB(Name, Loc);
4220 P.error(Loc,
"unable to create block named '" + Name +
"'");
4231 ForwardRefValIDs.erase(NameID);
4232 NumberedVals.add(NameID, BB);
4235 ForwardRefVals.erase(Name);
4252bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS,
Type *ExpectedTy) {
4253 ID.Loc = Lex.getLoc();
4254 switch (Lex.getKind()) {
4256 return tokError(
"expected value token");
4258 ID.UIntVal = Lex.getUIntVal();
4262 ID.StrVal = Lex.getStrVal();
4266 ID.UIntVal = Lex.getUIntVal();
4270 ID.StrVal = Lex.getStrVal();
4274 ID.APSIntVal = Lex.getAPSIntVal();
4278 ID.APFloatVal = Lex.getAPFloatVal();
4284 return error(
ID.Loc,
"unexpected floating-point literal");
4286 return error(
ID.Loc,
"floating-point constant invalid for type");
4291 "Invalid float strings should be caught by the lexer");
4296 return error(
ID.Loc,
"floating-point constant overflowed type");
4298 return error(
ID.Loc,
"floating-point constant underflowed type");
4304 return error(
ID.Loc,
"unexpected floating-point literal");
4306 const APInt &
Bits = Lex.getAPSIntVal();
4308 return error(
ID.Loc,
"float hex literal has incorrect number of bits");
4309 ID.APFloatVal =
APFloat(Semantics, Bits);
4331 if (parseGlobalValueVector(Elts) ||
4332 parseToken(
lltok::rbrace,
"expected end of struct constant"))
4335 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4336 ID.UIntVal = Elts.
size();
4337 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4338 Elts.
size() *
sizeof(Elts[0]));
4349 LocTy FirstEltLoc = Lex.getLoc();
4350 if (parseGlobalValueVector(Elts) ||
4352 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
4356 if (isPackedStruct) {
4357 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4358 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4359 Elts.
size() *
sizeof(Elts[0]));
4360 ID.UIntVal = Elts.
size();
4366 return error(
ID.Loc,
"constant vector must not be empty");
4368 if (!Elts[0]->
getType()->isIntegerTy() && !Elts[0]->
getType()->isByteTy() &&
4369 !Elts[0]->
getType()->isFloatingPointTy() &&
4373 "vector elements must have integer, byte, pointer or floating point "
4377 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
4379 return error(FirstEltLoc,
"vector element #" + Twine(i) +
4380 " is not of type '" +
4390 LocTy FirstEltLoc = Lex.getLoc();
4391 if (parseGlobalValueVector(Elts) ||
4403 if (!Elts[0]->
getType()->isFirstClassType())
4404 return error(FirstEltLoc,
"invalid array element type: " +
4410 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4412 return error(FirstEltLoc,
"array element #" + Twine(i) +
4413 " is not of type '" +
4425 Context, Lex.getStrVal(),
false, ATy->getElementType()->isByteTy());
4434 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4437 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4440 parseStringConstant(
ID.StrVal) ||
4441 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4444 ID.StrVal2 = Lex.getStrVal();
4445 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4446 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4457 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4458 parseValID(Fn, PFS) ||
4460 "expected comma in block address expression") ||
4461 parseValID(Label, PFS) ||
4462 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4466 return error(Fn.
Loc,
"expected function name in blockaddress");
4468 return error(
Label.Loc,
"expected basic block name in blockaddress");
4471 GlobalValue *GV =
nullptr;
4473 GV = NumberedVals.get(Fn.
UIntVal);
4474 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4475 GV = M->getNamedValue(Fn.
StrVal);
4481 return error(Fn.
Loc,
"expected function name in blockaddress");
4483 if (
F->isDeclaration())
4484 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4489 GlobalValue *&FwdRef =
4490 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4498 "type of blockaddress must be a pointer and not '" +
4503 FwdDeclAS = PFS->getFunction().getAddressSpace();
4507 FwdRef =
new GlobalVariable(
4512 ID.ConstantVal = FwdRef;
4520 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4522 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4524 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4526 return error(
Label.Loc,
"referenced value is not a basic block");
4529 return error(
Label.Loc,
"cannot take address of numeric label after "
4530 "the function is defined");
4532 F->getValueSymbolTable()->lookup(
Label.StrVal));
4534 return error(
Label.Loc,
"referenced value is not a basic block");
4548 if (parseValID(Fn, PFS))
4553 "expected global value name in dso_local_equivalent");
4556 GlobalValue *GV =
nullptr;
4558 GV = NumberedVals.get(Fn.
UIntVal);
4559 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4560 GV = M->getNamedValue(Fn.
StrVal);
4566 ? ForwardRefDSOLocalEquivalentIDs
4567 : ForwardRefDSOLocalEquivalentNames;
4568 GlobalValue *&FwdRef = FwdRefMap[Fn];
4575 ID.ConstantVal = FwdRef;
4581 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4582 "in dso_local_equivalent");
4593 if (parseValID(ID, PFS))
4597 return error(
ID.Loc,
"expected global value name in no_cfi");
4609 Constant *Disc =
nullptr, *AddrDisc =
nullptr,
4610 *DeactivationSymbol =
nullptr;
4613 "expected '(' in constant ptrauth expression") ||
4614 parseGlobalTypeAndValue(Ptr) ||
4616 "expected comma in constant ptrauth expression") ||
4617 parseGlobalTypeAndValue(
Key))
4620 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(Disc))
4622 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4625 parseGlobalTypeAndValue(DeactivationSymbol))
4628 "expected ')' in constant ptrauth expression"))
4632 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4635 if (!KeyC || KeyC->getBitWidth() != 32)
4636 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4638 ConstantInt *DiscC =
nullptr;
4644 "constant ptrauth integer discriminator must be i64 constant");
4650 if (!AddrDisc->getType()->isPointerTy())
4652 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4657 if (!DeactivationSymbol)
4658 DeactivationSymbol =
4660 if (!DeactivationSymbol->getType()->isPointerTy())
4662 "constant ptrauth deactivation symbol must be a pointer");
4676 unsigned Opc = Lex.getUIntVal();
4677 Type *DestTy =
nullptr;
4680 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4681 parseGlobalTypeAndValue(SrcVal) ||
4682 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4683 parseType(DestTy) ||
4684 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4687 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4696 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4698 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4700 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4702 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4704 return error(
ID.Loc,
"urem constexprs are no longer supported");
4706 return error(
ID.Loc,
"srem constexprs are no longer supported");
4708 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4710 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4712 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4714 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4716 return error(
ID.Loc,
"frem constexprs are no longer supported");
4718 return error(
ID.Loc,
"and constexprs are no longer supported");
4720 return error(
ID.Loc,
"or constexprs are no longer supported");
4722 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4724 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4726 return error(
ID.Loc,
"shl constexprs are no longer supported");
4728 return error(
ID.Loc,
"mul constexprs are no longer supported");
4730 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4732 return error(
ID.Loc,
"select constexprs are no longer supported");
4734 return error(
ID.Loc,
"zext constexprs are no longer supported");
4736 return error(
ID.Loc,
"sext constexprs are no longer supported");
4738 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4740 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4742 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4744 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4746 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4748 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4750 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4752 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4760 unsigned Opc = Lex.getUIntVal();
4763 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4764 Opc == Instruction::Mul) {
4773 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4774 parseGlobalTypeAndValue(Val0) ||
4775 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4776 parseGlobalTypeAndValue(Val1) ||
4777 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4780 return error(
ID.Loc,
"operands of constexpr must have same type");
4784 "constexpr requires integer or integer vector operands");
4795 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4798 if (parseGlobalTypeAndValue(
C))
4800 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4812 unsigned Opc = Lex.getUIntVal();
4815 bool HasInRange =
false;
4821 if (
Opc == Instruction::GetElementPtr) {
4837 return tokError(
"expected integer");
4838 InRangeStart = Lex.getAPSIntVal();
4843 return tokError(
"expected integer");
4844 InRangeEnd = Lex.getAPSIntVal();
4852 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4855 if (
Opc == Instruction::GetElementPtr) {
4856 if (parseType(Ty) ||
4857 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4861 if (parseGlobalValueVector(Elts) ||
4865 if (
Opc == Instruction::GetElementPtr) {
4866 if (Elts.
size() == 0 ||
4867 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4868 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4871 std::optional<ConstantRange>
InRange;
4873 unsigned IndexWidth =
4874 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4875 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4876 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4877 if (InRangeStart.
sge(InRangeEnd))
4878 return error(
ID.Loc,
"expected end to be larger than start");
4888 for (Constant *Val : Indices) {
4891 return error(
ID.Loc,
"getelementptr index must be an integer");
4894 if (GEPWidth && (ValNumEl != GEPWidth))
4897 "getelementptr vector index has a wrong number of elements");
4900 GEPWidth = ValNumEl;
4904 if (!Indices.empty() && !Ty->
isSized())
4905 return error(
ID.Loc,
"base element of getelementptr must be sized");
4908 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4911 return error(
ID.Loc,
"invalid getelementptr indices");
4917 }
else if (
Opc == Instruction::ShuffleVector) {
4918 if (Elts.
size() != 3)
4919 return error(
ID.Loc,
"expected three operands to shufflevector");
4921 return error(
ID.Loc,
"invalid operands to shufflevector");
4922 SmallVector<int, 16>
Mask;
4925 }
else if (
Opc == Instruction::ExtractElement) {
4926 if (Elts.
size() != 2)
4927 return error(
ID.Loc,
"expected two operands to extractelement");
4929 return error(
ID.Loc,
"invalid extractelement operands");
4932 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4933 if (Elts.
size() != 3)
4934 return error(
ID.Loc,
"expected three operands to insertelement");
4936 return error(
ID.Loc,
"invalid insertelement operands");
4951bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4955 bool Parsed = parseValID(ID,
nullptr, Ty) ||
4956 convertValIDToValue(Ty, ID, V,
nullptr);
4958 return error(
ID.Loc,
"global values must be constants");
4962bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4964 return parseType(Ty) || parseGlobalValue(Ty, V);
4967bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
4970 LocTy KwLoc = Lex.getLoc();
4976 return tokError(
"expected comdat variable");
4977 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4979 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
4982 if (GlobalName.
empty())
4983 return tokError(
"comdat cannot be unnamed");
4984 C = getComdat(std::string(GlobalName), KwLoc);
4993bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
5007 if (parseGlobalTypeAndValue(
C))
5015bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
5017 if (parseMDNodeVector(Elts))
5028bool LLParser::parseMDNode(MDNode *&
N) {
5030 return parseSpecializedMDNode(
N);
5032 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
5035bool LLParser::parseMDNodeTail(MDNode *&
N) {
5038 return parseMDTuple(
N);
5041 return parseMDNodeID(
N);
5047template <
class FieldTy>
struct MDFieldImpl {
5048 typedef MDFieldImpl ImplTy;
5052 void assign(FieldTy Val) {
5054 this->Val = std::move(Val);
5057 explicit MDFieldImpl(FieldTy
Default)
5065template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
5066 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5079 this->
A = std::move(
A);
5085 this->
B = std::move(
B);
5089 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5091 WhatIs(IsInvalid) {}
5094struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
5101struct LineField :
public MDUnsignedField {
5102 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5105struct ColumnField :
public MDUnsignedField {
5106 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5109struct DwarfTagField :
public MDUnsignedField {
5115struct DwarfMacinfoTypeField :
public MDUnsignedField {
5121struct DwarfAttEncodingField :
public MDUnsignedField {
5122 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
5125struct DwarfVirtualityField :
public MDUnsignedField {
5129struct DwarfLangField :
public MDUnsignedField {
5133struct DwarfSourceLangNameField :
public MDUnsignedField {
5134 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5137struct DwarfLangDialectField :
public MDUnsignedField {
5138 DwarfLangDialectField()
5142struct DwarfCCField :
public MDUnsignedField {
5143 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
5146struct DwarfEnumKindField :
public MDUnsignedField {
5147 DwarfEnumKindField()
5152struct EmissionKindField :
public MDUnsignedField {
5153 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5156struct FixedPointKindField :
public MDUnsignedField {
5157 FixedPointKindField()
5158 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5161struct NameTableKindField :
public MDUnsignedField {
5162 NameTableKindField()
5165 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5168struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
5169 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5172struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
5173 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5176struct MDAPSIntField :
public MDFieldImpl<APSInt> {
5177 MDAPSIntField() : ImplTy(
APSInt()) {}
5180struct MDSignedField :
public MDFieldImpl<int64_t> {
5184 MDSignedField(int64_t
Default = 0)
5186 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5190struct MDBoolField :
public MDFieldImpl<bool> {
5194struct MDField :
public MDFieldImpl<Metadata *> {
5197 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5200struct MDStringField :
public MDFieldImpl<MDString *> {
5201 enum class EmptyIs {
5206 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5207 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5210struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5214struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5218struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5219 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5220 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5222 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5223 bool AllowNull =
true)
5224 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5226 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5227 bool isMDField()
const {
return WhatIs == IsTypeB; }
5228 int64_t getMDSignedValue()
const {
5229 assert(isMDSignedField() &&
"Wrong field type");
5232 Metadata *getMDFieldValue()
const {
5233 assert(isMDField() &&
"Wrong field type");
5238struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5240 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5243 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5245 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5246 bool isMDField()
const {
return WhatIs == IsTypeB; }
5247 uint64_t getMDUnsignedValue()
const {
5248 assert(isMDUnsignedField() &&
"Wrong field type");
5251 Metadata *getMDFieldValue()
const {
5252 assert(isMDField() &&
"Wrong field type");
5257 if (isMDUnsignedField())
5259 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5261 return getMDFieldValue();
5273 return tokError(
"expected integer");
5275 Result.assign(Lex.getAPSIntVal());
5282 MDUnsignedField &Result) {
5283 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5284 return tokError(
"expected unsigned integer");
5286 auto &U = Lex.getAPSIntVal();
5287 if (U.ugt(Result.Max))
5288 return tokError(
"value for '" + Name +
"' too large, limit is " +
5290 Result.assign(U.getZExtValue());
5291 assert(Result.Val <= Result.Max &&
"Expected value in range");
5298 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5302 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5308 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5311 return tokError(
"expected DWARF tag");
5315 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5316 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5325 DwarfMacinfoTypeField &Result) {
5327 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5330 return tokError(
"expected DWARF macinfo type");
5334 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5335 Lex.getStrVal() +
"'");
5336 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5338 Result.assign(Macinfo);
5345 DwarfVirtualityField &Result) {
5347 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5350 return tokError(
"expected DWARF virtuality code");
5354 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5355 Lex.getStrVal() +
"'");
5356 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5357 Result.assign(Virtuality);
5364 DwarfEnumKindField &Result) {
5366 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5369 return tokError(
"expected DWARF enum kind code");
5373 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5374 Lex.getStrVal() +
"'");
5375 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5376 Result.assign(EnumKind);
5384 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5387 return tokError(
"expected DWARF language");
5391 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5393 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5394 Result.assign(Lang);
5401 DwarfSourceLangNameField &Result) {
5403 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5406 return tokError(
"expected DWARF source language name");
5410 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5411 Lex.getStrVal() +
"'");
5412 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5413 Result.assign(Lang);
5420 DwarfLangDialectField &Result) {
5425 if (Lex.getAPSIntVal() == 0)
5426 return tokError(
"value for 'dialect' must be a known DWARF language "
5427 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5428 "DW_LLVM_LANG_DIALECT_tile)");
5429 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5433 return tokError(
"expected DWARF language dialect");
5435 StringRef DialectString = Lex.getStrVal();
5440 if (Dialect > Result.Max)
5441 return tokError(
"invalid DWARF language dialect" +
Twine(
" '") +
5442 DialectString +
"'");
5443 Result.assign(Dialect);
5451 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5454 return tokError(
"expected DWARF calling convention");
5458 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5459 Lex.getStrVal() +
"'");
5460 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
5468 EmissionKindField &Result) {
5470 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5473 return tokError(
"expected emission kind");
5477 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5479 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5480 Result.assign(*Kind);
5487 FixedPointKindField &Result) {
5489 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5492 return tokError(
"expected fixed-point kind");
5496 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5498 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5499 Result.assign(*Kind);
5506 NameTableKindField &Result) {
5508 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5511 return tokError(
"expected nameTable kind");
5515 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5517 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5518 Result.assign((
unsigned)*Kind);
5525 DwarfAttEncodingField &Result) {
5527 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5530 return tokError(
"expected DWARF type attribute encoding");
5534 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5535 Lex.getStrVal() +
"'");
5536 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5537 Result.assign(Encoding);
5551 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5553 bool Res = parseUInt32(TempVal);
5559 return tokError(
"expected debug info flag");
5563 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5578 Result.assign(Combined);
5591 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5593 bool Res = parseUInt32(TempVal);
5599 return tokError(
"expected debug info flag");
5603 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5604 Lex.getStrVal() +
"'");
5618 Result.assign(Combined);
5625 return tokError(
"expected signed integer");
5627 auto &S = Lex.getAPSIntVal();
5629 return tokError(
"value for '" + Name +
"' too small, limit is " +
5632 return tokError(
"value for '" + Name +
"' too large, limit is " +
5634 Result.assign(S.getExtValue());
5635 assert(Result.Val >= Result.Min &&
"Expected value in range");
5636 assert(Result.Val <= Result.Max &&
"Expected value in range");
5643 switch (Lex.getKind()) {
5645 return tokError(
"expected 'true' or 'false'");
5647 Result.assign(
true);
5650 Result.assign(
false);
5660 if (!Result.AllowNull)
5661 return tokError(
"'" + Name +
"' cannot be null");
5663 Result.assign(
nullptr);
5668 if (parseMetadata(MD,
nullptr))
5677 MDSignedOrMDField &Result) {
5680 MDSignedField Res = Result.A;
5681 if (!parseMDField(
Loc, Name, Res)) {
5689 MDField Res = Result.B;
5690 if (!parseMDField(
Loc, Name, Res)) {
5700 MDUnsignedOrMDField &Result) {
5703 MDUnsignedField Res = Result.A;
5704 if (!parseMDField(
Loc, Name, Res)) {
5712 MDField Res = Result.B;
5713 if (!parseMDField(
Loc, Name, Res)) {
5723 LocTy ValueLoc = Lex.getLoc();
5725 if (parseStringConstant(S))
5729 switch (Result.EmptyIs) {
5730 case MDStringField::EmptyIs::Null:
5731 Result.assign(
nullptr);
5733 case MDStringField::EmptyIs::Empty:
5735 case MDStringField::EmptyIs::Error:
5736 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5747 if (parseMDNodeVector(MDs))
5750 Result.assign(std::move(MDs));
5756 ChecksumKindField &Result) {
5757 std::optional<DIFile::ChecksumKind> CSKind =
5761 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5764 Result.assign(*CSKind);
5771template <
class ParserTy>
5772bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5775 return tokError(
"expected field label here");
5784template <
class ParserTy>
5785bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5792 if (parseMDFieldsImplBody(ParseField))
5795 ClosingLoc = Lex.getLoc();
5799template <
class FieldTy>
5800bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5802 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5804 LocTy Loc = Lex.getLoc();
5806 return parseMDField(Loc, Name, Result);
5809bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5812#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5813 if (Lex.getStrVal() == #CLASS) \
5814 return parse##CLASS(N, IsDistinct);
5815#include "llvm/IR/Metadata.def"
5817 return tokError(
"expected metadata type");
5820#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5821#define NOP_FIELD(NAME, TYPE, INIT)
5822#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5824 return error(ClosingLoc, "missing required field '" #NAME "'");
5825#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5826 if (Lex.getStrVal() == #NAME) \
5827 return parseMDField(#NAME, NAME);
5828#define PARSE_MD_FIELDS() \
5829 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5832 if (parseMDFieldsImpl( \
5834 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5835 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5840 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5842#define GET_OR_DISTINCT(CLASS, ARGS) \
5843 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5848bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
5849#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5850 OPTIONAL(line, LineField, ); \
5851 OPTIONAL(column, ColumnField, ); \
5852 REQUIRED(scope, MDField, ( false)); \
5853 OPTIONAL(inlinedAt, MDField, ); \
5854 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5855 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5856 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX)); \
5857 OPTIONAL(irlayers, MDField, );
5859#undef VISIT_MD_FIELDS
5863 inlinedAt.Val, isImplicitCode.Val,
5864 atomGroup.Val, atomRank.Val, irlayers.Val));
5868bool LLParser::parseDILayerLoc(
MDNode *&Result,
bool IsDistinct) {
5869#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5870 OPTIONAL(line, LineField, ); \
5871 OPTIONAL(column, ColumnField, ); \
5872 REQUIRED(file, MDField, ( false)); \
5873 REQUIRED(kind, MDStringField, );
5875#undef VISIT_MD_FIELDS
5878 (Context, kind.Val,
file.Val, line.Val, column.Val));
5882bool LLParser::parseDILayerLocList(
MDNode *&Result,
bool IsDistinct) {
5891 if (parseMetadata(MD,
nullptr))
5904bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
5906 return tokError(
"missing 'distinct', required for !DIAssignID()");
5922bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
5923#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5924 REQUIRED(tag, DwarfTagField, ); \
5925 OPTIONAL(header, MDStringField, ); \
5926 OPTIONAL(operands, MDFieldList, );
5928#undef VISIT_MD_FIELDS
5931 (Context, tag.Val, header.Val, operands.Val));
5940bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
5941#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5942 OPTIONAL(name, MDStringField, ); \
5943 OPTIONAL(file, MDField, ); \
5944 OPTIONAL(line, LineField, ); \
5945 OPTIONAL(scope, MDField, ); \
5946 OPTIONAL(baseType, MDField, ); \
5947 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5948 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5949 OPTIONAL(flags, DIFlagField, ); \
5950 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5951 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5952 OPTIONAL(stride, MDSignedOrMDField, ); \
5953 OPTIONAL(bias, MDSignedOrMDField, );
5955#undef VISIT_MD_FIELDS
5957 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
5958 if (Bound.isMDSignedField())
5961 if (Bound.isMDField())
5962 return Bound.getMDFieldValue();
5968 Metadata *Stride = convToMetadata(stride);
5969 Metadata *Bias = convToMetadata(bias);
5972 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
5973 size.getValueAsMetadata(Context),
align.Val, flags.Val,
5974 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5983bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
5984#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5985 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5986 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5987 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5988 OPTIONAL(stride, MDSignedOrMDField, );
5990#undef VISIT_MD_FIELDS
5997 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
5998 if (Bound.isMDSignedField())
6001 if (Bound.isMDField())
6002 return Bound.getMDFieldValue();
6009 Stride = convToMetadata(stride);
6012 (Context,
Count, LowerBound, UpperBound, Stride));
6020bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
6021#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6022 OPTIONAL(count, MDSignedOrMDField, ); \
6023 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6024 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6025 OPTIONAL(stride, MDSignedOrMDField, );
6027#undef VISIT_MD_FIELDS
6029 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
6030 if (Bound.isMDSignedField())
6032 Context, {dwarf::DW_OP_consts,
6033 static_cast<uint64_t>(Bound.getMDSignedValue())});
6034 if (Bound.isMDField())
6035 return Bound.getMDFieldValue();
6042 Metadata *Stride = ConvToMetadata(stride);
6045 (Context,
Count, LowerBound, UpperBound, Stride));
6052bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
6053#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6054 REQUIRED(name, MDStringField, ); \
6055 REQUIRED(value, MDAPSIntField, ); \
6056 OPTIONAL(isUnsigned, MDBoolField, (false));
6058#undef VISIT_MD_FIELDS
6060 if (isUnsigned.Val && value.Val.isNegative())
6061 return tokError(
"unsigned enumerator with negative value");
6066 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
6078bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
6079#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6080 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6081 OPTIONAL(name, MDStringField, ); \
6082 OPTIONAL(file, MDField, ); \
6083 OPTIONAL(line, LineField, ); \
6084 OPTIONAL(scope, MDField, ); \
6085 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6086 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6087 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
6088 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6089 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6090 OPTIONAL(flags, DIFlagField, );
6092#undef VISIT_MD_FIELDS
6095 DIBasicType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6096 size.getValueAsMetadata(Context),
align.Val, encoding.Val,
6097 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6106bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
6107#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6108 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6109 OPTIONAL(name, MDStringField, ); \
6110 OPTIONAL(file, MDField, ); \
6111 OPTIONAL(line, LineField, ); \
6112 OPTIONAL(scope, MDField, ); \
6113 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6114 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6115 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6116 OPTIONAL(flags, DIFlagField, ); \
6117 OPTIONAL(kind, FixedPointKindField, ); \
6118 OPTIONAL(factor, MDSignedField, ); \
6119 OPTIONAL(numerator, MDAPSIntField, ); \
6120 OPTIONAL(denominator, MDAPSIntField, );
6122#undef VISIT_MD_FIELDS
6125 (Context, tag.Val,
name.Val,
file.Val, line.Val,
6126 scope.Val,
size.getValueAsMetadata(Context),
6127 align.Val, encoding.Val, flags.Val, kind.Val,
6128 factor.Val, numerator.Val, denominator.Val));
6134bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
6135#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6136 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6137 OPTIONAL(name, MDStringField, ); \
6138 OPTIONAL(stringLength, MDField, ); \
6139 OPTIONAL(stringLengthExpression, MDField, ); \
6140 OPTIONAL(stringLocationExpression, MDField, ); \
6141 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6142 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6143 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6144 OPTIONAL(charType, MDField, );
6146#undef VISIT_MD_FIELDS
6150 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
6151 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
6152 align.Val, encoding.Val, charType.Val));
6165bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
6166#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6167 REQUIRED(tag, DwarfTagField, ); \
6168 OPTIONAL(name, MDStringField, ); \
6169 OPTIONAL(file, MDField, ); \
6170 OPTIONAL(line, LineField, ); \
6171 OPTIONAL(scope, MDField, ); \
6172 REQUIRED(baseType, MDField, ); \
6173 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6174 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6175 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6176 OPTIONAL(flags, DIFlagField, ); \
6177 OPTIONAL(extraData, MDField, ); \
6178 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6179 OPTIONAL(annotations, MDField, ); \
6180 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6181 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6182 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6183 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6184 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6186#undef VISIT_MD_FIELDS
6188 std::optional<unsigned> DWARFAddressSpace;
6189 if (dwarfAddressSpace.Val != UINT32_MAX)
6190 DWARFAddressSpace = dwarfAddressSpace.Val;
6191 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6193 PtrAuthData.emplace(
6194 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6195 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6196 ptrAuthAuthenticatesNullValues.Val);
6199 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6200 baseType.Val,
size.getValueAsMetadata(Context),
align.Val,
6201 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6202 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6206bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
6207#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6208 REQUIRED(tag, DwarfTagField, ); \
6209 OPTIONAL(name, MDStringField, ); \
6210 OPTIONAL(file, MDField, ); \
6211 OPTIONAL(line, LineField, ); \
6212 OPTIONAL(scope, MDField, ); \
6213 OPTIONAL(baseType, MDField, ); \
6214 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6215 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6216 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6217 OPTIONAL(flags, DIFlagField, ); \
6218 OPTIONAL(elements, MDField, ); \
6219 OPTIONAL(runtimeLang, DwarfLangField, ); \
6220 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6221 OPTIONAL(vtableHolder, MDField, ); \
6222 OPTIONAL(templateParams, MDField, ); \
6223 OPTIONAL(identifier, MDStringField, ); \
6224 OPTIONAL(discriminator, MDField, ); \
6225 OPTIONAL(dataLocation, MDField, ); \
6226 OPTIONAL(associated, MDField, ); \
6227 OPTIONAL(allocated, MDField, ); \
6228 OPTIONAL(rank, MDSignedOrMDField, ); \
6229 OPTIONAL(annotations, MDField, ); \
6230 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6231 OPTIONAL(specification, MDField, ); \
6232 OPTIONAL(bitStride, MDField, );
6234#undef VISIT_MD_FIELDS
6237 if (rank.isMDSignedField())
6240 else if (rank.isMDField())
6241 Rank = rank.getMDFieldValue();
6243 std::optional<unsigned> EnumKind;
6245 EnumKind = enumKind.Val;
6250 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
6251 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
6252 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6253 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6254 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6255 dataLocation.Val, associated.Val, allocated.Val, Rank,
6256 annotations.Val, bitStride.Val)) {
6265 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6266 size.getValueAsMetadata(Context),
align.Val,
6267 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6268 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6269 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6270 allocated.Val, Rank, annotations.Val, specification.Val,
6271 num_extra_inhabitants.Val, bitStride.Val));
6275bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6276#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6277 OPTIONAL(flags, DIFlagField, ); \
6278 OPTIONAL(cc, DwarfCCField, ); \
6279 REQUIRED(types, MDField, );
6281#undef VISIT_MD_FIELDS
6284 (Context, flags.Val, cc.Val, types.Val));
6293bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6297#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6298 REQUIRED(filename, MDStringField, ); \
6299 REQUIRED(directory, MDStringField, ); \
6300 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6301 OPTIONAL(checksum, MDStringField, ); \
6302 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6304#undef VISIT_MD_FIELDS
6306 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6307 if (checksumkind.Seen && checksum.Seen)
6308 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6309 else if (checksumkind.Seen || checksum.Seen)
6310 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6312 MDString *
Source =
nullptr;
6316 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6328bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6330 return tokError(
"missing 'distinct', required for !DICompileUnit");
6332 LocTy Loc = Lex.getLoc();
6334#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6335 REQUIRED(file, MDField, ( false)); \
6336 OPTIONAL(language, DwarfLangField, ); \
6337 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6338 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6339 OPTIONAL(producer, MDStringField, ); \
6340 OPTIONAL(isOptimized, MDBoolField, ); \
6341 OPTIONAL(flags, MDStringField, ); \
6342 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6343 OPTIONAL(splitDebugFilename, MDStringField, ); \
6344 OPTIONAL(emissionKind, EmissionKindField, ); \
6345 OPTIONAL(enums, MDField, ); \
6346 OPTIONAL(retainedTypes, MDField, ); \
6347 OPTIONAL(globals, MDField, ); \
6348 OPTIONAL(imports, MDField, ); \
6349 OPTIONAL(macros, MDField, ); \
6350 OPTIONAL(dwoId, MDUnsignedField, ); \
6351 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6352 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6353 OPTIONAL(nameTableKind, NameTableKindField, ); \
6354 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6355 OPTIONAL(sysroot, MDStringField, ); \
6356 OPTIONAL(sdk, MDStringField, ); \
6357 OPTIONAL(dialect, DwarfLangDialectField, );
6359#undef VISIT_MD_FIELDS
6361 if (!language.Seen && !sourceLanguageName.Seen)
6362 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6363 "required for !DICompileUnit");
6365 if (language.Seen && sourceLanguageName.Seen)
6366 return error(Loc,
"can only specify one of 'language' and "
6367 "'sourceLanguageName' on !DICompileUnit");
6369 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6370 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6371 "'sourceLanguageName' on !DICompileUnit");
6373 uint16_t Dialect =
static_cast<uint16_t
>(dialect.Val);
6376 ? DISourceLanguageName(
static_cast<uint16_t
>(language.Val), Dialect)
6377 : DISourceLanguageName(
6378 static_cast<uint16_t>(sourceLanguageName.Val),
6379 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6382 Context, SourceLanguage,
file.Val, producer.Val, isOptimized.Val,
6383 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6384 enums.Val, retainedTypes.Val,
globals.Val, imports.Val, macros.Val,
6385 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6386 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6399bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6400 auto Loc = Lex.getLoc();
6401#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6402 OPTIONAL(scope, MDField, ); \
6403 OPTIONAL(name, MDStringField, ); \
6404 OPTIONAL(linkageName, MDStringField, ); \
6405 OPTIONAL(file, MDField, ); \
6406 OPTIONAL(line, LineField, ); \
6407 REQUIRED(type, MDField, ( false)); \
6408 OPTIONAL(isLocal, MDBoolField, ); \
6409 OPTIONAL(isDefinition, MDBoolField, (true)); \
6410 OPTIONAL(scopeLine, LineField, ); \
6411 OPTIONAL(containingType, MDField, ); \
6412 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6413 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6414 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6415 OPTIONAL(flags, DIFlagField, ); \
6416 OPTIONAL(spFlags, DISPFlagField, ); \
6417 OPTIONAL(isOptimized, MDBoolField, ); \
6418 OPTIONAL(unit, MDField, ); \
6419 OPTIONAL(templateParams, MDField, ); \
6420 OPTIONAL(declaration, MDField, ); \
6421 OPTIONAL(retainedNodes, MDField, ); \
6422 OPTIONAL(thrownTypes, MDField, ); \
6423 OPTIONAL(annotations, MDField, ); \
6424 OPTIONAL(targetFuncName, MDStringField, ); \
6425 OPTIONAL(keyInstructions, MDBoolField, );
6427#undef VISIT_MD_FIELDS
6432 spFlags.Seen ? spFlags.Val
6434 isOptimized.Val, virtuality.Val);
6435 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6438 "missing 'distinct', required for !DISubprogram that is a Definition");
6441 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6442 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6443 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6444 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6445 targetFuncName.Val, keyInstructions.Val));
6455bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6456#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6457 REQUIRED(scope, MDField, ( false)); \
6458 OPTIONAL(file, MDField, ); \
6459 OPTIONAL(line, LineField, ); \
6460 OPTIONAL(column, ColumnField, );
6462#undef VISIT_MD_FIELDS
6465 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6471bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6472#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6473 REQUIRED(scope, MDField, ( false)); \
6474 OPTIONAL(file, MDField, ); \
6475 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6477#undef VISIT_MD_FIELDS
6480 (Context, scope.Val,
file.Val, discriminator.Val));
6486bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6487#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6488 REQUIRED(scope, MDField, ); \
6489 OPTIONAL(declaration, MDField, ); \
6490 OPTIONAL(name, MDStringField, ); \
6491 OPTIONAL(file, MDField, ); \
6492 OPTIONAL(line, LineField, );
6494#undef VISIT_MD_FIELDS
6497 (Context, scope.Val, declaration.Val,
name.Val,
6498 file.Val, line.Val));
6504bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6505#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6506 REQUIRED(scope, MDField, ); \
6507 OPTIONAL(name, MDStringField, ); \
6508 OPTIONAL(exportSymbols, MDBoolField, );
6510#undef VISIT_MD_FIELDS
6513 (Context, scope.Val,
name.Val, exportSymbols.Val));
6520bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6521#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6522 REQUIRED(type, DwarfMacinfoTypeField, ); \
6523 OPTIONAL(line, LineField, ); \
6524 REQUIRED(name, MDStringField, ); \
6525 OPTIONAL(value, MDStringField, );
6527#undef VISIT_MD_FIELDS
6530 (Context, type.Val, line.Val,
name.Val, value.Val));
6536bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6537#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6538 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6539 OPTIONAL(line, LineField, ); \
6540 REQUIRED(file, MDField, ); \
6541 OPTIONAL(nodes, MDField, );
6543#undef VISIT_MD_FIELDS
6546 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6554bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6555#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6556 REQUIRED(scope, MDField, ); \
6557 REQUIRED(name, MDStringField, ); \
6558 OPTIONAL(configMacros, MDStringField, ); \
6559 OPTIONAL(includePath, MDStringField, ); \
6560 OPTIONAL(apinotes, MDStringField, ); \
6561 OPTIONAL(file, MDField, ); \
6562 OPTIONAL(line, LineField, ); \
6563 OPTIONAL(isDecl, MDBoolField, );
6565#undef VISIT_MD_FIELDS
6568 configMacros.Val, includePath.Val,
6569 apinotes.Val, line.Val, isDecl.Val));
6575bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6576#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6577 OPTIONAL(name, MDStringField, ); \
6578 REQUIRED(type, MDField, ); \
6579 OPTIONAL(defaulted, MDBoolField, );
6581#undef VISIT_MD_FIELDS
6584 (Context,
name.Val, type.Val, defaulted.Val));
6592bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6593#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6594 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6595 OPTIONAL(name, MDStringField, ); \
6596 OPTIONAL(type, MDField, ); \
6597 OPTIONAL(defaulted, MDBoolField, ); \
6598 REQUIRED(value, MDField, );
6601#undef VISIT_MD_FIELDS
6604 DITemplateValueParameter,
6605 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6614bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6615#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6616 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6617 OPTIONAL(scope, MDField, ); \
6618 OPTIONAL(linkageName, MDStringField, ); \
6619 OPTIONAL(file, MDField, ); \
6620 OPTIONAL(line, LineField, ); \
6621 OPTIONAL(type, MDField, ); \
6622 OPTIONAL(isLocal, MDBoolField, ); \
6623 OPTIONAL(isDefinition, MDBoolField, (true)); \
6624 OPTIONAL(templateParams, MDField, ); \
6625 OPTIONAL(declaration, MDField, ); \
6626 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6627 OPTIONAL(annotations, MDField, );
6629#undef VISIT_MD_FIELDS
6633 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6634 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6635 declaration.Val, templateParams.Val,
align.Val,
6647bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6648#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6649 REQUIRED(scope, MDField, ( false)); \
6650 OPTIONAL(name, MDStringField, ); \
6651 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6652 OPTIONAL(file, MDField, ); \
6653 OPTIONAL(line, LineField, ); \
6654 OPTIONAL(type, MDField, ); \
6655 OPTIONAL(flags, DIFlagField, ); \
6656 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6657 OPTIONAL(annotations, MDField, );
6659#undef VISIT_MD_FIELDS
6662 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6663 type.Val, arg.Val, flags.Val,
align.Val,
6670bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6671#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6672 REQUIRED(scope, MDField, ( false)); \
6673 REQUIRED(name, MDStringField, ); \
6674 REQUIRED(file, MDField, ); \
6675 REQUIRED(line, LineField, ); \
6676 OPTIONAL(column, ColumnField, ); \
6677 OPTIONAL(isArtificial, MDBoolField, ); \
6678 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6680#undef VISIT_MD_FIELDS
6682 std::optional<unsigned> CoroSuspendIdx =
6683 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6687 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6688 column.Val, isArtificial.Val, CoroSuspendIdx));
6694bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6707 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6716 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6717 Lex.getStrVal() +
"'");
6720 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6721 return tokError(
"expected unsigned integer");
6723 auto &
U = Lex.getAPSIntVal();
6725 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6739bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6741 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6744 return parseDIExpressionBody(Result, IsDistinct);
6749bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6750 assert(PFS &&
"Expected valid function state");
6761 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6775bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6777#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6778 REQUIRED(var, MDField, ); \
6779 REQUIRED(expr, MDField, );
6781#undef VISIT_MD_FIELDS
6784 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6791bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
6792#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6793 OPTIONAL(name, MDStringField, ); \
6794 OPTIONAL(file, MDField, ); \
6795 OPTIONAL(line, LineField, ); \
6796 OPTIONAL(setter, MDStringField, ); \
6797 OPTIONAL(getter, MDStringField, ); \
6798 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6799 OPTIONAL(type, MDField, );
6801#undef VISIT_MD_FIELDS
6804 (Context,
name.Val,
file.Val, line.Val, getter.Val,
6805 setter.Val, attributes.Val, type.Val));
6812bool LLParser::parseDIProperty(
MDNode *&Result,
bool IsDistinct) {
6813#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6814 OPTIONAL(name, MDStringField, ); \
6815 OPTIONAL(file, MDField, ); \
6816 OPTIONAL(line, LineField, ); \
6817 OPTIONAL(type, MDField, ); \
6818 OPTIONAL(backing_storage, MDField, );
6820#undef VISIT_MD_FIELDS
6823 type.Val, backing_storage.Val));
6830bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
6831#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6832 REQUIRED(tag, DwarfTagField, ); \
6833 REQUIRED(scope, MDField, ); \
6834 OPTIONAL(entity, MDField, ); \
6835 OPTIONAL(file, MDField, ); \
6836 OPTIONAL(line, LineField, ); \
6837 OPTIONAL(name, MDStringField, ); \
6838 OPTIONAL(elements, MDField, );
6840#undef VISIT_MD_FIELDS
6843 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
6844 line.Val,
name.Val, elements.Val));
6848#undef PARSE_MD_FIELD
6860bool LLParser::parseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
6863 if (parseMetadata(MD, &PFS))
6874bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
6875 PerFunctionState *PFS) {
6878 if (parseType(Ty, TypeMsg, Loc))
6881 return error(Loc,
"invalid metadata-value-metadata roundtrip");
6884 if (parseValue(Ty, V, PFS))
6899bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
6903 if (Lex.getStrVal() ==
"DIArgList") {
6905 if (parseDIArgList(AL, PFS))
6911 if (parseSpecializedMDNode(
N)) {
6921 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
6931 if (parseMDString(S))
6941 if (parseMDNodeTail(
N))
6951bool LLParser::convertValIDToValue(
Type *Ty,
ValID &ID,
Value *&V,
6952 PerFunctionState *PFS) {
6954 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
6959 return error(
ID.Loc,
"invalid use of function-local name");
6960 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
6961 return V ==
nullptr;
6964 return error(
ID.Loc,
"invalid use of function-local name");
6965 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
6966 return V ==
nullptr;
6969 return error(
ID.Loc,
"invalid type for inline asm constraint string");
6973 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
6978 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
6981 return V ==
nullptr;
6983 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
6986 return V ==
nullptr;
6989 return error(
ID.Loc,
"integer/byte constant must have integer/byte type");
6992 :
V = ConstantByte::
get(Context,
ID.APSIntVal);
6997 return error(
ID.Loc,
"floating point constant invalid for type");
7003 bool IsSNAN = ID.APFloatVal.isSignaling();
7006 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
7008 else if (Ty->isBFloatTy())
7009 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
7011 else if (Ty->isFloatTy())
7012 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
7018 APInt Payload = ID.APFloatVal.bitcastToAPInt();
7019 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
7020 ID.APFloatVal.isNegative(), &Payload);
7023 V = ConstantFP::get(Context,
ID.APFloatVal);
7025 if (
V->getType() != Ty)
7026 return error(
ID.Loc,
"floating point constant does not have type '" +
7032 return error(
ID.Loc,
"null must be a pointer type");
7038 return error(
ID.Loc,
"invalid type for undef constant");
7043 return error(
ID.Loc,
"invalid empty array initializer");
7049 return error(
ID.Loc,
"invalid type for null constant");
7052 return error(
ID.Loc,
"invalid type for null constant");
7057 return error(
ID.Loc,
"invalid type for none constant");
7063 return error(
ID.Loc,
"invalid type for poison constant");
7067 if (
ID.ConstantVal->getType() != Ty)
7068 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7075 return error(
ID.Loc,
"vector constant must have vector type");
7077 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7079 "' but expected '" +
7087 if (
ST->getNumElements() !=
ID.UIntVal)
7089 "initializer with struct type has wrong # elements");
7091 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
7094 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
7095 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
7098 "element " + Twine(i) +
7099 " of struct initializer doesn't match struct element type");
7102 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
7104 return error(
ID.Loc,
"constant expression type mismatch");
7113 auto Loc = Lex.getLoc();
7114 if (parseValID(ID,
nullptr, Ty))
7127 if (convertValIDToValue(Ty, ID, V,
nullptr))
7137 return error(Loc,
"expected a constant value");
7141bool LLParser::parseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
7145 FileLoc
Start = getTokLineColumnPos();
7146 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
7147 if (!Ret && ParserContext) {
7148 FileLoc End = getPrevTokEndLineColumnPos();
7149 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
7154bool LLParser::parseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
7156 return parseType(Ty) || parseValue(Ty, V, PFS);
7159bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
7160 PerFunctionState &PFS) {
7163 if (parseTypeAndValue(V, PFS))
7166 return error(Loc,
"expected a basic block");
7175 if (!Name.starts_with(
"llvm.dbg."))
7178 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7179 FnID == Intrinsic::dbg_assign;
7187bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
7188 unsigned &FunctionNumber,
7191 LocTy LinkageLoc = Lex.getLoc();
7193 unsigned Visibility;
7194 unsigned DLLStorageClass;
7196 AttrBuilder RetAttrs(M->getContext());
7199 Type *RetType =
nullptr;
7200 LocTy RetTypeLoc = Lex.getLoc();
7201 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
7203 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7204 parseType(RetType, RetTypeLoc,
true ))
7213 return error(LinkageLoc,
"invalid linkage for function definition");
7223 return error(LinkageLoc,
"invalid linkage for function declaration");
7227 return error(LinkageLoc,
"invalid function linkage type");
7231 return error(LinkageLoc,
7232 "symbol with local linkage must have default visibility");
7235 return error(LinkageLoc,
7236 "symbol with local linkage cannot have a DLL storage class");
7239 return error(RetTypeLoc,
"invalid function return type");
7241 LocTy NameLoc = Lex.getLoc();
7243 std::string FunctionName;
7245 FunctionName = Lex.getStrVal();
7247 FunctionNumber = Lex.getUIntVal();
7248 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
7252 return tokError(
"expected function name");
7258 return tokError(
"expected '(' in function argument list");
7262 AttrBuilder FuncAttrs(M->getContext());
7263 std::vector<unsigned> FwdRefAttrGrps;
7266 std::string Partition;
7270 unsigned AddrSpace = 0;
7276 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7277 parseOptionalUnnamedAddr(UnnamedAddr) ||
7278 parseOptionalProgramAddrSpace(AddrSpace) ||
7279 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7283 parseOptionalComdat(FunctionName,
C) ||
7284 parseOptionalAlignment(Alignment) ||
7285 parseOptionalPrefAlignment(PrefAlignment) ||
7286 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7290 parseGlobalTypeAndValue(PersonalityFn)))
7293 if (FuncAttrs.contains(Attribute::Builtin))
7294 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7297 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7299 FuncAttrs.removeAttribute(Attribute::Alignment);
7304 std::vector<Type*> ParamTypeList;
7307 for (
const ArgInfo &Arg : ArgList) {
7308 ParamTypeList.push_back(Arg.Ty);
7309 Attrs.push_back(Arg.Attrs);
7316 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7317 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7323 GlobalValue *FwdFn =
nullptr;
7324 if (!FunctionName.empty()) {
7327 auto FRVI = ForwardRefVals.find(FunctionName);
7328 if (FRVI != ForwardRefVals.end()) {
7329 FwdFn = FRVI->second.first;
7331 return error(FRVI->second.second,
7332 "invalid forward reference to "
7335 "' with wrong type: "
7339 ForwardRefVals.erase(FRVI);
7340 }
else if ((Fn = M->getFunction(FunctionName))) {
7342 return error(NameLoc,
7343 "invalid redefinition of function '" + FunctionName +
"'");
7344 }
else if (M->getNamedValue(FunctionName)) {
7345 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7351 if (FunctionNumber == (
unsigned)-1)
7352 FunctionNumber = NumberedVals.getNext();
7356 auto I = ForwardRefValIDs.find(FunctionNumber);
7357 if (
I != ForwardRefValIDs.end()) {
7358 FwdFn =
I->second.first;
7360 return error(NameLoc,
"type of definition and forward reference of '@" +
7361 Twine(FunctionNumber) +
7366 ForwardRefValIDs.erase(
I);
7375 if (FunctionName.empty())
7376 NumberedVals.add(FunctionNumber, Fn);
7392 if (!
GC.empty()) Fn->
setGC(GC);
7395 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7399 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7400 if (ParserContext && ArgList[i].IdentLoc)
7401 ParserContext->addInstructionOrArgumentLocation(
7402 &*ArgIt, ArgList[i].IdentLoc.value());
7404 if (ArgList[i].
Name.empty())
continue;
7407 ArgIt->
setName(ArgList[i].Name);
7409 if (ArgIt->
getName() != ArgList[i].Name)
7410 return error(ArgList[i].Loc,
7411 "redefinition of argument '%" + ArgList[i].Name +
"'");
7424 if (FunctionName.empty()) {
7426 ID.UIntVal = FunctionNumber;
7429 ID.StrVal = FunctionName;
7431 auto Blocks = ForwardRefBlockAddresses.find(ID);
7432 if (Blocks != ForwardRefBlockAddresses.end())
7433 return error(Blocks->first.Loc,
7434 "cannot take blockaddress inside a declaration");
7438bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7440 if (FunctionNumber == -1) {
7442 ID.StrVal = std::string(F.getName());
7445 ID.UIntVal = FunctionNumber;
7448 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7449 if (Blocks == P.ForwardRefBlockAddresses.end())
7452 for (
const auto &
I : Blocks->second) {
7453 const ValID &BBID =
I.first;
7454 GlobalValue *GV =
I.second;
7457 "Expected local id or name");
7464 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7467 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7475 P.ForwardRefBlockAddresses.erase(Blocks);
7481bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
7482 ArrayRef<unsigned> UnnamedArgNums) {
7484 return tokError(
"expected '{' in function body");
7487 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7491 if (PFS.resolveForwardRefBlockAddresses())
7497 return tokError(
"function body requires at least one basic block");
7501 if (parseBasicBlock(PFS))
7505 if (parseUseListOrder(&PFS))
7512 return PFS.finishFunction();
7517bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7518 FileLoc BBStart = getTokLineColumnPos();
7523 LocTy NameLoc = Lex.getLoc();
7525 Name = Lex.getStrVal();
7528 NameID = Lex.getUIntVal();
7532 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7536 std::string NameStr;
7541 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7542 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7549 if (SeenOldDbgInfoFormat)
7550 return error(Lex.getLoc(),
"debug record should not appear in a module "
7551 "containing debug info intrinsics");
7552 SeenNewDbgInfoFormat =
true;
7556 if (parseDebugRecord(DR, PFS))
7558 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7561 FileLoc InstStart = getTokLineColumnPos();
7564 LocTy NameLoc = Lex.getLoc();
7569 NameID = Lex.getUIntVal();
7571 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7574 NameStr = Lex.getStrVal();
7576 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7580 switch (parseInstruction(Inst, BB, PFS)) {
7583 case InstError:
return true;
7590 if (parseInstructionMetadata(*Inst))
7593 case InstExtraComma:
7598 if (parseInstructionMetadata(*Inst))
7604 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7608 for (DbgRecordPtr &DR : TrailingDbgRecord)
7610 TrailingDbgRecord.clear();
7611 if (ParserContext) {
7612 ParserContext->addInstructionOrArgumentLocation(
7613 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7618 ParserContext->addBlockLocation(
7619 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7621 assert(TrailingDbgRecord.empty() &&
7622 "All debug values should have been attached to an instruction.");
7631bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7634 LocTy DVRLoc = Lex.getLoc();
7636 return error(DVRLoc,
"expected debug record type here");
7637 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7638 .Case(
"declare", RecordKind::ValueKind)
7639 .Case(
"value", RecordKind::ValueKind)
7640 .Case(
"assign", RecordKind::ValueKind)
7641 .Case(
"label", RecordKind::LabelKind)
7642 .Case(
"declare_value", RecordKind::ValueKind);
7651 if (parseMDNode(Label))
7656 if (parseMDNode(DbgLoc))
7661 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7665 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7666 .Case(
"declare", LocType::Declare)
7667 .Case(
"value", LocType::Value)
7668 .Case(
"assign", LocType::Assign)
7669 .Case(
"declare_value", LocType::DeclareValue);
7677 if (parseMetadata(ValLocMD, &PFS))
7684 if (parseMDNode(Variable))
7691 if (parseMDNode(Expression))
7697 MDNode *AssignID =
nullptr;
7698 Metadata *AddressLocation =
nullptr;
7699 MDNode *AddressExpression =
nullptr;
7702 if (parseMDNode(AssignID))
7708 if (parseMetadata(AddressLocation, &PFS))
7714 if (parseMDNode(AddressExpression))
7728 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7730 PendingDbgRecords.emplace_back(DVRLoc, DR,
DebugLoc);
7739int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7740 PerFunctionState &PFS) {
7743 return tokError(
"found end of file when expecting more instructions");
7744 LocTy Loc = Lex.getLoc();
7745 unsigned KeywordVal = Lex.getUIntVal();
7750 return error(Loc,
"expected instruction opcode");
7754 return parseRet(Inst, BB, PFS);
7756 return parseBr(Inst, PFS);
7758 return parseSwitch(Inst, PFS);
7760 return parseIndirectBr(Inst, PFS);
7762 return parseInvoke(Inst, PFS);
7764 return parseResume(Inst, PFS);
7766 return parseCleanupRet(Inst, PFS);
7768 return parseCatchRet(Inst, PFS);
7770 return parseCatchSwitch(Inst, PFS);
7772 return parseCatchPad(Inst, PFS);
7774 return parseCleanupPad(Inst, PFS);
7776 return parseCallBr(Inst, PFS);
7779 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7780 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
7796 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7808 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7809 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
7823 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
7831 return parseArithmetic(Inst, PFS, KeywordVal,
7835 if (parseLogical(Inst, PFS, KeywordVal))
7843 return parseLogical(Inst, PFS, KeywordVal);
7846 if (parseCompare(Inst, PFS, KeywordVal))
7853 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7854 int Res = parseCompare(Inst, PFS, KeywordVal);
7864 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7866 bool Res = parseCast(Inst, PFS, KeywordVal);
7876 bool Res = parseCast(Inst, PFS, KeywordVal);
7888 if (parseCast(Inst, PFS, KeywordVal))
7897 bool NonNull = EatIfPresent(lltok::kw_nonnull);
7898 if (parseCast(Inst, PFS, KeywordVal))
7911 return parseCast(Inst, PFS, KeywordVal);
7915 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7916 if (parseCast(Inst, PFS, KeywordVal))
7925 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7926 int Res = parseSelect(Inst, PFS);
7932 return error(Loc,
"fast-math-flags specified for select without "
7933 "floating-point scalar or vector return type");
7940 return parseVAArg(Inst, PFS);
7942 return parseExtractElement(Inst, PFS);
7944 return parseInsertElement(Inst, PFS);
7946 return parseShuffleVector(Inst, PFS);
7948 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7949 int Res = parsePHI(Inst, PFS);
7955 return error(Loc,
"fast-math-flags specified for phi without "
7956 "floating-point scalar or vector return type");
7963 return parseLandingPad(Inst, PFS);
7965 return parseFreeze(Inst, PFS);
7967 return parseBitInsert(Inst, PFS);
7969 return parseBitExtract(Inst, PFS);
7981 return parseAlloc(Inst, PFS);
7983 return parseLoad(Inst, PFS);
7985 return parseStore(Inst, PFS);
7987 return parseCmpXchg(Inst, PFS);
7989 return parseAtomicRMW(Inst, PFS);
7991 return parseFence(Inst, PFS);
7993 return parseGetElementPtr(Inst, PFS);
7995 return parseExtractValue(Inst, PFS);
7997 return parseInsertValue(Inst, PFS);
8002bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
8003 if (
Opc == Instruction::FCmp) {
8004 switch (Lex.getKind()) {
8006 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
8025 switch (Lex.getKind()) {
8027 return tokError(
"expected icmp predicate (e.g. 'eq')");
8051bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
8052 PerFunctionState &PFS) {
8053 SMLoc TypeLoc = Lex.getLoc();
8055 if (parseType(Ty,
true ))
8058 Type *ResType = PFS.getFunction().getReturnType();
8062 return error(TypeLoc,
"value doesn't match function result type '" +
8070 if (parseValue(Ty, RV, PFS))
8074 return error(TypeLoc,
"value doesn't match function result type '" +
8084bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
8088 if (parseTypeAndValue(Op0, Loc, PFS))
8097 return error(Loc,
"branch condition must have 'i1' type");
8099 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
8100 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
8101 parseToken(
lltok::comma,
"expected ',' after true destination") ||
8102 parseTypeAndBasicBlock(Op2, Loc2, PFS))
8114bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8115 LocTy CondLoc, BBLoc;
8118 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
8119 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
8120 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8124 if (!
Cond->getType()->isIntegerTy())
8125 return error(CondLoc,
"switch condition must have integer type");
8128 SmallPtrSet<Value*, 32> SeenCases;
8134 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8135 parseToken(
lltok::comma,
"expected ',' after case value") ||
8136 parseTypeAndBasicBlock(DestBB, PFS))
8139 if (!SeenCases.
insert(Constant).second)
8140 return error(CondLoc,
"duplicate case value in switch");
8142 return error(CondLoc,
"case value is not a constant integer");
8150 for (
const auto &[OnVal, Dest] :
Table)
8151 SI->addCase(OnVal, Dest);
8159bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8162 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
8163 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
8167 if (!
Address->getType()->isPointerTy())
8168 return error(AddrLoc,
"indirectbr address must have pointer type");
8171 SmallVector<BasicBlock*, 16> DestList;
8175 if (parseTypeAndBasicBlock(DestBB, PFS))
8180 if (parseTypeAndBasicBlock(DestBB, PFS))
8186 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8190 for (BasicBlock *Dest : DestList)
8200 FunctionType *&FuncTy) {
8206 for (
const ParamInfo &Arg : ArgList)
8220bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8221 LocTy CallLoc = Lex.getLoc();
8222 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8223 std::vector<unsigned> FwdRefAttrGrps;
8226 unsigned InvokeAddrSpace;
8227 Type *RetType =
nullptr;
8234 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8235 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8236 parseType(RetType, RetTypeLoc,
true ) ||
8237 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8238 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8240 parseOptionalOperandBundles(BundleList, PFS) ||
8242 parseTypeAndBasicBlock(NormalBB, PFS) ||
8244 parseTypeAndBasicBlock(UnwindBB, PFS))
8251 if (resolveFunctionType(RetType, ArgList, Ty))
8252 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8258 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
8263 SmallVector<Value *, 8>
Args;
8270 for (
const ParamInfo &Arg : ArgList) {
8271 Type *ExpectedTy =
nullptr;
8274 }
else if (!Ty->isVarArg()) {
8275 return error(Arg.Loc,
"too many arguments specified");
8278 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8279 return error(Arg.Loc,
"argument is not of expected type '" +
8281 Args.push_back(Arg.V);
8286 return error(CallLoc,
"not enough parameters specified for call");
8295 II->setCallingConv(CC);
8296 II->setAttributes(PAL);
8297 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
8304bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8306 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8314bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8315 PerFunctionState &PFS) {
8316 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8321 if (!
Args.empty() &&
8322 parseToken(
lltok::comma,
"expected ',' in argument list"))
8327 Type *ArgTy =
nullptr;
8328 if (parseType(ArgTy, ArgLoc))
8333 if (parseMetadataAsValue(V, PFS))
8336 if (parseValue(ArgTy, V, PFS))
8348bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8349 Value *CleanupPad =
nullptr;
8351 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8366 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8377bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8378 Value *CatchPad =
nullptr;
8380 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8387 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8388 parseTypeAndBasicBlock(BB, PFS))
8397bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8405 return tokError(
"expected scope value for catchswitch");
8410 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8416 if (parseTypeAndBasicBlock(DestBB, PFS))
8418 Table.push_back(DestBB);
8421 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8424 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8432 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8438 for (BasicBlock *DestBB :
Table)
8439 CatchSwitch->addHandler(DestBB);
8446bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8447 Value *CatchSwitch =
nullptr;
8453 return tokError(
"expected scope value for catchpad");
8458 SmallVector<Value *, 8>
Args;
8459 if (parseExceptionArgs(Args, PFS))
8468bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8469 Value *ParentPad =
nullptr;
8476 return tokError(
"expected scope value for cleanuppad");
8481 SmallVector<Value *, 8>
Args;
8482 if (parseExceptionArgs(Args, PFS))
8498bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8499 unsigned Opc,
bool IsFP) {
8501 if (parseTypeAndValue(
LHS, Loc, PFS))
8508 return error(Loc,
"invalid operand type for instruction");
8518bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8519 LocTy CallLoc = Lex.getLoc();
8520 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8521 std::vector<unsigned> FwdRefAttrGrps;
8524 Type *RetType =
nullptr;
8531 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8532 parseType(RetType, RetTypeLoc,
true ) ||
8533 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8534 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8536 parseOptionalOperandBundles(BundleList, PFS) ||
8538 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8543 SmallVector<BasicBlock *, 16> IndirectDests;
8547 if (parseTypeAndBasicBlock(DestBB, PFS))
8552 if (parseTypeAndBasicBlock(DestBB, PFS))
8558 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8565 if (resolveFunctionType(RetType, ArgList, Ty))
8566 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8577 SmallVector<Value *, 8>
Args;
8584 for (
const ParamInfo &Arg : ArgList) {
8585 Type *ExpectedTy =
nullptr;
8588 }
else if (!Ty->isVarArg()) {
8589 return error(Arg.Loc,
"too many arguments specified");
8592 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8593 return error(Arg.Loc,
"argument is not of expected type '" +
8595 Args.push_back(Arg.V);
8600 return error(CallLoc,
"not enough parameters specified for call");
8612 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8626bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8627 unsigned Opc,
bool IsFP) {
8629 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8630 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8638 return error(Loc,
"invalid operand type for instruction");
8646bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8649 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8650 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8656 "instruction requires integer or integer vector operands");
8665bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8671 if (parseCmpPredicate(Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8672 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8676 if (
Opc == Instruction::FCmp) {
8678 return error(Loc,
"fcmp requires floating point operands");
8681 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8684 return error(Loc,
"icmp requires integer operands");
8696bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8700 Type *DestTy =
nullptr;
8701 if (parseTypeAndValue(
Op, Loc, PFS) ||
8702 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8707 return error(Loc,
"invalid cast opcode for cast from '" +
8716bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8718 Value *Op0, *Op1, *Op2;
8719 if (parseTypeAndValue(Op0, Loc, PFS) ||
8720 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8721 parseTypeAndValue(Op1, PFS) ||
8722 parseToken(
lltok::comma,
"expected ',' after select value") ||
8723 parseTypeAndValue(Op2, PFS))
8727 return error(Loc, Reason);
8735bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8737 Type *EltTy =
nullptr;
8739 if (parseTypeAndValue(
Op, PFS) ||
8740 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8741 parseType(EltTy, TypeLoc))
8745 return error(TypeLoc,
"va_arg requires operand with first class type");
8747 Inst =
new VAArgInst(
Op, EltTy);
8753bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8756 if (parseTypeAndValue(Op0, Loc, PFS) ||
8757 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8758 parseTypeAndValue(Op1, PFS))
8762 return error(Loc,
"invalid extractelement operands");
8770bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8772 Value *Op0, *Op1, *Op2;
8773 if (parseTypeAndValue(Op0, Loc, PFS) ||
8774 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8775 parseTypeAndValue(Op1, PFS) ||
8776 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8777 parseTypeAndValue(Op2, PFS))
8781 return error(Loc,
"invalid insertelement operands");
8789bool LLParser::parseBitExtract(Instruction *&Inst, PerFunctionState &PFS) {
8793 if (parseType(Ty, Loc) ||
8794 parseToken(
lltok::comma,
"expected ',' after bitextract type") ||
8795 parseTypeAndValue(Op0, Loc, PFS) ||
8796 parseToken(
lltok::comma,
"expected ',' after bitextract source value") ||
8797 parseTypeAndValue(Op1, PFS))
8801 return error(Loc, Reason);
8809bool LLParser::parseBitInsert(Instruction *&Inst, PerFunctionState &PFS) {
8811 Value *Op0, *Op1, *Op2;
8812 if (parseTypeAndValue(Op0, Loc, PFS) ||
8813 parseToken(
lltok::comma,
"expected ',' after bitinsert source value") ||
8814 parseTypeAndValue(Op1, PFS) ||
8815 parseToken(
lltok::comma,
"expected ',' after bitinsert insert value") ||
8816 parseTypeAndValue(Op2, PFS))
8820 return error(Loc, Reason);
8828bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8830 Value *Op0, *Op1, *Op2;
8831 if (parseTypeAndValue(Op0, Loc, PFS) ||
8832 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
8833 parseTypeAndValue(Op1, PFS) ||
8834 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
8835 parseTypeAndValue(Op2, PFS))
8839 return error(Loc,
"invalid shufflevector operands");
8841 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
8847int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8851 if (parseType(Ty, TypeLoc))
8855 return error(TypeLoc,
"phi node must have first class type");
8858 bool AteExtraComma =
false;
8870 AteExtraComma =
true;
8874 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
8875 parseValue(Ty, Op0, PFS) ||
8876 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8885 for (
const auto &[Val, BB] : PHIVals)
8888 return AteExtraComma ? InstExtraComma : InstNormal;
8897bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8900 if (parseType(Ty, TyLoc))
8913 return tokError(
"expected 'catch' or 'filter' clause type");
8917 if (parseTypeAndValue(V, VLoc, PFS))
8924 return error(VLoc,
"'catch' clause has an invalid type");
8927 return error(VLoc,
"'filter' clause has an invalid type");
8932 return error(VLoc,
"clause argument must be a constant");
8936 Inst = LP.release();
8942bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8945 if (parseTypeAndValue(
Op, Loc, PFS))
8948 Inst =
new FreezeInst(
Op);
8961bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8963 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8964 std::vector<unsigned> FwdRefAttrGrps;
8966 unsigned CallAddrSpace;
8968 Type *RetType =
nullptr;
8973 LocTy CallLoc = Lex.getLoc();
8977 "expected 'tail call', 'musttail call', or 'notail call'"))
8980 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8982 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8983 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8984 parseType(RetType, RetTypeLoc,
true ) ||
8985 parseValID(CalleeID, &PFS) ||
8987 PFS.getFunction().isVarArg()) ||
8988 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
8989 parseOptionalOperandBundles(BundleList, PFS))
8996 if (resolveFunctionType(RetType, ArgList, Ty))
8997 return error(RetTypeLoc,
"Invalid result type for LLVM function");
9003 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
9010 SmallVector<Value*, 8>
Args;
9016 for (
const ParamInfo &Arg : ArgList) {
9017 Type *ExpectedTy =
nullptr;
9020 }
else if (!Ty->isVarArg()) {
9021 return error(Arg.Loc,
"too many arguments specified");
9024 if (ExpectedTy && ExpectedTy != Arg.V->getType())
9025 return error(Arg.Loc,
"argument is not of expected type '" +
9027 Args.push_back(Arg.V);
9028 Attrs.push_back(Arg.Attrs);
9032 return error(CallLoc,
"not enough parameters specified for call");
9045 return error(CallLoc,
"fast-math-flags specified for call without "
9046 "floating-point scalar or vector return type");
9053 if (SeenNewDbgInfoFormat) {
9055 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
9056 "using non-intrinsic debug info");
9058 SeenOldDbgInfoFormat =
true;
9061 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
9073int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
9075 LocTy SizeLoc, TyLoc, ASLoc;
9077 unsigned AddrSpace = 0;
9080 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
9081 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
9083 if (parseType(Ty, TyLoc))
9087 return error(TyLoc,
"invalid type for alloca");
9089 bool AteExtraComma =
false;
9091 if (Lex.getKind() == lltok::kw_align) {
9092 if (parseOptionalAlignment(Alignment))
9094 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9097 ASLoc = Lex.getLoc();
9098 if (parseOptionalAddrSpace(AddrSpace))
9101 AteExtraComma =
true;
9103 if (parseTypeAndValue(
Size, SizeLoc, PFS))
9106 if (Lex.getKind() == lltok::kw_align) {
9107 if (parseOptionalAlignment(Alignment))
9109 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9112 ASLoc = Lex.getLoc();
9113 if (parseOptionalAddrSpace(AddrSpace))
9116 AteExtraComma =
true;
9122 if (
Size && !
Size->getType()->isIntegerTy())
9123 return error(SizeLoc,
"element count must have integer type");
9125 if (!Alignment && !Ty->
isSized())
9126 return error(TyLoc,
"Cannot allocate unsized type");
9128 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
9129 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
9133 return AteExtraComma ? InstExtraComma : InstNormal;
9140int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
9143 bool AteExtraComma =
false;
9153 bool isVolatile =
false;
9159 bool IsElementwise =
false;
9161 IsElementwise =
true;
9166 LocTy ExplicitTypeLoc = Lex.getLoc();
9167 if (parseType(Ty) ||
9168 parseToken(
lltok::comma,
"expected comma after load's type") ||
9169 parseTypeAndValue(Val, Loc, PFS) ||
9170 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9171 parseOptionalCommaAlign(Alignment, AteExtraComma))
9175 return error(Loc,
"load operand must be a pointer to a first class type");
9177 if (IsElementwise && !isAtomic)
9178 return error(Loc,
"elementwise load must be atomic");
9181 return error(ExplicitTypeLoc,
9182 "atomic elementwise load operand must have fixed vector type");
9184 if (isAtomic && !Alignment)
9185 return error(Loc,
"atomic load must have explicit non-zero alignment");
9189 return error(Loc,
"atomic load cannot use Release ordering");
9192 "atomic elementwise load cannot be sequentially consistent");
9194 if (!Alignment && !Ty->
isSized())
9195 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
9197 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9198 Inst =
new LoadInst(Ty, Val,
"",
9200 SSID, IsElementwise},
9202 return AteExtraComma ? InstExtraComma : InstNormal;
9210int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9214 bool AteExtraComma =
false;
9224 bool isVolatile =
false;
9230 bool IsElementwise =
false;
9232 IsElementwise =
true;
9236 if (parseTypeAndValue(Val, Loc, PFS) ||
9237 parseToken(
lltok::comma,
"expected ',' after store operand") ||
9238 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9239 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9240 parseOptionalCommaAlign(Alignment, AteExtraComma))
9244 return error(PtrLoc,
"store operand must be a pointer");
9246 return error(Loc,
"store operand must be a first class value");
9247 if (isAtomic && !Alignment)
9248 return error(Loc,
"atomic store must have explicit non-zero alignment");
9251 return error(Loc,
"atomic store cannot use Acquire ordering");
9253 if (IsElementwise && !isAtomic)
9254 return error(Loc,
"elementwise store must be atomic");
9258 Loc,
"atomic elementwise store operand must have fixed vector type");
9262 "atomic elementwise store cannot be sequentially consistent");
9265 return error(Loc,
"storing unsized types is not allowed");
9269 Inst =
new StoreInst(Val, Ptr,
9271 SSID, IsElementwise},
9273 return AteExtraComma ? InstExtraComma : InstNormal;
9280int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9282 bool AteExtraComma =
false;
9286 bool isVolatile =
false;
9287 bool isWeak =
false;
9296 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9297 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
9298 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9299 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
9300 parseTypeAndValue(New, NewLoc, PFS) ||
9301 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
9302 parseOrdering(FailureOrdering) ||
9303 parseOptionalCommaAlign(Alignment, AteExtraComma))
9307 return tokError(
"invalid cmpxchg success ordering");
9309 return tokError(
"invalid cmpxchg failure ordering");
9311 return error(PtrLoc,
"cmpxchg operand must be a pointer");
9312 if (
Cmp->getType() !=
New->getType())
9313 return error(NewLoc,
"compare value and new value type do not match");
9314 if (!
New->getType()->isFirstClassType())
9315 return error(NewLoc,
"cmpxchg operand must be a first class value");
9317 const Align DefaultAlignment(
9318 PFS.getFunction().getDataLayout().getTypeStoreSize(
9321 AtomicCmpXchgInst *CXI =
9322 new AtomicCmpXchgInst(Ptr, Cmp, New,
Alignment.value_or(DefaultAlignment),
9323 SuccessOrdering, FailureOrdering, SSID);
9328 return AteExtraComma ? InstExtraComma : InstNormal;
9335int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9337 bool AteExtraComma =
false;
9341 bool IsElementwise =
false;
9349 IsElementwise =
true;
9351 switch (Lex.getKind()) {
9353 return tokError(
"expected binary operation in atomicrmw");
9412 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9413 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9414 parseTypeAndValue(Val, ValLoc, PFS) ||
9415 parseScopeAndOrdering(
true , SSID, Ordering) ||
9416 parseOptionalCommaAlign(Alignment, AteExtraComma))
9420 return tokError(
"atomicrmw cannot be unordered");
9422 return tokError(
"atomicrmw elementwise cannot be sequentially consistent");
9424 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9426 return error(ValLoc,
"atomicrmw operand may not be scalable");
9429 if (IsElementwise) {
9431 return error(ValLoc,
9432 "atomicrmw elementwise operand must be a fixed vector type");
9441 " operand must be an integer type, a floating-point type, a "
9442 "pointer type, or a fixed vector of any of these types");
9446 return error(ValLoc,
"atomicrmw " +
9448 " operand must be a floating point or fixed "
9449 "vector of floating point type");
9456 " operand must be an integer or fixed vector of integer type");
9461 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9463 return error(ValLoc,
9464 "atomicrmw operand must have a power-of-two byte size");
9465 const Align DefaultAlignment(
9466 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->
getType()));
9467 AtomicRMWInst *RMWI =
new AtomicRMWInst(
Operation, Ptr, Val,
9469 Ordering, SSID, IsElementwise);
9472 return AteExtraComma ? InstExtraComma : InstNormal;
9477int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9480 if (parseScopeAndOrdering(
true , SSID, Ordering))
9484 return tokError(
"fence cannot be unordered");
9486 return tokError(
"fence cannot be monotonic");
9488 Inst =
new FenceInst(Context, Ordering, SSID);
9494int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9495 Value *Ptr =
nullptr;
9496 Value *Val =
nullptr;
9512 if (parseType(Ty) ||
9513 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9514 parseTypeAndValue(Ptr, Loc, PFS))
9519 if (!BasePointerType)
9520 return error(Loc,
"base of getelementptr must be a pointer");
9522 SmallVector<Value*, 16> Indices;
9523 bool AteExtraComma =
false;
9526 ElementCount GEPWidth =
BaseType->isVectorTy()
9532 AteExtraComma =
true;
9535 if (parseTypeAndValue(Val, EltLoc, PFS))
9538 return error(EltLoc,
"getelementptr index must be an integer");
9541 ElementCount ValNumEl = ValVTy->getElementCount();
9545 "getelementptr vector index has a wrong number of elements");
9546 GEPWidth = ValNumEl;
9552 return error(Loc,
"base element of getelementptr must be sized");
9556 return error(Loc,
"getelementptr cannot target structure that contains "
9557 "scalable vector type");
9560 return error(Loc,
"invalid getelementptr indices");
9563 GEP->setNoWrapFlags(NW);
9564 return AteExtraComma ? InstExtraComma : InstNormal;
9569int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9571 SmallVector<unsigned, 4> Indices;
9573 if (parseTypeAndValue(Val, Loc, PFS) ||
9574 parseIndexList(Indices, AteExtraComma))
9578 return error(Loc,
"extractvalue operand must be aggregate type");
9581 return error(Loc,
"invalid indices for extractvalue");
9583 return AteExtraComma ? InstExtraComma : InstNormal;
9588int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9590 SmallVector<unsigned, 4> Indices;
9592 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9593 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9594 parseTypeAndValue(Val1, Loc1, PFS) ||
9595 parseIndexList(Indices, AteExtraComma))
9599 return error(Loc0,
"insertvalue operand must be aggregate type");
9603 return error(Loc0,
"invalid indices for insertvalue");
9604 if (IndexedType != Val1->
getType())
9605 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9609 return AteExtraComma ? InstExtraComma : InstNormal;
9620bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9635 if (parseMetadata(MD,
nullptr))
9640 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9646bool LLParser::sortUseListOrder(
Value *V, ArrayRef<unsigned> Indexes,
9648 if (!
V->hasUseList())
9651 return error(Loc,
"value has no uses");
9653 unsigned NumUses = 0;
9654 SmallDenseMap<const Use *, unsigned, 16> Order;
9655 for (
const Use &U :
V->uses()) {
9656 if (++NumUses > Indexes.
size())
9658 Order[&
U] = Indexes[NumUses - 1];
9661 return error(Loc,
"value only has one use");
9662 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9664 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9666 V->sortUseList([&](
const Use &L,
const Use &R) {
9674bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9675 SMLoc Loc = Lex.getLoc();
9679 return tokError(
"expected non-empty list of uselistorder indexes");
9686 bool IsOrdered =
true;
9687 assert(Indexes.
empty() &&
"Expected empty order vector");
9690 if (parseUInt32(Index))
9695 Max = std::max(Max, Index);
9696 IsOrdered &= Index == Indexes.
size();
9704 if (Indexes.
size() < 2)
9705 return error(Loc,
"expected >= 2 uselistorder indexes");
9708 "expected distinct uselistorder indexes in range [0, size)");
9710 return error(Loc,
"expected uselistorder indexes to change the order");
9717bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9718 SMLoc Loc = Lex.getLoc();
9723 SmallVector<unsigned, 16> Indexes;
9724 if (parseTypeAndValue(V, PFS) ||
9725 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9726 parseUseListOrderIndexes(Indexes))
9729 return sortUseListOrder(V, Indexes, Loc);
9735bool LLParser::parseModuleEntry(
unsigned ID) {
9744 parseStringConstant(Path) ||
9752 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9753 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9754 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9755 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9756 parseUInt32(Hash[4]))
9763 auto ModuleEntry = Index->addModule(Path, Hash);
9764 ModuleIdMap[
ID] = ModuleEntry->first();
9771bool LLParser::parseTypeIdEntry(
unsigned ID) {
9780 parseStringConstant(Name))
9783 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9785 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9790 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9791 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9792 for (
auto TIDRef : FwdRefTIDs->second) {
9794 "Forward referenced type id GUID expected to be 0");
9797 ForwardRefTypeIds.erase(FwdRefTIDs);
9805bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9809 parseTypeTestResolution(TIS.
TTRes))
9814 if (parseOptionalWpdResolutions(TIS.
WPDRes))
9831bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
9840 parseStringConstant(Name))
9844 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9851 IdToIndexMapType IdToIndexMap;
9864 if (parseGVReference(VI, GVId))
9871 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
9872 TI.push_back({
Offset, VI});
9880 for (
auto I : IdToIndexMap) {
9881 auto &Infos = ForwardRefValueInfos[
I.first];
9882 for (
auto P :
I.second) {
9884 "Forward referenced ValueInfo expected to be empty");
9885 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
9895 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9896 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9897 for (
auto TIDRef : FwdRefTIDs->second) {
9899 "Forward referenced type id GUID expected to be 0");
9902 ForwardRefTypeIds.erase(FwdRefTIDs);
9914bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9922 switch (Lex.getKind()) {
9942 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
9954 switch (Lex.getKind()) {
9969 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
9982 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
9995bool LLParser::parseOptionalWpdResolutions(
9996 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
10004 WholeProgramDevirtResolution WPDRes;
10008 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
10011 WPDResMap[
Offset] = WPDRes;
10028bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
10036 switch (Lex.getKind()) {
10047 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
10053 switch (Lex.getKind()) {
10061 if (parseOptionalResByArg(WPDRes.
ResByArg))
10065 return error(Lex.getLoc(),
10066 "expected optional WholeProgramDevirtResolution field");
10083bool LLParser::parseOptionalResByArg(
10084 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
10092 std::vector<uint64_t>
Args;
10093 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
10101 WholeProgramDevirtResolution::ByArg ByArg;
10102 switch (Lex.getKind()) {
10116 return error(Lex.getLoc(),
10117 "unexpected WholeProgramDevirtResolution::ByArg kind");
10123 switch (Lex.getKind()) {
10127 parseUInt64(ByArg.
Info))
10133 parseUInt32(ByArg.
Byte))
10139 parseUInt32(ByArg.
Bit))
10143 return error(Lex.getLoc(),
10144 "expected optional whole program devirt field");
10151 ResByArg[
Args] = ByArg;
10162bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10170 if (parseUInt64(Val))
10172 Args.push_back(Val);
10196bool LLParser::addGlobalValueToIndex(
10198 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
10203 VI = Index->getOrInsertValueInfo(GUID);
10207 auto *GV = M->getNamedValue(Name);
10209 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
10215 VI = Index->getOrInsertValueInfo(GV, GUID);
10219 "Need a source_filename to compute GUID for local");
10222 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10227 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10228 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10229 for (
auto VIRef : FwdRefVIs->second) {
10231 "Forward referenced ValueInfo expected to be empty");
10234 ForwardRefValueInfos.erase(FwdRefVIs);
10238 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10239 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10240 for (
auto AliaseeRef : FwdRefAliasees->second) {
10241 assert(!AliaseeRef.first->hasAliasee() &&
10242 "Forward referencing alias already has aliasee");
10243 assert(Summary &&
"Aliasee must be a definition");
10244 AliaseeRef.first->setAliasee(VI,
Summary.get());
10246 ForwardRefAliasees.erase(FwdRefAliasees);
10251 Index->addGlobalValueSummary(VI, std::move(Summary));
10254 if (ID == NumberedValueInfos.size())
10255 NumberedValueInfos.push_back(VI);
10258 if (ID > NumberedValueInfos.size())
10259 NumberedValueInfos.resize(ID + 1);
10260 NumberedValueInfos[
ID] =
VI;
10268bool LLParser::parseSummaryIndexFlags() {
10275 if (parseUInt64(Flags))
10278 Index->setFlags(Flags);
10284bool LLParser::parseBlockCount() {
10291 if (parseUInt64(BlockCount))
10294 Index->setBlockCount(BlockCount);
10302bool LLParser::parseGVEntry(
unsigned ID) {
10310 LocTy Loc = Lex.getLoc();
10313 switch (Lex.getKind()) {
10317 parseStringConstant(Name))
10323 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
10327 return error(Lex.getLoc(),
"expected name or guid tag");
10350 switch (Lex.getKind()) {
10352 if (parseFunctionSummary(Name, GUID, ID))
10356 if (parseVariableSummary(Name, GUID, ID))
10360 if (parseAliasSummary(Name, GUID, ID))
10364 return error(Lex.getLoc(),
"expected summary type");
10382 LocTy Loc = Lex.getLoc();
10386 StringRef ModulePath;
10387 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10390 false,
false,
false,
10392 unsigned InstCount;
10394 FunctionSummary::TypeIdInfo TypeIdInfo;
10395 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10397 std::vector<CallsiteInfo> Callsites;
10398 std::vector<AllocInfo> Allocs;
10400 FunctionSummary::FFlags FFlags = {};
10403 parseModuleReference(ModulePath) ||
10404 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10407 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10412 switch (Lex.getKind()) {
10414 if (parseOptionalFFlags(FFlags))
10418 if (parseOptionalCalls(Calls))
10422 if (parseOptionalTypeIdInfo(TypeIdInfo))
10426 if (parseOptionalRefs(Refs))
10430 if (parseOptionalParamAccesses(ParamAccesses))
10434 if (parseOptionalAllocs(Allocs))
10438 if (parseOptionalCallsites(Callsites))
10442 return error(Lex.getLoc(),
"expected optional function summary field");
10449 auto FS = std::make_unique<FunctionSummary>(
10450 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10456 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10458 FS->setModulePath(ModulePath);
10460 return addGlobalValueToIndex(Name, GUID,
10462 std::move(FS), Loc);
10470 LocTy Loc = Lex.getLoc();
10474 StringRef ModulePath;
10475 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10478 false,
false,
false,
10480 GlobalVarSummary::GVarFlags GVarFlags(
false,
10488 parseModuleReference(ModulePath) ||
10489 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10491 parseGVarFlags(GVarFlags))
10496 switch (Lex.getKind()) {
10498 if (parseOptionalVTableFuncs(VTableFuncs))
10502 if (parseOptionalRefs(Refs))
10506 return error(Lex.getLoc(),
"expected optional variable summary field");
10514 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10516 GS->setModulePath(ModulePath);
10517 GS->setVTableFuncs(std::move(VTableFuncs));
10519 return addGlobalValueToIndex(Name, GUID,
10521 std::move(GS), Loc);
10530 LocTy Loc = Lex.getLoc();
10533 StringRef ModulePath;
10534 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10537 false,
false,
false,
10541 parseModuleReference(ModulePath) ||
10542 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10548 ValueInfo AliaseeVI;
10550 auto AS = std::make_unique<AliasSummary>(GVFlags);
10551 AS->setModulePath(ModulePath);
10554 if (parseGVReference(AliaseeVI, GVId))
10559 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10561 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10562 assert(Summary &&
"Aliasee must be a definition");
10563 AS->setAliasee(AliaseeVI, Summary);
10570 return addGlobalValueToIndex(Name, GUID,
10572 std::move(AS), Loc);
10577bool LLParser::parseFlag(
unsigned &Val) {
10578 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10579 return tokError(
"expected integer");
10580 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10596bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10600 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10606 switch (Lex.getKind()) {
10609 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10615 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10621 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10627 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10633 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10639 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10645 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10651 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10657 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10663 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10668 return error(Lex.getLoc(),
"expected function flag type");
10672 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10683bool LLParser::parseOptionalCalls(
10684 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10688 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10692 IdToIndexMapType IdToIndexMap;
10701 LocTy Loc = Lex.getLoc();
10703 if (parseGVReference(VI, GVId))
10707 unsigned RelBF = 0;
10708 unsigned HasTailCall =
false;
10712 switch (Lex.getKind()) {
10715 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10721 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10726 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10730 return error(Lex.getLoc(),
"expected hotness, relbf, or tail");
10737 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10747 for (
auto I : IdToIndexMap) {
10748 auto &Infos = ForwardRefValueInfos[
I.first];
10749 for (
auto P :
I.second) {
10751 "Forward referenced ValueInfo expected to be empty");
10752 Infos.emplace_back(&Calls[
P.first].first,
P.second);
10765 switch (Lex.getKind()) {
10769 case lltok::kw_cold:
10775 case lltok::kw_hot:
10782 return error(Lex.getLoc(),
"invalid call edge hotness");
10791bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
10795 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
10799 IdToIndexMapType IdToIndexMap;
10803 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
10808 LocTy Loc = Lex.getLoc();
10810 if (parseGVReference(VI, GVId))
10823 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10824 VTableFuncs.push_back({
VI,
Offset});
10826 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
10832 for (
auto I : IdToIndexMap) {
10833 auto &Infos = ForwardRefValueInfos[
I.first];
10834 for (
auto P :
I.second) {
10836 "Forward referenced ValueInfo expected to be empty");
10837 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
10841 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
10848bool LLParser::parseParamNo(
uint64_t &ParamNo) {
10850 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
10856bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
10859 auto ParseAPSInt = [&](
APSInt &Val) {
10861 return tokError(
"expected integer");
10862 Val = Lex.getAPSIntVal();
10864 Val.setIsSigned(
true);
10886bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
10887 IdLocListType &IdLocList) {
10895 LocTy Loc = Lex.getLoc();
10896 if (parseGVReference(VI, GVId))
10900 IdLocList.emplace_back(GVId, Loc);
10903 parseParamNo(
Call.ParamNo) ||
10905 parseParamAccessOffset(
Call.Offsets))
10917bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10918 IdLocListType &IdLocList) {
10920 parseParamNo(
Param.ParamNo) ||
10922 parseParamAccessOffset(
Param.Use))
10931 FunctionSummary::ParamAccess::Call
Call;
10932 if (parseParamAccessCall(
Call, IdLocList))
10949bool LLParser::parseOptionalParamAccesses(
10950 std::vector<FunctionSummary::ParamAccess> &Params) {
10958 IdLocListType VContexts;
10959 size_t CallsNum = 0;
10961 FunctionSummary::ParamAccess ParamAccess;
10962 if (parseParamAccess(ParamAccess, VContexts))
10964 CallsNum += ParamAccess.
Calls.size();
10965 assert(VContexts.size() == CallsNum);
10967 Params.emplace_back(std::move(ParamAccess));
10975 IdLocListType::const_iterator ItContext = VContexts.begin();
10976 for (
auto &PA : Params) {
10977 for (
auto &
C : PA.Calls) {
10979 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
10980 ItContext->second);
10984 assert(ItContext == VContexts.end());
10991bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10995 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
10999 struct ValueContext {
11004 std::vector<ValueContext> VContexts;
11008 VC.Loc = Lex.getLoc();
11009 if (parseGVReference(
VC.VI,
VC.GVId))
11011 VContexts.push_back(VC);
11017 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
11018 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
11021 IdToIndexMapType IdToIndexMap;
11022 for (
auto &VC : VContexts) {
11027 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
11033 for (
auto I : IdToIndexMap) {
11034 auto &Infos = ForwardRefValueInfos[
I.first];
11035 for (
auto P :
I.second) {
11037 "Forward referenced ValueInfo expected to be empty");
11038 Infos.emplace_back(&Refs[
P.first],
P.second);
11052bool LLParser::parseOptionalTypeIdInfo(
11053 FunctionSummary::TypeIdInfo &TypeIdInfo) {
11062 switch (Lex.getKind()) {
11064 if (parseTypeTests(TypeIdInfo.
TypeTests))
11088 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
11092 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11101bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
11109 IdToIndexMapType IdToIndexMap;
11113 unsigned ID = Lex.getUIntVal();
11114 LocTy Loc = Lex.getLoc();
11118 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
11120 }
else if (parseUInt64(GUID))
11122 TypeTests.push_back(GUID);
11127 for (
auto I : IdToIndexMap) {
11128 auto &Ids = ForwardRefTypeIds[
I.first];
11129 for (
auto P :
I.second) {
11130 assert(TypeTests[
P.first] == 0 &&
11131 "Forward referenced type id GUID expected to be 0");
11132 Ids.emplace_back(&TypeTests[
P.first],
P.second);
11136 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11144bool LLParser::parseVFuncIdList(
11145 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
11146 assert(Lex.getKind() == Kind);
11153 IdToIndexMapType IdToIndexMap;
11155 FunctionSummary::VFuncId VFuncId;
11156 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11158 VFuncIdList.push_back(VFuncId);
11166 for (
auto I : IdToIndexMap) {
11167 auto &Ids = ForwardRefTypeIds[
I.first];
11168 for (
auto P :
I.second) {
11169 assert(VFuncIdList[
P.first].GUID == 0 &&
11170 "Forward referenced type id GUID expected to be 0");
11171 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
11180bool LLParser::parseConstVCallList(
11182 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11183 assert(Lex.getKind() == Kind);
11190 IdToIndexMapType IdToIndexMap;
11192 FunctionSummary::ConstVCall ConstVCall;
11193 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11195 ConstVCallList.push_back(ConstVCall);
11203 for (
auto I : IdToIndexMap) {
11204 auto &Ids = ForwardRefTypeIds[
I.first];
11205 for (
auto P :
I.second) {
11206 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
11207 "Forward referenced type id GUID expected to be 0");
11208 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
11217bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11218 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11220 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
11224 if (parseArgs(ConstVCall.
Args))
11236bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11237 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11247 unsigned ID = Lex.getUIntVal();
11248 LocTy Loc = Lex.getLoc();
11252 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
11254 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
11256 parseUInt64(VFuncId.
GUID))
11262 parseUInt64(VFuncId.
Offset) ||
11274bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11284 switch (Lex.getKind()) {
11291 assert(HasLinkage &&
"Linkage not optional in summary entry");
11298 parseOptionalVisibility(Flag);
11303 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11309 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11315 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11321 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11330 if (parseOptionalImportType(Lex.getKind(), IK))
11332 GVFlags.
ImportType =
static_cast<unsigned>(IK);
11337 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11342 return error(Lex.getLoc(),
"expected gv flag type");
11356bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11364 auto ParseRest = [
this](
unsigned int &Val) {
11368 return parseFlag(Val);
11373 switch (Lex.getKind()) {
11374 case lltok::kw_readonly:
11375 if (ParseRest(Flag))
11379 case lltok::kw_writeonly:
11380 if (ParseRest(Flag))
11385 if (ParseRest(Flag))
11390 if (ParseRest(Flag))
11395 return error(Lex.getLoc(),
"expected gvar flag type");
11403bool LLParser::parseModuleReference(StringRef &ModulePath) {
11410 unsigned ModuleID = Lex.getUIntVal();
11411 auto I = ModuleIdMap.find(ModuleID);
11413 assert(
I != ModuleIdMap.end());
11414 ModulePath =
I->second;
11420bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11423 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11427 GVId = Lex.getUIntVal();
11429 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11431 VI = NumberedValueInfos[GVId];
11448bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11452 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11464 SmallVector<uint8_t> Versions;
11467 if (parseAllocType(V))
11472 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11476 std::vector<MIBInfo> MIBs;
11477 if (parseMemProfs(MIBs))
11480 Allocs.push_back({Versions, MIBs});
11497bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11501 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11507 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11516 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11522 SmallVector<unsigned> StackIdIndices;
11527 if (parseUInt64(StackId))
11529 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11550bool LLParser::parseAllocType(uint8_t &
AllocType) {
11551 switch (Lex.getKind()) {
11558 case lltok::kw_cold:
11561 case lltok::kw_hot:
11565 return error(Lex.getLoc(),
"invalid alloc type");
11578bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11582 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11586 IdToIndexMapType IdToIndexMap;
11589 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11596 LocTy Loc = Lex.getLoc();
11598 if (parseGVReference(VI, GVId))
11602 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11608 SmallVector<unsigned> Clones;
11611 if (parseUInt32(V))
11617 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11623 SmallVector<unsigned> StackIdIndices;
11628 if (parseUInt64(StackId))
11630 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11641 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11642 Callsites.push_back({
VI, Clones, StackIdIndices});
11650 for (
auto I : IdToIndexMap) {
11651 auto &Infos = ForwardRefValueInfos[
I.first];
11652 for (
auto P :
I.second) {
11654 "Forward referenced ValueInfo expected to be empty");
11655 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11659 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.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
@ X86_StdCall
stdcall is mostly used by the Win32 API.
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
constexpr bool isAtomic(const T &...O)
constexpr bool isPacked(const T &...O)
@ System
Synchronized with respect to all concurrently executing threads.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_LLVM_LANG_DIALECT_max
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
@ kw_aarch64_sme_preservemost_from_x1
@ kw_no_sanitize_hwaddress
@ kw_cheriot_librarycallcc
@ kw_cheriot_compartmentcalleecc
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_cheriot_compartmentcallcc
@ kw_amdgpu_gfx_whole_wave
@ kw_typeTestAssumeConstVCalls
@ kw_typeidCompatibleVTable
@ kw_typeCheckedLoadVCalls
@ kw_inaccessiblemem_or_argmemonly
@ kw_externally_initialized
@ kw_sanitize_address_dyninit
@ kw_amdgpu_cs_chain_preserve
@ kw_available_externally
@ kw_typeTestAssumeVCalls
@ kw_aarch64_sme_preservemost_from_x0
@ kw_dso_local_equivalent
@ kw_aarch64_sme_preservemost_from_x2
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
static void assign(DXContainerYAML::SourceInfo::SectionHeader &Dst, const dxbc::SourceInfo::SectionHeader &Src)
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
@ Async
"Asynchronous" unwind tables (instr precise)
@ Sync
"Synchronous" unwind tables
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
CaptureComponents
Components of the pointer that may be captured.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
IRMemLocation
The locations at which a function might access memory.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
bool capturesNothing(CaptureComponents CC)
@ 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.