66 "Allow incomplete IR on a best effort basis (references to unknown "
67 "metadata will be dropped)"));
82 const char *Boundary = BoundaryLoc.
getPointer();
83 const char *BlockCommentStart =
nullptr;
84 bool InLineComment =
false;
86 for (
const char *Ptr = Begin; Ptr <
End;) {
87 if (BlockCommentStart) {
88 if (Ptr + 1 <
End && Ptr[0] ==
'*' && Ptr[1] ==
'/') {
90 if (BlockCommentStart < Boundary && Ptr > Boundary)
92 BlockCommentStart =
nullptr;
100 if (*Ptr ==
'\n' || *Ptr ==
'\r')
101 InLineComment =
false;
107 InLineComment =
true;
111 if (Ptr + 1 <
End && Ptr[0] ==
'/' && Ptr[1] ==
'*') {
112 BlockCommentStart = Ptr;
119 return BlockCommentStart && BlockCommentStart < Boundary && End > Boundary;
128 if (Context.shouldDiscardValueNames())
131 "Can't read textual IR with a Context that discards named Values");
134 if (parseTargetDefinitions(DataLayoutCallback))
139 validateEndOfIndex();
144 restoreParsingState(Slots);
148 if (parseType(Ty) || parseConstantValue(Ty,
C))
151 return error(Lex.getLoc(),
"expected end of string");
157 restoreParsingState(Slots);
161 SMLoc Start = Lex.getLoc();
166 Read =
End.getPointer() - Start.getPointer();
173 restoreParsingState(Slots);
177 SMLoc Start = Lex.getLoc();
179 bool Status = parseDIExpressionBody(Result,
false);
181 Read =
End.getPointer() - Start.getPointer();
188 restoreParsingState(&Slots);
192 if (Lex.getLoc().getPointer() >=
End.getPointer())
193 return error(
End,
"expected end of metadata definition");
195 return tokError(
"expected a metadata definition");
196 if (parseStandaloneMetadata())
198 if (Lex.getPrevTokEndLoc().getPointer() >
End.getPointer() ||
200 Lex.getLoc().getPointer() <
End.getPointer()) ||
202 return error(
End,
"expected end of metadata definition");
206 return tokError(
"expected end of metadata definitions");
208 if (!ForwardRefMDNodes.empty())
209 return error(ForwardRefMDNodes.begin()->second.second,
210 "use of undefined metadata '!" +
211 Twine(ForwardRefMDNodes.begin()->first) +
"'");
213 for (
auto &[
_, MD] : NumberedMetadata)
214 if (MD && !MD->isResolved())
217 NewDistinctSPs.clear();
219 Slots.MetadataNodes = std::move(NumberedMetadata);
223void LLParser::restoreParsingState(
const SlotMapping *Slots) {
230 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
231 for (
const auto &
I : Slots->
Types)
232 NumberedTypes.insert(
233 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
239 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
246 if (MD->isTemporary())
250 assert(
II->use_empty() &&
"Cannot have uses");
251 II->eraseFromParent();
260void LLParser::dropUnknownMetadataReferences() {
261 auto Pred = [](
unsigned MDKind, MDNode *
Node) {
return Node->isTemporary(); };
263 F.eraseMetadataIf(
Pred);
265 I.eraseMetadataIf(
Pred);
272 for (GlobalVariable &GV : M->globals())
273 GV.eraseMetadataIf(
Pred);
276 [](
const auto &
E) {
return std::get<2>(
E)->isTemporary(); });
278 [](
const auto &
E) {
return std::get<2>(
E)->isTemporary(); });
280 for (
auto &[FLContext, TempScopes] : FLForwardRefScopes) {
282 [](
const auto &
E) {
return std::get<1>(
E)->isTemporary(); });
284 for (
auto &[FLContext, TempFLContexts] : FLForwardRefFLMDs) {
286 [](
const auto &
E) {
return std::get<1>(
E)->isTemporary(); });
292 if (
Info.first->getNumTemporaryUses() == 1) {
293 NumberedMetadata.erase(ID);
294 ForwardRefMDNodes.erase(ID);
307 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
308 "Mixed debug intrinsics/records seen without a parsing error?");
311 for (
const auto &RAG : ForwardRefAttrGroups) {
313 const std::vector<unsigned> &
Attrs = RAG.second;
314 AttrBuilder
B(Context);
316 for (
const auto &Attr : Attrs) {
317 auto R = NumberedAttrBuilders.find(Attr);
318 if (R != NumberedAttrBuilders.end())
323 AttributeList AS = Fn->getAttributes();
324 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
325 AS = AS.removeFnAttributes(Context);
331 if (MaybeAlign
A = FnAttrs.getAlignment()) {
332 Fn->setAlignment(*
A);
333 FnAttrs.removeAttribute(Attribute::Alignment);
336 AS = AS.addFnAttributes(Context, FnAttrs);
337 Fn->setAttributes(AS);
339 AttributeList AS = CI->getAttributes();
340 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
341 AS = AS.removeFnAttributes(Context);
343 AS = AS.addFnAttributes(Context, FnAttrs);
344 CI->setAttributes(AS);
346 AttributeList AS =
II->getAttributes();
347 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
348 AS = AS.removeFnAttributes(Context);
350 AS = AS.addFnAttributes(Context, FnAttrs);
351 II->setAttributes(AS);
353 AttributeList AS = CBI->getAttributes();
354 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
355 AS = AS.removeFnAttributes(Context);
357 AS = AS.addFnAttributes(Context, FnAttrs);
358 CBI->setAttributes(AS);
360 AttrBuilder
Attrs(M->getContext(), GV->getAttributes());
370 if (!ForwardRefBlockAddresses.empty())
371 return error(ForwardRefBlockAddresses.begin()->first.Loc,
372 "expected function name in blockaddress");
374 auto ResolveForwardRefDSOLocalEquivalents = [&](
const ValID &GVRef,
375 GlobalValue *FwdRef) {
376 GlobalValue *GV =
nullptr;
378 GV = M->getNamedValue(GVRef.
StrVal);
380 GV = NumberedVals.get(GVRef.
UIntVal);
385 "' referenced by dso_local_equivalent");
389 "expected a function, alias to function, or ifunc "
390 "in dso_local_equivalent");
393 FwdRef->replaceAllUsesWith(Equiv);
394 FwdRef->eraseFromParent();
401 for (
auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
402 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
405 for (
auto &Iter : ForwardRefDSOLocalEquivalentNames) {
406 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
409 ForwardRefDSOLocalEquivalentIDs.clear();
410 ForwardRefDSOLocalEquivalentNames.clear();
412 for (
const auto &NT : NumberedTypes)
413 if (
NT.second.second.isValid())
415 "use of undefined type '%" + Twine(
NT.first) +
"'");
417 for (
const auto &[Name, TypeInfo] : NamedTypes)
418 if (TypeInfo.second.isValid())
419 return error(TypeInfo.second,
420 "use of undefined type named '" + Name +
"'");
422 if (!ForwardRefComdats.empty())
423 return error(ForwardRefComdats.begin()->second,
424 "use of undefined comdat '$" +
425 ForwardRefComdats.begin()->first +
"'");
428 dropUnknownMetadataReferences();
430 if (!ForwardRefMDNodes.empty())
431 return error(ForwardRefMDNodes.begin()->second.second,
432 "use of undefined metadata '!" +
433 Twine(ForwardRefMDNodes.begin()->first) +
"'");
436 for (
auto [Loc, DR, MD] : PendingDbgRecords) {
440 return error(Loc,
"invalid debug location");
442 PendingDbgRecords.clear();
443 for (
auto [Loc,
I, MD] : PendingDbgInsts) {
447 return error(Loc,
"invalid !dbg metadata");
449 PendingDbgInsts.clear();
452 for (
auto &[FLContext, TempScopes] : FLForwardRefScopes)
453 for (
auto [ScopeIdx, TempScope] : TempScopes)
455 FLForwardRefScopes.clear();
456 for (
auto &[FLContext, TempFLContexts] : FLForwardRefFLMDs)
457 for (
auto [InlinedCallIdx, TempFLContext] : TempFLContexts)
458 FLContext->InlinedCalls[InlinedCallIdx].InlineeContext =
460 FLForwardRefFLMDs.clear();
474 if (!CB || !CB->isCallee(&U))
475 return error(
Info.second,
"intrinsic can only be used as callee");
477 std::string ErrorMsg;
478 raw_string_ostream ErrorOS(ErrorMsg);
492 return error(
Info.second,
"unknown intrinsic '" + Name +
"'");
503 Info.first->eraseFromParent();
504 ForwardRefVals.erase(Name);
513 auto GetCommonFunctionType = [](
Value *
V) -> FunctionType * {
514 FunctionType *FTy =
nullptr;
515 for (Use &U :
V->uses()) {
517 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
519 FTy = CB->getFunctionType();
527 Type *Ty = GetCommonFunctionType(
Info.first);
535 GV =
new GlobalVariable(*M, Ty,
false,
538 Info.first->replaceAllUsesWith(GV);
539 Info.first->eraseFromParent();
540 ForwardRefVals.erase(Name);
543 if (!ForwardRefVals.empty())
544 return error(ForwardRefVals.begin()->second.second,
545 "use of undefined value '@" + ForwardRefVals.begin()->first +
548 if (!ForwardRefValIDs.empty())
549 return error(ForwardRefValIDs.begin()->second.second,
550 "use of undefined value '@" +
551 Twine(ForwardRefValIDs.begin()->first) +
"'");
554 for (
auto &
N : NumberedMetadata) {
555 if (
N.second && !
N.second->isResolved())
556 N.second->resolveCycles();
560 NewDistinctSPs.clear();
582 Slots->GlobalValues = std::move(NumberedVals);
583 Slots->MetadataNodes = std::move(NumberedMetadata);
584 for (
const auto &
I : NamedTypes)
585 Slots->NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
586 for (
const auto &
I : NumberedTypes)
587 Slots->Types.insert(std::make_pair(
I.first,
I.second.first));
593bool LLParser::validateEndOfIndex() {
597 if (!ForwardRefValueInfos.empty())
598 return error(ForwardRefValueInfos.begin()->second.front().second,
599 "use of undefined summary '^" +
600 Twine(ForwardRefValueInfos.begin()->first) +
"'");
602 if (!ForwardRefAliasees.empty())
603 return error(ForwardRefAliasees.begin()->second.front().second,
604 "use of undefined summary '^" +
605 Twine(ForwardRefAliasees.begin()->first) +
"'");
607 if (!ForwardRefTypeIds.empty())
608 return error(ForwardRefTypeIds.begin()->second.front().second,
609 "use of undefined type id summary '^" +
610 Twine(ForwardRefTypeIds.begin()->first) +
"'");
624 std::string TentativeDLStr = M->getDataLayoutStr();
629 switch (Lex.getKind()) {
631 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
635 if (parseSourceFileName())
644 if (
auto LayoutOverride =
645 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
646 TentativeDLStr = *LayoutOverride;
652 M->setDataLayout(MaybeDL.
get());
656bool LLParser::parseTopLevelEntities() {
660 switch (Lex.getKind()) {
664 if (parseSummaryEntry())
668 if (parseSourceFileName())
678 switch (Lex.getKind()) {
680 return tokError(
"expected top-level entity");
691 if (parseModuleAsm())
695 if (parseUnnamedType())
699 if (parseNamedType())
703 if (parseUnnamedGlobal())
707 if (parseNamedGlobal())
712 if (parseStandaloneMetadata())
716 if (parseSummaryEntry())
720 if (parseNamedMetadata())
724 if (parseUnnamedAttrGrp())
728 if (parseUseListOrder())
740bool LLParser::parseModuleAsm() {
748 Module::GlobalAsmProperties Props;
752 SMLoc Loc = Lex.getLoc();
754 return error(Loc,
"expected property name followed by ':'");
756 Key = Lex.getStrVal();
759 if (parseStringConstant(
Value))
763 return error(Loc,
"unknown property name");
773 std::string AsmStrPart;
774 if (parseStringConstant(AsmStrPart))
776 AsmStr += AsmStrPart +
"\n";
779 M->appendModuleInlineAsm({AsmStr, Props});
786bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
792 return tokError(
"unknown target property");
795 if (parseToken(
lltok::equal,
"expected '=' after target triple") ||
796 parseStringConstant(Str))
798 M->setTargetTriple(Triple(std::move(Str)));
802 if (parseToken(
lltok::equal,
"expected '=' after target datalayout"))
804 DLStrLoc = Lex.getLoc();
805 if (parseStringConstant(TentativeDLStr))
813bool LLParser::parseSourceFileName() {
816 if (parseToken(
lltok::equal,
"expected '=' after source_filename") ||
817 parseStringConstant(SourceFileName))
820 M->setSourceFileName(SourceFileName);
826bool LLParser::parseUnnamedType() {
827 LocTy TypeLoc = Lex.getLoc();
828 unsigned TypeID = Lex.getUIntVal();
831 if (parseToken(
lltok::equal,
"expected '=' after name") ||
836 if (parseStructDefinition(TypeLoc,
"", NumberedTypes[
TypeID], Result))
840 std::pair<Type*, LocTy> &
Entry = NumberedTypes[
TypeID];
842 return error(TypeLoc,
"non-struct types may not be recursive");
844 Entry.second = SMLoc();
852bool LLParser::parseNamedType() {
853 std::string
Name = Lex.getStrVal();
854 LocTy NameLoc = Lex.getLoc();
857 if (parseToken(
lltok::equal,
"expected '=' after name") ||
862 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
866 std::pair<Type*, LocTy> &
Entry = NamedTypes[
Name];
868 return error(NameLoc,
"non-struct types may not be recursive");
870 Entry.second = SMLoc();
878bool LLParser::parseDeclare() {
882 std::vector<std::pair<unsigned, MDNode *>> MDs;
886 if (parseMetadataAttachment(MDK,
N))
888 MDs.push_back({MDK,
N});
892 unsigned FunctionNumber = -1;
893 SmallVector<unsigned> UnnamedArgNums;
894 if (parseFunctionHeader(
F,
false, FunctionNumber, UnnamedArgNums))
897 F->addMetadata(MD.first, *MD.second);
903bool LLParser::parseDefine() {
906 FileLoc FunctionStart = getTokLineColumnPos();
910 unsigned FunctionNumber = -1;
911 SmallVector<unsigned> UnnamedArgNums;
913 parseFunctionHeader(
F,
true, FunctionNumber, UnnamedArgNums) ||
914 parseOptionalFunctionMetadata(*
F) ||
915 parseFunctionBody(*
F, FunctionNumber, UnnamedArgNums);
917 ParserContext->addFunctionLocation(
918 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
926bool LLParser::parseGlobalType(
bool &IsConstant) {
933 return tokError(
"expected 'global' or 'constant'");
939bool LLParser::parseOptionalUnnamedAddr(
960bool LLParser::parseUnnamedGlobal() {
963 LocTy NameLoc = Lex.getLoc();
967 VarID = Lex.getUIntVal();
968 if (checkValueID(NameLoc,
"global",
"@", NumberedVals.getNext(),
VarID))
972 if (parseToken(
lltok::equal,
"expected '=' after name"))
975 VarID = NumberedVals.getNext();
979 unsigned Linkage, Visibility, DLLStorageClass;
983 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
985 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
988 switch (Lex.getKind()) {
990 return parseGlobal(Name,
VarID, NameLoc,
Linkage, HasLinkage, Visibility,
991 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
994 return parseAliasOrIFunc(Name,
VarID, NameLoc,
Linkage, Visibility,
995 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1004bool LLParser::parseNamedGlobal() {
1006 LocTy NameLoc = Lex.getLoc();
1007 std::string
Name = Lex.getStrVal();
1011 unsigned Linkage, Visibility, DLLStorageClass;
1015 if (parseToken(
lltok::equal,
"expected '=' in global variable") ||
1016 parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
1018 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
1021 switch (Lex.getKind()) {
1023 return parseGlobal(Name, -1, NameLoc,
Linkage, HasLinkage, Visibility,
1024 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1027 return parseAliasOrIFunc(Name, -1, NameLoc,
Linkage, Visibility,
1028 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1032bool LLParser::parseComdat() {
1034 std::string
Name = Lex.getStrVal();
1035 LocTy NameLoc = Lex.getLoc();
1042 return tokError(
"expected comdat type");
1045 switch (Lex.getKind()) {
1047 return tokError(
"unknown selection kind");
1069 if (
I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
1070 return error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
1073 if (
I != ComdatSymTab.
end())
1076 C = M->getOrInsertComdat(Name);
1077 C->setSelectionKind(SK);
1084bool LLParser::parseMDString(
MDString *&Result) {
1086 if (parseStringConstant(Str))
1094bool LLParser::parseMDNodeID(
MDNode *&Result) {
1096 LocTy IDLoc = Lex.getLoc();
1098 if (parseUInt32(MID))
1102 auto [It,
Inserted] = NumberedMetadata.try_emplace(MID);
1109 auto &FwdRef = ForwardRefMDNodes[MID];
1112 Result = FwdRef.first.get();
1113 It->second.reset(Result);
1119bool LLParser::parseNamedMetadata() {
1121 std::string
Name = Lex.getStrVal();
1129 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1132 MDNode *
N =
nullptr;
1137 Lex.getStrVal() ==
"DIExpression") {
1138 if (parseDIExpression(
N,
false))
1143 Lex.getStrVal() ==
"DIArgList") {
1144 return tokError(
"found DIArgList outside of function");
1152 return parseToken(
lltok::rbrace,
"expected end of metadata node");
1157bool LLParser::parseStandaloneMetadata() {
1160 unsigned MetadataID = 0;
1163 if (parseUInt32(MetadataID) || parseToken(
lltok::equal,
"expected '=' here"))
1168 return tokError(
"unexpected type in metadata definition");
1172 if (parseSpecializedMDNode(Init, IsDistinct))
1175 parseMDTuple(Init, IsDistinct))
1179 auto FI = ForwardRefMDNodes.find(MetadataID);
1180 if (FI != ForwardRefMDNodes.end()) {
1181 auto *ToReplace = FI->second.first.get();
1185 for (
auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1186 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1187 "Inst unexpectedly already has DIAssignID attachment");
1188 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1192 ToReplace->replaceAllUsesWith(Init);
1193 ForwardRefMDNodes.erase(FI);
1195 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
1197 auto [It,
Inserted] = NumberedMetadata.try_emplace(MetadataID);
1199 return tokError(
"Metadata id is already used");
1200 It->second.reset(Init);
1207bool LLParser::skipModuleSummaryEntry() {
1220 return tokError(
"Expected 'gv', 'module', 'typeid', "
1221 "'typeidCompatibleVTable', 'flags', 'blockcount', "
1222 "'cfiFunctionDefs' or 'cfiFunctionDecls' at the start of "
1225 return parseSummaryIndexFlags();
1227 return parseBlockCount();
1229 if (parseToken(
lltok::colon,
"expected ':' at start of summary entry") ||
1230 parseToken(
lltok::lparen,
"expected '(' at start of summary entry"))
1234 unsigned NumOpenParen = 1;
1236 switch (Lex.getKind()) {
1244 return tokError(
"found end of file while parsing summary entry");
1250 }
while (NumOpenParen > 0);
1256bool LLParser::parseSummaryEntry() {
1262 Lex.setIgnoreColonInIdentifiers(
true);
1270 return skipModuleSummaryEntry();
1272 bool result =
false;
1273 switch (Lex.getKind()) {
1275 result = parseGVEntry(SummaryID);
1278 result = parseModuleEntry(SummaryID);
1281 result = parseTypeIdEntry(SummaryID);
1284 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1287 result = parseSummaryIndexFlags();
1290 result = parseBlockCount();
1294 result = parseCfiFunctions();
1297 result =
error(Lex.getLoc(),
"unexpected summary kind");
1300 Lex.setIgnoreColonInIdentifiers(
false);
1334bool LLParser::parseAliasOrIFunc(
const std::string &Name,
unsigned NameID,
1335 LocTy NameLoc,
unsigned L,
unsigned Visibility,
1336 unsigned DLLStorageClass,
bool DSOLocal,
1351 return error(NameLoc,
"invalid linkage type for alias");
1354 return error(NameLoc,
1355 "symbol with local linkage must have default visibility");
1358 return error(NameLoc,
1359 "symbol with local linkage cannot have a DLL storage class");
1362 LocTy ExplicitTypeLoc = Lex.getLoc();
1363 if (parseType(Ty) ||
1364 parseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
1368 LocTy AliaseeLoc = Lex.getLoc();
1373 if (parseGlobalTypeAndValue(Aliasee))
1378 if (parseValID(ID,
nullptr))
1381 return error(AliaseeLoc,
"invalid aliasee");
1382 Aliasee =
ID.ConstantVal;
1388 return error(AliaseeLoc,
"An alias or ifunc must have pointer type");
1389 unsigned AddrSpace = PTy->getAddressSpace();
1391 GlobalValue *GVal =
nullptr;
1395 if (!
Name.empty()) {
1396 auto I = ForwardRefVals.find(Name);
1397 if (
I != ForwardRefVals.end()) {
1398 GVal =
I->second.first;
1399 ForwardRefVals.erase(Name);
1400 }
else if (M->getNamedValue(Name)) {
1401 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1404 auto I = ForwardRefValIDs.find(NameID);
1405 if (
I != ForwardRefValIDs.end()) {
1406 GVal =
I->second.first;
1407 ForwardRefValIDs.erase(
I);
1412 std::unique_ptr<GlobalAlias> GA;
1413 std::unique_ptr<GlobalIFunc> GI;
1441 if (parseGlobalObjectMetadataAttachment(*GI))
1444 return tokError(
"unknown alias or ifunc property!");
1449 NumberedVals.add(NameID, GV);
1456 "forward reference and definition of alias have different types");
1466 M->insertAlias(GA.release());
1468 M->insertIFunc(GI.release());
1469 assert(GV->
getName() == Name &&
"Should not be a name conflict!");
1478 case lltok::kw_sanitize_memtag:
1492 switch (Lex.getKind()) {
1494 Meta.NoAddress =
true;
1497 Meta.NoHWAddress =
true;
1499 case lltok::kw_sanitize_memtag:
1503 Meta.IsDynInit =
true;
1506 return tokError(
"non-sanitizer token passed to LLParser::parseSanitizer()");
1526bool LLParser::parseGlobal(
const std::string &Name,
unsigned NameID,
1527 LocTy NameLoc,
unsigned Linkage,
bool HasLinkage,
1528 unsigned Visibility,
unsigned DLLStorageClass,
1532 return error(NameLoc,
1533 "symbol with local linkage must have default visibility");
1536 return error(NameLoc,
1537 "symbol with local linkage cannot have a DLL storage class");
1541 LocTy IsExternallyInitializedLoc;
1545 if (parseOptionalAddrSpace(AddrSpace) ||
1547 IsExternallyInitialized,
1548 &IsExternallyInitializedLoc) ||
1549 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1558 if (parseGlobalValue(Ty, Init))
1563 return error(TyLoc,
"invalid type for global variable");
1565 GlobalValue *GVal =
nullptr;
1568 if (!
Name.empty()) {
1569 auto I = ForwardRefVals.find(Name);
1570 if (
I != ForwardRefVals.end()) {
1571 GVal =
I->second.first;
1572 ForwardRefVals.erase(
I);
1573 }
else if (M->getNamedValue(Name)) {
1574 return error(NameLoc,
"redefinition of global '@" + Name +
"'");
1579 if (NameID == (
unsigned)-1)
1580 NameID = NumberedVals.getNext();
1582 auto I = ForwardRefValIDs.find(NameID);
1583 if (
I != ForwardRefValIDs.end()) {
1584 GVal =
I->second.first;
1585 ForwardRefValIDs.erase(
I);
1589 GlobalVariable *GV =
new GlobalVariable(
1594 NumberedVals.add(NameID, GV);
1612 "forward reference and definition of global have different types");
1632 }
else if (Lex.getKind() == lltok::kw_align) {
1634 if (parseOptionalAlignment(Alignment))
1640 if (parseOptionalCodeModel(CodeModel))
1644 if (parseGlobalObjectMetadataAttachment(*GV))
1647 if (parseSanitizer(GV))
1651 if (parseOptionalComdat(Name,
C))
1656 return tokError(
"unknown global variable property!");
1660 AttrBuilder
Attrs(M->getContext());
1662 std::vector<unsigned> FwdRefAttrGrps;
1663 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps,
false, BuiltinLoc))
1665 if (
Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1667 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1675bool LLParser::parseUnnamedAttrGrp() {
1677 LocTy AttrGrpLoc = Lex.getLoc();
1681 return tokError(
"expected attribute group id");
1683 unsigned VarID = Lex.getUIntVal();
1684 std::vector<unsigned> unused;
1692 auto R = NumberedAttrBuilders.find(
VarID);
1693 if (R == NumberedAttrBuilders.end())
1694 R = NumberedAttrBuilders.emplace(
VarID, AttrBuilder(M->getContext())).first;
1696 if (parseFnAttributeValuePairs(
R->second, unused,
true, BuiltinLoc) ||
1697 parseToken(
lltok::rbrace,
"expected end of attribute group"))
1700 if (!
R->second.hasAttributes())
1701 return error(AttrGrpLoc,
"attribute group has no attributes");
1708#define GET_ATTR_NAMES
1709#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1710 case lltok::kw_##DISPLAY_NAME: \
1711 return Attribute::ENUM_NAME;
1712#include "llvm/IR/Attributes.inc"
1721 return parseRequiredTypeAttr(
B, Lex.getKind(), Attr);
1724 case Attribute::Alignment: {
1733 if (parseOptionalAlignment(Alignment,
true))
1736 B.addAlignmentAttr(Alignment);
1739 case Attribute::StackAlignment: {
1744 parseUInt32(Alignment))
1747 if (parseOptionalStackAlignment(Alignment))
1750 B.addStackAlignmentAttr(Alignment);
1753 case Attribute::AllocSize: {
1754 unsigned ElemSizeArg;
1755 std::optional<unsigned> NumElemsArg;
1756 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1758 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1761 case Attribute::VScaleRange: {
1762 unsigned MinValue, MaxValue;
1763 if (parseVScaleRangeArguments(MinValue, MaxValue))
1765 B.addVScaleRangeAttr(MinValue,
1766 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1769 case Attribute::Dereferenceable: {
1770 std::optional<uint64_t> Bytes;
1771 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1773 assert(Bytes.has_value());
1774 B.addDereferenceableAttr(Bytes.value());
1777 case Attribute::DeadOnReturn: {
1778 std::optional<uint64_t> Bytes;
1779 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1782 if (Bytes.has_value()) {
1783 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1785 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1789 case Attribute::DereferenceableOrNull: {
1790 std::optional<uint64_t> Bytes;
1791 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1793 assert(Bytes.has_value());
1794 B.addDereferenceableOrNullAttr(Bytes.value());
1797 case Attribute::UWTable: {
1799 if (parseOptionalUWTableKind(Kind))
1801 B.addUWTableAttr(Kind);
1804 case Attribute::AllocKind: {
1806 if (parseAllocKind(Kind))
1808 B.addAllocKindAttr(Kind);
1811 case Attribute::Memory: {
1812 std::optional<MemoryEffects> ME = parseMemoryAttr();
1815 B.addMemoryAttr(*ME);
1818 case Attribute::DenormalFPEnv: {
1819 std::optional<DenormalFPEnv>
Mode = parseDenormalFPEnvAttr();
1823 B.addDenormalFPEnvAttr(*
Mode);
1826 case Attribute::NoFPClass: {
1829 B.addNoFPClassAttr(NoFPClass);
1835 case Attribute::Range:
1836 return parseRangeAttr(
B);
1837 case Attribute::Initializes:
1838 return parseInitializesAttr(
B);
1839 case Attribute::Captures:
1840 return parseCapturesAttr(
B);
1842 B.addAttribute(Attr);
1850 case lltok::kw_readnone:
1853 case lltok::kw_readonly:
1856 case lltok::kw_writeonly:
1875bool LLParser::parseFnAttributeValuePairs(AttrBuilder &
B,
1876 std::vector<unsigned> &FwdRefAttrGrps,
1877 bool InAttrGrp, LocTy &BuiltinLoc) {
1878 bool HaveError =
false;
1889 if (parseStringAttribute(
B))
1901 "cannot have an attribute group reference in an attribute group");
1904 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1910 SMLoc Loc = Lex.getLoc();
1911 if (Token == lltok::kw_builtin)
1923 return error(Lex.getLoc(),
"unterminated attribute group");
1926 if (parseEnumAttribute(Attr,
B, InAttrGrp))
1933 HaveError |=
error(Loc,
"this attribute does not apply to functions");
1937 B.addMemoryAttr(ME);
1951 PTy->getAddressSpace());
1960 error(Loc,
"'" + Name +
"' is not a basic block");
1962 error(Loc,
"'" + Name +
"' defined with type '" +
1975 error(Loc,
"global variable reference must have pointer type");
1986 auto I = ForwardRefVals.find(Name);
1987 if (
I != ForwardRefVals.end())
1988 Val =
I->second.first;
1994 checkValidVariableType(Loc,
"@" + Name, Ty, Val));
1998 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
2005 error(Loc,
"global variable reference must have pointer type");
2009 GlobalValue *Val = NumberedVals.get(ID);
2014 auto I = ForwardRefValIDs.find(ID);
2015 if (
I != ForwardRefValIDs.end())
2016 Val =
I->second.first;
2022 checkValidVariableType(Loc,
"@" + Twine(ID), Ty, Val));
2026 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
2034Comdat *LLParser::getComdat(
const std::string &Name, LocTy
Loc) {
2038 if (
I != ComdatSymTab.
end())
2042 Comdat *
C = M->getOrInsertComdat(Name);
2043 ForwardRefComdats[
Name] = Loc;
2053bool LLParser::parseToken(
lltok::Kind T,
const char *ErrMsg) {
2054 if (Lex.getKind() !=
T)
2055 return tokError(ErrMsg);
2062bool LLParser::parseStringConstant(std::string &Result) {
2064 return tokError(
"expected string constant");
2065 Result = Lex.getStrVal();
2072bool LLParser::parseUInt32(uint32_t &Val) {
2073 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
2074 return tokError(
"expected integer");
2075 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
2076 if (Val64 !=
unsigned(Val64))
2077 return tokError(
"expected 32-bit integer (too large)");
2085bool LLParser::parseUInt64(
uint64_t &Val) {
2086 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
2087 return tokError(
"expected integer");
2088 Val = Lex.getAPSIntVal().getLimitedValue();
2098 switch (Lex.getKind()) {
2100 return tokError(
"expected localdynamic, initialexec or localexec");
2128 return parseTLSModel(TLM) ||
2129 parseToken(
lltok::rparen,
"expected ')' after thread local model");
2137bool LLParser::parseOptionalAddrSpace(
unsigned &AddrSpace,
unsigned DefaultAS) {
2138 AddrSpace = DefaultAS;
2142 auto ParseAddrspaceValue = [&](
unsigned &AddrSpace) ->
bool {
2144 const std::string &AddrSpaceStr = Lex.getStrVal();
2145 if (AddrSpaceStr ==
"A") {
2146 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2147 }
else if (AddrSpaceStr ==
"G") {
2148 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2149 }
else if (AddrSpaceStr ==
"P") {
2150 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2151 }
else if (std::optional<unsigned> AS =
2152 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2155 return tokError(
"invalid symbolic addrspace '" + AddrSpaceStr +
"'");
2161 return tokError(
"expected integer or string constant");
2162 SMLoc Loc = Lex.getLoc();
2163 if (parseUInt32(AddrSpace))
2166 return error(Loc,
"invalid address space, must be a 24-bit integer");
2170 return parseToken(
lltok::lparen,
"expected '(' in address space") ||
2171 ParseAddrspaceValue(AddrSpace) ||
2178bool LLParser::parseStringAttribute(AttrBuilder &
B) {
2179 std::string Attr = Lex.getStrVal();
2182 if (EatIfPresent(
lltok::equal) && parseStringConstant(Val))
2184 B.addAttribute(Attr, Val);
2189bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &
B,
bool IsParam) {
2190 bool HaveError =
false;
2197 if (parseStringAttribute(
B))
2208 SMLoc Loc = Lex.getLoc();
2213 if (parseEnumAttribute(Attr,
B,
false))
2217 HaveError |=
error(Loc,
"this attribute does not apply to parameters");
2219 HaveError |=
error(Loc,
"this attribute does not apply to return values");
2267bool LLParser::parseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
2268 unsigned &Visibility,
2269 unsigned &DLLStorageClass,
bool &DSOLocal) {
2273 parseOptionalDSOLocal(DSOLocal);
2274 parseOptionalVisibility(Visibility);
2275 parseOptionalDLLStorageClass(DLLStorageClass);
2278 return error(Lex.getLoc(),
"dso_location and DLL-StorageClass mismatch");
2284void LLParser::parseOptionalDSOLocal(
bool &DSOLocal) {
2285 switch (Lex.getKind()) {
2306void LLParser::parseOptionalVisibility(
unsigned &Res) {
2307 switch (Lex.getKind()) {
2324bool LLParser::parseOptionalImportType(
lltok::Kind Kind,
2328 return tokError(
"unknown import kind. Expect definition or declaration.");
2343void LLParser::parseOptionalDLLStorageClass(
unsigned &Res) {
2344 switch (Lex.getKind()) {
2416bool LLParser::parseOptionalCallingConv(
unsigned &
CC) {
2417 switch (Lex.getKind()) {
2510 return tokError(
"unknown RISC-V ABI VLEN");
2511#define CC_VLS_CASE(ABIVlen) \
2513 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2541 return parseUInt32(
CC);
2551bool LLParser::parseMetadataAttachment(
unsigned &Kind,
MDNode *&MD) {
2554 std::string
Name = Lex.getStrVal();
2555 Kind = M->getMDKindID(Name);
2558 return parseMDNode(MD);
2563bool LLParser::parseInstructionMetadata(
Instruction &Inst) {
2566 return tokError(
"expected metadata after comma");
2570 auto Loc = Lex.getLoc();
2571 if (parseMetadataAttachment(MDK,
N))
2574 if (MDK == LLVMContext::MD_DIAssignID)
2575 TempDIAssignIDAttachments[
N].push_back(&Inst);
2576 else if (MDK == LLVMContext::MD_dbg)
2577 PendingDbgInsts.emplace_back(Loc, &Inst,
N);
2588bool LLParser::parseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
2591 if (parseMetadataAttachment(MDK,
N))
2600bool LLParser::parseOptionalFunctionMetadata(
Function &
F) {
2602 if (parseGlobalObjectMetadataAttachment(
F))
2610bool LLParser::parseOptionalAlignment(
MaybeAlign &Alignment,
bool AllowParens) {
2612 if (!EatIfPresent(lltok::kw_align))
2614 LocTy AlignLoc = Lex.getLoc();
2617 LocTy ParenLoc = Lex.getLoc();
2618 bool HaveParens =
false;
2624 if (parseUInt64(
Value))
2628 return error(ParenLoc,
"expected ')'");
2631 return error(AlignLoc,
"alignment is not a power of two");
2633 return error(AlignLoc,
"huge alignments are not supported yet");
2641bool LLParser::parseOptionalPrefAlignment(
MaybeAlign &Alignment) {
2645 LocTy AlignLoc = Lex.getLoc();
2648 LocTy ParenLoc = Lex.getLoc();
2650 return error(ParenLoc,
"expected '('");
2652 if (parseUInt64(
Value))
2655 ParenLoc = Lex.getLoc();
2657 return error(ParenLoc,
"expected ')'");
2660 return error(AlignLoc,
"alignment is not a power of two");
2662 return error(AlignLoc,
"huge alignments are not supported yet");
2672 auto StrVal = Lex.getStrVal();
2673 auto ErrMsg =
"expected global code model string";
2674 if (StrVal ==
"tiny")
2676 else if (StrVal ==
"small")
2678 else if (StrVal ==
"kernel")
2680 else if (StrVal ==
"medium")
2682 else if (StrVal ==
"large")
2685 return tokError(ErrMsg);
2697bool LLParser::parseOptionalAttrBytes(
lltok::Kind AttrKind,
2698 std::optional<uint64_t> &Bytes,
2699 bool ErrorNoBytes) {
2700 assert((AttrKind == lltok::kw_dereferenceable ||
2701 AttrKind == lltok::kw_dereferenceable_or_null ||
2702 AttrKind == lltok::kw_dead_on_return) &&
2706 if (!EatIfPresent(AttrKind))
2708 LocTy ParenLoc = Lex.getLoc();
2711 return error(ParenLoc,
"expected '('");
2712 Bytes = std::nullopt;
2715 LocTy DerefLoc = Lex.getLoc();
2716 if (parseUInt64(Bytes.value()))
2718 ParenLoc = Lex.getLoc();
2720 return error(ParenLoc,
"expected ')'");
2722 return error(DerefLoc,
"byte count specified must be non-zero");
2726bool LLParser::parseOptionalUWTableKind(
UWTableKind &Kind) {
2731 LocTy KindLoc = Lex.getLoc();
2737 return error(KindLoc,
"expected unwind table kind");
2744 LocTy ParenLoc = Lex.getLoc();
2746 return error(ParenLoc,
"expected '('");
2747 LocTy KindLoc = Lex.getLoc();
2749 if (parseStringConstant(Arg))
2750 return error(KindLoc,
"expected allockind value");
2754 }
else if (
A ==
"realloc") {
2756 }
else if (
A ==
"free") {
2758 }
else if (
A ==
"uninitialized") {
2760 }
else if (
A ==
"zeroed") {
2762 }
else if (
A ==
"aligned") {
2765 return error(KindLoc, Twine(
"unknown allockind ") +
A);
2768 ParenLoc = Lex.getLoc();
2770 return error(ParenLoc,
"expected ')'");
2772 return error(KindLoc,
"expected allockind value");
2781 return {Loc::ArgMem};
2783 return {Loc::InaccessibleMem};
2785 return {Loc::ErrnoMem};
2787 return {Loc::TargetMem0};
2789 return {Loc::TargetMem1};
2812 return std::nullopt;
2816static std::optional<DenormalMode::DenormalModeKind>
2828 return std::nullopt;
2832std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2837 Lex.setIgnoreColonInIdentifiers(
true);
2842 tokError(
"expected '('");
2843 return std::nullopt;
2846 bool SeenLoc =
false;
2847 bool SeenTargetLoc =
false;
2850 if (!Locs.
empty()) {
2853 tokError(
"expected ':' after location");
2854 return std::nullopt;
2861 tokError(
"expected memory location (argmem, inaccessiblemem, errnomem) "
2862 "or access kind (none, read, write, readwrite)");
2864 tokError(
"expected access kind (none, read, write, readwrite)");
2865 return std::nullopt;
2869 if (!Locs.
empty()) {
2874 SeenTargetLoc =
true;
2876 if (Locs.size() > 1 && SeenTargetLoc) {
2877 tokError(
"target memory default access kind must be specified first");
2878 return std::nullopt;
2883 tokError(
"default access kind must be specified first");
2884 return std::nullopt;
2893 tokError(
"unterminated memory attribute");
2894 return std::nullopt;
2897std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2898 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2901 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2902 "positivezero, dynamic)");
2908 std::optional<DenormalMode::DenormalModeKind> InputMode;
2912 tokError(
"expected denormal behavior kind (ieee, preservesign, "
2913 "positivezero, dynamic)");
2920 InputMode = OutputMode;
2923 return DenormalMode(*OutputMode, *InputMode);
2926std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2929 Lex.setIgnoreColonInIdentifiers(
true);
2940 bool HasDefaultSection =
false;
2942 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2943 if (!ParsedDefaultMode)
2945 DefaultMode = *ParsedDefaultMode;
2946 HasDefaultSection =
true;
2951 if (HasDefaultSection && !HasComma) {
2952 tokError(
"expected ',' before float:");
2957 if (parseType(Ty) || !Ty->
isFloatTy()) {
2958 tokError(
"expected float:");
2962 if (parseToken(
lltok::colon,
"expected ':' before float denormal_fpenv"))
2965 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2969 F32Mode = *ParsedF32Mode;
2972 if (parseToken(
lltok::rparen,
"unterminated denormal_fpenv"))
2975 return DenormalFPEnv(DefaultMode, F32Mode);
3017unsigned LLParser::parseNoFPClassAttr() {
3022 tokError(
"expected '('");
3029 if (TestMask != 0) {
3033 !parseUInt64(
Value)) {
3035 error(Lex.getLoc(),
"invalid mask value for 'nofpclass'");
3040 error(Lex.getLoc(),
"expected ')'");
3046 error(Lex.getLoc(),
"expected nofpclass test mask");
3064bool LLParser::parseOptionalCommaAlign(
MaybeAlign &Alignment,
3065 bool &AteExtraComma) {
3066 AteExtraComma =
false;
3070 AteExtraComma =
true;
3074 if (Lex.getKind() != lltok::kw_align)
3075 return error(Lex.getLoc(),
"expected metadata or 'align'");
3077 if (parseOptionalAlignment(Alignment))
3090bool LLParser::parseOptionalCommaAddrSpace(
unsigned &AddrSpace, LocTy &
Loc,
3091 bool &AteExtraComma) {
3092 AteExtraComma =
false;
3096 AteExtraComma =
true;
3102 return error(Lex.getLoc(),
"expected metadata or 'addrspace'");
3104 if (parseOptionalAddrSpace(AddrSpace))
3111bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
3112 std::optional<unsigned> &HowManyArg) {
3115 auto StartParen = Lex.getLoc();
3117 return error(StartParen,
"expected '('");
3119 if (parseUInt32(BaseSizeArg))
3123 auto HowManyAt = Lex.getLoc();
3125 if (parseUInt32(HowMany))
3127 if (HowMany == BaseSizeArg)
3128 return error(HowManyAt,
3129 "'allocsize' indices can't refer to the same parameter");
3130 HowManyArg = HowMany;
3132 HowManyArg = std::nullopt;
3134 auto EndParen = Lex.getLoc();
3136 return error(EndParen,
"expected ')'");
3140bool LLParser::parseVScaleRangeArguments(
unsigned &MinValue,
3141 unsigned &MaxValue) {
3144 auto StartParen = Lex.getLoc();
3146 return error(StartParen,
"expected '('");
3148 if (parseUInt32(MinValue))
3152 if (parseUInt32(MaxValue))
3155 MaxValue = MinValue;
3157 auto EndParen = Lex.getLoc();
3159 return error(EndParen,
"expected ')'");
3168bool LLParser::parseScopeAndOrdering(
bool IsAtomic,
SyncScope::ID &SSID,
3173 return parseScope(SSID) || parseOrdering(Ordering);
3183 auto StartParenAt = Lex.getLoc();
3185 return error(StartParenAt,
"Expected '(' in syncscope");
3188 auto SSNAt = Lex.getLoc();
3189 if (parseStringConstant(SSN))
3190 return error(SSNAt,
"Expected synchronization scope name");
3192 auto EndParenAt = Lex.getLoc();
3194 return error(EndParenAt,
"Expected ')' in syncscope");
3196 SSID = Context.getOrInsertSyncScopeID(SSN);
3207 switch (Lex.getKind()) {
3209 return tokError(
"Expected ordering on atomic instruction");
3228bool LLParser::parseOptionalStackAlignment(
unsigned &Alignment) {
3230 if (!EatIfPresent(lltok::kw_alignstack))
3232 LocTy ParenLoc = Lex.getLoc();
3234 return error(ParenLoc,
"expected '('");
3235 LocTy AlignLoc = Lex.getLoc();
3236 if (parseUInt32(Alignment))
3238 ParenLoc = Lex.getLoc();
3240 return error(ParenLoc,
"expected ')'");
3242 return error(AlignLoc,
"stack alignment is not a power of two");
3256 bool &AteExtraComma) {
3257 AteExtraComma =
false;
3260 return tokError(
"expected ',' as start of index list");
3264 if (Indices.
empty())
3265 return tokError(
"expected index");
3266 AteExtraComma =
true;
3270 if (parseUInt32(Idx))
3283bool LLParser::parseType(
Type *&Result,
const Twine &
Msg,
bool AllowVoid) {
3284 SMLoc TypeLoc = Lex.getLoc();
3285 switch (Lex.getKind()) {
3287 return tokError(
Msg);
3296 if (
Result->isPointerTy()) {
3298 if (parseOptionalAddrSpace(AddrSpace))
3304 return tokError(
"ptr* is invalid - use ptr instead");
3315 if (parseTargetExtType(Result))
3321 if (parseAnonStructType(Result,
false))
3327 if (parseArrayVectorType(Result,
false))
3334 if (parseAnonStructType(Result,
true) ||
3335 parseToken(
lltok::greater,
"expected '>' at end of packed struct"))
3337 }
else if (parseArrayVectorType(Result,
true))
3342 std::pair<Type*, LocTy> &
Entry = NamedTypes[Lex.getStrVal()];
3348 Entry.second = Lex.getLoc();
3357 std::pair<Type*, LocTy> &
Entry = NumberedTypes[Lex.getUIntVal()];
3363 Entry.second = Lex.getLoc();
3373 switch (Lex.getKind()) {
3376 if (!AllowVoid &&
Result->isVoidTy())
3377 return error(TypeLoc,
"void type only allowed for function results");
3383 return tokError(
"basic block pointers are invalid");
3385 return tokError(
"pointers to void are invalid - use i8* instead");
3387 return tokError(
"pointer to this type is invalid");
3395 return tokError(
"basic block pointers are invalid");
3397 return tokError(
"pointers to void are invalid; use i8* instead");
3399 return tokError(
"pointer to this type is invalid");
3401 if (parseOptionalAddrSpace(AddrSpace) ||
3402 parseToken(
lltok::star,
"expected '*' in address space"))
3411 if (parseFunctionType(Result))
3424 PerFunctionState &PFS,
bool IsMustTailCall,
3425 bool InVarArgsFunc) {
3431 if (!ArgList.
empty() &&
3432 parseToken(
lltok::comma,
"expected ',' in argument list"))
3437 const char *
Msg =
"unexpected ellipsis in argument list for ";
3438 if (!IsMustTailCall)
3439 return tokError(Twine(
Msg) +
"non-musttail call");
3441 return tokError(Twine(
Msg) +
"musttail call in non-varargs function");
3443 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3448 Type *ArgTy =
nullptr;
3450 if (parseType(ArgTy, ArgLoc))
3453 return error(ArgLoc,
"invalid type for function argument");
3455 AttrBuilder ArgAttrs(M->getContext());
3458 if (parseMetadataAsValue(
V, PFS))
3462 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy,
V, PFS))
3469 if (IsMustTailCall && InVarArgsFunc)
3470 return tokError(
"expected '...' at end of argument list for musttail call "
3471 "in varargs function");
3479bool LLParser::parseRequiredTypeAttr(AttrBuilder &
B,
lltok::Kind AttrToken,
3482 if (!EatIfPresent(AttrToken))
3485 return error(Lex.getLoc(),
"expected '('");
3489 return error(Lex.getLoc(),
"expected ')'");
3491 B.addTypeAttr(AttrKind, Ty);
3497bool LLParser::parseRangeAttr(AttrBuilder &
B) {
3505 auto ParseAPSInt = [&](
unsigned BitWidth, APInt &Val) {
3507 return tokError(
"expected integer");
3508 if (Lex.getAPSIntVal().getBitWidth() >
BitWidth)
3510 "integer is too large for the bit width of specified type");
3511 Val = Lex.getAPSIntVal().extend(
BitWidth);
3516 if (parseToken(
lltok::lparen,
"expected '('") || parseType(Ty, TyLoc))
3519 return error(TyLoc,
"the range must have integer type!");
3527 return tokError(
"the range represent the empty set but limits aren't 0!");
3538bool LLParser::parseInitializesAttr(AttrBuilder &
B) {
3541 auto ParseAPSInt = [&](APInt &Val) {
3543 return tokError(
"expected integer");
3544 Val = Lex.getAPSIntVal().extend(64);
3564 return tokError(
"the range should not represent the full or empty set!");
3576 if (!CRLOrNull.has_value())
3577 return tokError(
"Invalid (unordered or overlapping) range list");
3578 B.addInitializesAttr(*CRLOrNull);
3582bool LLParser::parseCapturesAttr(AttrBuilder &
B) {
3584 std::optional<CaptureComponents> Ret;
3588 Lex.setIgnoreColonInIdentifiers(
true);
3596 bool SeenComponent =
false;
3602 return tokError(
"duplicate 'ret' location");
3605 SeenComponent =
false;
3610 return tokError(
"cannot use 'none' with other component");
3614 return tokError(
"cannot use 'none' with other component");
3625 return tokError(
"expected one of 'none', 'address', 'address_is_null', "
3626 "'provenance' or 'read_provenance'");
3629 SeenComponent =
true;
3637 B.addCapturesAttr(CaptureInfo(
Other, Ret.value_or(
Other)));
3650bool LLParser::parseOptionalOperandBundles(
3652 LocTy BeginLoc = Lex.getLoc();
3658 if (!BundleList.
empty() &&
3659 parseToken(
lltok::comma,
"expected ',' in input list"))
3663 if (parseStringConstant(
Tag))
3666 if (parseToken(
lltok::lparen,
"expected '(' in operand bundle"))
3669 std::vector<Value *> Inputs;
3672 if (!Inputs.empty() &&
3673 parseToken(
lltok::comma,
"expected ',' in input list"))
3681 if (parseMetadataAsValue(Input, PFS))
3683 }
else if (parseValue(Ty, Input, PFS)) {
3686 Inputs.push_back(Input);
3694 if (BundleList.
empty())
3695 return error(BeginLoc,
"operand bundle set must not be empty");
3702 unsigned NextID,
unsigned ID) {
3704 return error(Loc, Kind +
" expected to be numbered '" + Prefix +
3705 Twine(NextID) +
"' or greater");
3722 unsigned CurValID = 0;
3736 LocTy TypeLoc = Lex.getLoc();
3737 Type *ArgTy =
nullptr;
3738 AttrBuilder
Attrs(M->getContext());
3739 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3743 return error(TypeLoc,
"argument can not have void type");
3748 bool Unnamed =
false;
3750 Name = Lex.getStrVal();
3751 IdentStart = getTokLineColumnPos();
3753 IdentEnd = getPrevTokEndLineColumnPos();
3757 ArgID = Lex.getUIntVal();
3758 IdentStart = getTokLineColumnPos();
3759 if (checkValueID(TypeLoc,
"argument",
"%", CurValID, ArgID))
3762 IdentEnd = getPrevTokEndLineColumnPos();
3768 CurValID = ArgID + 1;
3772 return error(TypeLoc,
"invalid type for function argument");
3776 Unnamed ? std::nullopt
3777 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3782 return parseToken(
lltok::rparen,
"expected ')' at end of argument list");
3787bool LLParser::parseFunctionType(
Type *&Result) {
3791 return tokError(
"invalid function return type");
3795 SmallVector<unsigned> UnnamedArgNums;
3796 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3800 for (
const ArgInfo &Arg : ArgList) {
3801 if (!Arg.Name.empty())
3802 return error(Arg.Loc,
"argument name invalid in function type");
3803 if (Arg.Attrs.hasAttributes())
3804 return error(Arg.Loc,
"argument attributes invalid in function type");
3808 for (
const ArgInfo &Arg : ArgList)
3817bool LLParser::parseAnonStructType(
Type *&Result,
bool Packed) {
3819 if (parseStructBody(Elts))
3827bool LLParser::parseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
3828 std::pair<Type *, LocTy> &Entry,
3832 return error(TypeLoc,
"redefinition of type");
3838 Entry.second = SMLoc();
3843 ResultTy =
Entry.first;
3855 return error(TypeLoc,
"forward references to non-struct type");
3859 return parseArrayVectorType(ResultTy,
true);
3860 return parseType(ResultTy);
3864 Entry.second = SMLoc();
3873 if (parseStructBody(Body) ||
3874 (isPacked && parseToken(
lltok::greater,
"expected '>' in packed struct")))
3878 return tokError(
toString(std::move(
E)));
3898 LocTy EltTyLoc = Lex.getLoc();
3905 return error(EltTyLoc,
"invalid element type for struct");
3908 EltTyLoc = Lex.getLoc();
3913 return error(EltTyLoc,
"invalid element type for struct");
3918 return parseToken(
lltok::rbrace,
"expected '}' at end of struct");
3927bool LLParser::parseArrayVectorType(
Type *&Result,
bool IsVector) {
3928 bool Scalable =
false;
3932 if (parseToken(
lltok::kw_x,
"expected 'x' after vscale"))
3938 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3939 Lex.getAPSIntVal().getBitWidth() > 64)
3940 return tokError(
"expected number in address space");
3942 LocTy SizeLoc = Lex.getLoc();
3946 if (parseToken(
lltok::kw_x,
"expected 'x' after element count"))
3949 LocTy TypeLoc = Lex.getLoc();
3950 Type *EltTy =
nullptr;
3951 if (parseType(EltTy))
3955 "expected end of sequential type"))
3960 return error(SizeLoc,
"zero element vector is illegal");
3962 return error(SizeLoc,
"size too large for vector");
3964 return error(TypeLoc,
"invalid vector element type");
3968 return error(TypeLoc,
"invalid array element type");
3985bool LLParser::parseTargetExtType(
Type *&Result) {
3990 if (parseToken(
lltok::lparen,
"expected '(' in target extension type") ||
3991 parseStringConstant(TypeName))
3998 SmallVector<unsigned> IntParams;
3999 bool SeenInt =
false;
4006 if (parseUInt32(IntVal))
4009 }
else if (SeenInt) {
4012 return tokError(
"expected uint32 param");
4015 if (parseType(TypeParam,
true))
4021 if (parseToken(
lltok::rparen,
"expected ')' in target extension type"))
4026 if (
auto E = TTy.takeError())
4027 return tokError(
toString(std::move(
E)));
4040 :
P(
p),
F(
f), FunctionNumber(functionNumber) {
4043 auto It = UnnamedArgNums.
begin();
4046 unsigned ArgNum = *It++;
4047 NumberedVals.add(ArgNum, &A);
4052LLParser::PerFunctionState::~PerFunctionState() {
4055 for (
const auto &P : ForwardRefVals) {
4058 P.second.first->replaceAllUsesWith(
4060 P.second.first->deleteValue();
4063 for (
const auto &P : ForwardRefValIDs) {
4066 P.second.first->replaceAllUsesWith(
4068 P.second.first->deleteValue();
4072bool LLParser::PerFunctionState::finishFunction() {
4073 if (!ForwardRefVals.empty())
4074 return P.error(ForwardRefVals.begin()->second.second,
4075 "use of undefined value '%" + ForwardRefVals.begin()->first +
4077 if (!ForwardRefValIDs.empty())
4078 return P.error(ForwardRefValIDs.begin()->second.second,
4079 "use of undefined value '%" +
4080 Twine(ForwardRefValIDs.begin()->first) +
"'");
4087Value *LLParser::PerFunctionState::getVal(
const std::string &Name,
Type *Ty,
4090 Value *Val =
F.getValueSymbolTable()->lookup(Name);
4095 auto I = ForwardRefVals.find(Name);
4096 if (
I != ForwardRefVals.end())
4097 Val =
I->second.first;
4102 return P.checkValidVariableType(Loc,
"%" + Name, Ty, Val);
4106 P.error(Loc,
"invalid use of a non-first-class type");
4117 if (FwdVal->
getName() != Name) {
4118 P.error(Loc,
"name is too long which can result in name collisions, "
4119 "consider making the name shorter or "
4120 "increasing -non-global-value-max-name-size");
4124 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
4128Value *LLParser::PerFunctionState::getVal(
unsigned ID,
Type *Ty,
LocTy Loc) {
4130 Value *Val = NumberedVals.get(ID);
4135 auto I = ForwardRefValIDs.find(ID);
4136 if (
I != ForwardRefValIDs.end())
4137 Val =
I->second.first;
4142 return P.checkValidVariableType(Loc,
"%" + Twine(ID), Ty, Val);
4145 P.error(Loc,
"invalid use of a non-first-class type");
4157 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
4163bool LLParser::PerFunctionState::setInstName(
int NameID,
4164 const std::string &NameStr,
4165 LocTy NameLoc, Instruction *Inst) {
4168 if (NameID != -1 || !NameStr.empty())
4169 return P.error(NameLoc,
"instructions returning void cannot have a name");
4175 if (NameStr.empty()) {
4178 NameID = NumberedVals.getNext();
4180 if (
P.checkValueID(NameLoc,
"instruction",
"%", NumberedVals.getNext(),
4184 auto FI = ForwardRefValIDs.find(NameID);
4185 if (FI != ForwardRefValIDs.end()) {
4188 return P.error(NameLoc,
"instruction forward referenced with type '" +
4192 Sentinel->replaceAllUsesWith(Inst);
4194 ForwardRefValIDs.erase(FI);
4197 NumberedVals.add(NameID, Inst);
4202 auto FI = ForwardRefVals.find(NameStr);
4203 if (FI != ForwardRefVals.end()) {
4206 return P.error(NameLoc,
"instruction forward referenced with type '" +
4210 Sentinel->replaceAllUsesWith(Inst);
4212 ForwardRefVals.erase(FI);
4218 if (Inst->
getName() != NameStr)
4219 return P.error(NameLoc,
"multiple definition of local value named '" +
4226BasicBlock *LLParser::PerFunctionState::getBB(
const std::string &Name,
4232BasicBlock *LLParser::PerFunctionState::getBB(
unsigned ID,
LocTy Loc) {
4240BasicBlock *LLParser::PerFunctionState::defineBB(
const std::string &Name,
4241 int NameID,
LocTy Loc) {
4245 if (
P.checkValueID(Loc,
"label",
"", NumberedVals.getNext(), NameID))
4248 NameID = NumberedVals.getNext();
4250 BB = getBB(NameID, Loc);
4252 P.error(Loc,
"unable to create block numbered '" + Twine(NameID) +
"'");
4256 BB = getBB(Name, Loc);
4258 P.error(Loc,
"unable to create block named '" + Name +
"'");
4269 ForwardRefValIDs.erase(NameID);
4270 NumberedVals.add(NameID, BB);
4273 ForwardRefVals.erase(Name);
4290bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS,
Type *ExpectedTy) {
4291 ID.Loc = Lex.getLoc();
4292 switch (Lex.getKind()) {
4294 return tokError(
"expected value token");
4296 ID.UIntVal = Lex.getUIntVal();
4300 ID.StrVal = Lex.getStrVal();
4304 ID.UIntVal = Lex.getUIntVal();
4308 ID.StrVal = Lex.getStrVal();
4312 ID.APSIntVal = Lex.getAPSIntVal();
4316 ID.APFloatVal = Lex.getAPFloatVal();
4322 return error(
ID.Loc,
"unexpected floating-point literal");
4324 return error(
ID.Loc,
"floating-point constant invalid for type");
4329 "Invalid float strings should be caught by the lexer");
4334 return error(
ID.Loc,
"floating-point constant overflowed type");
4336 return error(
ID.Loc,
"floating-point constant underflowed type");
4342 return error(
ID.Loc,
"unexpected floating-point literal");
4344 const APInt &
Bits = Lex.getAPSIntVal();
4346 return error(
ID.Loc,
"float hex literal has incorrect number of bits");
4347 ID.APFloatVal =
APFloat(Semantics, Bits);
4369 if (parseGlobalValueVector(Elts) ||
4370 parseToken(
lltok::rbrace,
"expected end of struct constant"))
4373 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4374 ID.UIntVal = Elts.
size();
4375 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4376 Elts.
size() *
sizeof(Elts[0]));
4387 LocTy FirstEltLoc = Lex.getLoc();
4388 if (parseGlobalValueVector(Elts) ||
4390 parseToken(
lltok::rbrace,
"expected end of packed struct")) ||
4394 if (isPackedStruct) {
4395 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.
size());
4396 memcpy(
ID.ConstantStructElts.get(), Elts.
data(),
4397 Elts.
size() *
sizeof(Elts[0]));
4398 ID.UIntVal = Elts.
size();
4404 return error(
ID.Loc,
"constant vector must not be empty");
4406 if (!Elts[0]->
getType()->isIntegerTy() && !Elts[0]->
getType()->isByteTy() &&
4407 !Elts[0]->
getType()->isFloatingPointTy() &&
4411 "vector elements must have integer, byte, pointer or floating point "
4415 for (
unsigned i = 1, e = Elts.
size(); i != e; ++i)
4417 return error(FirstEltLoc,
"vector element #" + Twine(i) +
4418 " is not of type '" +
4428 LocTy FirstEltLoc = Lex.getLoc();
4429 if (parseGlobalValueVector(Elts) ||
4441 if (!Elts[0]->
getType()->isFirstClassType())
4442 return error(FirstEltLoc,
"invalid array element type: " +
4448 for (
unsigned i = 0, e = Elts.
size(); i != e; ++i) {
4450 return error(FirstEltLoc,
"array element #" + Twine(i) +
4451 " is not of type '" +
4463 Context, Lex.getStrVal(),
false, ATy->getElementType()->isByteTy());
4472 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4475 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4478 parseStringConstant(
ID.StrVal) ||
4479 parseToken(
lltok::comma,
"expected comma in inline asm expression") ||
4482 ID.StrVal2 = Lex.getStrVal();
4483 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4484 (
unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4495 if (parseToken(
lltok::lparen,
"expected '(' in block address expression") ||
4496 parseValID(Fn, PFS) ||
4498 "expected comma in block address expression") ||
4499 parseValID(Label, PFS) ||
4500 parseToken(
lltok::rparen,
"expected ')' in block address expression"))
4504 return error(Fn.
Loc,
"expected function name in blockaddress");
4506 return error(
Label.Loc,
"expected basic block name in blockaddress");
4509 GlobalValue *GV =
nullptr;
4511 GV = NumberedVals.get(Fn.
UIntVal);
4512 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4513 GV = M->getNamedValue(Fn.
StrVal);
4519 return error(Fn.
Loc,
"expected function name in blockaddress");
4521 if (
F->isDeclaration())
4522 return error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
4527 GlobalValue *&FwdRef =
4528 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4536 "type of blockaddress must be a pointer and not '" +
4541 FwdDeclAS = PFS->getFunction().getAddressSpace();
4545 FwdRef =
new GlobalVariable(
4550 ID.ConstantVal = FwdRef;
4558 if (BlockAddressPFS &&
F == &BlockAddressPFS->getFunction()) {
4560 BB = BlockAddressPFS->getBB(
Label.UIntVal,
Label.Loc);
4562 BB = BlockAddressPFS->getBB(
Label.StrVal,
Label.Loc);
4564 return error(
Label.Loc,
"referenced value is not a basic block");
4567 return error(
Label.Loc,
"cannot take address of numeric label after "
4568 "the function is defined");
4570 F->getValueSymbolTable()->lookup(
Label.StrVal));
4572 return error(
Label.Loc,
"referenced value is not a basic block");
4586 if (parseValID(Fn, PFS))
4591 "expected global value name in dso_local_equivalent");
4594 GlobalValue *GV =
nullptr;
4596 GV = NumberedVals.get(Fn.
UIntVal);
4597 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
4598 GV = M->getNamedValue(Fn.
StrVal);
4604 ? ForwardRefDSOLocalEquivalentIDs
4605 : ForwardRefDSOLocalEquivalentNames;
4606 GlobalValue *&FwdRef = FwdRefMap[Fn];
4613 ID.ConstantVal = FwdRef;
4619 return error(Fn.
Loc,
"expected a function, alias to function, or ifunc "
4620 "in dso_local_equivalent");
4631 if (parseValID(ID, PFS))
4635 return error(
ID.Loc,
"expected global value name in no_cfi");
4647 Constant *Disc =
nullptr, *AddrDisc =
nullptr,
4648 *DeactivationSymbol =
nullptr;
4651 "expected '(' in constant ptrauth expression") ||
4652 parseGlobalTypeAndValue(Ptr) ||
4654 "expected comma in constant ptrauth expression") ||
4655 parseGlobalTypeAndValue(
Key))
4658 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(Disc))
4660 if (EatIfPresent(
lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4663 parseGlobalTypeAndValue(DeactivationSymbol))
4666 "expected ')' in constant ptrauth expression"))
4670 return error(
ID.Loc,
"constant ptrauth base pointer must be a pointer");
4673 if (!KeyC || KeyC->getBitWidth() != 32)
4674 return error(
ID.Loc,
"constant ptrauth key must be i32 constant");
4676 ConstantInt *DiscC =
nullptr;
4682 "constant ptrauth integer discriminator must be i64 constant");
4688 if (!AddrDisc->getType()->isPointerTy())
4690 ID.Loc,
"constant ptrauth address discriminator must be a pointer");
4695 if (!DeactivationSymbol)
4696 DeactivationSymbol =
4698 if (!DeactivationSymbol->getType()->isPointerTy())
4700 "constant ptrauth deactivation symbol must be a pointer");
4714 unsigned Opc = Lex.getUIntVal();
4715 Type *DestTy =
nullptr;
4718 if (parseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
4719 parseGlobalTypeAndValue(SrcVal) ||
4720 parseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
4721 parseType(DestTy) ||
4722 parseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
4725 return error(
ID.Loc,
"invalid cast opcode for cast from '" +
4734 return error(
ID.Loc,
"extractvalue constexprs are no longer supported");
4736 return error(
ID.Loc,
"insertvalue constexprs are no longer supported");
4738 return error(
ID.Loc,
"udiv constexprs are no longer supported");
4740 return error(
ID.Loc,
"sdiv constexprs are no longer supported");
4742 return error(
ID.Loc,
"urem constexprs are no longer supported");
4744 return error(
ID.Loc,
"srem constexprs are no longer supported");
4746 return error(
ID.Loc,
"fadd constexprs are no longer supported");
4748 return error(
ID.Loc,
"fsub constexprs are no longer supported");
4750 return error(
ID.Loc,
"fmul constexprs are no longer supported");
4752 return error(
ID.Loc,
"fdiv constexprs are no longer supported");
4754 return error(
ID.Loc,
"frem constexprs are no longer supported");
4756 return error(
ID.Loc,
"and constexprs are no longer supported");
4758 return error(
ID.Loc,
"or constexprs are no longer supported");
4760 return error(
ID.Loc,
"lshr constexprs are no longer supported");
4762 return error(
ID.Loc,
"ashr constexprs are no longer supported");
4764 return error(
ID.Loc,
"shl constexprs are no longer supported");
4766 return error(
ID.Loc,
"mul constexprs are no longer supported");
4768 return error(
ID.Loc,
"fneg constexprs are no longer supported");
4770 return error(
ID.Loc,
"select constexprs are no longer supported");
4772 return error(
ID.Loc,
"zext constexprs are no longer supported");
4774 return error(
ID.Loc,
"sext constexprs are no longer supported");
4776 return error(
ID.Loc,
"fptrunc constexprs are no longer supported");
4778 return error(
ID.Loc,
"fpext constexprs are no longer supported");
4780 return error(
ID.Loc,
"uitofp constexprs are no longer supported");
4782 return error(
ID.Loc,
"sitofp constexprs are no longer supported");
4784 return error(
ID.Loc,
"fptoui constexprs are no longer supported");
4786 return error(
ID.Loc,
"fptosi constexprs are no longer supported");
4788 return error(
ID.Loc,
"icmp constexprs are no longer supported");
4790 return error(
ID.Loc,
"fcmp constexprs are no longer supported");
4798 unsigned Opc = Lex.getUIntVal();
4801 if (
Opc == Instruction::Add ||
Opc == Instruction::Sub ||
4802 Opc == Instruction::Mul) {
4811 if (parseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
4812 parseGlobalTypeAndValue(Val0) ||
4813 parseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
4814 parseGlobalTypeAndValue(Val1) ||
4815 parseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
4818 return error(
ID.Loc,
"operands of constexpr must have same type");
4822 "constexpr requires integer or integer vector operands");
4833 if (parseToken(
lltok::lparen,
"expected '(' after vector splat"))
4836 if (parseGlobalTypeAndValue(
C))
4838 if (parseToken(
lltok::rparen,
"expected ')' at end of vector splat"))
4850 unsigned Opc = Lex.getUIntVal();
4853 bool HasInRange =
false;
4859 if (
Opc == Instruction::GetElementPtr) {
4875 return tokError(
"expected integer");
4876 InRangeStart = Lex.getAPSIntVal();
4881 return tokError(
"expected integer");
4882 InRangeEnd = Lex.getAPSIntVal();
4890 if (parseToken(
lltok::lparen,
"expected '(' in constantexpr"))
4893 if (
Opc == Instruction::GetElementPtr) {
4894 if (parseType(Ty) ||
4895 parseToken(
lltok::comma,
"expected comma after getelementptr's type"))
4899 if (parseGlobalValueVector(Elts) ||
4903 if (
Opc == Instruction::GetElementPtr) {
4904 if (Elts.
size() == 0 ||
4905 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4906 return error(
ID.Loc,
"base of getelementptr must be a pointer");
4909 std::optional<ConstantRange>
InRange;
4911 unsigned IndexWidth =
4912 M->getDataLayout().getIndexTypeSizeInBits(
BaseType);
4913 InRangeStart = InRangeStart.
extOrTrunc(IndexWidth);
4914 InRangeEnd = InRangeEnd.
extOrTrunc(IndexWidth);
4915 if (InRangeStart.
sge(InRangeEnd))
4916 return error(
ID.Loc,
"expected end to be larger than start");
4926 for (Constant *Val : Indices) {
4929 return error(
ID.Loc,
"getelementptr index must be an integer");
4932 if (GEPWidth && (ValNumEl != GEPWidth))
4935 "getelementptr vector index has a wrong number of elements");
4938 GEPWidth = ValNumEl;
4942 if (!Indices.empty() && !Ty->
isSized())
4943 return error(
ID.Loc,
"base element of getelementptr must be sized");
4946 return error(
ID.Loc,
"invalid base element for constant getelementptr");
4949 return error(
ID.Loc,
"invalid getelementptr indices");
4955 }
else if (
Opc == Instruction::ShuffleVector) {
4956 if (Elts.
size() != 3)
4957 return error(
ID.Loc,
"expected three operands to shufflevector");
4959 return error(
ID.Loc,
"invalid operands to shufflevector");
4960 SmallVector<int, 16>
Mask;
4963 }
else if (
Opc == Instruction::ExtractElement) {
4964 if (Elts.
size() != 2)
4965 return error(
ID.Loc,
"expected two operands to extractelement");
4967 return error(
ID.Loc,
"invalid extractelement operands");
4970 assert(
Opc == Instruction::InsertElement &&
"Unknown opcode");
4971 if (Elts.
size() != 3)
4972 return error(
ID.Loc,
"expected three operands to insertelement");
4974 return error(
ID.Loc,
"invalid insertelement operands");
4989bool LLParser::parseGlobalValue(
Type *Ty, Constant *&
C) {
4993 bool Parsed = parseValID(ID,
nullptr, Ty) ||
4994 convertValIDToValue(Ty, ID,
V,
nullptr);
4996 return error(
ID.Loc,
"global values must be constants");
5000bool LLParser::parseGlobalTypeAndValue(Constant *&
V) {
5002 return parseType(Ty) || parseGlobalValue(Ty,
V);
5005bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&
C) {
5008 LocTy KwLoc = Lex.getLoc();
5014 return tokError(
"expected comdat variable");
5015 C = getComdat(Lex.getStrVal(), Lex.getLoc());
5017 if (parseToken(
lltok::rparen,
"expected ')' after comdat var"))
5020 if (GlobalName.
empty())
5021 return tokError(
"comdat cannot be unnamed");
5022 C = getComdat(std::string(GlobalName), KwLoc);
5031bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
5045 if (parseGlobalTypeAndValue(
C))
5053bool LLParser::parseMDTuple(MDNode *&MD,
bool IsDistinct) {
5055 if (parseMDNodeVector(Elts))
5066bool LLParser::parseMDNode(MDNode *&
N) {
5068 return parseSpecializedMDNode(
N);
5070 return parseToken(
lltok::exclaim,
"expected '!' here") || parseMDNodeTail(
N);
5073bool LLParser::parseMDNodeTail(MDNode *&
N) {
5076 return parseMDTuple(
N);
5079 return parseMDNodeID(
N);
5085template <
class FieldTy>
struct MDFieldImpl {
5086 typedef MDFieldImpl ImplTy;
5090 void assign(FieldTy Val) {
5092 this->Val = std::move(Val);
5095 explicit MDFieldImpl(FieldTy
Default)
5103template <
class FieldTypeA,
class FieldTypeB>
struct MDEitherFieldImpl {
5104 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5117 this->
A = std::move(
A);
5123 this->
B = std::move(
B);
5127 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5129 WhatIs(IsInvalid) {}
5132struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
5139struct LineField :
public MDUnsignedField {
5140 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5143struct ColumnField :
public MDUnsignedField {
5144 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5147struct DwarfTagField :
public MDUnsignedField {
5153struct DwarfMacinfoTypeField :
public MDUnsignedField {
5159struct DwarfAttEncodingField :
public MDUnsignedField {
5160 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
5163struct DwarfVirtualityField :
public MDUnsignedField {
5167struct DwarfLangField :
public MDUnsignedField {
5171struct DwarfSourceLangNameField :
public MDUnsignedField {
5172 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5175struct DwarfLangDialectField :
public MDUnsignedField {
5176 DwarfLangDialectField()
5180struct DwarfCCField :
public MDUnsignedField {
5181 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
5184struct DwarfEnumKindField :
public MDUnsignedField {
5185 DwarfEnumKindField()
5190struct EmissionKindField :
public MDUnsignedField {
5191 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5194struct FixedPointKindField :
public MDUnsignedField {
5195 FixedPointKindField()
5196 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5199struct NameTableKindField :
public MDUnsignedField {
5200 NameTableKindField()
5203 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5206struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
5207 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5210struct DISPFlagField :
public MDFieldImpl<DISubprogram::DISPFlags> {
5211 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5214struct MDAPSIntField :
public MDFieldImpl<APSInt> {
5215 MDAPSIntField() : ImplTy(
APSInt()) {}
5218struct MDSignedField :
public MDFieldImpl<int64_t> {
5222 MDSignedField(int64_t
Default = 0)
5224 MDSignedField(int64_t
Default, int64_t Min, int64_t Max)
5228struct MDBoolField :
public MDFieldImpl<bool> {
5232struct MDField :
public MDFieldImpl<Metadata *> {
5235 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5239struct MDNodeField :
public MDFieldImpl<MDNode *> {
5242 MDNodeField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5245struct MDStringField :
public MDFieldImpl<MDString *> {
5246 enum class EmptyIs {
5251 MDStringField(
enum EmptyIs EmptyIs = EmptyIs::Null)
5252 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5255struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
5259struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
5263struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5264 MDSignedOrMDField(int64_t
Default = 0,
bool AllowNull =
true)
5265 : ImplTy(MDSignedField(
Default), MDField(AllowNull)) {}
5267 MDSignedOrMDField(int64_t
Default, int64_t Min, int64_t Max,
5268 bool AllowNull =
true)
5269 : ImplTy(MDSignedField(
Default, Min,
Max), MDField(AllowNull)) {}
5271 bool isMDSignedField()
const {
return WhatIs == IsTypeA; }
5272 bool isMDField()
const {
return WhatIs == IsTypeB; }
5273 int64_t getMDSignedValue()
const {
5274 assert(isMDSignedField() &&
"Wrong field type");
5277 Metadata *getMDFieldValue()
const {
5278 assert(isMDField() &&
"Wrong field type");
5283struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5285 : ImplTy(MDUnsignedField(
Default), MDField(AllowNull)) {}
5288 : ImplTy(MDUnsignedField(
Default,
Max), MDField(AllowNull)) {}
5290 bool isMDUnsignedField()
const {
return WhatIs == IsTypeA; }
5291 bool isMDField()
const {
return WhatIs == IsTypeB; }
5292 uint64_t getMDUnsignedValue()
const {
5293 assert(isMDUnsignedField() &&
"Wrong field type");
5296 Metadata *getMDFieldValue()
const {
5297 assert(isMDField() &&
"Wrong field type");
5302 if (isMDUnsignedField())
5304 ConstantInt::get(Type::getInt64Ty(
Context), getMDUnsignedValue()));
5306 return getMDFieldValue();
5318 return tokError(
"expected integer");
5320 Result.assign(Lex.getAPSIntVal());
5327 MDUnsignedField &Result) {
5328 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
5329 return tokError(
"expected unsigned integer");
5331 auto &U = Lex.getAPSIntVal();
5332 if (U.ugt(Result.Max))
5333 return tokError(
"value for '" + Name +
"' too large, limit is " +
5335 Result.assign(U.getZExtValue());
5336 assert(Result.Val <= Result.Max &&
"Expected value in range");
5343 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5347 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5353 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5356 return tokError(
"expected DWARF tag");
5360 return tokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.getStrVal() +
"'");
5361 assert(
Tag <= Result.Max &&
"Expected valid DWARF tag");
5370 DwarfMacinfoTypeField &Result) {
5372 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5375 return tokError(
"expected DWARF macinfo type");
5379 return tokError(
"invalid DWARF macinfo type" +
Twine(
" '") +
5380 Lex.getStrVal() +
"'");
5381 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
5383 Result.assign(Macinfo);
5390 DwarfVirtualityField &Result) {
5392 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5395 return tokError(
"expected DWARF virtuality code");
5399 return tokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
5400 Lex.getStrVal() +
"'");
5401 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
5402 Result.assign(Virtuality);
5409 DwarfEnumKindField &Result) {
5411 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5414 return tokError(
"expected DWARF enum kind code");
5418 return tokError(
"invalid DWARF enum kind code" +
Twine(
" '") +
5419 Lex.getStrVal() +
"'");
5420 assert(EnumKind <= Result.Max &&
"Expected valid DWARF enum kind code");
5421 Result.assign(EnumKind);
5429 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5432 return tokError(
"expected DWARF language");
5436 return tokError(
"invalid DWARF language" +
Twine(
" '") + Lex.getStrVal() +
5438 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
5439 Result.assign(Lang);
5446 DwarfSourceLangNameField &Result) {
5448 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5451 return tokError(
"expected DWARF source language name");
5455 return tokError(
"invalid DWARF source language name" +
Twine(
" '") +
5456 Lex.getStrVal() +
"'");
5457 assert(Lang <= Result.Max &&
"Expected valid DWARF source language name");
5458 Result.assign(Lang);
5465 DwarfLangDialectField &Result) {
5470 if (Lex.getAPSIntVal() == 0)
5471 return tokError(
"value for 'dialect' must be a known DWARF language "
5472 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5473 "DW_LLVM_LANG_DIALECT_tile)");
5474 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5478 return tokError(
"expected DWARF language dialect");
5480 StringRef DialectString = Lex.getStrVal();
5485 if (Dialect > Result.Max)
5486 return tokError(
"invalid DWARF language dialect" +
Twine(
" '") +
5487 DialectString +
"'");
5488 Result.assign(Dialect);
5496 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5499 return tokError(
"expected DWARF calling convention");
5503 return tokError(
"invalid DWARF calling convention" +
Twine(
" '") +
5504 Lex.getStrVal() +
"'");
5505 assert(
CC <= Result.Max &&
"Expected valid DWARF calling convention");
5513 EmissionKindField &Result) {
5515 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5518 return tokError(
"expected emission kind");
5522 return tokError(
"invalid emission kind" +
Twine(
" '") + Lex.getStrVal() +
5524 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
5525 Result.assign(*Kind);
5532 FixedPointKindField &Result) {
5534 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5537 return tokError(
"expected fixed-point kind");
5541 return tokError(
"invalid fixed-point kind" +
Twine(
" '") + Lex.getStrVal() +
5543 assert(*Kind <= Result.Max &&
"Expected valid fixed-point kind");
5544 Result.assign(*Kind);
5551 NameTableKindField &Result) {
5553 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5556 return tokError(
"expected nameTable kind");
5560 return tokError(
"invalid nameTable kind" +
Twine(
" '") + Lex.getStrVal() +
5562 assert(((
unsigned)*Kind) <= Result.Max &&
"Expected valid nameTable kind");
5563 Result.assign((
unsigned)*Kind);
5570 DwarfAttEncodingField &Result) {
5572 return parseMDField(
Loc, Name,
static_cast<MDUnsignedField &
>(Result));
5575 return tokError(
"expected DWARF type attribute encoding");
5579 return tokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
5580 Lex.getStrVal() +
"'");
5581 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
5582 Result.assign(Encoding);
5596 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5598 bool Res = parseUInt32(TempVal);
5604 return tokError(
"expected debug info flag");
5608 return tokError(
Twine(
"invalid debug info flag '") + Lex.getStrVal() +
5623 Result.assign(Combined);
5636 if (Lex.getKind() ==
lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5638 bool Res = parseUInt32(TempVal);
5644 return tokError(
"expected debug info flag");
5648 return tokError(
Twine(
"invalid subprogram debug info flag '") +
5649 Lex.getStrVal() +
"'");
5663 Result.assign(Combined);
5670 return tokError(
"expected signed integer");
5672 auto &S = Lex.getAPSIntVal();
5674 return tokError(
"value for '" + Name +
"' too small, limit is " +
5677 return tokError(
"value for '" + Name +
"' too large, limit is " +
5679 Result.assign(S.getExtValue());
5680 assert(Result.Val >= Result.Min &&
"Expected value in range");
5681 assert(Result.Val <= Result.Max &&
"Expected value in range");
5688 switch (Lex.getKind()) {
5690 return tokError(
"expected 'true' or 'false'");
5692 Result.assign(
true);
5695 Result.assign(
false);
5705 if (!Result.AllowNull)
5706 return tokError(
"'" + Name +
"' cannot be null");
5708 Result.assign(
nullptr);
5713 if (parseMDNode(MD))
5723 if (!Result.AllowNull)
5724 return tokError(
"'" + Name +
"' cannot be null");
5726 Result.assign(
nullptr);
5731 if (parseMetadata(MD,
nullptr))
5740 MDSignedOrMDField &Result) {
5743 MDSignedField Res = Result.A;
5744 if (!parseMDField(
Loc, Name, Res)) {
5752 MDField Res = Result.B;
5753 if (!parseMDField(
Loc, Name, Res)) {
5763 MDUnsignedOrMDField &Result) {
5766 MDUnsignedField Res = Result.A;
5767 if (!parseMDField(
Loc, Name, Res)) {
5775 MDField Res = Result.B;
5776 if (!parseMDField(
Loc, Name, Res)) {
5786 LocTy ValueLoc = Lex.getLoc();
5788 if (parseStringConstant(S))
5792 switch (Result.EmptyIs) {
5793 case MDStringField::EmptyIs::Null:
5794 Result.assign(
nullptr);
5796 case MDStringField::EmptyIs::Empty:
5798 case MDStringField::EmptyIs::Error:
5799 return error(ValueLoc,
"'" + Name +
"' cannot be empty");
5810 if (parseMDNodeVector(MDs))
5813 Result.assign(std::move(MDs));
5819 ChecksumKindField &Result) {
5820 std::optional<DIFile::ChecksumKind> CSKind =
5824 return tokError(
"invalid checksum kind" +
Twine(
" '") + Lex.getStrVal() +
5827 Result.assign(*CSKind);
5834template <
class ParserTy>
5835bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5838 return tokError(
"expected field label here");
5847template <
class ParserTy>
5848bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5851 "Expected metadata type name");
5857 if (parseMDFieldsImplBody(ParseField))
5860 ClosingLoc = Lex.getLoc();
5864template <
class FieldTy>
5865bool LLParser::parseMDField(
StringRef Name, FieldTy &Result) {
5867 return tokError(
"field '" + Name +
"' cannot be specified more than once");
5869 LocTy Loc = Lex.getLoc();
5871 return parseMDField(Loc, Name, Result);
5874bool LLParser::parseSpecializedMDNode(
MDNode *&
N,
bool IsDistinct) {
5877#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5878 if (Lex.getStrVal() == #CLASS) \
5879 return parse##CLASS(N, IsDistinct);
5880#include "llvm/IR/Metadata.def"
5882 return tokError(
"expected metadata type");
5885#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5886#define NOP_FIELD(NAME, TYPE, INIT)
5887#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5889 return error(ClosingLoc, "missing required field '" #NAME "'");
5890#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5891 if (Lex.getStrVal() == #NAME) \
5892 return parseMDField(#NAME, NAME);
5893#define PARSE_MD_FIELDS() \
5894 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5897 if (parseMDFieldsImpl( \
5899 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5900 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5905 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5907#define GET_OR_DISTINCT(CLASS, ARGS) \
5908 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5913 return tokError(
"expected !!scope");
5914#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5915 REQUIRED(scope, MDNodeField, ( false));
5917#undef VISIT_MD_FIELDS
5921 FLForwardRefScopes.try_emplace(Context).first->second.emplace_back(
5928bool LLParser::parseFLMDEntry(LocTy
Loc,
FLSrcLoc &Result, uint32_t Index,
5931 return tokError(
"expected !!srcLoc");
5932#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5933 REQUIRED(line, LineField, ); \
5934 OPTIONAL(column, ColumnField, ); \
5935 REQUIRED(scope, MDUnsignedField, (0, UINT16_MAX - 1));
5937#undef VISIT_MD_FIELDS
5938 Result = FLSrcLoc(line.Val, column.Val, scope.Val);
5942bool LLParser::parseFLMDEntry(LocTy
Loc,
FLInlinedCall &Result, uint32_t Index,
5944 if (Lex.getKind() !=
lltok::FLMDType || Lex.getStrVal() !=
"inlinedCall")
5945 return tokError(
"expected !!inlinedCall");
5946#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5947 OPTIONAL(srcLoc, MDUnsignedField, (0, UINT32_MAX - 1)); \
5948 OPTIONAL(inlinedAt, MDUnsignedField, (0, UINT16_MAX - 1)); \
5949 OPTIONAL(uniquable, MDBoolField, (false)); \
5950 REQUIRED(inlineeContext, MDNodeField, ( false));
5952#undef VISIT_MD_FIELDS
5955 FLIndex<FLSrcLoc> ActualSrcLoc;
5957 ActualSrcLoc = FLIndex<FLSrcLoc>(srcLoc.Val);
5958 FLIndex<FLInlinedCall> ActualInlinedAt;
5960 ActualInlinedAt = FLIndex<FLInlinedCall>(inlinedAt.Val);
5961 if (inlineeContext.Val) {
5962 FLForwardRefFLMDs.try_emplace(Context).first->second.emplace_back(
5963 Index, inlineeContext.Val);
5965 Result = FLInlinedCall(ActualSrcLoc, ActualInlinedAt,
nullptr, uniquable.Val);
5969template <
class FLMDTy>
5972 if (parseToken(
lltok::lsquare,
"expected '[' at FLMD storage field"))
5980 uint32_t EntryIndex = 0;
5982 if (parseFLMDEntry(Loc, NextEntry, EntryIndex++, Context))
5984 Result.push_back(NextEntry);
5986 if (parseToken(
lltok::comma,
"expected ',' between FLMD storage entries"))
5991 if (parseFLMDEntry(Loc, NextEntry, EntryIndex++, Context))
5993 Result.push_back(NextEntry);
6002bool LLParser::parseMDFunctionLocalContext(
MDNode *&Result,
bool IsDistinct) {
6004 return tokError(
"missing 'distinct', required for "
6005 "!MDFunctionLocalContext()");
6011 MDBoolField NonDebug(
false);
6012 bool SeenScopes =
false;
6014 bool SeenSrcLocs =
false;
6016 bool SeenInlinedCalls =
false;
6018 auto ParseStorageField = [&](StringRef
Name,
bool &Seen,
auto &Storage) {
6020 return tokError(
"field '" + Name +
6021 "' cannot be specified more than once");
6024 LocTy Loc = Lex.getLoc();
6026 return parseFLMDStorage(Loc, Storage, FLMD);
6029 if (parseMDFieldsImpl(
6031 StringRef
Label = Lex.getStrVal();
6032 if (Label ==
"nonDebug")
6033 return parseMDField(
"nonDebug", NonDebug);
6034 if (Label ==
"scopes")
6035 return ParseStorageField(
"scopes", SeenScopes, ScopesStorage);
6036 if (Label ==
"srcLocs")
6037 return ParseStorageField(
"srcLocs", SeenSrcLocs, SrcLocsStorage);
6038 if (Label ==
"inlinedCalls")
6039 return ParseStorageField(
"inlinedCalls", SeenInlinedCalls,
6040 InlinedCallsStorage);
6041 return tokError(Twine(
"invalid field '") + Label +
"'");
6047 FLMD->setNonDebug(NonDebug.Val);
6048 FLMD->SrcLocs.append(SrcLocsStorage);
6049 FLMD->Scopes.append(ScopesStorage);
6050 FLMD->InlinedCalls.append(InlinedCallsStorage);
6058bool LLParser::parseDILocation(
MDNode *&Result,
bool IsDistinct) {
6059#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6060 OPTIONAL(line, LineField, ); \
6061 OPTIONAL(column, ColumnField, ); \
6062 REQUIRED(scope, MDField, ( false)); \
6063 OPTIONAL(inlinedAt, MDField, ); \
6064 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
6065 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
6066 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX)); \
6067 OPTIONAL(irlayers, MDField, );
6069#undef VISIT_MD_FIELDS
6072 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
6073 inlinedAt.Val, isImplicitCode.Val,
6074 atomGroup.Val, atomRank.Val, irlayers.Val));
6078bool LLParser::parseDILayerLoc(
MDNode *&Result,
bool IsDistinct) {
6079#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6080 OPTIONAL(line, LineField, ); \
6081 OPTIONAL(column, ColumnField, ); \
6082 REQUIRED(file, MDField, ( false)); \
6083 REQUIRED(kind, MDStringField, );
6085#undef VISIT_MD_FIELDS
6088 (Context, kind.Val,
file.Val, line.Val, column.Val));
6092bool LLParser::parseDILayerLocList(
MDNode *&Result,
bool IsDistinct) {
6101 if (parseMetadata(MD,
nullptr))
6114bool LLParser::parseDIAssignID(
MDNode *&Result,
bool IsDistinct) {
6116 return tokError(
"missing 'distinct', required for !DIAssignID()");
6132bool LLParser::parseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
6133#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6134 REQUIRED(tag, DwarfTagField, ); \
6135 OPTIONAL(header, MDStringField, ); \
6136 OPTIONAL(operands, MDFieldList, );
6138#undef VISIT_MD_FIELDS
6141 (Context, tag.Val, header.Val, operands.Val));
6150bool LLParser::parseDISubrangeType(
MDNode *&Result,
bool IsDistinct) {
6151#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6152 OPTIONAL(name, MDStringField, ); \
6153 OPTIONAL(file, MDField, ); \
6154 OPTIONAL(line, LineField, ); \
6155 OPTIONAL(scope, MDField, ); \
6156 OPTIONAL(baseType, MDField, ); \
6157 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6158 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6159 OPTIONAL(flags, DIFlagField, ); \
6160 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6161 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6162 OPTIONAL(stride, MDSignedOrMDField, ); \
6163 OPTIONAL(bias, MDSignedOrMDField, );
6165#undef VISIT_MD_FIELDS
6167 auto convToMetadata = [&](MDSignedOrMDField Bound) ->
Metadata * {
6168 if (Bound.isMDSignedField())
6171 if (Bound.isMDField())
6172 return Bound.getMDFieldValue();
6178 Metadata *Stride = convToMetadata(stride);
6179 Metadata *Bias = convToMetadata(bias);
6182 DISubrangeType, (Context,
name.Val,
file.Val, line.Val, scope.Val,
6183 size.getValueAsMetadata(Context),
align.Val, flags.Val,
6184 baseType.Val, LowerBound, UpperBound, Stride, Bias));
6193bool LLParser::parseDISubrange(
MDNode *&Result,
bool IsDistinct) {
6194#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6195 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
6196 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6197 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6198 OPTIONAL(stride, MDSignedOrMDField, );
6200#undef VISIT_MD_FIELDS
6207 auto convToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
6208 if (Bound.isMDSignedField())
6211 if (Bound.isMDField())
6212 return Bound.getMDFieldValue();
6219 Stride = convToMetadata(stride);
6222 (Context,
Count, LowerBound, UpperBound, Stride));
6230bool LLParser::parseDIGenericSubrange(
MDNode *&Result,
bool IsDistinct) {
6231#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6232 OPTIONAL(count, MDSignedOrMDField, ); \
6233 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6234 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6235 OPTIONAL(stride, MDSignedOrMDField, );
6237#undef VISIT_MD_FIELDS
6239 auto ConvToMetadata = [&](
const MDSignedOrMDField &Bound) ->
Metadata * {
6240 if (Bound.isMDSignedField())
6242 Context, {dwarf::DW_OP_consts,
6243 static_cast<uint64_t>(Bound.getMDSignedValue())});
6244 if (Bound.isMDField())
6245 return Bound.getMDFieldValue();
6252 Metadata *Stride = ConvToMetadata(stride);
6255 (Context,
Count, LowerBound, UpperBound, Stride));
6262bool LLParser::parseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
6263#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6264 REQUIRED(name, MDStringField, ); \
6265 REQUIRED(value, MDAPSIntField, ); \
6266 OPTIONAL(isUnsigned, MDBoolField, (false));
6268#undef VISIT_MD_FIELDS
6270 if (isUnsigned.Val && value.Val.isNegative())
6271 return tokError(
"unsigned enumerator with negative value");
6276 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
6288bool LLParser::parseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
6289#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6290 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6291 OPTIONAL(name, MDStringField, ); \
6292 OPTIONAL(file, MDField, ); \
6293 OPTIONAL(line, LineField, ); \
6294 OPTIONAL(scope, MDField, ); \
6295 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6296 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6297 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
6298 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6299 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6300 OPTIONAL(flags, DIFlagField, );
6302#undef VISIT_MD_FIELDS
6305 DIBasicType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6306 size.getValueAsMetadata(Context),
align.Val, encoding.Val,
6307 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6316bool LLParser::parseDIFixedPointType(
MDNode *&Result,
bool IsDistinct) {
6317#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6318 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6319 OPTIONAL(name, MDStringField, ); \
6320 OPTIONAL(file, MDField, ); \
6321 OPTIONAL(line, LineField, ); \
6322 OPTIONAL(scope, MDField, ); \
6323 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6324 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6325 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6326 OPTIONAL(flags, DIFlagField, ); \
6327 OPTIONAL(kind, FixedPointKindField, ); \
6328 OPTIONAL(factor, MDSignedField, ); \
6329 OPTIONAL(numerator, MDAPSIntField, ); \
6330 OPTIONAL(denominator, MDAPSIntField, );
6332#undef VISIT_MD_FIELDS
6335 (Context, tag.Val,
name.Val,
file.Val, line.Val,
6336 scope.Val,
size.getValueAsMetadata(Context),
6337 align.Val, encoding.Val, flags.Val, kind.Val,
6338 factor.Val, numerator.Val, denominator.Val));
6344bool LLParser::parseDIStringType(
MDNode *&Result,
bool IsDistinct) {
6345#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6346 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6347 OPTIONAL(name, MDStringField, ); \
6348 OPTIONAL(stringLength, MDField, ); \
6349 OPTIONAL(stringLengthExpression, MDField, ); \
6350 OPTIONAL(stringLocationExpression, MDField, ); \
6351 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6352 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6353 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6354 OPTIONAL(charType, MDField, );
6356#undef VISIT_MD_FIELDS
6360 (Context, tag.Val,
name.Val, stringLength.Val, stringLengthExpression.Val,
6361 stringLocationExpression.Val,
size.getValueAsMetadata(Context),
6362 align.Val, encoding.Val, charType.Val));
6375bool LLParser::parseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
6376#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6377 REQUIRED(tag, DwarfTagField, ); \
6378 OPTIONAL(name, MDStringField, ); \
6379 OPTIONAL(file, MDField, ); \
6380 OPTIONAL(line, LineField, ); \
6381 OPTIONAL(scope, MDField, ); \
6382 REQUIRED(baseType, MDField, ); \
6383 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6384 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6385 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6386 OPTIONAL(flags, DIFlagField, ); \
6387 OPTIONAL(extraData, MDField, ); \
6388 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6389 OPTIONAL(annotations, MDField, ); \
6390 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6391 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6392 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6393 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6394 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6396#undef VISIT_MD_FIELDS
6398 std::optional<unsigned> DWARFAddressSpace;
6399 if (dwarfAddressSpace.Val != UINT32_MAX)
6400 DWARFAddressSpace = dwarfAddressSpace.Val;
6401 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6403 PtrAuthData.emplace(
6404 (
unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6405 (
unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6406 ptrAuthAuthenticatesNullValues.Val);
6409 DIDerivedType, (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val,
6410 baseType.Val,
size.getValueAsMetadata(Context),
align.Val,
6411 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6412 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6416bool LLParser::parseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
6417#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6418 REQUIRED(tag, DwarfTagField, ); \
6419 OPTIONAL(name, MDStringField, ); \
6420 OPTIONAL(file, MDField, ); \
6421 OPTIONAL(line, LineField, ); \
6422 OPTIONAL(scope, MDField, ); \
6423 OPTIONAL(baseType, MDField, ); \
6424 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6425 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6426 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6427 OPTIONAL(flags, DIFlagField, ); \
6428 OPTIONAL(elements, MDField, ); \
6429 OPTIONAL(runtimeLang, DwarfLangField, ); \
6430 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6431 OPTIONAL(vtableHolder, MDField, ); \
6432 OPTIONAL(templateParams, MDField, ); \
6433 OPTIONAL(identifier, MDStringField, ); \
6434 OPTIONAL(discriminator, MDField, ); \
6435 OPTIONAL(dataLocation, MDField, ); \
6436 OPTIONAL(associated, MDField, ); \
6437 OPTIONAL(allocated, MDField, ); \
6438 OPTIONAL(rank, MDSignedOrMDField, ); \
6439 OPTIONAL(annotations, MDField, ); \
6440 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6441 OPTIONAL(specification, MDField, ); \
6442 OPTIONAL(bitStride, MDField, );
6444#undef VISIT_MD_FIELDS
6447 if (rank.isMDSignedField())
6450 else if (rank.isMDField())
6451 Rank = rank.getMDFieldValue();
6453 std::optional<unsigned> EnumKind;
6455 EnumKind = enumKind.Val;
6460 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
6461 scope.Val, baseType.Val,
size.getValueAsMetadata(Context),
6462 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6463 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6464 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6465 dataLocation.Val, associated.Val, allocated.Val, Rank,
6466 annotations.Val, bitStride.Val)) {
6475 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
6476 size.getValueAsMetadata(Context),
align.Val,
6477 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6478 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6479 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6480 allocated.Val, Rank, annotations.Val, specification.Val,
6481 num_extra_inhabitants.Val, bitStride.Val));
6485bool LLParser::parseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
6486#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6487 OPTIONAL(flags, DIFlagField, ); \
6488 OPTIONAL(cc, DwarfCCField, ); \
6489 REQUIRED(types, MDField, );
6491#undef VISIT_MD_FIELDS
6494 (Context, flags.Val, cc.Val, types.Val));
6503bool LLParser::parseDIFile(
MDNode *&Result,
bool IsDistinct) {
6507#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6508 REQUIRED(filename, MDStringField, ); \
6509 REQUIRED(directory, MDStringField, ); \
6510 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6511 OPTIONAL(checksum, MDStringField, ); \
6512 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6514#undef VISIT_MD_FIELDS
6516 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6517 if (checksumkind.Seen && checksum.Seen)
6518 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6519 else if (checksumkind.Seen || checksum.Seen)
6520 return tokError(
"'checksumkind' and 'checksum' must be provided together");
6522 MDString *
Source =
nullptr;
6526 DIFile, (Context,
filename.Val, directory.Val, OptChecksum, Source));
6538bool LLParser::parseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
6540 return tokError(
"missing 'distinct', required for !DICompileUnit");
6542 LocTy Loc = Lex.getLoc();
6544#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6545 REQUIRED(file, MDField, ( false)); \
6546 OPTIONAL(language, DwarfLangField, ); \
6547 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6548 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6549 OPTIONAL(producer, MDStringField, ); \
6550 OPTIONAL(isOptimized, MDBoolField, ); \
6551 OPTIONAL(flags, MDStringField, ); \
6552 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6553 OPTIONAL(splitDebugFilename, MDStringField, ); \
6554 OPTIONAL(emissionKind, EmissionKindField, ); \
6555 OPTIONAL(enums, MDField, ); \
6556 OPTIONAL(retainedTypes, MDField, ); \
6557 OPTIONAL(globals, MDField, ); \
6558 OPTIONAL(imports, MDField, ); \
6559 OPTIONAL(macros, MDField, ); \
6560 OPTIONAL(dwoId, MDUnsignedField, ); \
6561 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6562 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6563 OPTIONAL(nameTableKind, NameTableKindField, ); \
6564 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6565 OPTIONAL(sysroot, MDStringField, ); \
6566 OPTIONAL(sdk, MDStringField, ); \
6567 OPTIONAL(dialect, DwarfLangDialectField, );
6569#undef VISIT_MD_FIELDS
6571 if (!language.Seen && !sourceLanguageName.Seen)
6572 return error(Loc,
"missing one of 'language' or 'sourceLanguageName', "
6573 "required for !DICompileUnit");
6575 if (language.Seen && sourceLanguageName.Seen)
6576 return error(Loc,
"can only specify one of 'language' and "
6577 "'sourceLanguageName' on !DICompileUnit");
6579 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6580 return error(Loc,
"'sourceLanguageVersion' requires an associated "
6581 "'sourceLanguageName' on !DICompileUnit");
6583 uint16_t Dialect =
static_cast<uint16_t
>(dialect.Val);
6586 ? DISourceLanguageName(
static_cast<uint16_t
>(language.Val), Dialect)
6587 : DISourceLanguageName(
6588 static_cast<uint16_t>(sourceLanguageName.Val),
6589 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6592 Context, SourceLanguage,
file.Val, producer.Val, isOptimized.Val,
6593 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6594 enums.Val, retainedTypes.Val,
globals.Val, imports.Val, macros.Val,
6595 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6596 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6609bool LLParser::parseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
6610 auto Loc = Lex.getLoc();
6611#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6612 OPTIONAL(scope, MDField, ); \
6613 OPTIONAL(name, MDStringField, ); \
6614 OPTIONAL(linkageName, MDStringField, ); \
6615 OPTIONAL(file, MDField, ); \
6616 OPTIONAL(line, LineField, ); \
6617 REQUIRED(type, MDField, ( false)); \
6618 OPTIONAL(isLocal, MDBoolField, ); \
6619 OPTIONAL(isDefinition, MDBoolField, (true)); \
6620 OPTIONAL(scopeLine, LineField, ); \
6621 OPTIONAL(containingType, MDField, ); \
6622 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6623 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6624 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6625 OPTIONAL(flags, DIFlagField, ); \
6626 OPTIONAL(spFlags, DISPFlagField, ); \
6627 OPTIONAL(isOptimized, MDBoolField, ); \
6628 OPTIONAL(unit, MDField, ); \
6629 OPTIONAL(templateParams, MDField, ); \
6630 OPTIONAL(declaration, MDField, ); \
6631 OPTIONAL(retainedNodes, MDField, ); \
6632 OPTIONAL(thrownTypes, MDField, ); \
6633 OPTIONAL(annotations, MDField, ); \
6634 OPTIONAL(targetFuncName, MDStringField, ); \
6635 OPTIONAL(keyInstructions, MDBoolField, );
6637#undef VISIT_MD_FIELDS
6642 spFlags.Seen ? spFlags.Val
6644 isOptimized.Val, virtuality.Val);
6645 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6648 "missing 'distinct', required for !DISubprogram that is a Definition");
6651 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val, line.Val,
6652 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6653 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6654 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6655 targetFuncName.Val, keyInstructions.Val));
6665bool LLParser::parseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
6666#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6667 REQUIRED(scope, MDField, ( false)); \
6668 OPTIONAL(file, MDField, ); \
6669 OPTIONAL(line, LineField, ); \
6670 OPTIONAL(column, ColumnField, );
6672#undef VISIT_MD_FIELDS
6675 DILexicalBlock, (Context, scope.Val,
file.Val, line.Val, column.Val));
6681bool LLParser::parseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
6682#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6683 REQUIRED(scope, MDField, ( false)); \
6684 OPTIONAL(file, MDField, ); \
6685 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6687#undef VISIT_MD_FIELDS
6690 (Context, scope.Val,
file.Val, discriminator.Val));
6696bool LLParser::parseDICommonBlock(
MDNode *&Result,
bool IsDistinct) {
6697#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6698 REQUIRED(scope, MDField, ); \
6699 OPTIONAL(declaration, MDField, ); \
6700 OPTIONAL(name, MDStringField, ); \
6701 OPTIONAL(file, MDField, ); \
6702 OPTIONAL(line, LineField, );
6704#undef VISIT_MD_FIELDS
6707 (Context, scope.Val, declaration.Val,
name.Val,
6708 file.Val, line.Val));
6714bool LLParser::parseDINamespace(
MDNode *&Result,
bool IsDistinct) {
6715#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6716 REQUIRED(scope, MDField, ); \
6717 OPTIONAL(name, MDStringField, ); \
6718 OPTIONAL(exportSymbols, MDBoolField, );
6720#undef VISIT_MD_FIELDS
6723 (Context, scope.Val,
name.Val, exportSymbols.Val));
6730bool LLParser::parseDIMacro(
MDNode *&Result,
bool IsDistinct) {
6731#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6732 REQUIRED(type, DwarfMacinfoTypeField, ); \
6733 OPTIONAL(line, LineField, ); \
6734 REQUIRED(name, MDStringField, ); \
6735 OPTIONAL(value, MDStringField, );
6737#undef VISIT_MD_FIELDS
6740 (Context, type.Val, line.Val,
name.Val, value.Val));
6746bool LLParser::parseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
6747#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6748 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6749 OPTIONAL(line, LineField, ); \
6750 REQUIRED(file, MDField, ); \
6751 OPTIONAL(nodes, MDField, );
6753#undef VISIT_MD_FIELDS
6756 (Context, type.Val, line.Val,
file.Val,
nodes.Val));
6764bool LLParser::parseDIModule(
MDNode *&Result,
bool IsDistinct) {
6765#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6766 REQUIRED(scope, MDField, ); \
6767 REQUIRED(name, MDStringField, ); \
6768 OPTIONAL(configMacros, MDStringField, ); \
6769 OPTIONAL(includePath, MDStringField, ); \
6770 OPTIONAL(apinotes, MDStringField, ); \
6771 OPTIONAL(file, MDField, ); \
6772 OPTIONAL(line, LineField, ); \
6773 OPTIONAL(isDecl, MDBoolField, );
6775#undef VISIT_MD_FIELDS
6778 configMacros.Val, includePath.Val,
6779 apinotes.Val, line.Val, isDecl.Val));
6785bool LLParser::parseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
6786#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6787 OPTIONAL(name, MDStringField, ); \
6788 REQUIRED(type, MDField, ); \
6789 OPTIONAL(defaulted, MDBoolField, );
6791#undef VISIT_MD_FIELDS
6794 (Context,
name.Val, type.Val, defaulted.Val));
6802bool LLParser::parseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
6803#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6804 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6805 OPTIONAL(name, MDStringField, ); \
6806 OPTIONAL(type, MDField, ); \
6807 OPTIONAL(defaulted, MDBoolField, ); \
6808 REQUIRED(value, MDField, );
6811#undef VISIT_MD_FIELDS
6814 DITemplateValueParameter,
6815 (Context, tag.Val,
name.Val, type.Val, defaulted.Val, value.Val));
6824bool LLParser::parseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
6825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6826 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6827 OPTIONAL(scope, MDField, ); \
6828 OPTIONAL(linkageName, MDStringField, ); \
6829 OPTIONAL(file, MDField, ); \
6830 OPTIONAL(line, LineField, ); \
6831 OPTIONAL(type, MDField, ); \
6832 OPTIONAL(isLocal, MDBoolField, ); \
6833 OPTIONAL(isDefinition, MDBoolField, (true)); \
6834 OPTIONAL(templateParams, MDField, ); \
6835 OPTIONAL(declaration, MDField, ); \
6836 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6837 OPTIONAL(annotations, MDField, );
6839#undef VISIT_MD_FIELDS
6843 (Context, scope.Val,
name.Val, linkageName.Val,
file.Val,
6844 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6845 declaration.Val, templateParams.Val,
align.Val,
6857bool LLParser::parseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
6858#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6859 REQUIRED(scope, MDField, ( false)); \
6860 OPTIONAL(name, MDStringField, ); \
6861 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6862 OPTIONAL(file, MDField, ); \
6863 OPTIONAL(line, LineField, ); \
6864 OPTIONAL(type, MDField, ); \
6865 OPTIONAL(flags, DIFlagField, ); \
6866 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6867 OPTIONAL(annotations, MDField, );
6869#undef VISIT_MD_FIELDS
6872 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6873 type.Val, arg.Val, flags.Val,
align.Val,
6880bool LLParser::parseDILabel(
MDNode *&Result,
bool IsDistinct) {
6881#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6882 REQUIRED(scope, MDField, ( false)); \
6883 REQUIRED(name, MDStringField, ); \
6884 REQUIRED(file, MDField, ); \
6885 REQUIRED(line, LineField, ); \
6886 OPTIONAL(column, ColumnField, ); \
6887 OPTIONAL(isArtificial, MDBoolField, ); \
6888 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6890#undef VISIT_MD_FIELDS
6892 std::optional<unsigned> CoroSuspendIdx =
6893 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6897 (Context, scope.Val,
name.Val,
file.Val, line.Val,
6898 column.Val, isArtificial.Val, CoroSuspendIdx));
6904bool LLParser::parseDIExpressionBody(
MDNode *&Result,
bool IsDistinct) {
6917 return tokError(Twine(
"invalid DWARF op '") + Lex.getStrVal() +
"'");
6926 return tokError(Twine(
"invalid DWARF attribute encoding '") +
6927 Lex.getStrVal() +
"'");
6930 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
6931 return tokError(
"expected unsigned integer");
6933 auto &
U = Lex.getAPSIntVal();
6935 return tokError(
"element too large, limit is " + Twine(
UINT64_MAX));
6949bool LLParser::parseDIExpression(
MDNode *&Result,
bool IsDistinct) {
6951 assert(Lex.getStrVal() ==
"DIExpression" &&
"Expected '!DIExpression'");
6954 return parseDIExpressionBody(Result, IsDistinct);
6959bool LLParser::parseDIArgList(
Metadata *&MD, PerFunctionState *PFS) {
6960 assert(PFS &&
"Expected valid function state");
6971 if (parseValueAsMetadata(MD,
"expected value-as-metadata operand", PFS))
6985bool LLParser::parseDIGlobalVariableExpression(
MDNode *&Result,
6987#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6988 REQUIRED(var, MDField, ); \
6989 REQUIRED(expr, MDField, );
6991#undef VISIT_MD_FIELDS
6994 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
7001bool LLParser::parseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
7002#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
7003 OPTIONAL(name, MDStringField, ); \
7004 OPTIONAL(file, MDField, ); \
7005 OPTIONAL(line, LineField, ); \
7006 OPTIONAL(setter, MDStringField, ); \
7007 OPTIONAL(getter, MDStringField, ); \
7008 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
7009 OPTIONAL(type, MDField, );
7011#undef VISIT_MD_FIELDS
7014 (Context,
name.Val,
file.Val, line.Val, getter.Val,
7015 setter.Val, attributes.Val, type.Val));
7022bool LLParser::parseDIProperty(
MDNode *&Result,
bool IsDistinct) {
7023#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
7024 OPTIONAL(name, MDStringField, ); \
7025 OPTIONAL(file, MDField, ); \
7026 OPTIONAL(line, LineField, ); \
7027 OPTIONAL(type, MDField, ); \
7028 OPTIONAL(backing_storage, MDField, );
7030#undef VISIT_MD_FIELDS
7033 type.Val, backing_storage.Val));
7040bool LLParser::parseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
7041#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
7042 REQUIRED(tag, DwarfTagField, ); \
7043 REQUIRED(scope, MDField, ); \
7044 OPTIONAL(entity, MDField, ); \
7045 OPTIONAL(file, MDField, ); \
7046 OPTIONAL(line, LineField, ); \
7047 OPTIONAL(name, MDStringField, ); \
7048 OPTIONAL(elements, MDField, );
7050#undef VISIT_MD_FIELDS
7053 (Context, tag.Val, scope.Val, entity.Val,
file.Val,
7054 line.Val,
name.Val, elements.Val));
7058#undef PARSE_MD_FIELD
7070bool LLParser::parseMetadataAsValue(
Value *&
V, PerFunctionState &PFS) {
7073 if (parseMetadata(MD, &PFS))
7084bool LLParser::parseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
7085 PerFunctionState *PFS) {
7088 if (parseType(Ty, TypeMsg, Loc))
7091 return error(Loc,
"invalid metadata-value-metadata roundtrip");
7094 if (parseValue(Ty,
V, PFS))
7109bool LLParser::parseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
7113 if (Lex.getStrVal() ==
"DIArgList") {
7115 if (parseDIArgList(AL, PFS))
7121 if (parseSpecializedMDNode(
N)) {
7131 return parseValueAsMetadata(MD,
"expected metadata operand", PFS);
7141 if (parseMDString(S))
7151 if (parseMDNodeTail(
N))
7162 PerFunctionState *PFS) {
7164 return error(
ID.Loc,
"functions are not values, refer to them as pointers");
7169 return error(
ID.Loc,
"invalid use of function-local name");
7170 V = PFS->getVal(
ID.UIntVal, Ty,
ID.Loc);
7171 return V ==
nullptr;
7174 return error(
ID.Loc,
"invalid use of function-local name");
7175 V = PFS->getVal(
ID.StrVal, Ty,
ID.Loc);
7176 return V ==
nullptr;
7179 return error(
ID.Loc,
"invalid type for inline asm constraint string");
7183 ID.FTy,
ID.StrVal,
ID.StrVal2,
ID.UIntVal & 1, (
ID.UIntVal >> 1) & 1,
7188 V = getGlobalVal(
ID.StrVal, Ty,
ID.Loc);
7191 return V ==
nullptr;
7193 V = getGlobalVal(
ID.UIntVal, Ty,
ID.Loc);
7196 return V ==
nullptr;
7199 return error(
ID.Loc,
"integer/byte constant must have integer/byte type");
7202 :
V = ConstantByte::
get(Context,
ID.APSIntVal);
7207 return error(
ID.Loc,
"floating point constant invalid for type");
7213 bool IsSNAN = ID.APFloatVal.isSignaling();
7216 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
7218 else if (Ty->isBFloatTy())
7219 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
7221 else if (Ty->isFloatTy())
7222 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
7228 APInt Payload = ID.APFloatVal.bitcastToAPInt();
7229 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
7230 ID.APFloatVal.isNegative(), &Payload);
7233 V = ConstantFP::get(Context,
ID.APFloatVal);
7235 if (
V->getType() != Ty)
7236 return error(
ID.Loc,
"floating point constant does not have type '" +
7242 return error(
ID.Loc,
"null must be a pointer type");
7248 return error(
ID.Loc,
"invalid type for undef constant");
7253 return error(
ID.Loc,
"invalid empty array initializer");
7259 return error(
ID.Loc,
"invalid type for null constant");
7262 return error(
ID.Loc,
"invalid type for null constant");
7267 return error(
ID.Loc,
"invalid type for none constant");
7273 return error(
ID.Loc,
"invalid type for poison constant");
7277 if (
ID.ConstantVal->getType() != Ty)
7278 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7285 return error(
ID.Loc,
"vector constant must have vector type");
7287 return error(
ID.Loc,
"constant expression type mismatch: got type '" +
7289 "' but expected '" +
7297 if (
ST->getNumElements() !=
ID.UIntVal)
7299 "initializer with struct type has wrong # elements");
7301 return error(
ID.Loc,
"packed'ness of initializer and type don't match");
7304 for (
unsigned i = 0, e =
ID.UIntVal; i != e; ++i)
7305 if (
ID.ConstantStructElts[i]->getType() !=
ST->getElementType(i))
7308 "element " + Twine(i) +
7309 " of struct initializer doesn't match struct element type");
7312 ST,
ArrayRef(
ID.ConstantStructElts.get(),
ID.UIntVal));
7314 return error(
ID.Loc,
"constant expression type mismatch");
7323 auto Loc = Lex.getLoc();
7324 if (parseValID(ID,
nullptr, Ty))
7337 if (convertValIDToValue(Ty, ID,
V,
nullptr))
7347 return error(Loc,
"expected a constant value");
7351bool LLParser::parseValue(
Type *Ty,
Value *&
V, PerFunctionState *PFS) {
7355 FileLoc
Start = getTokLineColumnPos();
7356 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID,
V, PFS);
7357 if (!Ret && ParserContext) {
7358 FileLoc
End = getPrevTokEndLineColumnPos();
7359 ParserContext->addValueReferenceAtLocation(
V, FileLocRange(Start,
End));
7364bool LLParser::parseTypeAndValue(
Value *&
V, PerFunctionState *PFS) {
7366 return parseType(Ty) || parseValue(Ty,
V, PFS);
7369bool LLParser::parseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &
Loc,
7370 PerFunctionState &PFS) {
7373 if (parseTypeAndValue(
V, PFS))
7376 return error(Loc,
"expected a basic block");
7385 if (!Name.starts_with(
"llvm.dbg."))
7388 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7389 FnID == Intrinsic::dbg_assign;
7397bool LLParser::parseFunctionHeader(
Function *&Fn,
bool IsDefine,
7398 unsigned &FunctionNumber,
7401 LocTy LinkageLoc = Lex.getLoc();
7403 unsigned Visibility;
7404 unsigned DLLStorageClass;
7406 AttrBuilder RetAttrs(M->getContext());
7409 Type *RetType =
nullptr;
7410 LocTy RetTypeLoc = Lex.getLoc();
7411 if (parseOptionalLinkage(
Linkage, HasLinkage, Visibility, DLLStorageClass,
7413 parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
7414 parseType(RetType, RetTypeLoc,
true ))
7423 return error(LinkageLoc,
"invalid linkage for function definition");
7433 return error(LinkageLoc,
"invalid linkage for function declaration");
7437 return error(LinkageLoc,
"invalid function linkage type");
7441 return error(LinkageLoc,
7442 "symbol with local linkage must have default visibility");
7445 return error(LinkageLoc,
7446 "symbol with local linkage cannot have a DLL storage class");
7449 return error(RetTypeLoc,
"invalid function return type");
7451 LocTy NameLoc = Lex.getLoc();
7453 std::string FunctionName;
7455 FunctionName = Lex.getStrVal();
7457 FunctionNumber = Lex.getUIntVal();
7458 if (checkValueID(NameLoc,
"function",
"@", NumberedVals.getNext(),
7462 return tokError(
"expected function name");
7468 return tokError(
"expected '(' in function argument list");
7472 AttrBuilder FuncAttrs(M->getContext());
7473 std::vector<unsigned> FwdRefAttrGrps;
7476 std::string Partition;
7480 unsigned AddrSpace = 0;
7486 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7487 parseOptionalUnnamedAddr(UnnamedAddr) ||
7488 parseOptionalProgramAddrSpace(AddrSpace) ||
7489 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
7493 parseOptionalComdat(FunctionName,
C) ||
7494 parseOptionalAlignment(Alignment) ||
7495 parseOptionalPrefAlignment(PrefAlignment) ||
7496 (EatIfPresent(
lltok::kw_gc) && parseStringConstant(GC)) ||
7500 parseGlobalTypeAndValue(PersonalityFn)))
7503 if (FuncAttrs.contains(Attribute::Builtin))
7504 return error(BuiltinLoc,
"'builtin' attribute not valid on function");
7507 if (MaybeAlign
A = FuncAttrs.getAlignment()) {
7509 FuncAttrs.removeAttribute(Attribute::Alignment);
7514 std::vector<Type*> ParamTypeList;
7517 for (
const ArgInfo &Arg : ArgList) {
7518 ParamTypeList.push_back(Arg.Ty);
7519 Attrs.push_back(Arg.Attrs);
7526 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->
isVoidTy())
7527 return error(RetTypeLoc,
"functions with 'sret' argument must return void");
7533 GlobalValue *FwdFn =
nullptr;
7534 if (!FunctionName.empty()) {
7537 auto FRVI = ForwardRefVals.find(FunctionName);
7538 if (FRVI != ForwardRefVals.end()) {
7539 FwdFn = FRVI->second.first;
7541 return error(FRVI->second.second,
7542 "invalid forward reference to "
7545 "' with wrong type: "
7549 ForwardRefVals.erase(FRVI);
7550 }
else if ((Fn = M->getFunction(FunctionName))) {
7552 return error(NameLoc,
7553 "invalid redefinition of function '" + FunctionName +
"'");
7554 }
else if (M->getNamedValue(FunctionName)) {
7555 return error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
7561 if (FunctionNumber == (
unsigned)-1)
7562 FunctionNumber = NumberedVals.getNext();
7566 auto I = ForwardRefValIDs.find(FunctionNumber);
7567 if (
I != ForwardRefValIDs.end()) {
7568 FwdFn =
I->second.first;
7570 return error(NameLoc,
"type of definition and forward reference of '@" +
7571 Twine(FunctionNumber) +
7576 ForwardRefValIDs.erase(
I);
7585 if (FunctionName.empty())
7586 NumberedVals.add(FunctionNumber, Fn);
7602 if (!
GC.empty()) Fn->
setGC(GC);
7605 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7609 for (
unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7610 if (ParserContext && ArgList[i].IdentLoc)
7611 ParserContext->addInstructionOrArgumentLocation(
7612 &*ArgIt, ArgList[i].IdentLoc.value());
7614 if (ArgList[i].
Name.empty())
continue;
7617 ArgIt->
setName(ArgList[i].Name);
7619 if (ArgIt->
getName() != ArgList[i].Name)
7620 return error(ArgList[i].Loc,
7621 "redefinition of argument '%" + ArgList[i].Name +
"'");
7634 if (FunctionName.empty()) {
7636 ID.UIntVal = FunctionNumber;
7639 ID.StrVal = FunctionName;
7641 auto Blocks = ForwardRefBlockAddresses.find(ID);
7642 if (Blocks != ForwardRefBlockAddresses.end())
7643 return error(Blocks->first.Loc,
7644 "cannot take blockaddress inside a declaration");
7648bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7650 if (FunctionNumber == -1) {
7652 ID.StrVal = std::string(F.getName());
7655 ID.UIntVal = FunctionNumber;
7658 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7659 if (Blocks == P.ForwardRefBlockAddresses.end())
7662 for (
const auto &
I : Blocks->second) {
7663 const ValID &BBID =
I.first;
7664 GlobalValue *GV =
I.second;
7667 "Expected local id or name");
7674 return P.error(BBID.
Loc,
"referenced value is not a basic block");
7677 ResolvedVal = P.checkValidVariableType(BBID.
Loc, BBID.
StrVal, GV->
getType(),
7685 P.ForwardRefBlockAddresses.erase(Blocks);
7691bool LLParser::parseFunctionBody(
Function &Fn,
unsigned FunctionNumber,
7692 ArrayRef<unsigned> UnnamedArgNums) {
7694 return tokError(
"expected '{' in function body");
7697 PerFunctionState PFS(*
this, Fn, FunctionNumber, UnnamedArgNums);
7701 if (PFS.resolveForwardRefBlockAddresses())
7707 return tokError(
"function body requires at least one basic block");
7711 if (parseBasicBlock(PFS))
7715 if (parseUseListOrder(&PFS))
7722 return PFS.finishFunction();
7727bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7728 FileLoc BBStart = getTokLineColumnPos();
7733 LocTy NameLoc = Lex.getLoc();
7735 Name = Lex.getStrVal();
7738 NameID = Lex.getUIntVal();
7742 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7746 std::string NameStr;
7751 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7752 using DbgRecordPtr = std::unique_ptr<DbgRecord,
decltype(DeleteDbgRecord)>;
7759 if (SeenOldDbgInfoFormat)
7760 return error(Lex.getLoc(),
"debug record should not appear in a module "
7761 "containing debug info intrinsics");
7762 SeenNewDbgInfoFormat =
true;
7766 if (parseDebugRecord(DR, PFS))
7768 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7771 FileLoc InstStart = getTokLineColumnPos();
7774 LocTy NameLoc = Lex.getLoc();
7779 NameID = Lex.getUIntVal();
7781 if (parseToken(
lltok::equal,
"expected '=' after instruction id"))
7784 NameStr = Lex.getStrVal();
7786 if (parseToken(
lltok::equal,
"expected '=' after instruction name"))
7790 switch (parseInstruction(Inst, BB, PFS)) {
7793 case InstError:
return true;
7800 if (parseInstructionMetadata(*Inst))
7803 case InstExtraComma:
7808 if (parseInstructionMetadata(*Inst))
7814 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7818 for (DbgRecordPtr &DR : TrailingDbgRecord)
7820 TrailingDbgRecord.clear();
7821 if (ParserContext) {
7822 ParserContext->addInstructionOrArgumentLocation(
7823 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7828 ParserContext->addBlockLocation(
7829 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7831 assert(TrailingDbgRecord.empty() &&
7832 "All debug values should have been attached to an instruction.");
7841bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7844 LocTy DVRLoc = Lex.getLoc();
7846 return error(DVRLoc,
"expected debug record type here");
7847 RecordKind
RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7848 .Case(
"declare", RecordKind::ValueKind)
7849 .Case(
"value", RecordKind::ValueKind)
7850 .Case(
"assign", RecordKind::ValueKind)
7851 .Case(
"label", RecordKind::LabelKind)
7852 .Case(
"declare_value", RecordKind::ValueKind);
7861 if (parseMDNode(Label))
7866 if (parseMDNode(DbgLoc))
7871 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7875 LocType
ValueType = StringSwitch<LocType>(Lex.getStrVal())
7876 .Case(
"declare", LocType::Declare)
7877 .Case(
"value", LocType::Value)
7878 .Case(
"assign", LocType::Assign)
7879 .Case(
"declare_value", LocType::DeclareValue);
7887 if (parseMetadata(ValLocMD, &PFS))
7894 if (parseMDNode(Variable))
7901 if (parseMDNode(Expression))
7907 MDNode *AssignID =
nullptr;
7908 Metadata *AddressLocation =
nullptr;
7909 MDNode *AddressExpression =
nullptr;
7912 if (parseMDNode(AssignID))
7918 if (parseMetadata(AddressLocation, &PFS))
7924 if (parseMDNode(AddressExpression))
7938 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7940 PendingDbgRecords.emplace_back(DVRLoc, DR,
DebugLoc);
7949int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7950 PerFunctionState &PFS) {
7953 return tokError(
"found end of file when expecting more instructions");
7954 LocTy Loc = Lex.getLoc();
7955 unsigned KeywordVal = Lex.getUIntVal();
7960 return error(Loc,
"expected instruction opcode");
7964 return parseRet(Inst, BB, PFS);
7966 return parseBr(Inst, PFS);
7968 return parseSwitch(Inst, PFS);
7970 return parseIndirectBr(Inst, PFS);
7972 return parseInvoke(Inst, PFS);
7974 return parseResume(Inst, PFS);
7976 return parseCleanupRet(Inst, PFS);
7978 return parseCatchRet(Inst, PFS);
7980 return parseCatchSwitch(Inst, PFS);
7982 return parseCatchPad(Inst, PFS);
7984 return parseCleanupPad(Inst, PFS);
7986 return parseCallBr(Inst, PFS);
7989 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7990 int Res = parseUnaryOp(Inst, PFS, KeywordVal,
true);
8006 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
8018 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8019 int Res = parseArithmetic(Inst, PFS, KeywordVal,
true);
8033 if (parseArithmetic(Inst, PFS, KeywordVal,
false))
8041 return parseArithmetic(Inst, PFS, KeywordVal,
8045 if (parseLogical(Inst, PFS, KeywordVal))
8053 return parseLogical(Inst, PFS, KeywordVal);
8056 if (parseCompare(Inst, PFS, KeywordVal))
8063 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8064 int Res = parseCompare(Inst, PFS, KeywordVal);
8074 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8076 bool Res = parseCast(Inst, PFS, KeywordVal);
8086 bool Res = parseCast(Inst, PFS, KeywordVal);
8098 if (parseCast(Inst, PFS, KeywordVal))
8107 bool NonNull = EatIfPresent(lltok::kw_nonnull);
8108 if (parseCast(Inst, PFS, KeywordVal))
8121 return parseCast(Inst, PFS, KeywordVal);
8125 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8126 if (parseCast(Inst, PFS, KeywordVal))
8135 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8136 int Res = parseSelect(Inst, PFS);
8142 return error(Loc,
"fast-math-flags specified for select without "
8143 "floating-point scalar or vector return type");
8150 return parseVAArg(Inst, PFS);
8152 return parseExtractElement(Inst, PFS);
8154 return parseInsertElement(Inst, PFS);
8156 return parseShuffleVector(Inst, PFS);
8158 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8159 int Res = parsePHI(Inst, PFS);
8165 return error(Loc,
"fast-math-flags specified for phi without "
8166 "floating-point scalar or vector return type");
8173 return parseLandingPad(Inst, PFS);
8175 return parseFreeze(Inst, PFS);
8177 return parseBitInsert(Inst, PFS);
8179 return parseBitExtract(Inst, PFS);
8191 return parseAlloc(Inst, PFS);
8193 return parseLoad(Inst, PFS);
8195 return parseStore(Inst, PFS);
8197 return parseCmpXchg(Inst, PFS);
8199 return parseAtomicRMW(Inst, PFS);
8201 return parseFence(Inst, PFS);
8203 return parseGetElementPtr(Inst, PFS);
8205 return parseExtractValue(Inst, PFS);
8207 return parseInsertValue(Inst, PFS);
8212bool LLParser::parseCmpPredicate(
unsigned &
P,
unsigned Opc) {
8213 if (
Opc == Instruction::FCmp) {
8214 switch (Lex.getKind()) {
8216 return tokError(
"expected fcmp predicate (e.g. 'oeq')");
8235 switch (Lex.getKind()) {
8237 return tokError(
"expected icmp predicate (e.g. 'eq')");
8261bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
8262 PerFunctionState &PFS) {
8263 SMLoc TypeLoc = Lex.getLoc();
8265 if (parseType(Ty,
true ))
8268 Type *ResType = PFS.getFunction().getReturnType();
8272 return error(TypeLoc,
"value doesn't match function result type '" +
8280 if (parseValue(Ty, RV, PFS))
8284 return error(TypeLoc,
"value doesn't match function result type '" +
8294bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
8298 if (parseTypeAndValue(Op0, Loc, PFS))
8307 return error(Loc,
"branch condition must have 'i1' type");
8309 if (parseToken(
lltok::comma,
"expected ',' after branch condition") ||
8310 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
8311 parseToken(
lltok::comma,
"expected ',' after true destination") ||
8312 parseTypeAndBasicBlock(Op2, Loc2, PFS))
8324bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8325 LocTy CondLoc, BBLoc;
8328 if (parseTypeAndValue(
Cond, CondLoc, PFS) ||
8329 parseToken(
lltok::comma,
"expected ',' after switch condition") ||
8330 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8334 if (!
Cond->getType()->isIntegerTy())
8335 return error(CondLoc,
"switch condition must have integer type");
8338 SmallPtrSet<Value*, 32> SeenCases;
8344 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8345 parseToken(
lltok::comma,
"expected ',' after case value") ||
8346 parseTypeAndBasicBlock(DestBB, PFS))
8349 if (!SeenCases.
insert(Constant).second)
8350 return error(CondLoc,
"duplicate case value in switch");
8352 return error(CondLoc,
"case value is not a constant integer");
8360 for (
const auto &[OnVal, Dest] :
Table)
8361 SI->addCase(OnVal, Dest);
8369bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8372 if (parseTypeAndValue(
Address, AddrLoc, PFS) ||
8373 parseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
8377 if (!
Address->getType()->isPointerTy())
8378 return error(AddrLoc,
"indirectbr address must have pointer type");
8381 SmallVector<BasicBlock*, 16> DestList;
8385 if (parseTypeAndBasicBlock(DestBB, PFS))
8390 if (parseTypeAndBasicBlock(DestBB, PFS))
8396 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8400 for (BasicBlock *Dest : DestList)
8410 FunctionType *&FuncTy) {
8416 for (
const ParamInfo &Arg : ArgList)
8430bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8431 LocTy CallLoc = Lex.getLoc();
8432 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8433 std::vector<unsigned> FwdRefAttrGrps;
8436 unsigned InvokeAddrSpace;
8437 Type *RetType =
nullptr;
8444 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
8445 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8446 parseType(RetType, RetTypeLoc,
true ) ||
8447 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8448 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8450 parseOptionalOperandBundles(BundleList, PFS) ||
8452 parseTypeAndBasicBlock(NormalBB, PFS) ||
8454 parseTypeAndBasicBlock(UnwindBB, PFS))
8461 if (resolveFunctionType(RetType, ArgList, Ty))
8462 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8468 if (convertValIDToValue(
PointerType::get(Context, InvokeAddrSpace), CalleeID,
8473 SmallVector<Value *, 8>
Args;
8480 for (
const ParamInfo &Arg : ArgList) {
8481 Type *ExpectedTy =
nullptr;
8484 }
else if (!Ty->isVarArg()) {
8485 return error(Arg.Loc,
"too many arguments specified");
8488 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8489 return error(Arg.Loc,
"argument is not of expected type '" +
8491 Args.push_back(Arg.V);
8496 return error(CallLoc,
"not enough parameters specified for call");
8505 II->setCallingConv(
CC);
8506 II->setAttributes(PAL);
8507 ForwardRefAttrGroups[
II] = FwdRefAttrGrps;
8514bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8516 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8524bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8525 PerFunctionState &PFS) {
8526 if (parseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
8531 if (!
Args.empty() &&
8532 parseToken(
lltok::comma,
"expected ',' in argument list"))
8537 Type *ArgTy =
nullptr;
8538 if (parseType(ArgTy, ArgLoc))
8543 if (parseMetadataAsValue(
V, PFS))
8546 if (parseValue(ArgTy,
V, PFS))
8558bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8559 Value *CleanupPad =
nullptr;
8561 if (parseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
8576 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8587bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8588 Value *CatchPad =
nullptr;
8590 if (parseToken(
lltok::kw_from,
"expected 'from' after catchret"))
8597 if (parseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
8598 parseTypeAndBasicBlock(BB, PFS))
8607bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8615 return tokError(
"expected scope value for catchswitch");
8620 if (parseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
8626 if (parseTypeAndBasicBlock(DestBB, PFS))
8628 Table.push_back(DestBB);
8631 if (parseToken(
lltok::rsquare,
"expected ']' after catchswitch labels"))
8634 if (parseToken(
lltok::kw_unwind,
"expected 'unwind' after catchswitch scope"))
8642 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8648 for (BasicBlock *DestBB :
Table)
8649 CatchSwitch->addHandler(DestBB);
8656bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8657 Value *CatchSwitch =
nullptr;
8663 return tokError(
"expected scope value for catchpad");
8668 SmallVector<Value *, 8>
Args;
8669 if (parseExceptionArgs(Args, PFS))
8678bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8679 Value *ParentPad =
nullptr;
8686 return tokError(
"expected scope value for cleanuppad");
8691 SmallVector<Value *, 8>
Args;
8692 if (parseExceptionArgs(Args, PFS))
8708bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8709 unsigned Opc,
bool IsFP) {
8711 if (parseTypeAndValue(
LHS, Loc, PFS))
8718 return error(Loc,
"invalid operand type for instruction");
8728bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8729 LocTy CallLoc = Lex.getLoc();
8730 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8731 std::vector<unsigned> FwdRefAttrGrps;
8734 Type *RetType =
nullptr;
8741 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
8742 parseType(RetType, RetTypeLoc,
true ) ||
8743 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8744 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
8746 parseOptionalOperandBundles(BundleList, PFS) ||
8748 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8753 SmallVector<BasicBlock *, 16> IndirectDests;
8757 if (parseTypeAndBasicBlock(DestBB, PFS))
8762 if (parseTypeAndBasicBlock(DestBB, PFS))
8768 if (parseToken(
lltok::rsquare,
"expected ']' at end of block list"))
8775 if (resolveFunctionType(RetType, ArgList, Ty))
8776 return error(RetTypeLoc,
"Invalid result type for LLVM function");
8787 SmallVector<Value *, 8>
Args;
8794 for (
const ParamInfo &Arg : ArgList) {
8795 Type *ExpectedTy =
nullptr;
8798 }
else if (!Ty->isVarArg()) {
8799 return error(Arg.Loc,
"too many arguments specified");
8802 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8803 return error(Arg.Loc,
"argument is not of expected type '" +
8805 Args.push_back(Arg.V);
8810 return error(CallLoc,
"not enough parameters specified for call");
8822 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8836bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8837 unsigned Opc,
bool IsFP) {
8839 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8840 parseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
8848 return error(Loc,
"invalid operand type for instruction");
8856bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8859 if (parseTypeAndValue(
LHS, Loc, PFS) ||
8860 parseToken(
lltok::comma,
"expected ',' in logical operation") ||
8866 "instruction requires integer or integer vector operands");
8875bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8881 if (parseCmpPredicate(
Pred,
Opc) || parseTypeAndValue(
LHS, Loc, PFS) ||
8882 parseToken(
lltok::comma,
"expected ',' after compare value") ||
8886 if (
Opc == Instruction::FCmp) {
8888 return error(Loc,
"fcmp requires floating point operands");
8891 assert(
Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
8894 return error(Loc,
"icmp requires integer operands");
8906bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8910 Type *DestTy =
nullptr;
8911 if (parseTypeAndValue(
Op, Loc, PFS) ||
8912 parseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
8917 return error(Loc,
"invalid cast opcode for cast from '" +
8926bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8928 Value *Op0, *Op1, *Op2;
8929 if (parseTypeAndValue(Op0, Loc, PFS) ||
8930 parseToken(
lltok::comma,
"expected ',' after select condition") ||
8931 parseTypeAndValue(Op1, PFS) ||
8932 parseToken(
lltok::comma,
"expected ',' after select value") ||
8933 parseTypeAndValue(Op2, PFS))
8937 return error(Loc, Reason);
8945bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8947 Type *EltTy =
nullptr;
8949 if (parseTypeAndValue(
Op, PFS) ||
8950 parseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
8951 parseType(EltTy, TypeLoc))
8955 return error(TypeLoc,
"va_arg requires operand with first class type");
8957 Inst =
new VAArgInst(
Op, EltTy);
8963bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8966 if (parseTypeAndValue(Op0, Loc, PFS) ||
8967 parseToken(
lltok::comma,
"expected ',' after extract value") ||
8968 parseTypeAndValue(Op1, PFS))
8972 return error(Loc,
"invalid extractelement operands");
8980bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8982 Value *Op0, *Op1, *Op2;
8983 if (parseTypeAndValue(Op0, Loc, PFS) ||
8984 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8985 parseTypeAndValue(Op1, PFS) ||
8986 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
8987 parseTypeAndValue(Op2, PFS))
8991 return error(Loc,
"invalid insertelement operands");
8999bool LLParser::parseBitExtract(Instruction *&Inst, PerFunctionState &PFS) {
9003 if (parseType(Ty, Loc) ||
9004 parseToken(
lltok::comma,
"expected ',' after bitextract type") ||
9005 parseTypeAndValue(Op0, Loc, PFS) ||
9006 parseToken(
lltok::comma,
"expected ',' after bitextract source value") ||
9007 parseTypeAndValue(Op1, PFS))
9011 return error(Loc, Reason);
9019bool LLParser::parseBitInsert(Instruction *&Inst, PerFunctionState &PFS) {
9021 Value *Op0, *Op1, *Op2;
9022 if (parseTypeAndValue(Op0, Loc, PFS) ||
9023 parseToken(
lltok::comma,
"expected ',' after bitinsert source value") ||
9024 parseTypeAndValue(Op1, PFS) ||
9025 parseToken(
lltok::comma,
"expected ',' after bitinsert insert value") ||
9026 parseTypeAndValue(Op2, PFS))
9030 return error(Loc, Reason);
9038bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
9040 Value *Op0, *Op1, *Op2;
9041 if (parseTypeAndValue(Op0, Loc, PFS) ||
9042 parseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
9043 parseTypeAndValue(Op1, PFS) ||
9044 parseToken(
lltok::comma,
"expected ',' after shuffle value") ||
9045 parseTypeAndValue(Op2, PFS))
9049 return error(Loc,
"invalid shufflevector operands");
9051 Inst =
new ShuffleVectorInst(Op0, Op1, Op2);
9057int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
9061 if (parseType(Ty, TypeLoc))
9065 return error(TypeLoc,
"phi node must have first class type");
9068 bool AteExtraComma =
false;
9080 AteExtraComma =
true;
9084 if (parseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
9085 parseValue(Ty, Op0, PFS) ||
9086 parseToken(
lltok::comma,
"expected ',' after insertelement value") ||
9095 for (
const auto &[Val, BB] : PHIVals)
9098 return AteExtraComma ? InstExtraComma : InstNormal;
9107bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
9110 if (parseType(Ty, TyLoc))
9123 return tokError(
"expected 'catch' or 'filter' clause type");
9127 if (parseTypeAndValue(
V, VLoc, PFS))
9134 return error(VLoc,
"'catch' clause has an invalid type");
9137 return error(VLoc,
"'filter' clause has an invalid type");
9142 return error(VLoc,
"clause argument must be a constant");
9146 Inst = LP.release();
9152bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
9155 if (parseTypeAndValue(
Op, Loc, PFS))
9158 Inst =
new FreezeInst(
Op);
9171bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
9173 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
9174 std::vector<unsigned> FwdRefAttrGrps;
9176 unsigned CallAddrSpace;
9178 Type *RetType =
nullptr;
9183 LocTy CallLoc = Lex.getLoc();
9187 "expected 'tail call', 'musttail call', or 'notail call'"))
9190 FastMathFlags FMF = EatFastMathFlagsIfPresent();
9192 if (parseOptionalCallingConv(
CC) || parseOptionalReturnAttrs(RetAttrs) ||
9193 parseOptionalProgramAddrSpace(CallAddrSpace) ||
9194 parseType(RetType, RetTypeLoc,
true ) ||
9195 parseValID(CalleeID, &PFS) ||
9197 PFS.getFunction().isVarArg()) ||
9198 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
9199 parseOptionalOperandBundles(BundleList, PFS))
9206 if (resolveFunctionType(RetType, ArgList, Ty))
9207 return error(RetTypeLoc,
"Invalid result type for LLVM function");
9213 if (convertValIDToValue(
PointerType::get(Context, CallAddrSpace), CalleeID,
9220 SmallVector<Value*, 8>
Args;
9226 for (
const ParamInfo &Arg : ArgList) {
9227 Type *ExpectedTy =
nullptr;
9230 }
else if (!Ty->isVarArg()) {
9231 return error(Arg.Loc,
"too many arguments specified");
9234 if (ExpectedTy && ExpectedTy != Arg.V->getType())
9235 return error(Arg.Loc,
"argument is not of expected type '" +
9237 Args.push_back(Arg.V);
9238 Attrs.push_back(Arg.Attrs);
9242 return error(CallLoc,
"not enough parameters specified for call");
9255 return error(CallLoc,
"fast-math-flags specified for call without "
9256 "floating-point scalar or vector return type");
9263 if (SeenNewDbgInfoFormat) {
9265 return error(CallLoc,
"llvm.dbg intrinsic should not appear in a module "
9266 "using non-intrinsic debug info");
9268 SeenOldDbgInfoFormat =
true;
9271 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
9283int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
9285 LocTy SizeLoc, TyLoc, ASLoc;
9287 unsigned AddrSpace = 0;
9290 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
9291 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
9293 if (parseType(Ty, TyLoc))
9297 return error(TyLoc,
"invalid type for alloca");
9299 bool AteExtraComma =
false;
9301 if (Lex.getKind() == lltok::kw_align) {
9302 if (parseOptionalAlignment(Alignment))
9304 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9307 ASLoc = Lex.getLoc();
9308 if (parseOptionalAddrSpace(AddrSpace))
9311 AteExtraComma =
true;
9313 if (parseTypeAndValue(
Size, SizeLoc, PFS))
9316 if (Lex.getKind() == lltok::kw_align) {
9317 if (parseOptionalAlignment(Alignment))
9319 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9322 ASLoc = Lex.getLoc();
9323 if (parseOptionalAddrSpace(AddrSpace))
9326 AteExtraComma =
true;
9332 if (
Size && !
Size->getType()->isIntegerTy())
9333 return error(SizeLoc,
"element count must have integer type");
9335 if (!Alignment && !Ty->
isSized())
9336 return error(TyLoc,
"Cannot allocate unsized type");
9338 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
9339 AllocaInst *AI =
new AllocaInst(Ty, AddrSpace,
Size, *Alignment);
9343 return AteExtraComma ? InstExtraComma : InstNormal;
9350int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
9353 bool AteExtraComma =
false;
9363 bool isVolatile =
false;
9369 bool IsElementwise =
false;
9371 IsElementwise =
true;
9376 LocTy ExplicitTypeLoc = Lex.getLoc();
9377 if (parseType(Ty) ||
9378 parseToken(
lltok::comma,
"expected comma after load's type") ||
9379 parseTypeAndValue(Val, Loc, PFS) ||
9380 parseScopeAndOrdering(
isAtomic, SSID, Ordering) ||
9381 parseOptionalCommaAlign(Alignment, AteExtraComma))
9385 return error(Loc,
"load operand must be a pointer to a first class type");
9388 return error(Loc,
"elementwise load must be atomic");
9391 return error(ExplicitTypeLoc,
9392 "atomic elementwise load operand must have fixed vector type");
9395 return error(Loc,
"atomic load must have explicit non-zero alignment");
9399 return error(Loc,
"atomic load cannot use Release ordering");
9402 "atomic elementwise load cannot be sequentially consistent");
9404 if (!Alignment && !Ty->
isSized())
9405 return error(ExplicitTypeLoc,
"loading unsized types is not allowed");
9407 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9408 Inst =
new LoadInst(Ty, Val,
"",
9410 SSID, IsElementwise},
9412 return AteExtraComma ? InstExtraComma : InstNormal;
9420int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9424 bool AteExtraComma =
false;
9434 bool isVolatile =
false;
9440 bool IsElementwise =
false;
9442 IsElementwise =
true;
9446 if (parseTypeAndValue(Val, Loc, PFS) ||
9447 parseToken(
lltok::comma,
"expected ',' after store operand") ||
9448 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9449 parseScopeAndOrdering(
isAtomic, SSID, Ordering) ||
9450 parseOptionalCommaAlign(Alignment, AteExtraComma))
9454 return error(PtrLoc,
"store operand must be a pointer");
9456 return error(Loc,
"store operand must be a first class value");
9458 return error(Loc,
"atomic store must have explicit non-zero alignment");
9461 return error(Loc,
"atomic store cannot use Acquire ordering");
9464 return error(Loc,
"elementwise store must be atomic");
9468 Loc,
"atomic elementwise store operand must have fixed vector type");
9472 "atomic elementwise store cannot be sequentially consistent");
9475 return error(Loc,
"storing unsized types is not allowed");
9479 Inst =
new StoreInst(Val, Ptr,
9481 SSID, IsElementwise},
9483 return AteExtraComma ? InstExtraComma : InstNormal;
9490int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9492 bool AteExtraComma =
false;
9496 bool isVolatile =
false;
9497 bool isWeak =
false;
9506 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9507 parseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
9508 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9509 parseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
9510 parseTypeAndValue(New, NewLoc, PFS) ||
9511 parseScopeAndOrdering(
true , SSID, SuccessOrdering) ||
9512 parseOrdering(FailureOrdering) ||
9513 parseOptionalCommaAlign(Alignment, AteExtraComma))
9517 return tokError(
"invalid cmpxchg success ordering");
9519 return tokError(
"invalid cmpxchg failure ordering");
9521 return error(PtrLoc,
"cmpxchg operand must be a pointer");
9522 if (
Cmp->getType() !=
New->getType())
9523 return error(NewLoc,
"compare value and new value type do not match");
9524 if (!
New->getType()->isFirstClassType())
9525 return error(NewLoc,
"cmpxchg operand must be a first class value");
9527 const Align DefaultAlignment(
9528 PFS.getFunction().getDataLayout().getTypeStoreSize(
9531 AtomicCmpXchgInst *CXI =
9532 new AtomicCmpXchgInst(Ptr, Cmp, New,
Alignment.value_or(DefaultAlignment),
9533 SuccessOrdering, FailureOrdering, SSID);
9538 return AteExtraComma ? InstExtraComma : InstNormal;
9545int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9547 bool AteExtraComma =
false;
9551 bool IsElementwise =
false;
9559 IsElementwise =
true;
9561 switch (Lex.getKind()) {
9563 return tokError(
"expected binary operation in atomicrmw");
9622 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9623 parseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
9624 parseTypeAndValue(Val, ValLoc, PFS) ||
9625 parseScopeAndOrdering(
true , SSID, Ordering) ||
9626 parseOptionalCommaAlign(Alignment, AteExtraComma))
9630 return tokError(
"atomicrmw cannot be unordered");
9632 return tokError(
"atomicrmw elementwise cannot be sequentially consistent");
9634 return error(PtrLoc,
"atomicrmw operand must be a pointer");
9636 return error(ValLoc,
"atomicrmw operand may not be scalable");
9639 if (IsElementwise) {
9641 return error(ValLoc,
9642 "atomicrmw elementwise operand must be a fixed vector type");
9651 " operand must be an integer type, a floating-point type, a "
9652 "pointer type, or a fixed vector of any of these types");
9656 return error(ValLoc,
"atomicrmw " +
9658 " operand must be a floating point or fixed "
9659 "vector of floating point type");
9666 " operand must be an integer or fixed vector of integer type");
9671 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9673 return error(ValLoc,
9674 "atomicrmw operand must have a power-of-two byte size");
9675 const Align DefaultAlignment(
9676 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->
getType()));
9677 AtomicRMWInst *RMWI =
new AtomicRMWInst(
Operation, Ptr, Val,
9679 Ordering, SSID, IsElementwise);
9682 return AteExtraComma ? InstExtraComma : InstNormal;
9687int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9690 if (parseScopeAndOrdering(
true , SSID, Ordering))
9694 return tokError(
"fence cannot be unordered");
9696 return tokError(
"fence cannot be monotonic");
9698 Inst =
new FenceInst(Context, Ordering, SSID);
9704int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9705 Value *Ptr =
nullptr;
9706 Value *Val =
nullptr;
9722 if (parseType(Ty) ||
9723 parseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
9724 parseTypeAndValue(Ptr, Loc, PFS))
9729 if (!BasePointerType)
9730 return error(Loc,
"base of getelementptr must be a pointer");
9732 SmallVector<Value*, 16> Indices;
9733 bool AteExtraComma =
false;
9736 ElementCount GEPWidth =
BaseType->isVectorTy()
9742 AteExtraComma =
true;
9745 if (parseTypeAndValue(Val, EltLoc, PFS))
9748 return error(EltLoc,
"getelementptr index must be an integer");
9751 ElementCount ValNumEl = ValVTy->getElementCount();
9755 "getelementptr vector index has a wrong number of elements");
9756 GEPWidth = ValNumEl;
9762 return error(Loc,
"base element of getelementptr must be sized");
9765 return error(Loc,
"invalid getelementptr indices");
9768 GEP->setNoWrapFlags(NW);
9769 return AteExtraComma ? InstExtraComma : InstNormal;
9774int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9776 SmallVector<unsigned, 4> Indices;
9778 if (parseTypeAndValue(Val, Loc, PFS) ||
9779 parseIndexList(Indices, AteExtraComma))
9783 return error(Loc,
"extractvalue operand must be aggregate type");
9786 return error(Loc,
"invalid indices for extractvalue");
9788 return AteExtraComma ? InstExtraComma : InstNormal;
9793int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9795 SmallVector<unsigned, 4> Indices;
9797 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9798 parseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
9799 parseTypeAndValue(Val1, Loc1, PFS) ||
9800 parseIndexList(Indices, AteExtraComma))
9804 return error(Loc0,
"insertvalue operand must be aggregate type");
9808 return error(Loc0,
"invalid indices for insertvalue");
9809 if (IndexedType != Val1->
getType())
9810 return error(Loc1,
"insertvalue operand and field disagree in type: '" +
9814 return AteExtraComma ? InstExtraComma : InstNormal;
9825bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9840 if (parseMetadata(MD,
nullptr))
9845 return parseToken(
lltok::rbrace,
"expected end of metadata node");
9851bool LLParser::sortUseListOrder(
Value *
V, ArrayRef<unsigned> Indexes,
9853 if (!
V->hasUseList())
9856 return error(Loc,
"value has no uses");
9858 unsigned NumUses = 0;
9859 SmallDenseMap<const Use *, unsigned, 16> Order;
9860 for (
const Use &U :
V->uses()) {
9861 if (++NumUses > Indexes.
size())
9863 Order[&
U] = Indexes[NumUses - 1];
9866 return error(Loc,
"value only has one use");
9867 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
9869 "wrong number of indexes, expected " + Twine(
V->getNumUses()));
9871 V->sortUseList([&](
const Use &L,
const Use &R) {
9879bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9880 SMLoc Loc = Lex.getLoc();
9884 return tokError(
"expected non-empty list of uselistorder indexes");
9891 bool IsOrdered =
true;
9892 assert(Indexes.
empty() &&
"Expected empty order vector");
9895 if (parseUInt32(Index))
9900 Max = std::max(Max, Index);
9901 IsOrdered &= Index == Indexes.
size();
9909 if (Indexes.
size() < 2)
9910 return error(Loc,
"expected >= 2 uselistorder indexes");
9913 "expected distinct uselistorder indexes in range [0, size)");
9915 return error(Loc,
"expected uselistorder indexes to change the order");
9922bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9923 SMLoc Loc = Lex.getLoc();
9928 SmallVector<unsigned, 16> Indexes;
9929 if (parseTypeAndValue(
V, PFS) ||
9930 parseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
9931 parseUseListOrderIndexes(Indexes))
9934 return sortUseListOrder(
V, Indexes, Loc);
9940bool LLParser::parseModuleEntry(
unsigned ID) {
9949 parseStringConstant(Path) ||
9957 if (parseUInt32(Hash[0]) || parseToken(
lltok::comma,
"expected ',' here") ||
9958 parseUInt32(Hash[1]) || parseToken(
lltok::comma,
"expected ',' here") ||
9959 parseUInt32(Hash[2]) || parseToken(
lltok::comma,
"expected ',' here") ||
9960 parseUInt32(Hash[3]) || parseToken(
lltok::comma,
"expected ',' here") ||
9961 parseUInt32(Hash[4]))
9968 auto ModuleEntry = Index->addModule(Path, Hash);
9969 ModuleIdMap[
ID] = ModuleEntry->first();
9976bool LLParser::parseTypeIdEntry(
unsigned ID) {
9985 parseStringConstant(Name))
9988 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9990 parseTypeIdSummary(TIS) || parseToken(
lltok::rparen,
"expected ')' here"))
9995 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9996 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9997 for (
auto TIDRef : FwdRefTIDs->second) {
9999 "Forward referenced type id GUID expected to be 0");
10002 ForwardRefTypeIds.erase(FwdRefTIDs);
10010bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
10014 parseTypeTestResolution(TIS.
TTRes))
10019 if (parseOptionalWpdResolutions(TIS.
WPDRes))
10036bool LLParser::parseTypeIdCompatibleVtableEntry(
unsigned ID) {
10045 parseStringConstant(Name))
10049 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
10056 IdToIndexMapType IdToIndexMap;
10069 if (parseGVReference(VI, GVId))
10076 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(),
Loc));
10077 TI.push_back({
Offset, VI});
10085 for (
auto I : IdToIndexMap) {
10086 auto &Infos = ForwardRefValueInfos[
I.first];
10087 for (
auto P :
I.second) {
10089 "Forward referenced ValueInfo expected to be empty");
10090 Infos.emplace_back(&TI[
P.first].VTableVI,
P.second);
10100 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
10101 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
10102 for (
auto TIDRef : FwdRefTIDs->second) {
10103 assert(!*TIDRef.first &&
10104 "Forward referenced type id GUID expected to be 0");
10107 ForwardRefTypeIds.erase(FwdRefTIDs);
10119bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
10127 switch (Lex.getKind()) {
10147 return error(Lex.getLoc(),
"unexpected TypeTestResolution kind");
10159 switch (Lex.getKind()) {
10174 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(Val))
10177 TTRes.
BitMask = (uint8_t)Val;
10187 return error(Lex.getLoc(),
"expected optional TypeTestResolution field");
10200bool LLParser::parseOptionalWpdResolutions(
10201 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
10209 WholeProgramDevirtResolution WPDRes;
10213 parseToken(
lltok::comma,
"expected ',' here") || parseWpdRes(WPDRes) ||
10216 WPDResMap[
Offset] = WPDRes;
10233bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
10241 switch (Lex.getKind()) {
10255 return error(Lex.getLoc(),
"unexpected WholeProgramDevirtResolution kind");
10261 switch (Lex.getKind()) {
10269 if (parseOptionalResByArg(WPDRes.
ResByArg))
10273 return error(Lex.getLoc(),
10274 "expected optional WholeProgramDevirtResolution field");
10291bool LLParser::parseOptionalResByArg(
10292 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
10300 std::vector<uint64_t>
Args;
10301 if (parseArgs(Args) || parseToken(
lltok::comma,
"expected ',' here") ||
10309 WholeProgramDevirtResolution::ByArg ByArg;
10310 switch (Lex.getKind()) {
10324 return error(Lex.getLoc(),
10325 "unexpected WholeProgramDevirtResolution::ByArg kind");
10331 switch (Lex.getKind()) {
10335 parseUInt64(ByArg.
Info))
10341 parseUInt32(ByArg.
Byte))
10347 parseUInt32(ByArg.
Bit))
10351 return error(Lex.getLoc(),
10352 "expected optional whole program devirt field");
10359 ResByArg[
Args] = ByArg;
10370bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10378 if (parseUInt64(Val))
10380 Args.push_back(Val);
10404bool LLParser::addGlobalValueToIndex(
10406 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary,
LocTy Loc) {
10411 VI = Index->getOrInsertValueInfo(GUID);
10415 auto *GV = M->getNamedValue(Name);
10417 return error(Loc,
"Reference to undefined global \"" + Name +
"\"");
10423 VI = Index->getOrInsertValueInfo(GV, GUID);
10427 "Need a source_filename to compute GUID for local");
10430 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10435 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10436 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10437 for (
auto VIRef : FwdRefVIs->second) {
10439 "Forward referenced ValueInfo expected to be empty");
10442 ForwardRefValueInfos.erase(FwdRefVIs);
10446 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10447 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10448 for (
auto AliaseeRef : FwdRefAliasees->second) {
10449 assert(!AliaseeRef.first->hasAliasee() &&
10450 "Forward referencing alias already has aliasee");
10451 assert(Summary &&
"Aliasee must be a definition");
10452 AliaseeRef.first->setAliasee(VI,
Summary.get());
10454 ForwardRefAliasees.erase(FwdRefAliasees);
10459 Index->addGlobalValueSummary(VI, std::move(Summary));
10462 if (ID == NumberedValueInfos.size())
10463 NumberedValueInfos.push_back(VI);
10466 if (ID > NumberedValueInfos.size())
10467 NumberedValueInfos.resize(ID + 1);
10468 NumberedValueInfos[
ID] =
VI;
10476bool LLParser::parseSummaryIndexFlags() {
10483 if (parseUInt64(Flags))
10486 Index->setFlags(Flags);
10492bool LLParser::parseBlockCount() {
10499 if (parseUInt64(BlockCount))
10502 Index->setBlockCount(BlockCount);
10510bool LLParser::parseCfiFunctions() {
10514 ? Index->cfiFunctionDefs()
10515 : Index->cfiFunctionDecls();
10527 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID) ||
10531 parseStringConstant(Name) ||
10544bool LLParser::parseGVEntry(
unsigned ID) {
10552 LocTy Loc = Lex.getLoc();
10555 switch (Lex.getKind()) {
10559 parseStringConstant(Name))
10565 if (parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(GUID))
10569 return error(Lex.getLoc(),
"expected name or guid tag");
10592 switch (Lex.getKind()) {
10594 if (parseFunctionSummary(Name, GUID, ID))
10598 if (parseVariableSummary(Name, GUID, ID))
10602 if (parseAliasSummary(Name, GUID, ID))
10606 return error(Lex.getLoc(),
"expected summary type");
10624 LocTy Loc = Lex.getLoc();
10628 StringRef ModulePath;
10629 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10632 false,
false,
false,
10634 unsigned InstCount;
10636 FunctionSummary::TypeIdInfo TypeIdInfo;
10637 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10639 std::vector<CallsiteInfo> Callsites;
10640 std::vector<AllocInfo> Allocs;
10642 FunctionSummary::FFlags FFlags = {};
10645 parseModuleReference(ModulePath) ||
10646 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10649 parseToken(
lltok::colon,
"expected ':' here") || parseUInt32(InstCount))
10654 switch (Lex.getKind()) {
10656 if (parseOptionalFFlags(FFlags))
10660 if (parseOptionalCalls(Calls))
10664 if (parseOptionalTypeIdInfo(TypeIdInfo))
10668 if (parseOptionalRefs(Refs))
10672 if (parseOptionalParamAccesses(ParamAccesses))
10676 if (parseOptionalAllocs(Allocs))
10680 if (parseOptionalCallsites(Callsites))
10684 return error(Lex.getLoc(),
"expected optional function summary field");
10691 auto FS = std::make_unique<FunctionSummary>(
10692 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10698 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10700 FS->setModulePath(ModulePath);
10702 return addGlobalValueToIndex(Name, GUID,
10704 std::move(FS), Loc);
10712 LocTy Loc = Lex.getLoc();
10716 StringRef ModulePath;
10717 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10720 false,
false,
false,
10722 GlobalVarSummary::GVarFlags GVarFlags(
false,
10730 parseModuleReference(ModulePath) ||
10731 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10733 parseGVarFlags(GVarFlags))
10738 switch (Lex.getKind()) {
10740 if (parseOptionalVTableFuncs(VTableFuncs))
10744 if (parseOptionalRefs(Refs))
10748 return error(Lex.getLoc(),
"expected optional variable summary field");
10756 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10758 GS->setModulePath(ModulePath);
10759 GS->setVTableFuncs(std::move(VTableFuncs));
10761 return addGlobalValueToIndex(Name, GUID,
10763 std::move(GS), Loc);
10772 LocTy Loc = Lex.getLoc();
10775 StringRef ModulePath;
10776 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10779 false,
false,
false,
10783 parseModuleReference(ModulePath) ||
10784 parseToken(
lltok::comma,
"expected ',' here") || parseGVFlags(GVFlags) ||
10790 ValueInfo AliaseeVI;
10792 auto AS = std::make_unique<AliasSummary>(GVFlags);
10793 AS->setModulePath(ModulePath);
10796 if (parseGVReference(AliaseeVI, GVId))
10801 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10803 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10804 assert(Summary &&
"Aliasee must be a definition");
10805 AS->setAliasee(AliaseeVI, Summary);
10812 return addGlobalValueToIndex(Name, GUID,
10814 std::move(AS), Loc);
10819bool LLParser::parseFlag(
unsigned &Val) {
10820 if (Lex.getKind() !=
lltok::APSInt || Lex.getAPSIntVal().isSigned())
10821 return tokError(
"expected integer");
10822 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10839bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10843 if (parseToken(
lltok::colon,
"expected ':' in funcFlags") ||
10849 switch (Lex.getKind()) {
10852 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10858 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10864 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10870 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10876 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10882 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10888 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10894 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10900 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10906 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10912 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Val))
10917 return error(Lex.getLoc(),
"expected function flag type");
10921 if (parseToken(
lltok::rparen,
"expected ')' in funcFlags"))
10932bool LLParser::parseOptionalCalls(
10933 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10937 if (parseToken(
lltok::colon,
"expected ':' in calls") ||
10941 IdToIndexMapType IdToIndexMap;
10950 LocTy Loc = Lex.getLoc();
10952 if (parseGVReference(VI, GVId))
10956 unsigned RelBF = 0;
10957 unsigned HasTailCall =
false;
10958 unsigned HasIndirectCall =
false;
10962 switch (Lex.getKind()) {
10965 if (parseToken(
lltok::colon,
"expected ':'") || parseHotness(Hotness))
10971 if (parseToken(
lltok::colon,
"expected ':'") || parseUInt32(RelBF))
10976 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(HasTailCall))
10982 parseFlag(HasIndirectCall))
10986 return error(Lex.getLoc(),
10987 "expected hotness, relbf, tail, or indirect");
10994 IdToIndexMap[GVId].push_back(std::make_pair(Calls.
size(), Loc));
10996 VI, CalleeInfo(Hotness, HasTailCall, HasIndirectCall)});
11004 for (
auto I : IdToIndexMap) {
11005 auto &Infos = ForwardRefValueInfos[
I.first];
11006 for (
auto P :
I.second) {
11008 "Forward referenced ValueInfo expected to be empty");
11009 Infos.emplace_back(&Calls[
P.first].first,
P.second);
11022 switch (Lex.getKind()) {
11026 case lltok::kw_cold:
11032 case lltok::kw_hot:
11039 return error(Lex.getLoc(),
"invalid call edge hotness");
11048bool LLParser::parseOptionalVTableFuncs(
VTableFuncList &VTableFuncs) {
11052 if (parseToken(
lltok::colon,
"expected ':' in vTableFuncs") ||
11056 IdToIndexMapType IdToIndexMap;
11060 if (parseToken(
lltok::lparen,
"expected '(' in vTableFunc") ||
11065 LocTy Loc = Lex.getLoc();
11067 if (parseGVReference(VI, GVId))
11080 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
11081 VTableFuncs.push_back({
VI,
Offset});
11083 if (parseToken(
lltok::rparen,
"expected ')' in vTableFunc"))
11089 for (
auto I : IdToIndexMap) {
11090 auto &Infos = ForwardRefValueInfos[
I.first];
11091 for (
auto P :
I.second) {
11093 "Forward referenced ValueInfo expected to be empty");
11094 Infos.emplace_back(&VTableFuncs[
P.first].FuncVI,
P.second);
11098 if (parseToken(
lltok::rparen,
"expected ')' in vTableFuncs"))
11105bool LLParser::parseParamNo(
uint64_t &ParamNo) {
11107 parseToken(
lltok::colon,
"expected ':' here") || parseUInt64(ParamNo))
11113bool LLParser::parseParamAccessOffset(ConstantRange &
Range) {
11116 auto ParseAPSInt = [&](
APSInt &Val) {
11118 return tokError(
"expected integer");
11119 Val = Lex.getAPSIntVal();
11121 Val.setIsSigned(
true);
11143bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &
Call,
11144 IdLocListType &IdLocList) {
11152 LocTy Loc = Lex.getLoc();
11153 if (parseGVReference(VI, GVId))
11157 IdLocList.emplace_back(GVId, Loc);
11160 parseParamNo(
Call.ParamNo) ||
11162 parseParamAccessOffset(
Call.Offsets))
11174bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
11175 IdLocListType &IdLocList) {
11177 parseParamNo(
Param.ParamNo) ||
11179 parseParamAccessOffset(
Param.Use))
11188 FunctionSummary::ParamAccess::Call
Call;
11189 if (parseParamAccessCall(
Call, IdLocList))
11206bool LLParser::parseOptionalParamAccesses(
11207 std::vector<FunctionSummary::ParamAccess> &Params) {
11215 IdLocListType VContexts;
11216 size_t CallsNum = 0;
11218 FunctionSummary::ParamAccess ParamAccess;
11219 if (parseParamAccess(ParamAccess, VContexts))
11221 CallsNum += ParamAccess.
Calls.size();
11222 assert(VContexts.size() == CallsNum);
11224 Params.emplace_back(std::move(ParamAccess));
11232 IdLocListType::const_iterator ItContext = VContexts.begin();
11233 for (
auto &PA : Params) {
11234 for (
auto &
C : PA.Calls) {
11236 ForwardRefValueInfos[ItContext->first].emplace_back(&
C.Callee,
11237 ItContext->second);
11241 assert(ItContext == VContexts.end());
11248bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
11252 if (parseToken(
lltok::colon,
"expected ':' in refs") ||
11256 struct ValueContext {
11261 std::vector<ValueContext> VContexts;
11265 VC.Loc = Lex.getLoc();
11266 if (parseGVReference(
VC.VI,
VC.GVId))
11268 VContexts.push_back(VC);
11274 llvm::sort(VContexts, [](
const ValueContext &VC1,
const ValueContext &VC2) {
11275 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
11278 IdToIndexMapType IdToIndexMap;
11279 for (
auto &VC : VContexts) {
11284 IdToIndexMap[
VC.GVId].push_back(std::make_pair(Refs.
size(),
VC.Loc));
11290 for (
auto I : IdToIndexMap) {
11291 auto &Infos = ForwardRefValueInfos[
I.first];
11292 for (
auto P :
I.second) {
11294 "Forward referenced ValueInfo expected to be empty");
11295 Infos.emplace_back(&Refs[
P.first],
P.second);
11309bool LLParser::parseOptionalTypeIdInfo(
11310 FunctionSummary::TypeIdInfo &TypeIdInfo) {
11319 switch (Lex.getKind()) {
11321 if (parseTypeTests(TypeIdInfo.
TypeTests))
11345 return error(Lex.getLoc(),
"invalid typeIdInfo list type");
11349 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11358bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
11366 IdToIndexMapType IdToIndexMap;
11370 unsigned ID = Lex.getUIntVal();
11371 LocTy Loc = Lex.getLoc();
11375 IdToIndexMap[
ID].push_back(std::make_pair(TypeTests.size(), Loc));
11377 }
else if (parseUInt64(GUID))
11379 TypeTests.push_back(GUID);
11384 for (
auto I : IdToIndexMap) {
11385 auto &Ids = ForwardRefTypeIds[
I.first];
11386 for (
auto P :
I.second) {
11387 assert(TypeTests[
P.first] == 0 &&
11388 "Forward referenced type id GUID expected to be 0");
11389 Ids.emplace_back(&TypeTests[
P.first],
P.second);
11393 if (parseToken(
lltok::rparen,
"expected ')' in typeIdInfo"))
11401bool LLParser::parseVFuncIdList(
11402 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
11403 assert(Lex.getKind() == Kind);
11410 IdToIndexMapType IdToIndexMap;
11412 FunctionSummary::VFuncId VFuncId;
11413 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11415 VFuncIdList.push_back(VFuncId);
11423 for (
auto I : IdToIndexMap) {
11424 auto &Ids = ForwardRefTypeIds[
I.first];
11425 for (
auto P :
I.second) {
11426 assert(VFuncIdList[
P.first].GUID == 0 &&
11427 "Forward referenced type id GUID expected to be 0");
11428 Ids.emplace_back(&VFuncIdList[
P.first].GUID,
P.second);
11437bool LLParser::parseConstVCallList(
11439 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11440 assert(Lex.getKind() == Kind);
11447 IdToIndexMapType IdToIndexMap;
11449 FunctionSummary::ConstVCall ConstVCall;
11450 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11452 ConstVCallList.push_back(ConstVCall);
11460 for (
auto I : IdToIndexMap) {
11461 auto &Ids = ForwardRefTypeIds[
I.first];
11462 for (
auto P :
I.second) {
11463 assert(ConstVCallList[
P.first].VFunc.GUID == 0 &&
11464 "Forward referenced type id GUID expected to be 0");
11465 Ids.emplace_back(&ConstVCallList[
P.first].VFunc.GUID,
P.second);
11474bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11475 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11477 parseVFuncId(ConstVCall.
VFunc, IdToIndexMap, Index))
11481 if (parseArgs(ConstVCall.
Args))
11493bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11494 IdToIndexMapType &IdToIndexMap,
unsigned Index) {
11504 unsigned ID = Lex.getUIntVal();
11505 LocTy Loc = Lex.getLoc();
11509 IdToIndexMap[
ID].push_back(std::make_pair(Index, Loc));
11511 }
else if (parseToken(
lltok::kw_guid,
"expected 'guid' here") ||
11513 parseUInt64(VFuncId.
GUID))
11519 parseUInt64(VFuncId.
Offset) ||
11531bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11541 switch (Lex.getKind()) {
11548 assert(HasLinkage &&
"Linkage not optional in summary entry");
11555 parseOptionalVisibility(Flag);
11560 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11566 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11572 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11578 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11587 if (parseOptionalImportType(Lex.getKind(), IK))
11589 GVFlags.
ImportType =
static_cast<unsigned>(IK);
11594 if (parseToken(
lltok::colon,
"expected ':'") || parseFlag(Flag))
11599 return error(Lex.getLoc(),
"expected gv flag type");
11613bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11621 auto ParseRest = [
this](
unsigned int &Val) {
11625 return parseFlag(Val);
11630 switch (Lex.getKind()) {
11631 case lltok::kw_readonly:
11632 if (ParseRest(Flag))
11636 case lltok::kw_writeonly:
11637 if (ParseRest(Flag))
11642 if (ParseRest(Flag))
11647 if (ParseRest(Flag))
11652 return error(Lex.getLoc(),
"expected gvar flag type");
11660bool LLParser::parseModuleReference(StringRef &ModulePath) {
11667 unsigned ModuleID = Lex.getUIntVal();
11668 auto I = ModuleIdMap.find(ModuleID);
11670 assert(
I != ModuleIdMap.end());
11671 ModulePath =
I->second;
11677bool LLParser::parseGVReference(ValueInfo &VI,
unsigned &GVId) {
11680 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11684 GVId = Lex.getUIntVal();
11686 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11688 VI = NumberedValueInfos[GVId];
11705bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11709 if (parseToken(
lltok::colon,
"expected ':' in allocs") ||
11721 SmallVector<uint8_t> Versions;
11724 if (parseAllocType(
V))
11729 if (parseToken(
lltok::rparen,
"expected ')' in versions") ||
11733 std::vector<MIBInfo> MIBs;
11734 if (parseMemProfs(MIBs))
11737 Allocs.push_back({Versions, MIBs});
11754bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11758 if (parseToken(
lltok::colon,
"expected ':' in memprof") ||
11764 if (parseToken(
lltok::lparen,
"expected '(' in memprof") ||
11770 if (parseAllocType(AllocType))
11773 if (parseToken(
lltok::comma,
"expected ',' in memprof") ||
11779 SmallVector<unsigned> StackIdIndices;
11784 if (parseUInt64(StackId))
11786 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11807bool LLParser::parseAllocType(uint8_t &AllocType) {
11808 switch (Lex.getKind()) {
11821 case lltok::kw_cold:
11824 case lltok::kw_hot:
11828 return error(Lex.getLoc(),
"invalid alloc type");
11841bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11845 if (parseToken(
lltok::colon,
"expected ':' in callsites") ||
11849 IdToIndexMapType IdToIndexMap;
11852 if (parseToken(
lltok::lparen,
"expected '(' in callsite") ||
11859 LocTy Loc = Lex.getLoc();
11861 if (parseGVReference(VI, GVId))
11865 if (parseToken(
lltok::comma,
"expected ',' in callsite") ||
11871 SmallVector<unsigned> Clones;
11874 if (parseUInt32(
V))
11880 parseToken(
lltok::comma,
"expected ',' in callsite") ||
11886 SmallVector<unsigned> StackIdIndices;
11891 if (parseUInt64(StackId))
11893 StackIdIndices.
push_back(Index->addOrGetStackIdIndex(StackId));
11904 IdToIndexMap[GVId].
push_back(std::make_pair(Callsites.size(), Loc));
11905 Callsites.push_back({
VI, Clones, StackIdIndices});
11913 for (
auto I : IdToIndexMap) {
11914 auto &Infos = ForwardRefValueInfos[
I.first];
11915 for (
auto P :
I.second) {
11917 "Forward referenced ValueInfo expected to be empty");
11918 Infos.emplace_back(&Callsites[
P.first].Callee,
P.second);
11922 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 isAtomic(MachineBasicBlock::iterator I)
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
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)
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 LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
static constexpr const fltSemantics & IEEEdouble()
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)
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
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)
void addSymbolWithThinLTOGUID(StringRef Name, GlobalValue::GUID GUID)
Add the function name and the GUID that ThinLTO uses for it.
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
const std::string & getStrVal() 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...
Storage class for function-local metadata objects.
static LLVM_ABI MDFunctionLocalContext * getDistinct(LLVMContext &Context, bool NonDebug=false)
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().
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
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.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
bool isByteTy() const
True if this is an instance of ByteType.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isAggregateType() const
Return true if the type is an aggregate type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isFunctionTy() const
True if this is an instance of FunctionType.
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isTokenTy() const
Return true if this is 'token'.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
LLVM_ABI const fltSemantics & getFltSemantics() const
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
static constexpr uint64_t MaximumAlignment
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
LLVM_ABI unsigned getLanguageDialect(StringRef LanguageDialectString)
LLVM_ABI unsigned getTag(StringRef TagString)
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ WASM_EmscriptenInvoke
For emscripten __invoke_* functions.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AVR_BUILTIN
Used for special AVR rtlib functions which have an "optimized" convention to preserve registers.
@ 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 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)
@ Init
Initialization function, sets up the coroutine frame.
@ DW_LLVM_LANG_DIALECT_max
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
@ DW_MACINFO_invalid
Macinfo type for invalid results.
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
@ kw_aarch64_sme_preservemost_from_x1
@ kw_wasm_emscripten_invokecc
@ kw_no_sanitize_hwaddress
@ kw_cheriot_librarycallcc
@ kw_cheriot_compartmentcalleecc
@ kw_typeCheckedLoadConstVCalls
@ kw_aarch64_sve_vector_pcs
@ kw_cheriot_compartmentcallcc
@ kw_amdgpu_gfx_whole_wave
@ kw_typeTestAssumeConstVCalls
@ kw_typeidCompatibleVTable
@ kw_typeCheckedLoadVCalls
@ kw_inaccessiblemem_or_argmemonly
@ kw_externally_initialized
@ kw_sanitize_address_dyninit
@ kw_amdgpu_cs_chain_preserve
@ kw_available_externally
@ kw_typeTestAssumeVCalls
@ kw_aarch64_sme_preservemost_from_x0
@ kw_hasEscapingBlockAddress
@ 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.
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.
DebugVariableAggregate VarID
A unique key that represents one instance of a debug variable.
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 UpgradeInstructionMetadata(Module &M)
Discover metadata used by instructions in this module, and apply the suitable upgrade.
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
static void assign(DXContainerYAML::SourceInfo::SectionHeader &Dst, const dxbc::SourceInfo::SectionHeader &Src)
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
@ Async
"Asynchronous" unwind tables (instr precise)
@ Sync
"Synchronous" unwind tables
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
CaptureComponents
Components of the pointer that may be captured.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
IRMemLocation
The locations at which a function might access memory.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
@ End
Run the machine verifier once, at the end of the pipeline.
bool capturesNothing(CaptureComponents CC)
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getInvalid()
static constexpr DenormalMode getIEEE()
Unique FLMD, just a wrapper around a DILocalScope.
std::vector< uint64_t > Args
unsigned HasEscapingBlockAddress
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.
@ Speculative
Speculative devirtualization.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.