72 "Can't read textual IR with a Context that discards named Values");
74 return ParseTopLevelEntities() ||
75 ValidateEndOfModule();
80 restoreParsingState(Slots);
84 if (ParseType(Ty) || parseConstantValue(Ty, C))
87 return Error(Lex.
getLoc(),
"expected end of string");
93 restoreParsingState(Slots);
107 void LLParser::restoreParsingState(
const SlotMapping *Slots) {
114 std::make_pair(
I.getKey(), std::make_pair(
I.second,
LocTy())));
115 for (
const auto &
I : Slots->
Types)
116 NumberedTypes.insert(
117 std::make_pair(
I.first, std::make_pair(
I.second,
LocTy())));
122 bool LLParser::ValidateEndOfModule() {
124 for (
const auto &RAG : ForwardRefAttrGroups) {
125 Value *V = RAG.first;
126 const std::vector<unsigned> &Attrs = RAG.second;
129 for (
const auto &Attr : Attrs)
130 B.
merge(NumberedAttrBuilders[Attr]);
132 if (
Function *Fn = dyn_cast<Function>(V)) {
136 AS.getFnAttributes());
142 if (FnAttrs.hasAlignmentAttr()) {
143 Fn->setAlignment(FnAttrs.getAlignment());
148 AttributeSet::get(Context,
151 Fn->setAttributes(AS);
152 }
else if (
CallInst *CI = dyn_cast<CallInst>(V)) {
156 AS.getFnAttributes());
159 AttributeSet::get(Context,
162 CI->setAttributes(AS);
163 }
else if (
InvokeInst *II = dyn_cast<InvokeInst>(V)) {
167 AS.getFnAttributes());
170 AttributeSet::get(Context,
173 II->setAttributes(AS);
181 if (!ForwardRefBlockAddresses.empty())
182 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
183 "expected function name in blockaddress");
185 for (
const auto &NT : NumberedTypes)
186 if (NT.second.second.isValid())
187 return Error(NT.second.second,
188 "use of undefined type '%" +
Twine(NT.first) +
"'");
190 for (
StringMap<std::pair<Type*, LocTy> >::iterator
I =
191 NamedTypes.begin(),
E = NamedTypes.end();
I !=
E; ++
I)
192 if (
I->second.second.isValid())
193 return Error(
I->second.second,
194 "use of undefined type named '" +
I->getKey() +
"'");
196 if (!ForwardRefComdats.empty())
197 return Error(ForwardRefComdats.begin()->second,
198 "use of undefined comdat '$" +
199 ForwardRefComdats.begin()->first +
"'");
201 if (!ForwardRefVals.empty())
202 return Error(ForwardRefVals.begin()->second.second,
203 "use of undefined value '@" + ForwardRefVals.begin()->first +
206 if (!ForwardRefValIDs.empty())
207 return Error(ForwardRefValIDs.begin()->second.second,
208 "use of undefined value '@" +
209 Twine(ForwardRefValIDs.begin()->first) +
"'");
211 if (!ForwardRefMDNodes.empty())
212 return Error(ForwardRefMDNodes.begin()->second.second,
213 "use of undefined metadata '!" +
214 Twine(ForwardRefMDNodes.begin()->first) +
"'");
217 for (
auto &
N : NumberedMetadata) {
218 if (
N.second && !
N.second->isResolved())
219 N.second->resolveCycles();
222 for (
auto *Inst : InstsWithTBAATag) {
224 assert(MD &&
"UpgradeInstWithTBAATag should have a TBAA tag");
226 if (MD != UpgradedMD)
256 for (
const auto &
I : NamedTypes)
257 Slots->
NamedTypes.insert(std::make_pair(
I.getKey(),
I.second.first));
258 for (
const auto &
I : NumberedTypes)
259 Slots->
Types.insert(std::make_pair(
I.first,
I.second.first));
268 bool LLParser::ParseTopLevelEntities() {
271 default:
return TokError(
"expected top-level entity");
278 if (ParseSourceFileName())
287 case lltok::exclaim:
if (ParseStandaloneMetadata())
return true;
break;
292 if (ParseUseListOrderBB())
301 bool LLParser::ParseModuleAsm() {
307 ParseStringConstant(AsmStr))
return true;
316 bool LLParser::ParseTargetDefinition() {
320 default:
return TokError(
"unknown target property");
323 if (ParseToken(
lltok::equal,
"expected '=' after target triple") ||
324 ParseStringConstant(Str))
330 if (ParseToken(
lltok::equal,
"expected '=' after target datalayout") ||
331 ParseStringConstant(Str))
340 bool LLParser::ParseSourceFileName() {
344 if (ParseToken(
lltok::equal,
"expected '=' after source_filename") ||
345 ParseStringConstant(Str))
355 bool LLParser::ParseDepLibs() {
358 if (ParseToken(
lltok::equal,
"expected '=' after deplibs") ||
367 if (ParseStringConstant(Str))
return true;
375 bool LLParser::ParseUnnamedType() {
380 if (ParseToken(
lltok::equal,
"expected '=' after name") ||
384 Type *Result =
nullptr;
385 if (ParseStructDefinition(TypeLoc,
"",
386 NumberedTypes[TypeID], Result))
return true;
388 if (!isa<StructType>(Result)) {
389 std::pair<Type*, LocTy> &Entry = NumberedTypes[
TypeID];
391 return Error(TypeLoc,
"non-struct types may not be recursive");
392 Entry.first = Result;
393 Entry.second =
SMLoc();
401 bool LLParser::ParseNamedType() {
406 if (ParseToken(
lltok::equal,
"expected '=' after name") ||
410 Type *Result =
nullptr;
411 if (ParseStructDefinition(NameLoc, Name,
412 NamedTypes[Name], Result))
return true;
414 if (!isa<StructType>(Result)) {
415 std::pair<Type*, LocTy> &Entry = NamedTypes[
Name];
417 return Error(NameLoc,
"non-struct types may not be recursive");
418 Entry.first = Result;
419 Entry.second =
SMLoc();
427 bool LLParser::ParseDeclare() {
431 std::vector<std::pair<unsigned, MDNode *>> MDs;
435 if (ParseMetadataAttachment(MDK, N))
437 MDs.push_back({MDK, N});
441 if (ParseFunctionHeader(F,
false))
450 bool LLParser::ParseDefine() {
455 return ParseFunctionHeader(F,
true) ||
456 ParseOptionalFunctionMetadata(*F) ||
457 ParseFunctionBody(*F);
463 bool LLParser::ParseGlobalType(
bool &IsConstant) {
470 return TokError(
"expected 'global' or 'constant'");
476 bool LLParser::ParseOptionalUnnamedAddr(
494 bool LLParser::ParseUnnamedGlobal() {
495 unsigned VarID = NumberedVals.size();
502 return Error(Lex.
getLoc(),
"variable expected to be numbered '%" +
506 if (ParseToken(
lltok::equal,
"expected '=' after name"))
511 unsigned Linkage,
Visibility, DLLStorageClass;
514 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
515 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
519 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
520 DLLStorageClass, TLM, UnnamedAddr);
522 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
523 DLLStorageClass, TLM, UnnamedAddr);
530 bool LLParser::ParseNamedGlobal() {
537 unsigned Linkage,
Visibility, DLLStorageClass;
540 if (ParseToken(
lltok::equal,
"expected '=' in global variable") ||
541 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
542 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
546 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
547 DLLStorageClass, TLM, UnnamedAddr);
549 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
550 DLLStorageClass, TLM, UnnamedAddr);
553 bool LLParser::parseComdat() {
563 return TokError(
"expected comdat type");
568 return TokError(
"unknown selection kind");
590 if (I != ComdatSymTab.
end() && !ForwardRefComdats.erase(Name))
591 return Error(NameLoc,
"redefinition of comdat '$" + Name +
"'");
594 if (I != ComdatSymTab.
end())
605 bool LLParser::ParseMDString(
MDString *&Result) {
607 if (ParseStringConstant(Str))
return true;
614 bool LLParser::ParseMDNodeID(
MDNode *&Result) {
618 if (ParseUInt32(MID))
622 if (NumberedMetadata.count(MID)) {
623 Result = NumberedMetadata[MID];
628 auto &FwdRef = ForwardRefMDNodes[MID];
631 Result = FwdRef.first.
get();
632 NumberedMetadata[MID].reset(Result);
638 bool LLParser::ParseNamedMetadata() {
655 if (ParseMDNodeID(N))
return true;
659 return ParseToken(
lltok::rbrace,
"expected end of metadata node");
664 bool LLParser::ParseStandaloneMetadata() {
667 unsigned MetadataID = 0;
670 if (ParseUInt32(MetadataID) ||
676 return TokError(
"unexpected type in metadata definition");
680 if (ParseSpecializedMDNode(Init, IsDistinct))
683 ParseMDTuple(Init, IsDistinct))
687 auto FI = ForwardRefMDNodes.find(MetadataID);
688 if (FI != ForwardRefMDNodes.end()) {
689 FI->second.first->replaceAllUsesWith(Init);
690 ForwardRefMDNodes.erase(FI);
692 assert(NumberedMetadata[MetadataID] == Init &&
"Tracking VH didn't work");
694 if (NumberedMetadata.count(MetadataID))
695 return TokError(
"Metadata id is already used");
696 NumberedMetadata[MetadataID].reset(Init);
717 bool LLParser::parseIndirectSymbol(
718 const std::string &Name, LocTy NameLoc,
unsigned L,
unsigned Visibility,
733 return Error(NameLoc,
"invalid linkage type for alias");
736 return Error(NameLoc,
737 "symbol with local linkage must have default visibility");
742 ParseToken(
lltok::comma,
"expected comma after alias or ifunc's type"))
751 if (ParseGlobalTypeAndValue(Aliasee))
759 return Error(AliaseeLoc,
"invalid aliasee");
766 return Error(AliaseeLoc,
"An alias or ifunc must have pointer type");
767 unsigned AddrSpace = PTy->getAddressSpace();
769 if (IsAlias && Ty != PTy->getElementType())
772 "explicit pointee type doesn't match operand's pointee type");
774 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
777 "explicit pointee type should be a function type");
786 if (!ForwardRefVals.erase(Name))
787 return Error(NameLoc,
"redefinition of global '@" + Name +
"'");
790 auto I = ForwardRefValIDs.find(NumberedVals.size());
791 if (I != ForwardRefValIDs.end()) {
792 GVal = I->second.first;
793 ForwardRefValIDs.erase(I);
798 std::unique_ptr<GlobalIndirectSymbol> GA;
807 GA->setThreadLocalMode(TLM);
810 GA->setUnnamedAddr(UnnamedAddr);
813 NumberedVals.push_back(GA.get());
817 if (GVal->
getType() != GA->getType())
820 "forward reference and definition of alias have different types");
833 assert(GA->getName() == Name &&
"Should not be a name conflict!");
852 bool LLParser::ParseGlobal(
const std::string &Name, LocTy NameLoc,
853 unsigned Linkage,
bool HasLinkage,
854 unsigned Visibility,
unsigned DLLStorageClass,
858 return Error(NameLoc,
859 "symbol with local linkage must have default visibility");
862 bool IsConstant, IsExternallyInitialized;
863 LocTy IsExternallyInitializedLoc;
867 if (ParseOptionalAddrSpace(AddrSpace) ||
869 IsExternallyInitialized,
870 &IsExternallyInitializedLoc) ||
871 ParseGlobalType(IsConstant) ||
872 ParseType(Ty, TyLoc))
881 if (ParseGlobalValue(Ty, Init))
886 return Error(TyLoc,
"invalid type for global variable");
894 if (!ForwardRefVals.erase(Name))
895 return Error(NameLoc,
"redefinition of global '@" + Name +
"'");
898 auto I = ForwardRefValIDs.find(NumberedVals.size());
899 if (I != ForwardRefValIDs.end()) {
900 GVal = I->second.first;
901 ForwardRefValIDs.erase(I);
913 "forward reference and definition of global have different types");
915 GV = cast<GlobalVariable>(GVal);
922 NumberedVals.push_back(GV);
946 if (ParseOptionalAlignment(Alignment))
return true;
949 if (ParseGlobalObjectMetadataAttachment(*GV))
953 if (parseOptionalComdat(Name, C))
958 return TokError(
"unknown global variable property!");
967 bool LLParser::ParseUnnamedAttrGrp() {
973 return TokError(
"expected attribute group id");
976 std::vector<unsigned> unused;
982 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused,
true,
984 ParseToken(
lltok::rbrace,
"expected end of attribute group"))
987 if (!NumberedAttrBuilders[VarID].hasAttributes())
988 return Error(AttrGrpLoc,
"attribute group has no attributes");
995 bool LLParser::ParseFnAttributeValuePairs(
AttrBuilder &B,
996 std::vector<unsigned> &FwdRefAttrGrps,
997 bool inAttrGrp, LocTy &BuiltinLoc) {
998 bool HaveError =
false;
1005 BuiltinLoc = Lex.
getLoc();
1008 if (!inAttrGrp)
return HaveError;
1009 return Error(Lex.
getLoc(),
"unterminated attribute group");
1021 "cannot have an attribute group reference in an attribute group");
1024 if (inAttrGrp)
break;
1027 FwdRefAttrGrps.push_back(AttrGrpNum);
1032 if (ParseStringAttribute(B))
1046 ParseUInt32(Alignment))
1049 if (ParseOptionalAlignment(Alignment))
1060 ParseUInt32(Alignment))
1063 if (ParseOptionalStackAlignment(Alignment))
1070 unsigned ElemSizeArg;
1073 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1086 B.
addAttribute(Attribute::InaccessibleMemOrArgMemOnly);
break;
1127 "invalid use of attribute on a function");
1143 "invalid use of parameter-only attribute on a function");
1156 const std::string &Name) {
1169 GlobalValue *LLParser::GetGlobalVal(
const std::string &Name,
Type *Ty,
1173 Error(Loc,
"global variable reference must have pointer type");
1184 auto I = ForwardRefVals.find(Name);
1185 if (I != ForwardRefVals.end())
1186 Val = I->second.first;
1191 if (Val->
getType() == Ty)
return Val;
1192 Error(Loc,
"'@" + Name +
"' defined with type '" +
1199 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
1203 GlobalValue *LLParser::GetGlobalVal(
unsigned ID,
Type *Ty, LocTy Loc) {
1206 Error(Loc,
"global variable reference must have pointer type");
1210 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[
ID] :
nullptr;
1215 auto I = ForwardRefValIDs.find(ID);
1216 if (I != ForwardRefValIDs.end())
1217 Val = I->second.first;
1222 if (Val->
getType() == Ty)
return Val;
1223 Error(Loc,
"'@" +
Twine(ID) +
"' defined with type '" +
1230 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
1238 Comdat *LLParser::getComdat(
const std::string &Name, LocTy Loc) {
1242 if (I != ComdatSymTab.
end())
1247 ForwardRefComdats[
Name] = Loc;
1257 bool LLParser::ParseToken(
lltok::Kind T,
const char *ErrMsg) {
1259 return TokError(ErrMsg);
1266 bool LLParser::ParseStringConstant(std::string &Result) {
1268 return TokError(
"expected string constant");
1276 bool LLParser::ParseUInt32(
uint32_t &Val) {
1278 return TokError(
"expected integer");
1280 if (Val64 !=
unsigned(Val64))
1281 return TokError(
"expected 32-bit integer (too large)");
1289 bool LLParser::ParseUInt64(uint64_t &Val) {
1291 return TokError(
"expected integer");
1304 return TokError(
"expected localdynamic, initialexec or localexec");
1332 return ParseTLSModel(TLM) ||
1333 ParseToken(
lltok::rparen,
"expected ')' after thread local model");
1341 bool LLParser::ParseOptionalAddrSpace(
unsigned &AddrSpace) {
1345 return ParseToken(
lltok::lparen,
"expected '(' in address space") ||
1346 ParseUInt32(AddrSpace) ||
1353 bool LLParser::ParseStringAttribute(
AttrBuilder &B) {
1357 if (EatIfPresent(
lltok::equal) && ParseStringConstant(Val))
1364 bool LLParser::ParseOptionalParamAttrs(
AttrBuilder &B) {
1365 bool HaveError =
false;
1375 if (ParseStringAttribute(B))
1381 if (ParseOptionalAlignment(Alignment))
1444 HaveError |=
Error(Lex.
getLoc(),
"invalid use of function-only attribute");
1453 bool LLParser::ParseOptionalReturnAttrs(
AttrBuilder &B) {
1454 bool HaveError =
false;
1464 if (ParseStringAttribute(B))
1484 if (ParseOptionalAlignment(Alignment))
1504 HaveError |=
Error(Lex.
getLoc(),
"invalid use of parameter-only attribute");
1535 HaveError |=
Error(Lex.
getLoc(),
"invalid use of function-only attribute");
1540 HaveError |=
Error(Lex.
getLoc(),
"invalid use of attribute on return type");
1591 bool LLParser::ParseOptionalLinkage(
unsigned &Res,
bool &HasLinkage,
1592 unsigned &Visibility,
1593 unsigned &DLLStorageClass) {
1597 ParseOptionalVisibility(Visibility);
1598 ParseOptionalDLLStorageClass(DLLStorageClass);
1608 void LLParser::ParseOptionalVisibility(
unsigned &Res) {
1631 void LLParser::ParseOptionalDLLStorageClass(
unsigned &Res) {
1687 bool LLParser::ParseOptionalCallingConv(
unsigned &CC) {
1728 return ParseUInt32(CC);
1738 bool LLParser::ParseMetadataAttachment(
unsigned &
Kind,
MDNode *&MD) {
1745 return ParseMDNode(MD);
1750 bool LLParser::ParseInstructionMetadata(
Instruction &Inst) {
1753 return TokError(
"expected metadata after comma");
1757 if (ParseMetadataAttachment(MDK, N))
1762 InstsWithTBAATag.push_back(&Inst);
1771 bool LLParser::ParseGlobalObjectMetadataAttachment(
GlobalObject &GO) {
1774 if (ParseMetadataAttachment(MDK, N))
1783 bool LLParser::ParseOptionalFunctionMetadata(
Function &F) {
1785 if (ParseGlobalObjectMetadataAttachment(F))
1793 bool LLParser::ParseOptionalAlignment(
unsigned &Alignment) {
1798 if (ParseUInt32(Alignment))
return true;
1800 return Error(AlignLoc,
"alignment is not a power of two");
1802 return Error(AlignLoc,
"huge alignments are not supported yet");
1811 bool LLParser::ParseOptionalDerefAttrBytes(
lltok::Kind AttrKind,
1818 if (!EatIfPresent(AttrKind))
1822 return Error(ParenLoc,
"expected '('");
1824 if (ParseUInt64(Bytes))
return true;
1827 return Error(ParenLoc,
"expected ')'");
1829 return Error(DerefLoc,
"dereferenceable bytes must be non-zero");
1839 bool LLParser::ParseOptionalCommaAlign(
unsigned &Alignment,
1840 bool &AteExtraComma) {
1841 AteExtraComma =
false;
1845 AteExtraComma =
true;
1850 return Error(Lex.
getLoc(),
"expected metadata or 'align'");
1852 if (ParseOptionalAlignment(Alignment))
return true;
1858 bool LLParser::parseAllocSizeArguments(
unsigned &BaseSizeArg,
1862 auto StartParen = Lex.
getLoc();
1864 return Error(StartParen,
"expected '('");
1866 if (ParseUInt32(BaseSizeArg))
1870 auto HowManyAt = Lex.
getLoc();
1872 if (ParseUInt32(HowMany))
1874 if (HowMany == BaseSizeArg)
1875 return Error(HowManyAt,
1876 "'allocsize' indices can't refer to the same parameter");
1877 HowManyArg = HowMany;
1881 auto EndParen = Lex.
getLoc();
1883 return Error(EndParen,
"expected ')'");
1901 return ParseOrdering(Ordering);
1910 default:
return TokError(
"Expected ordering on atomic instruction");
1929 bool LLParser::ParseOptionalStackAlignment(
unsigned &Alignment) {
1935 return Error(ParenLoc,
"expected '('");
1937 if (ParseUInt32(Alignment))
return true;
1940 return Error(ParenLoc,
"expected ')'");
1942 return Error(AlignLoc,
"stack alignment is not a power of two");
1956 bool &AteExtraComma) {
1957 AteExtraComma =
false;
1960 return TokError(
"expected ',' as start of index list");
1964 if (Indices.
empty())
return TokError(
"expected index");
1965 AteExtraComma =
true;
1969 if (ParseUInt32(Idx))
return true;
1981 bool LLParser::ParseType(
Type *&Result,
const Twine &Msg,
bool AllowVoid) {
1985 return TokError(Msg);
1993 if (ParseAnonStructType(Result,
false))
1999 if (ParseArrayVectorType(Result,
false))
2006 if (ParseAnonStructType(Result,
true) ||
2007 ParseToken(
lltok::greater,
"expected '>' at end of packed struct"))
2009 }
else if (ParseArrayVectorType(Result,
true))
2014 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.
getStrVal()];
2020 Entry.second = Lex.
getLoc();
2022 Result = Entry.first;
2029 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.
getUIntVal()];
2035 Entry.second = Lex.
getLoc();
2037 Result = Entry.first;
2048 if (!AllowVoid && Result->
isVoidTy())
2049 return Error(TypeLoc,
"void type only allowed for function results");
2055 return TokError(
"basic block pointers are invalid");
2057 return TokError(
"pointers to void are invalid - use i8* instead");
2059 return TokError(
"pointer to this type is invalid");
2067 return TokError(
"basic block pointers are invalid");
2069 return TokError(
"pointers to void are invalid; use i8* instead");
2071 return TokError(
"pointer to this type is invalid");
2073 if (ParseOptionalAddrSpace(AddrSpace) ||
2074 ParseToken(
lltok::star,
"expected '*' in address space"))
2083 if (ParseFunctionType(Result))
2096 PerFunctionState &PFS,
bool IsMustTailCall,
2097 bool InVarArgsFunc) {
2101 unsigned AttrIndex = 1;
2104 if (!ArgList.
empty() &&
2105 ParseToken(
lltok::comma,
"expected ',' in argument list"))
2110 const char *Msg =
"unexpected ellipsis in argument list for ";
2111 if (!IsMustTailCall)
2112 return TokError(
Twine(Msg) +
"non-musttail call");
2114 return TokError(
Twine(Msg) +
"musttail call in non-varargs function");
2116 return ParseToken(
lltok::rparen,
"expected ')' at end of argument list");
2121 Type *ArgTy =
nullptr;
2124 if (ParseType(ArgTy, ArgLoc))
2128 if (ParseMetadataAsValue(V, PFS))
2132 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2140 if (IsMustTailCall && InVarArgsFunc)
2141 return TokError(
"expected '...' at end of argument list for musttail call "
2142 "in varargs function");
2157 bool LLParser::ParseOptionalOperandBundles(
2165 if (!BundleList.
empty() &&
2166 ParseToken(
lltok::comma,
"expected ',' in input list"))
2170 if (ParseStringConstant(Tag))
2173 if (ParseToken(
lltok::lparen,
"expected '(' in operand bundle"))
2176 std::vector<Value *> Inputs;
2179 if (!Inputs.empty() &&
2180 ParseToken(
lltok::comma,
"expected ',' in input list"))
2184 Value *Input =
nullptr;
2185 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2187 Inputs.push_back(Input);
2190 BundleList.
emplace_back(std::move(Tag), std::move(Inputs));
2195 if (BundleList.
empty())
2196 return Error(BeginLoc,
"operand bundle set must not be empty");
2224 Type *ArgTy =
nullptr;
2228 if (ParseType(ArgTy) ||
2229 ParseOptionalParamAttrs(Attrs))
return true;
2232 return Error(TypeLoc,
"argument can not have void type");
2240 return Error(TypeLoc,
"invalid type for function argument");
2242 unsigned AttrIndex = 1;
2244 AttrIndex++, Attrs),
2256 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs))
return true;
2259 return Error(TypeLoc,
"argument can not have void type");
2269 return Error(TypeLoc,
"invalid type for function argument");
2273 AttributeSet::get(ArgTy->
getContext(), AttrIndex++, Attrs),
2278 return ParseToken(
lltok::rparen,
"expected ')' at end of argument list");
2283 bool LLParser::ParseFunctionType(
Type *&Result) {
2287 return TokError(
"invalid function return type");
2291 if (ParseArgumentList(ArgList, isVarArg))
2295 for (
unsigned i = 0, e = ArgList.
size();
i != e; ++
i) {
2296 if (!ArgList[
i].Name.
empty())
2297 return Error(ArgList[
i].Loc,
"argument name invalid in function type");
2299 return Error(ArgList[
i].Loc,
2300 "argument attributes invalid in function type");
2304 for (
unsigned i = 0, e = ArgList.
size();
i != e; ++
i)
2313 bool LLParser::ParseAnonStructType(
Type *&Result,
bool Packed) {
2315 if (ParseStructBody(Elts))
return true;
2322 bool LLParser::ParseStructDefinition(
SMLoc TypeLoc,
StringRef Name,
2323 std::pair<Type*, LocTy> &Entry,
2326 if (Entry.first && !Entry.second.isValid())
2327 return Error(TypeLoc,
"redefinition of type");
2333 Entry.second =
SMLoc();
2338 ResultTy = Entry.first;
2350 return Error(TypeLoc,
"forward references to non-struct type");
2354 return ParseArrayVectorType(ResultTy,
true);
2355 return ParseType(ResultTy);
2359 Entry.second =
SMLoc();
2365 StructType *STy = cast<StructType>(Entry.first);
2368 if (ParseStructBody(Body) ||
2369 (isPacked && ParseToken(
lltok::greater,
"expected '>' in packed struct")))
2393 if (ParseType(Ty))
return true;
2397 return Error(EltTyLoc,
"invalid element type for struct");
2401 if (ParseType(Ty))
return true;
2404 return Error(EltTyLoc,
"invalid element type for struct");
2409 return ParseToken(
lltok::rbrace,
"expected '}' at end of struct");
2417 bool LLParser::ParseArrayVectorType(
Type *&Result,
bool isVector) {
2420 return TokError(
"expected number in address space");
2426 if (ParseToken(
lltok::kw_x,
"expected 'x' after element count"))
2430 Type *EltTy =
nullptr;
2431 if (ParseType(EltTy))
return true;
2434 "expected end of sequential type"))
2439 return Error(SizeLoc,
"zero element vector is illegal");
2440 if ((
unsigned)Size != Size)
2441 return Error(SizeLoc,
"size too large for vector");
2443 return Error(TypeLoc,
"invalid vector element type");
2447 return Error(TypeLoc,
"invalid array element type");
2464 NumberedVals.push_back(&
A);
2467 LLParser::PerFunctionState::~PerFunctionState() {
2470 for (
const auto &
P : ForwardRefVals) {
2471 if (isa<BasicBlock>(
P.second.first))
2473 P.second.first->replaceAllUsesWith(
2475 delete P.second.first;
2478 for (
const auto &
P : ForwardRefValIDs) {
2479 if (isa<BasicBlock>(
P.second.first))
2481 P.second.first->replaceAllUsesWith(
2483 delete P.second.first;
2487 bool LLParser::PerFunctionState::FinishFunction() {
2488 if (!ForwardRefVals.empty())
2489 return P.Error(ForwardRefVals.begin()->second.second,
2490 "use of undefined value '%" + ForwardRefVals.begin()->first +
2492 if (!ForwardRefValIDs.empty())
2493 return P.Error(ForwardRefValIDs.begin()->second.second,
2494 "use of undefined value '%" +
2495 Twine(ForwardRefValIDs.begin()->first) +
"'");
2502 Value *LLParser::PerFunctionState::GetVal(
const std::string &Name,
Type *Ty,
2510 auto I = ForwardRefVals.find(Name);
2511 if (I != ForwardRefVals.end())
2512 Val = I->second.first;
2517 if (Val->
getType() == Ty)
return Val;
2519 P.Error(Loc,
"'%" + Name +
"' is not a basic block");
2521 P.Error(Loc,
"'%" + Name +
"' defined with type '" +
2528 P.Error(Loc,
"invalid use of a non-first-class type");
2540 ForwardRefVals[
Name] = std::make_pair(FwdVal, Loc);
2544 Value *LLParser::PerFunctionState::GetVal(
unsigned ID,
Type *Ty, LocTy Loc) {
2546 Value *Val = ID < NumberedVals.size() ? NumberedVals[
ID] :
nullptr;
2551 auto I = ForwardRefValIDs.find(ID);
2552 if (I != ForwardRefValIDs.end())
2553 Val = I->second.first;
2558 if (Val->
getType() == Ty)
return Val;
2560 P.Error(Loc,
"'%" +
Twine(ID) +
"' is not a basic block");
2562 P.Error(Loc,
"'%" +
Twine(ID) +
"' defined with type '" +
2568 P.Error(Loc,
"invalid use of a non-first-class type");
2580 ForwardRefValIDs[
ID] = std::make_pair(FwdVal, Loc);
2586 bool LLParser::PerFunctionState::SetInstName(
int NameID,
2587 const std::string &NameStr,
2591 if (NameID != -1 || !NameStr.empty())
2592 return P.Error(NameLoc,
"instructions returning void cannot have a name");
2598 if (NameStr.empty()) {
2601 NameID = NumberedVals.size();
2603 if (
unsigned(NameID) != NumberedVals.size())
2604 return P.Error(NameLoc,
"instruction expected to be numbered '%" +
2605 Twine(NumberedVals.size()) +
"'");
2607 auto FI = ForwardRefValIDs.find(NameID);
2608 if (FI != ForwardRefValIDs.end()) {
2609 Value *Sentinel = FI->second.first;
2611 return P.Error(NameLoc,
"instruction forward referenced with type '" +
2616 ForwardRefValIDs.erase(FI);
2619 NumberedVals.push_back(Inst);
2624 auto FI = ForwardRefVals.find(NameStr);
2625 if (FI != ForwardRefVals.end()) {
2626 Value *Sentinel = FI->second.first;
2628 return P.Error(NameLoc,
"instruction forward referenced with type '" +
2633 ForwardRefVals.erase(FI);
2639 if (Inst->
getName() != NameStr)
2640 return P.Error(NameLoc,
"multiple definition of local value named '" +
2647 BasicBlock *LLParser::PerFunctionState::GetBB(
const std::string &Name,
2649 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2653 BasicBlock *LLParser::PerFunctionState::GetBB(
unsigned ID, LocTy Loc) {
2654 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2661 BasicBlock *LLParser::PerFunctionState::DefineBB(
const std::string &Name,
2665 BB = GetBB(NumberedVals.size(), Loc);
2667 BB = GetBB(Name, Loc);
2668 if (!BB)
return nullptr;
2676 ForwardRefValIDs.erase(NumberedVals.size());
2677 NumberedVals.push_back(BB);
2680 ForwardRefVals.erase(Name);
2696 bool LLParser::ParseValID(
ValID &ID, PerFunctionState *PFS) {
2699 default:
return TokError(
"expected value token");
2741 if (ParseGlobalValueVector(Elts) ||
2742 ParseToken(
lltok::rbrace,
"expected end of struct constant"))
2748 Elts.
size() *
sizeof(Elts[0]));
2760 if (ParseGlobalValueVector(Elts) ||
2762 ParseToken(
lltok::rbrace,
"expected end of packed struct")) ||
2766 if (isPackedStruct) {
2769 Elts.
size() *
sizeof(Elts[0]));
2776 return Error(ID.
Loc,
"constant vector must not be empty");
2779 !Elts[0]->getType()->isFloatingPointTy() &&
2780 !Elts[0]->getType()->isPointerTy())
2781 return Error(FirstEltLoc,
2782 "vector elements must have integer, pointer or floating point type");
2785 for (
unsigned i = 1, e = Elts.
size();
i != e; ++
i)
2786 if (Elts[
i]->
getType() != Elts[0]->getType())
2787 return Error(FirstEltLoc,
2788 "vector element #" +
Twine(
i) +
2799 if (ParseGlobalValueVector(Elts) ||
2800 ParseToken(lltok::rsquare,
"expected end of array constant"))
2812 return Error(FirstEltLoc,
"invalid array element type: " +
2818 for (
unsigned i = 0, e = Elts.
size();
i != e; ++
i) {
2819 if (Elts[
i]->
getType() != Elts[0]->getType())
2820 return Error(FirstEltLoc,
2821 "array element #" +
Twine(
i) +
2840 bool HasSideEffect, AlignStack, AsmDialect;
2845 ParseStringConstant(ID.
StrVal) ||
2846 ParseToken(
lltok::comma,
"expected comma in inline asm expression") ||
2851 (
unsigned(AsmDialect)<<2);
2862 if (ParseToken(
lltok::lparen,
"expected '(' in block address expression") ||
2864 ParseToken(
lltok::comma,
"expected comma in block address expression")||
2865 ParseValID(Label) ||
2866 ParseToken(
lltok::rparen,
"expected ')' in block address expression"))
2870 return Error(Fn.
Loc,
"expected function name in blockaddress");
2872 return Error(Label.
Loc,
"expected basic block name in blockaddress");
2877 if (Fn.
UIntVal < NumberedVals.size())
2878 GV = NumberedVals[Fn.
UIntVal];
2879 }
else if (!ForwardRefVals.count(Fn.
StrVal)) {
2885 if (!isa<Function>(GV))
2886 return Error(Fn.
Loc,
"expected function name in blockaddress");
2887 F = cast<Function>(GV);
2889 return Error(Fn.
Loc,
"cannot take blockaddress inside a declaration");
2895 ForwardRefBlockAddresses.insert(std::make_pair(
2897 std::map<ValID, GlobalValue *>()))
2898 .first->second.insert(std::make_pair(std::move(Label),
nullptr))
2911 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2913 BB = BlockAddressPFS->GetBB(Label.
UIntVal, Label.
Loc);
2915 BB = BlockAddressPFS->GetBB(Label.
StrVal, Label.
Loc);
2917 return Error(Label.
Loc,
"referenced value is not a basic block");
2920 return Error(Label.
Loc,
"cannot take address of numeric label after "
2921 "the function is defined");
2922 BB = dyn_cast_or_null<BasicBlock>(
2925 return Error(Label.
Loc,
"referenced value is not a basic block");
2947 Type *DestTy =
nullptr;
2950 if (ParseToken(
lltok::lparen,
"expected '(' after constantexpr cast") ||
2951 ParseGlobalTypeAndValue(SrcVal) ||
2952 ParseToken(
lltok::kw_to,
"expected 'to' in constantexpr cast") ||
2953 ParseType(DestTy) ||
2954 ParseToken(
lltok::rparen,
"expected ')' at end of constantexpr cast"))
2957 return Error(ID.
Loc,
"invalid cast opcode for cast from '" +
2969 if (ParseToken(
lltok::lparen,
"expected '(' in extractvalue constantexpr")||
2970 ParseGlobalTypeAndValue(Val) ||
2971 ParseIndexList(Indices) ||
2972 ParseToken(
lltok::rparen,
"expected ')' in extractvalue constantexpr"))
2976 return Error(ID.
Loc,
"extractvalue operand must be aggregate type");
2978 return Error(ID.
Loc,
"invalid indices for extractvalue");
2987 if (ParseToken(
lltok::lparen,
"expected '(' in insertvalue constantexpr")||
2988 ParseGlobalTypeAndValue(Val0) ||
2989 ParseToken(
lltok::comma,
"expected comma in insertvalue constantexpr")||
2990 ParseGlobalTypeAndValue(Val1) ||
2991 ParseIndexList(Indices) ||
2992 ParseToken(
lltok::rparen,
"expected ')' in insertvalue constantexpr"))
2995 return Error(ID.
Loc,
"insertvalue operand must be aggregate type");
2999 return Error(ID.
Loc,
"invalid indices for insertvalue");
3000 if (IndexedType != Val1->
getType())
3001 return Error(ID.
Loc,
"insertvalue operand and field disagree in type: '" +
3014 if (ParseCmpPredicate(PredVal, Opc) ||
3015 ParseToken(
lltok::lparen,
"expected '(' in compare constantexpr") ||
3016 ParseGlobalTypeAndValue(Val0) ||
3017 ParseToken(
lltok::comma,
"expected comma in compare constantexpr") ||
3018 ParseGlobalTypeAndValue(Val1) ||
3019 ParseToken(
lltok::rparen,
"expected ')' in compare constantexpr"))
3023 return Error(ID.
Loc,
"compare operands must have the same type");
3027 if (Opc == Instruction::FCmp) {
3029 return Error(ID.
Loc,
"fcmp requires floating point operands");
3032 assert(Opc == Instruction::ICmp &&
"Unexpected opcode for CmpInst!");
3035 return Error(ID.
Loc,
"icmp requires pointer or integer operands");
3066 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3074 }
else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3075 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3079 if (ParseToken(
lltok::lparen,
"expected '(' in binary constantexpr") ||
3080 ParseGlobalTypeAndValue(Val0) ||
3081 ParseToken(
lltok::comma,
"expected comma in binary constantexpr") ||
3082 ParseGlobalTypeAndValue(Val1) ||
3083 ParseToken(
lltok::rparen,
"expected ')' in binary constantexpr"))
3086 return Error(ID.
Loc,
"operands of constexpr must have same type");
3089 return Error(ModifierLoc,
"nuw only applies to integer operations");
3091 return Error(ModifierLoc,
"nsw only applies to integer operations");
3096 case Instruction::Sub:
3097 case Instruction::Mul:
3098 case Instruction::UDiv:
3099 case Instruction::SDiv:
3100 case Instruction::URem:
3101 case Instruction::SRem:
3102 case Instruction::Shl:
3103 case Instruction::AShr:
3104 case Instruction::LShr:
3106 return Error(ID.
Loc,
"constexpr requires integer operands");
3108 case Instruction::FAdd:
3109 case Instruction::FSub:
3110 case Instruction::FMul:
3111 case Instruction::FDiv:
3112 case Instruction::FRem:
3114 return Error(ID.
Loc,
"constexpr requires fp operands");
3135 if (ParseToken(
lltok::lparen,
"expected '(' in logical constantexpr") ||
3136 ParseGlobalTypeAndValue(Val0) ||
3137 ParseToken(
lltok::comma,
"expected comma in logical constantexpr") ||
3138 ParseGlobalTypeAndValue(Val1) ||
3139 ParseToken(
lltok::rparen,
"expected ')' in logical constantexpr"))
3142 return Error(ID.
Loc,
"operands of constexpr must have same type");
3145 "constexpr requires integer or integer vector operands");
3158 bool InBounds =
false;
3162 if (Opc == Instruction::GetElementPtr)
3165 if (ParseToken(
lltok::lparen,
"expected '(' in constantexpr"))
3169 if (Opc == Instruction::GetElementPtr) {
3170 if (ParseType(Ty) ||
3171 ParseToken(
lltok::comma,
"expected comma after getelementptr's type"))
3176 if (ParseGlobalValueVector(
3177 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp :
nullptr) ||
3181 if (Opc == Instruction::GetElementPtr) {
3182 if (Elts.
size() == 0 ||
3183 !Elts[0]->getType()->getScalarType()->isPointerTy())
3184 return Error(ID.
Loc,
"base of getelementptr must be a pointer");
3186 Type *BaseType = Elts[0]->getType();
3187 auto *BasePointerType = cast<PointerType>(BaseType->
getScalarType());
3188 if (Ty != BasePointerType->getElementType())
3191 "explicit pointee type doesn't match operand's pointee type");
3200 return Error(ID.
Loc,
"getelementptr index must be an integer");
3203 if (GEPWidth && (ValNumEl != GEPWidth))
3206 "getelementptr vector index has a wrong number of elements");
3209 GEPWidth = ValNumEl;
3214 if (!Indices.empty() && !Ty->
isSized(&Visited))
3215 return Error(ID.
Loc,
"base element of getelementptr must be sized");
3218 return Error(ID.
Loc,
"invalid getelementptr indices");
3221 if (*InRangeOp == 0)
3223 "inrange keyword may not appear on pointer operand");
3228 InBounds, InRangeOp);
3230 if (Elts.
size() != 3)
3231 return Error(ID.
Loc,
"expected three operands to select");
3236 }
else if (Opc == Instruction::ShuffleVector) {
3237 if (Elts.
size() != 3)
3238 return Error(ID.
Loc,
"expected three operands to shufflevector");
3240 return Error(ID.
Loc,
"invalid operands to shufflevector");
3243 }
else if (Opc == Instruction::ExtractElement) {
3244 if (Elts.
size() != 2)
3245 return Error(ID.
Loc,
"expected two operands to extractelement");
3247 return Error(ID.
Loc,
"invalid extractelement operands");
3250 assert(Opc == Instruction::InsertElement &&
"Unknown opcode");
3251 if (Elts.
size() != 3)
3252 return Error(ID.
Loc,
"expected three operands to insertelement");
3254 return Error(ID.
Loc,
"invalid insertelement operands");
3269 bool LLParser::ParseGlobalValue(
Type *Ty,
Constant *&C) {
3273 bool Parsed = ParseValID(ID) ||
3274 ConvertValIDToValue(Ty, ID, V,
nullptr);
3275 if (V && !(C = dyn_cast<Constant>(V)))
3276 return Error(ID.
Loc,
"global values must be constants");
3280 bool LLParser::ParseGlobalTypeAndValue(
Constant *&V) {
3282 return ParseType(Ty) ||
3283 ParseGlobalValue(Ty, V);
3286 bool LLParser::parseOptionalComdat(
StringRef GlobalName,
Comdat *&C) {
3295 return TokError(
"expected comdat variable");
3298 if (ParseToken(
lltok::rparen,
"expected ')' after comdat var"))
3301 if (GlobalName.
empty())
3302 return TokError(
"comdat cannot be unnamed");
3303 C = getComdat(GlobalName, KwLoc);
3316 Lex.
getKind() == lltok::rsquare ||
3323 *InRangeOp = Elts.
size();
3326 if (ParseGlobalTypeAndValue(C))
return true;
3333 bool LLParser::ParseMDTuple(
MDNode *&MD,
bool IsDistinct) {
3335 if (ParseMDNodeVector(Elts))
3346 bool LLParser::ParseMDNode(
MDNode *&N) {
3348 return ParseSpecializedMDNode(N);
3354 bool LLParser::ParseMDNodeTail(
MDNode *&N) {
3357 return ParseMDTuple(N);
3360 return ParseMDNodeID(N);
3366 template <
class FieldTy>
struct MDFieldImpl {
3367 typedef MDFieldImpl ImplTy;
3371 void assign(FieldTy Val) {
3373 this->Val = std::move(Val);
3376 explicit MDFieldImpl(FieldTy
Default)
3377 : Val(std::move(Default)), Seen(
false) {}
3380 struct MDUnsignedField :
public MDFieldImpl<uint64_t> {
3383 MDUnsignedField(uint64_t
Default = 0, uint64_t
Max = UINT64_MAX)
3387 struct LineField :
public MDUnsignedField {
3388 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3391 struct ColumnField :
public MDUnsignedField {
3392 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3395 struct DwarfTagField :
public MDUnsignedField {
3401 struct DwarfMacinfoTypeField :
public MDUnsignedField {
3407 struct DwarfAttEncodingField :
public MDUnsignedField {
3408 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::
DW_ATE_hi_user) {}
3411 struct DwarfVirtualityField :
public MDUnsignedField {
3415 struct DwarfLangField :
public MDUnsignedField {
3419 struct DwarfCCField :
public MDUnsignedField {
3420 DwarfCCField() : MDUnsignedField(0, dwarf::
DW_CC_hi_user) {}
3423 struct EmissionKindField :
public MDUnsignedField {
3424 EmissionKindField() : MDUnsignedField(0,
DICompileUnit::LastEmissionKind) {}
3427 struct DIFlagField :
public MDFieldImpl<DINode::DIFlags> {
3428 DIFlagField() : MDFieldImpl(
DINode::FlagZero) {}
3431 struct MDSignedField :
public MDFieldImpl<int64_t> {
3435 MDSignedField(int64_t
Default = 0)
3438 : ImplTy(Default), Min(Min), Max(Max) {}
3441 struct MDBoolField :
public MDFieldImpl<bool> {
3445 struct MDField :
public MDFieldImpl<Metadata *> {
3448 MDField(
bool AllowNull =
true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3451 struct MDConstant :
public MDFieldImpl<ConstantAsMetadata *> {
3452 MDConstant() : ImplTy(nullptr) {}
3455 struct MDStringField :
public MDFieldImpl<MDString *> {
3457 MDStringField(
bool AllowEmpty =
true)
3458 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3461 struct MDFieldList :
public MDFieldImpl<SmallVector<Metadata *, 4>> {
3465 struct ChecksumKindField :
public MDFieldImpl<DIFile::ChecksumKind> {
3466 ChecksumKindField() : ImplTy(
DIFile::CSK_None) {}
3475 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name,
3476 MDUnsignedField &Result) {
3478 return TokError(
"expected unsigned integer");
3481 if (U.ugt(Result.Max))
3482 return TokError(
"value for '" + Name +
"' too large, limit is " +
3484 Result.assign(U.getZExtValue());
3485 assert(Result.Val <= Result.Max &&
"Expected value in range");
3491 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name, LineField &Result) {
3492 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3495 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name, ColumnField &Result) {
3496 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3500 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name, DwarfTagField &Result) {
3502 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3505 return TokError(
"expected DWARF tag");
3509 return TokError(
"invalid DWARF tag" +
Twine(
" '") + Lex.
getStrVal() +
"'");
3510 assert(Tag <= Result.Max &&
"Expected valid DWARF tag");
3518 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name,
3519 DwarfMacinfoTypeField &Result) {
3521 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3524 return TokError(
"expected DWARF macinfo type");
3529 "invalid DWARF macinfo type" +
Twine(
" '") + Lex.
getStrVal() +
"'");
3530 assert(Macinfo <= Result.Max &&
"Expected valid DWARF macinfo type");
3532 Result.assign(Macinfo);
3538 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name,
3539 DwarfVirtualityField &Result) {
3541 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3544 return TokError(
"expected DWARF virtuality code");
3548 return TokError(
"invalid DWARF virtuality code" +
Twine(
" '") +
3550 assert(Virtuality <= Result.Max &&
"Expected valid DWARF virtuality code");
3551 Result.assign(Virtuality);
3557 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name, DwarfLangField &Result) {
3559 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3562 return TokError(
"expected DWARF language");
3566 return TokError(
"invalid DWARF language" +
Twine(
" '") + Lex.
getStrVal() +
3568 assert(Lang <= Result.Max &&
"Expected valid DWARF language");
3569 Result.assign(Lang);
3575 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name, DwarfCCField &Result) {
3577 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3580 return TokError(
"expected DWARF calling convention");
3584 return TokError(
"invalid DWARF calling convention" +
Twine(
" '") + Lex.
getStrVal() +
3586 assert(CC <= Result.Max &&
"Expected valid DWARF calling convention");
3593 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name, EmissionKindField &Result) {
3595 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3598 return TokError(
"expected emission kind");
3602 return TokError(
"invalid emission kind" +
Twine(
" '") + Lex.
getStrVal() +
3604 assert(*Kind <= Result.Max &&
"Expected valid emission kind");
3605 Result.assign(*Kind);
3611 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name,
3612 DwarfAttEncodingField &Result) {
3614 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3617 return TokError(
"expected DWARF type attribute encoding");
3621 return TokError(
"invalid DWARF type attribute encoding" +
Twine(
" '") +
3623 assert(Encoding <= Result.Max &&
"Expected valid DWARF language");
3624 Result.assign(Encoding);
3634 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name, DIFlagField &Result) {
3640 bool Res = ParseUInt32(TempVal);
3646 return TokError(
"expected debug info flag");
3650 return TokError(
Twine(
"invalid debug info flag flag '") +
3665 Result.assign(Combined);
3670 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name,
3671 MDSignedField &Result) {
3673 return TokError(
"expected signed integer");
3677 return TokError(
"value for '" + Name +
"' too small, limit is " +
3680 return TokError(
"value for '" + Name +
"' too large, limit is " +
3682 Result.assign(S.getExtValue());
3683 assert(Result.Val >= Result.Min &&
"Expected value in range");
3684 assert(Result.Val <= Result.Max &&
"Expected value in range");
3690 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name, MDBoolField &Result) {
3693 return TokError(
"expected 'true' or 'false'");
3695 Result.assign(
true);
3698 Result.assign(
false);
3706 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name, MDField &Result) {
3708 if (!Result.AllowNull)
3709 return TokError(
"'" + Name +
"' cannot be null");
3711 Result.assign(
nullptr);
3716 if (ParseMetadata(MD,
nullptr))
3724 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name, MDStringField &Result) {
3727 if (ParseStringConstant(S))
3730 if (!Result.AllowEmpty && S.empty())
3731 return Error(ValueLoc,
"'" + Name +
"' cannot be empty");
3733 Result.assign(S.empty() ?
nullptr :
MDString::get(Context, S));
3738 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name, MDFieldList &Result) {
3740 if (ParseMDNodeVector(MDs))
3743 Result.assign(std::move(MDs));
3748 bool LLParser::ParseMDField(LocTy Loc,
StringRef Name,
3749 ChecksumKindField &Result) {
3756 Result.assign(CSKind);
3763 template <
class ParserTy>
3764 bool LLParser::ParseMDFieldsImplBody(ParserTy
parseField) {
3767 return TokError(
"expected field label here");
3776 template <
class ParserTy>
3777 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3784 if (ParseMDFieldsImplBody(parseField))
3787 ClosingLoc = Lex.
getLoc();
3791 template <
class FieldTy>
3792 bool LLParser::ParseMDField(
StringRef Name, FieldTy &Result) {
3794 return TokError(
"field '" + Name +
"' cannot be specified more than once");
3798 return ParseMDField(Loc, Name, Result);
3801 bool LLParser::ParseSpecializedMDNode(
MDNode *&N,
bool IsDistinct) {
3804 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3805 if (Lex.getStrVal() == #CLASS) \
3806 return Parse##CLASS(N, IsDistinct);
3807 #include "llvm/IR/Metadata.def"
3809 return TokError(
"expected metadata type");
3812 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3813 #define NOP_FIELD(NAME, TYPE, INIT)
3814 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3816 return Error(ClosingLoc, "missing required field '" #NAME "'");
3817 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3818 if (Lex.getStrVal() == #NAME) \
3819 return ParseMDField(#NAME, NAME);
3820 #define PARSE_MD_FIELDS() \
3821 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3824 if (ParseMDFieldsImpl([&]() -> bool { \
3825 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3826 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3829 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3831 #define GET_OR_DISTINCT(CLASS, ARGS) \
3832 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3836 bool LLParser::ParseDILocation(
MDNode *&Result,
bool IsDistinct) {
3837 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3838 OPTIONAL(line, LineField, ); \
3839 OPTIONAL(column, ColumnField, ); \
3840 REQUIRED(scope, MDField, ( false)); \
3841 OPTIONAL(inlinedAt, MDField, );
3843 #undef VISIT_MD_FIELDS
3846 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3852 bool LLParser::ParseGenericDINode(
MDNode *&Result,
bool IsDistinct) {
3853 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3854 REQUIRED(tag, DwarfTagField, ); \
3855 OPTIONAL(header, MDStringField, ); \
3856 OPTIONAL(operands, MDFieldList, );
3858 #undef VISIT_MD_FIELDS
3861 (Context, tag.Val, header.Val, operands.Val));
3867 bool LLParser::ParseDISubrange(
MDNode *&Result,
bool IsDistinct) {
3868 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3869 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3870 OPTIONAL(lowerBound, MDSignedField, );
3872 #undef VISIT_MD_FIELDS
3880 bool LLParser::ParseDIEnumerator(
MDNode *&Result,
bool IsDistinct) {
3881 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3882 REQUIRED(name, MDStringField, ); \
3883 REQUIRED(value, MDSignedField, );
3885 #undef VISIT_MD_FIELDS
3893 bool LLParser::ParseDIBasicType(
MDNode *&Result,
bool IsDistinct) {
3894 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3895 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3896 OPTIONAL(name, MDStringField, ); \
3897 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3898 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3899 OPTIONAL(encoding, DwarfAttEncodingField, );
3901 #undef VISIT_MD_FIELDS
3904 align.Val, encoding.Val));
3912 bool LLParser::ParseDIDerivedType(
MDNode *&Result,
bool IsDistinct) {
3913 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3914 REQUIRED(tag, DwarfTagField, ); \
3915 OPTIONAL(name, MDStringField, ); \
3916 OPTIONAL(file, MDField, ); \
3917 OPTIONAL(line, LineField, ); \
3918 OPTIONAL(scope, MDField, ); \
3919 REQUIRED(baseType, MDField, ); \
3920 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3921 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3922 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3923 OPTIONAL(flags, DIFlagField, ); \
3924 OPTIONAL(extraData, MDField, );
3926 #undef VISIT_MD_FIELDS
3929 (Context, tag.Val,
name.Val,
file.Val, line.Val,
3930 scope.Val, baseType.Val, size.Val, align.Val,
3931 offset.Val, flags.Val, extraData.Val));
3935 bool LLParser::ParseDICompositeType(
MDNode *&Result,
bool IsDistinct) {
3936 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3937 REQUIRED(tag, DwarfTagField, ); \
3938 OPTIONAL(name, MDStringField, ); \
3939 OPTIONAL(file, MDField, ); \
3940 OPTIONAL(line, LineField, ); \
3941 OPTIONAL(scope, MDField, ); \
3942 OPTIONAL(baseType, MDField, ); \
3943 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3944 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
3945 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3946 OPTIONAL(flags, DIFlagField, ); \
3947 OPTIONAL(elements, MDField, ); \
3948 OPTIONAL(runtimeLang, DwarfLangField, ); \
3949 OPTIONAL(vtableHolder, MDField, ); \
3950 OPTIONAL(templateParams, MDField, ); \
3951 OPTIONAL(identifier, MDStringField, );
3953 #undef VISIT_MD_FIELDS
3958 Context, *identifier.Val, tag.Val,
name.Val,
file.Val, line.Val,
3959 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
3960 elements.Val, runtimeLang.Val, vtableHolder.Val,
3961 templateParams.Val)) {
3970 (Context, tag.Val,
name.Val,
file.Val, line.Val, scope.Val, baseType.Val,
3971 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3972 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3976 bool LLParser::ParseDISubroutineType(
MDNode *&Result,
bool IsDistinct) {
3977 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3978 OPTIONAL(flags, DIFlagField, ); \
3979 OPTIONAL(cc, DwarfCCField, ); \
3980 REQUIRED(types, MDField, );
3982 #undef VISIT_MD_FIELDS
3985 (Context, flags.Val, cc.Val, types.Val));
3993 bool LLParser::ParseDIFile(
MDNode *&Result,
bool IsDistinct) {
3994 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3995 REQUIRED(filename, MDStringField, ); \
3996 REQUIRED(directory, MDStringField, ); \
3997 OPTIONAL(checksumkind, ChecksumKindField, ); \
3998 OPTIONAL(checksum, MDStringField, );
4000 #undef VISIT_MD_FIELDS
4003 checksumkind.Val, checksum.Val));
4013 bool LLParser::ParseDICompileUnit(
MDNode *&Result,
bool IsDistinct) {
4015 return Lex.
Error(
"missing 'distinct', required for !DICompileUnit");
4017 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4018 REQUIRED(language, DwarfLangField, ); \
4019 REQUIRED(file, MDField, ( false)); \
4020 OPTIONAL(producer, MDStringField, ); \
4021 OPTIONAL(isOptimized, MDBoolField, ); \
4022 OPTIONAL(flags, MDStringField, ); \
4023 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4024 OPTIONAL(splitDebugFilename, MDStringField, ); \
4025 OPTIONAL(emissionKind, EmissionKindField, ); \
4026 OPTIONAL(enums, MDField, ); \
4027 OPTIONAL(retainedTypes, MDField, ); \
4028 OPTIONAL(globals, MDField, ); \
4029 OPTIONAL(imports, MDField, ); \
4030 OPTIONAL(macros, MDField, ); \
4031 OPTIONAL(dwoId, MDUnsignedField, ); \
4032 OPTIONAL(splitDebugInlining, MDBoolField, = true);
4034 #undef VISIT_MD_FIELDS
4037 Context, language.Val,
file.Val, producer.Val, isOptimized.Val, flags.Val,
4038 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4039 retainedTypes.Val,
globals.Val, imports.Val, macros.Val, dwoId.Val,
4040 splitDebugInlining.Val);
4052 bool LLParser::ParseDISubprogram(
MDNode *&Result,
bool IsDistinct) {
4054 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4055 OPTIONAL(scope, MDField, ); \
4056 OPTIONAL(name, MDStringField, ); \
4057 OPTIONAL(linkageName, MDStringField, ); \
4058 OPTIONAL(file, MDField, ); \
4059 OPTIONAL(line, LineField, ); \
4060 OPTIONAL(type, MDField, ); \
4061 OPTIONAL(isLocal, MDBoolField, ); \
4062 OPTIONAL(isDefinition, MDBoolField, (true)); \
4063 OPTIONAL(scopeLine, LineField, ); \
4064 OPTIONAL(containingType, MDField, ); \
4065 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4066 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4067 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4068 OPTIONAL(flags, DIFlagField, ); \
4069 OPTIONAL(isOptimized, MDBoolField, ); \
4070 OPTIONAL(unit, MDField, ); \
4071 OPTIONAL(templateParams, MDField, ); \
4072 OPTIONAL(declaration, MDField, ); \
4073 OPTIONAL(variables, MDField, );
4075 #undef VISIT_MD_FIELDS
4077 if (isDefinition.Val && !IsDistinct)
4080 "missing 'distinct', required for !DISubprogram when 'isDefinition'");
4084 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4085 scopeLine.Val, containingType.Val, virtuality.Val,
4086 virtualIndex.Val, thisAdjustment.Val, flags.Val,
4087 isOptimized.Val, unit.Val, templateParams.Val,
4094 bool LLParser::ParseDILexicalBlock(
MDNode *&Result,
bool IsDistinct) {
4095 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4096 REQUIRED(scope, MDField, ( false)); \
4097 OPTIONAL(file, MDField, ); \
4098 OPTIONAL(line, LineField, ); \
4099 OPTIONAL(column, ColumnField, );
4101 #undef VISIT_MD_FIELDS
4110 bool LLParser::ParseDILexicalBlockFile(
MDNode *&Result,
bool IsDistinct) {
4111 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4112 REQUIRED(scope, MDField, ( false)); \
4113 OPTIONAL(file, MDField, ); \
4114 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4116 #undef VISIT_MD_FIELDS
4119 (Context, scope.Val,
file.Val, discriminator.Val));
4125 bool LLParser::ParseDINamespace(
MDNode *&Result,
bool IsDistinct) {
4126 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4127 REQUIRED(scope, MDField, ); \
4128 OPTIONAL(file, MDField, ); \
4129 OPTIONAL(name, MDStringField, ); \
4130 OPTIONAL(line, LineField, ); \
4131 OPTIONAL(exportSymbols, MDBoolField, );
4133 #undef VISIT_MD_FIELDS
4136 (Context, scope.Val,
file.Val,
name.Val, line.Val, exportSymbols.Val));
4142 bool LLParser::ParseDIMacro(
MDNode *&Result,
bool IsDistinct) {
4143 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4144 REQUIRED(type, DwarfMacinfoTypeField, ); \
4145 OPTIONAL(line, LineField, ); \
4146 REQUIRED(name, MDStringField, ); \
4147 OPTIONAL(value, MDStringField, );
4149 #undef VISIT_MD_FIELDS
4152 (Context, type.Val, line.Val,
name.Val, value.Val));
4158 bool LLParser::ParseDIMacroFile(
MDNode *&Result,
bool IsDistinct) {
4159 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4160 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4161 OPTIONAL(line, LineField, ); \
4162 REQUIRED(file, MDField, ); \
4163 OPTIONAL(nodes, MDField, );
4165 #undef VISIT_MD_FIELDS
4168 (Context, type.Val, line.Val,
file.Val, nodes.Val));
4175 bool LLParser::ParseDIModule(
MDNode *&Result,
bool IsDistinct) {
4176 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4177 REQUIRED(scope, MDField, ); \
4178 REQUIRED(name, MDStringField, ); \
4179 OPTIONAL(configMacros, MDStringField, ); \
4180 OPTIONAL(includePath, MDStringField, ); \
4181 OPTIONAL(isysroot, MDStringField, );
4183 #undef VISIT_MD_FIELDS
4186 configMacros.Val, includePath.Val, isysroot.Val));
4192 bool LLParser::ParseDITemplateTypeParameter(
MDNode *&Result,
bool IsDistinct) {
4193 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4194 OPTIONAL(name, MDStringField, ); \
4195 REQUIRED(type, MDField, );
4197 #undef VISIT_MD_FIELDS
4207 bool LLParser::ParseDITemplateValueParameter(
MDNode *&Result,
bool IsDistinct) {
4208 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4209 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4210 OPTIONAL(name, MDStringField, ); \
4211 OPTIONAL(type, MDField, ); \
4212 REQUIRED(value, MDField, );
4214 #undef VISIT_MD_FIELDS
4217 (Context, tag.Val,
name.Val, type.Val, value.Val));
4225 bool LLParser::ParseDIGlobalVariable(
MDNode *&Result,
bool IsDistinct) {
4226 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4227 REQUIRED(name, MDStringField, ( false)); \
4228 OPTIONAL(scope, MDField, ); \
4229 OPTIONAL(linkageName, MDStringField, ); \
4230 OPTIONAL(file, MDField, ); \
4231 OPTIONAL(line, LineField, ); \
4232 OPTIONAL(type, MDField, ); \
4233 OPTIONAL(isLocal, MDBoolField, ); \
4234 OPTIONAL(isDefinition, MDBoolField, (true)); \
4235 OPTIONAL(declaration, MDField, ); \
4236 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4238 #undef VISIT_MD_FIELDS
4241 (Context, scope.Val,
name.Val, linkageName.Val,
4242 file.Val, line.Val, type.Val, isLocal.Val,
4243 isDefinition.Val, declaration.Val, align.Val));
4254 bool LLParser::ParseDILocalVariable(
MDNode *&Result,
bool IsDistinct) {
4255 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4256 REQUIRED(scope, MDField, ( false)); \
4257 OPTIONAL(name, MDStringField, ); \
4258 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4259 OPTIONAL(file, MDField, ); \
4260 OPTIONAL(line, LineField, ); \
4261 OPTIONAL(type, MDField, ); \
4262 OPTIONAL(flags, DIFlagField, ); \
4263 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4265 #undef VISIT_MD_FIELDS
4268 (Context, scope.Val,
name.Val,
file.Val, line.Val,
4269 type.Val, arg.Val, flags.Val, align.Val));
4275 bool LLParser::ParseDIExpression(
MDNode *&Result,
bool IsDistinct) {
4291 return TokError(
Twine(
"invalid DWARF op '") + Lex.
getStrVal() +
"'");
4295 return TokError(
"expected unsigned integer");
4298 if (U.ugt(UINT64_MAX))
4299 return TokError(
"element too large, limit is " +
Twine(UINT64_MAX));
4313 bool LLParser::ParseDIGlobalVariableExpression(
MDNode *&Result,
4315 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4316 REQUIRED(var, MDField, ); \
4317 OPTIONAL(expr, MDField, );
4319 #undef VISIT_MD_FIELDS
4329 bool LLParser::ParseDIObjCProperty(
MDNode *&Result,
bool IsDistinct) {
4330 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4331 OPTIONAL(name, MDStringField, ); \
4332 OPTIONAL(file, MDField, ); \
4333 OPTIONAL(line, LineField, ); \
4334 OPTIONAL(setter, MDStringField, ); \
4335 OPTIONAL(getter, MDStringField, ); \
4336 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4337 OPTIONAL(type, MDField, );
4339 #undef VISIT_MD_FIELDS
4342 (Context,
name.Val,
file.Val, line.Val, setter.Val,
4350 bool LLParser::ParseDIImportedEntity(
MDNode *&Result,
bool IsDistinct) {
4351 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4352 REQUIRED(tag, DwarfTagField, ); \
4353 REQUIRED(scope, MDField, ); \
4354 OPTIONAL(entity, MDField, ); \
4355 OPTIONAL(line, LineField, ); \
4356 OPTIONAL(name, MDStringField, );
4358 #undef VISIT_MD_FIELDS
4361 entity.Val, line.Val,
name.Val));
4365 #undef PARSE_MD_FIELD
4367 #undef REQUIRE_FIELD
4368 #undef DECLARE_FIELD
4377 bool LLParser::ParseMetadataAsValue(
Value *&V, PerFunctionState &PFS) {
4380 if (ParseMetadata(MD, &PFS))
4391 bool LLParser::ParseValueAsMetadata(
Metadata *&MD,
const Twine &TypeMsg,
4392 PerFunctionState *PFS) {
4395 if (ParseType(Ty, TypeMsg, Loc))
4398 return Error(Loc,
"invalid metadata-value-metadata roundtrip");
4401 if (ParseValue(Ty, V, PFS))
4416 bool LLParser::ParseMetadata(
Metadata *&MD, PerFunctionState *PFS) {
4419 if (ParseSpecializedMDNode(N))
4428 return ParseValueAsMetadata(MD,
"expected metadata operand", PFS);
4438 if (ParseMDString(S))
4448 if (ParseMDNodeTail(N))
4458 bool LLParser::ConvertValIDToValue(
Type *Ty,
ValID &ID,
Value *&V,
4459 PerFunctionState *PFS) {
4461 return Error(ID.
Loc,
"functions are not values, refer to them as pointers");
4465 if (!PFS)
return Error(ID.
Loc,
"invalid use of function-local name");
4467 return V ==
nullptr;
4469 if (!PFS)
return Error(ID.
Loc,
"invalid use of function-local name");
4471 return V ==
nullptr;
4474 return Error(ID.
Loc,
"invalid type for inline asm constraint string");
4481 V = GetGlobalVal(ID.
StrVal, Ty, ID.
Loc);
4482 return V ==
nullptr;
4485 return V ==
nullptr;
4488 return Error(ID.
Loc,
"integer constant must have integer type");
4495 return Error(ID.
Loc,
"floating point constant invalid for type");
4511 return Error(ID.
Loc,
"floating point constant does not have type '" +
4517 return Error(ID.
Loc,
"null must be a pointer type");
4523 return Error(ID.
Loc,
"invalid type for undef constant");
4527 if (!Ty->
isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
4528 return Error(ID.
Loc,
"invalid empty array initializer");
4534 return Error(ID.
Loc,
"invalid type for null constant");
4539 return Error(ID.
Loc,
"invalid type for none constant");
4544 return Error(ID.
Loc,
"constant expression type mismatch");
4553 "initializer with struct type has wrong # elements");
4555 return Error(ID.
Loc,
"packed'ness of initializer and type don't match");
4558 for (
unsigned i = 0, e = ID.
UIntVal;
i != e; ++
i)
4561 " of struct initializer doesn't match struct element type");
4566 return Error(ID.
Loc,
"constant expression type mismatch");
4572 bool LLParser::parseConstantValue(
Type *Ty,
Constant *&C) {
4576 if (ParseValID(ID,
nullptr))
4586 if (ConvertValIDToValue(Ty, ID, V,
nullptr))
4588 assert(isa<Constant>(V) &&
"Expected a constant value");
4589 C = cast<Constant>(V);
4593 return Error(Loc,
"expected a constant value");
4597 bool LLParser::ParseValue(
Type *Ty,
Value *&V, PerFunctionState *PFS) {
4600 return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
4603 bool LLParser::ParseTypeAndValue(
Value *&V, PerFunctionState *PFS) {
4605 return ParseType(Ty) ||
4606 ParseValue(Ty, V, PFS);
4609 bool LLParser::ParseTypeAndBasicBlock(
BasicBlock *&BB, LocTy &Loc,
4610 PerFunctionState &PFS) {
4613 if (ParseTypeAndValue(V, PFS))
return true;
4614 if (!isa<BasicBlock>(V))
4615 return Error(Loc,
"expected a basic block");
4616 BB = cast<BasicBlock>(V);
4624 bool LLParser::ParseFunctionHeader(
Function *&Fn,
bool isDefine) {
4630 unsigned DLLStorageClass;
4634 Type *RetType =
nullptr;
4636 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
4637 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
4638 ParseType(RetType, RetTypeLoc,
true ))
4647 return Error(LinkageLoc,
"invalid linkage for function definition");
4657 return Error(LinkageLoc,
"invalid linkage for function declaration");
4661 return Error(LinkageLoc,
"invalid function linkage type");
4665 return Error(LinkageLoc,
4666 "symbol with local linkage must have default visibility");
4669 return Error(RetTypeLoc,
"invalid function return type");
4673 std::string FunctionName;
4679 if (NameID != NumberedVals.size())
4680 return TokError(
"function expected to be numbered '%" +
4681 Twine(NumberedVals.size()) +
"'");
4683 return TokError(
"expected function name");
4689 return TokError(
"expected '(' in function argument list");
4694 std::vector<unsigned> FwdRefAttrGrps;
4700 LocTy UnnamedAddrLoc;
4706 if (ParseArgumentList(ArgList, isVarArg) ||
4707 ParseOptionalUnnamedAddr(UnnamedAddr) ||
4708 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps,
false,
4711 ParseStringConstant(Section)) ||
4712 parseOptionalComdat(FunctionName, C) ||
4713 ParseOptionalAlignment(Alignment) ||
4715 ParseStringConstant(GC)) ||
4717 ParseGlobalTypeAndValue(Prefix)) ||
4719 ParseGlobalTypeAndValue(Prologue)) ||
4721 ParseGlobalTypeAndValue(PersonalityFn)))
4724 if (FuncAttrs.
contains(Attribute::Builtin))
4725 return Error(BuiltinLoc,
"'builtin' attribute not valid on function");
4735 std::vector<Type*> ParamTypeList;
4743 for (
unsigned i = 0, e = ArgList.
size();
i != e; ++
i) {
4744 ParamTypeList.push_back(ArgList[
i].Ty);
4745 if (ArgList[
i].Attrs.hasAttributes(
i + 1)) {
4759 return Error(RetTypeLoc,
"functions with 'sret' argument must return void");
4766 if (!FunctionName.empty()) {
4769 auto FRVI = ForwardRefVals.find(FunctionName);
4770 if (FRVI != ForwardRefVals.end()) {
4773 return Error(FRVI->second.second,
"invalid forward reference to "
4774 "function as global value!");
4776 return Error(FRVI->second.second,
"invalid forward reference to "
4777 "function '" + FunctionName +
"' with wrong type!");
4779 ForwardRefVals.erase(FRVI);
4782 return Error(NameLoc,
"invalid redefinition of function '" +
4783 FunctionName +
"'");
4785 return Error(NameLoc,
"redefinition of function '@" + FunctionName +
"'");
4791 auto I = ForwardRefValIDs.find(NumberedVals.size());
4792 if (I != ForwardRefValIDs.end()) {
4793 Fn = cast<Function>(I->second.first);
4795 return Error(NameLoc,
"type of definition and forward reference of '@" +
4796 Twine(NumberedVals.size()) +
"' disagree");
4797 ForwardRefValIDs.erase(I);
4806 if (FunctionName.empty())
4807 NumberedVals.push_back(Fn);
4819 if (!GC.empty()) Fn->
setGC(GC);
4822 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4826 for (
unsigned i = 0, e = ArgList.
size();
i != e; ++
i, ++ArgIt) {
4828 if (ArgList[
i].Name.
empty())
continue;
4831 ArgIt->setName(ArgList[
i].Name);
4833 if (ArgIt->getName() != ArgList[
i].Name)
4834 return Error(ArgList[
i].Loc,
"redefinition of argument '%" +
4835 ArgList[
i].Name +
"'");
4843 if (FunctionName.empty()) {
4845 ID.
UIntVal = NumberedVals.size() - 1;
4848 ID.
StrVal = FunctionName;
4850 auto Blocks = ForwardRefBlockAddresses.find(ID);
4851 if (Blocks != ForwardRefBlockAddresses.end())
4852 return Error(Blocks->first.Loc,
4853 "cannot take blockaddress inside a declaration");
4857 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4867 auto Blocks =
P.ForwardRefBlockAddresses.find(ID);
4868 if (Blocks ==
P.ForwardRefBlockAddresses.end())
4871 for (
const auto &I : Blocks->second) {
4872 const ValID &BBID = I.first;
4876 "Expected local id or name");
4883 return P.Error(BBID.
Loc,
"referenced value is not a basic block");
4889 P.ForwardRefBlockAddresses.erase(Blocks);
4895 bool LLParser::ParseFunctionBody(
Function &Fn) {
4897 return TokError(
"expected '{' in function body");
4901 if (!Fn.
hasName()) FunctionNumber = NumberedVals.size()-1;
4903 PerFunctionState PFS(*
this, Fn, FunctionNumber);
4907 if (PFS.resolveForwardRefBlockAddresses())
4913 return TokError(
"function body requires at least one basic block");
4917 if (ParseBasicBlock(PFS))
return true;
4920 if (ParseUseListOrder(&PFS))
4927 return PFS.FinishFunction();
4932 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4941 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4943 return Error(NameLoc,
4944 "unable to create block named '" + Name +
"'");
4946 std::string NameStr;
4960 if (ParseToken(
lltok::equal,
"expected '=' after instruction id"))
4965 if (ParseToken(
lltok::equal,
"expected '=' after instruction name"))
4969 switch (ParseInstruction(Inst, BB, PFS)) {
4971 case InstError:
return true;
4978 if (ParseInstructionMetadata(*Inst))
4981 case InstExtraComma:
4986 if (ParseInstructionMetadata(*Inst))
4992 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst))
return true;
4993 }
while (!isa<TerminatorInst>(Inst));
5005 PerFunctionState &PFS) {
5008 return TokError(
"found end of file when expecting more instructions");
5014 default:
return Error(Loc,
"expected instruction opcode");
5037 if (ParseArithmetic(Inst, PFS, KeywordVal, 1))
return true;
5039 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(
true);
5040 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(
true);
5049 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5063 if (ParseArithmetic(Inst, PFS, KeywordVal, 1))
return true;
5064 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(
true);
5069 case lltok::kw_srem:
return ParseArithmetic(Inst, PFS, KeywordVal, 1);
5072 case lltok::kw_xor:
return ParseLogical(Inst, PFS, KeywordVal);
5076 int Res = ParseCompare(Inst, PFS, KeywordVal);
5125 bool LLParser::ParseCmpPredicate(
unsigned &
P,
unsigned Opc) {
5126 if (Opc == Instruction::FCmp) {
5128 default:
return TokError(
"expected fcmp predicate (e.g. 'oeq')");
5148 default:
return TokError(
"expected icmp predicate (e.g. 'eq')");
5173 PerFunctionState &PFS) {
5176 if (ParseType(Ty,
true ))
return true;
5178 Type *ResType = PFS.getFunction().getReturnType();
5182 return Error(TypeLoc,
"value doesn't match function result type '" +
5190 if (ParseValue(Ty, RV, PFS))
return true;
5193 return Error(TypeLoc,
"value doesn't match function result type '" +
5203 bool LLParser::ParseBr(
Instruction *&Inst, PerFunctionState &PFS) {
5207 if (ParseTypeAndValue(Op0, Loc, PFS))
return true;
5209 if (
BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5215 return Error(Loc,
"branch condition must have 'i1' type");
5217 if (ParseToken(
lltok::comma,
"expected ',' after branch condition") ||
5218 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5219 ParseToken(
lltok::comma,
"expected ',' after true destination") ||
5220 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5232 bool LLParser::ParseSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
5233 LocTy CondLoc, BBLoc;
5236 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5237 ParseToken(
lltok::comma,
"expected ',' after switch condition") ||
5238 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5243 return Error(CondLoc,
"switch condition must have integer type");
5252 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5253 ParseToken(
lltok::comma,
"expected ',' after case value") ||
5254 ParseTypeAndBasicBlock(DestBB, PFS))
5257 if (!SeenCases.
insert(Constant).second)
5258 return Error(CondLoc,
"duplicate case value in switch");
5259 if (!isa<ConstantInt>(Constant))
5260 return Error(CondLoc,
"case value is not a constant integer");
5262 Table.
push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5268 for (
unsigned i = 0, e = Table.
size();
i != e; ++
i)
5269 SI->
addCase(Table[
i].first, Table[i].second);
5277 bool LLParser::ParseIndirectBr(
Instruction *&Inst, PerFunctionState &PFS) {
5280 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5281 ParseToken(
lltok::comma,
"expected ',' after indirectbr address") ||
5286 return Error(AddrLoc,
"indirectbr address must have pointer type");
5293 if (ParseTypeAndBasicBlock(DestBB, PFS))
5298 if (ParseTypeAndBasicBlock(DestBB, PFS))
5304 if (ParseToken(lltok::rsquare,
"expected ']' at end of block list"))
5308 for (
unsigned i = 0, e = DestList.
size();
i != e; ++
i)
5317 bool LLParser::ParseInvoke(
Instruction *&Inst, PerFunctionState &PFS) {
5320 std::vector<unsigned> FwdRefAttrGrps;
5323 Type *RetType =
nullptr;
5330 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5331 ParseType(RetType, RetTypeLoc,
true ) ||
5332 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5333 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false,
5335 ParseOptionalOperandBundles(BundleList, PFS) ||
5337 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5339 ParseTypeAndBasicBlock(UnwindBB, PFS))
5348 std::vector<Type*> ParamTypes;
5349 for (
unsigned i = 0, e = ArgList.
size();
i != e; ++
i)
5350 ParamTypes.push_back(ArgList[
i].V->getType());
5353 return Error(RetTypeLoc,
"Invalid result type for LLVM function");
5378 for (
unsigned i = 0, e = ArgList.
size();
i != e; ++
i) {
5379 Type *ExpectedTy =
nullptr;
5383 return Error(ArgList[
i].Loc,
"too many arguments specified");
5386 if (ExpectedTy && ExpectedTy != ArgList[
i].V->
getType())
5387 return Error(ArgList[
i].Loc,
"argument is not of expected type '" +
5390 if (ArgList[
i].Attrs.hasAttributes(
i + 1)) {
5397 return Error(CallLoc,
"not enough parameters specified for call");
5401 return Error(CallLoc,
"invoke instructions may not have an alignment");
5415 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5422 bool LLParser::ParseResume(
Instruction *&Inst, PerFunctionState &PFS) {
5424 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5433 PerFunctionState &PFS) {
5434 if (ParseToken(
lltok::lsquare,
"expected '[' in catchpad/cleanuppad"))
5439 if (!Args.
empty() &&
5440 ParseToken(
lltok::comma,
"expected ',' in argument list"))
5445 Type *ArgTy =
nullptr;
5446 if (ParseType(ArgTy, ArgLoc))
5451 if (ParseMetadataAsValue(V, PFS))
5454 if (ParseValue(ArgTy, V, PFS))
5466 bool LLParser::ParseCleanupRet(
Instruction *&Inst, PerFunctionState &PFS) {
5467 Value *CleanupPad =
nullptr;
5469 if (ParseToken(
lltok::kw_from,
"expected 'from' after cleanupret"))
5484 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
5495 bool LLParser::ParseCatchRet(
Instruction *&Inst, PerFunctionState &PFS) {
5496 Value *CatchPad =
nullptr;
5498 if (ParseToken(
lltok::kw_from,
"expected 'from' after catchret"))
5505 if (ParseToken(
lltok::kw_to,
"expected 'to' in catchret") ||
5506 ParseTypeAndBasicBlock(BB, PFS))
5515 bool LLParser::ParseCatchSwitch(
Instruction *&Inst, PerFunctionState &PFS) {
5524 return TokError(
"expected scope value for catchswitch");
5529 if (ParseToken(
lltok::lsquare,
"expected '[' with catchswitch labels"))
5535 if (ParseTypeAndBasicBlock(DestBB, PFS))
5540 if (ParseToken(lltok::rsquare,
"expected ']' after catchswitch labels"))
5544 "expected 'unwind' after catchswitch scope"))
5552 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
5566 bool LLParser::ParseCatchPad(
Instruction *&Inst, PerFunctionState &PFS) {
5567 Value *CatchSwitch =
nullptr;
5573 return TokError(
"expected scope value for catchpad");
5579 if (ParseExceptionArgs(Args, PFS))
5588 bool LLParser::ParseCleanupPad(
Instruction *&Inst, PerFunctionState &PFS) {
5589 Value *ParentPad =
nullptr;
5596 return TokError(
"expected scope value for cleanuppad");
5602 if (ParseExceptionArgs(Args, PFS))
5618 bool LLParser::ParseArithmetic(
Instruction *&Inst, PerFunctionState &PFS,
5621 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5622 ParseToken(
lltok::comma,
"expected ',' in arithmetic operation") ||
5623 ParseValue(LHS->
getType(), RHS, PFS))
5627 switch (OperandType) {
5638 return Error(Loc,
"invalid operand type for instruction");
5646 bool LLParser::ParseLogical(
Instruction *&Inst, PerFunctionState &PFS,
5649 if (ParseTypeAndValue(LHS, Loc, PFS) ||
5650 ParseToken(
lltok::comma,
"expected ',' in logical operation") ||
5651 ParseValue(LHS->
getType(), RHS, PFS))
5655 return Error(Loc,
"instruction requires integer or integer vector operands");
5664 bool LLParser::ParseCompare(
Instruction *&Inst, PerFunctionState &PFS,
5670 if (ParseCmpPredicate(Pred, Opc) ||
5671 ParseTypeAndValue(LHS, Loc, PFS) ||
5672 ParseToken(
lltok::comma,
"expected ',' after compare value") ||
5673 ParseValue(LHS->
getType(), RHS, PFS))
5676 if (Opc == Instruction::FCmp) {
5678 return Error(Loc,
"fcmp requires floating point operands");
5681 assert(Opc == Instruction::ICmp &&
"Unknown opcode for CmpInst!");
5684 return Error(Loc,
"icmp requires integer operands");
5697 bool LLParser::ParseCast(
Instruction *&Inst, PerFunctionState &PFS,
5701 Type *DestTy =
nullptr;
5702 if (ParseTypeAndValue(Op, Loc, PFS) ||
5703 ParseToken(
lltok::kw_to,
"expected 'to' after cast value") ||
5709 return Error(Loc,
"invalid cast opcode for cast from '" +
5719 bool LLParser::ParseSelect(
Instruction *&Inst, PerFunctionState &PFS) {
5721 Value *Op0, *Op1, *Op2;
5722 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5723 ParseToken(
lltok::comma,
"expected ',' after select condition") ||
5724 ParseTypeAndValue(Op1, PFS) ||
5725 ParseToken(
lltok::comma,
"expected ',' after select value") ||
5726 ParseTypeAndValue(Op2, PFS))
5730 return Error(Loc, Reason);
5738 bool LLParser::ParseVA_Arg(
Instruction *&Inst, PerFunctionState &PFS) {
5740 Type *EltTy =
nullptr;
5742 if (ParseTypeAndValue(Op, PFS) ||
5743 ParseToken(
lltok::comma,
"expected ',' after vaarg operand") ||
5744 ParseType(EltTy, TypeLoc))
5748 return Error(TypeLoc,
"va_arg requires operand with first class type");
5756 bool LLParser::ParseExtractElement(
Instruction *&Inst, PerFunctionState &PFS) {
5759 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5760 ParseToken(
lltok::comma,
"expected ',' after extract value") ||
5761 ParseTypeAndValue(Op1, PFS))
5765 return Error(Loc,
"invalid extractelement operands");
5773 bool LLParser::ParseInsertElement(
Instruction *&Inst, PerFunctionState &PFS) {
5775 Value *Op0, *Op1, *Op2;
5776 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5777 ParseToken(
lltok::comma,
"expected ',' after insertelement value") ||
5778 ParseTypeAndValue(Op1, PFS) ||
5779 ParseToken(
lltok::comma,
"expected ',' after insertelement value") ||
5780 ParseTypeAndValue(Op2, PFS))
5784 return Error(Loc,
"invalid insertelement operands");
5792 bool LLParser::ParseShuffleVector(
Instruction *&Inst, PerFunctionState &PFS) {
5794 Value *Op0, *Op1, *Op2;
5795 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5796 ParseToken(
lltok::comma,
"expected ',' after shuffle mask") ||
5797 ParseTypeAndValue(Op1, PFS) ||
5798 ParseToken(
lltok::comma,
"expected ',' after shuffle value") ||
5799 ParseTypeAndValue(Op2, PFS))
5803 return Error(Loc,
"invalid shufflevector operands");
5811 int LLParser::ParsePHI(
Instruction *&Inst, PerFunctionState &PFS) {
5815 if (ParseType(Ty, TypeLoc) ||
5817 ParseValue(Ty, Op0, PFS) ||
5818 ParseToken(
lltok::comma,
"expected ',' after insertelement value") ||
5820 ParseToken(lltok::rsquare,
"expected ']' in phi value list"))
5823 bool AteExtraComma =
false;
5827 PHIVals.
push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5833 AteExtraComma =
true;
5837 if (ParseToken(
lltok::lsquare,
"expected '[' in phi value list") ||
5838 ParseValue(Ty, Op0, PFS) ||
5839 ParseToken(
lltok::comma,
"expected ',' after insertelement value") ||
5841 ParseToken(lltok::rsquare,
"expected ']' in phi value list"))
5846 return Error(TypeLoc,
"phi node must have first class type");
5849 for (
unsigned i = 0, e = PHIVals.
size();
i != e; ++
i)
5852 return AteExtraComma ? InstExtraComma : InstNormal;
5861 bool LLParser::ParseLandingPad(
Instruction *&Inst, PerFunctionState &PFS) {
5864 if (ParseType(Ty, TyLoc))
5877 return TokError(
"expected 'catch' or 'filter' clause type");
5881 if (ParseTypeAndValue(V, VLoc, PFS))
5887 if (isa<ArrayType>(V->
getType()))
5888 Error(VLoc,
"'catch' clause has an invalid type");
5890 if (!isa<ArrayType>(V->
getType()))
5891 Error(VLoc,
"'filter' clause has an invalid type");
5894 Constant *CV =
dyn_cast<Constant>(V);
5896 return Error(VLoc,
"clause argument must be a constant");
5900 Inst = LP.release();
5913 bool LLParser::ParseCall(
Instruction *&Inst, PerFunctionState &PFS,
5916 std::vector<unsigned> FwdRefAttrGrps;
5919 Type *RetType =
nullptr;
5928 "expected 'tail call', 'musttail call', or 'notail call'"))
5933 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5934 ParseType(RetType, RetTypeLoc,
true ) ||
5935 ParseValID(CalleeID) ||
5937 PFS.getFunction().isVarArg()) ||
5938 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps,
false, BuiltinLoc) ||
5939 ParseOptionalOperandBundles(BundleList, PFS))
5943 return Error(CallLoc,
"fast-math-flags specified for call without "
5944 "floating-point scalar or vector return type");
5952 std::vector<Type*> ParamTypes;
5953 for (
unsigned i = 0, e = ArgList.
size();
i != e; ++
i)
5954 ParamTypes.push_back(ArgList[
i].V->getType());
5957 return Error(RetTypeLoc,
"Invalid result type for LLVM function");
5982 for (
unsigned i = 0, e = ArgList.
size();
i != e; ++
i) {
5983 Type *ExpectedTy =
nullptr;
5987 return Error(ArgList[
i].Loc,
"too many arguments specified");
5990 if (ExpectedTy && ExpectedTy != ArgList[
i].V->
getType())
5991 return Error(ArgList[
i].Loc,
"argument is not of expected type '" +
5994 if (ArgList[
i].Attrs.hasAttributes(
i + 1)) {
6001 return Error(CallLoc,
"not enough parameters specified for call");
6005 return Error(CallLoc,
"call instructions may not have an alignment");
6021 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6033 int LLParser::ParseAlloc(
Instruction *&Inst, PerFunctionState &PFS) {
6034 Value *Size =
nullptr;
6035 LocTy SizeLoc, TyLoc;
6036 unsigned Alignment = 0;
6042 if (ParseType(Ty, TyLoc))
return true;
6045 return Error(TyLoc,
"invalid type for alloca");
6047 bool AteExtraComma =
false;
6050 if (ParseOptionalAlignment(Alignment))
return true;
6052 AteExtraComma =
true;
6054 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
6055 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6061 return Error(SizeLoc,
"element count must have integer type");
6067 return AteExtraComma ? InstExtraComma : InstNormal;
6074 int LLParser::ParseLoad(
Instruction *&Inst, PerFunctionState &PFS) {
6076 unsigned Alignment = 0;
6077 bool AteExtraComma =
false;
6078 bool isAtomic =
false;
6095 if (ParseType(Ty) ||
6096 ParseToken(
lltok::comma,
"expected comma after load's type") ||
6097 ParseTypeAndValue(Val, Loc, PFS) ||
6098 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6099 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6103 return Error(Loc,
"load operand must be a pointer to a first class type");
6104 if (isAtomic && !Alignment)
6105 return Error(Loc,
"atomic load must have explicit non-zero alignment");
6108 return Error(Loc,
"atomic load cannot use Release ordering");
6110 if (Ty != cast<PointerType>(Val->
getType())->getElementType())
6111 return Error(ExplicitTypeLoc,
6112 "explicit pointee type doesn't match operand's pointee type");
6114 Inst =
new LoadInst(Ty, Val,
"", isVolatile, Alignment, Ordering, Scope);
6115 return AteExtraComma ? InstExtraComma : InstNormal;
6123 int LLParser::ParseStore(
Instruction *&Inst, PerFunctionState &PFS) {
6125 unsigned Alignment = 0;
6126 bool AteExtraComma =
false;
6127 bool isAtomic =
false;
6136 bool isVolatile =
false;
6142 if (ParseTypeAndValue(Val, Loc, PFS) ||
6143 ParseToken(
lltok::comma,
"expected ',' after store operand") ||
6144 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6145 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
6146 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6150 return Error(PtrLoc,
"store operand must be a pointer");
6152 return Error(Loc,
"store operand must be a first class value");
6153 if (cast<PointerType>(Ptr->
getType())->getElementType() != Val->
getType())
6154 return Error(Loc,
"stored value and pointer type do not match");
6155 if (isAtomic && !Alignment)
6156 return Error(Loc,
"atomic store must have explicit non-zero alignment");
6159 return Error(Loc,
"atomic store cannot use Acquire ordering");
6161 Inst =
new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
6162 return AteExtraComma ? InstExtraComma : InstNormal;
6168 int LLParser::ParseCmpXchg(
Instruction *&Inst, PerFunctionState &PFS) {
6170 bool AteExtraComma =
false;
6174 bool isVolatile =
false;
6183 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6184 ParseToken(
lltok::comma,
"expected ',' after cmpxchg address") ||
6185 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6186 ParseToken(
lltok::comma,
"expected ',' after cmpxchg cmp operand") ||
6187 ParseTypeAndValue(New, NewLoc, PFS) ||
6188 ParseScopeAndOrdering(
true , Scope, SuccessOrdering) ||
6189 ParseOrdering(FailureOrdering))
6194 return TokError(
"cmpxchg cannot be unordered");
6196 return TokError(
"cmpxchg failure argument shall be no stronger than the "
6197 "success argument");
6201 "cmpxchg failure ordering cannot include release semantics");
6203 return Error(PtrLoc,
"cmpxchg operand must be a pointer");
6204 if (cast<PointerType>(Ptr->
getType())->getElementType() != Cmp->
getType())
6205 return Error(CmpLoc,
"compare value and pointer type do not match");
6206 if (cast<PointerType>(Ptr->
getType())->getElementType() != New->
getType())
6207 return Error(NewLoc,
"new value and pointer type do not match");
6209 return Error(NewLoc,
"cmpxchg operand must be a first class value");
6211 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
6215 return AteExtraComma ? InstExtraComma : InstNormal;
6221 int LLParser::ParseAtomicRMW(
Instruction *&Inst, PerFunctionState &PFS) {
6223 bool AteExtraComma =
false;
6226 bool isVolatile =
false;
6233 default:
return TokError(
"expected binary operation in atomicrmw");
6248 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6249 ParseToken(
lltok::comma,
"expected ',' after atomicrmw address") ||
6250 ParseTypeAndValue(Val, ValLoc, PFS) ||
6251 ParseScopeAndOrdering(
true , Scope, Ordering))
6255 return TokError(
"atomicrmw cannot be unordered");
6257 return Error(PtrLoc,
"atomicrmw operand must be a pointer");
6258 if (cast<PointerType>(Ptr->
getType())->getElementType() != Val->
getType())
6259 return Error(ValLoc,
"atomicrmw value and pointer type do not match");
6261 return Error(ValLoc,
"atomicrmw operand must be an integer");
6263 if (Size < 8 || (Size & (Size - 1)))
6264 return Error(ValLoc,
"atomicrmw operand must be power-of-two byte-sized"
6271 return AteExtraComma ? InstExtraComma : InstNormal;
6276 int LLParser::ParseFence(
Instruction *&Inst, PerFunctionState &PFS) {
6279 if (ParseScopeAndOrdering(
true , Scope, Ordering))
6283 return TokError(
"fence cannot be unordered");
6285 return TokError(
"fence cannot be monotonic");
6287 Inst =
new FenceInst(Context, Ordering, Scope);
6293 int LLParser::ParseGetElementPtr(
Instruction *&Inst, PerFunctionState &PFS) {
6294 Value *Ptr =
nullptr;
6295 Value *Val =
nullptr;
6302 if (ParseType(Ty) ||
6303 ParseToken(
lltok::comma,
"expected comma after getelementptr's type") ||
6304 ParseTypeAndValue(Ptr, Loc, PFS))
6309 if (!BasePointerType)
6310 return Error(Loc,
"base of getelementptr must be a pointer");
6313 return Error(ExplicitTypeLoc,
6314 "explicit pointee type doesn't match operand's pointee type");
6317 bool AteExtraComma =
false;
6325 AteExtraComma =
true;
6328 if (ParseTypeAndValue(Val, EltLoc, PFS))
return true;
6330 return Error(EltLoc,
"getelementptr index must be an integer");
6334 if (GEPWidth && GEPWidth != ValNumEl)
6335 return Error(EltLoc,
6336 "getelementptr vector index has a wrong number of elements");
6337 GEPWidth = ValNumEl;
6344 return Error(Loc,
"base element of getelementptr must be sized");
6347 return Error(Loc,
"invalid getelementptr indices");
6350 cast<GetElementPtrInst>(Inst)->setIsInBounds(
true);
6351 return AteExtraComma ? InstExtraComma : InstNormal;
6356 int LLParser::ParseExtractValue(
Instruction *&Inst, PerFunctionState &PFS) {
6360 if (ParseTypeAndValue(Val, Loc, PFS) ||
6361 ParseIndexList(Indices, AteExtraComma))
6365 return Error(Loc,
"extractvalue operand must be aggregate type");
6368 return Error(Loc,
"invalid indices for extractvalue");
6370 return AteExtraComma ? InstExtraComma : InstNormal;
6375 int LLParser::ParseInsertValue(
Instruction *&Inst, PerFunctionState &PFS) {
6379 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
6380 ParseToken(
lltok::comma,
"expected comma after insertvalue operand") ||
6381 ParseTypeAndValue(Val1, Loc1, PFS) ||
6382 ParseIndexList(Indices, AteExtraComma))
6386 return Error(Loc0,
"insertvalue operand must be aggregate type");
6390 return Error(Loc0,
"invalid indices for insertvalue");
6391 if (IndexedType != Val1->
getType())
6392 return Error(Loc1,
"insertvalue operand and field disagree in type: '" +
6396 return AteExtraComma ? InstExtraComma : InstNormal;
6423 if (ParseMetadata(MD,
nullptr))
6428 return ParseToken(
lltok::rbrace,
"expected end of metadata node");
6437 return Error(Loc,
"value has no uses");
6439 unsigned NumUses = 0;
6441 for (
const Use &U : V->
uses()) {
6442 if (++NumUses > Indexes.
size())
6444 Order[&U] = Indexes[NumUses - 1];
6447 return Error(Loc,
"value only has one use");
6448 if (Order.
size() != Indexes.
size() || NumUses > Indexes.
size())
6449 return Error(Loc,
"wrong number of indexes, expected " +
6465 return Lex.
Error(
"expected non-empty list of uselistorder indexes");
6472 bool IsOrdered =
true;
6473 assert(Indexes.
empty() &&
"Expected empty order vector");
6476 if (ParseUInt32(Index))
6480 Offset += Index - Indexes.
size();
6481 Max = std::max(Max, Index);
6482 IsOrdered &= Index == Indexes.
size();
6490 if (Indexes.
size() < 2)
6491 return Error(Loc,
"expected >= 2 uselistorder indexes");
6492 if (Offset != 0 || Max >= Indexes.
size())
6493 return Error(Loc,
"expected distinct uselistorder indexes in range [0, size)");
6495 return Error(Loc,
"expected uselistorder indexes to change the order");
6502 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
6509 if (ParseTypeAndValue(V, PFS) ||
6510 ParseToken(
lltok::comma,
"expected comma in uselistorder directive") ||
6511 ParseUseListOrderIndexes(Indexes))
6514 return sortUseListOrder(V, Indexes, Loc);
6519 bool LLParser::ParseUseListOrderBB() {
6526 if (ParseValID(Fn) ||
6527 ParseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
6528 ParseValID(Label) ||
6529 ParseToken(
lltok::comma,
"expected comma in uselistorder_bb directive") ||
6530 ParseUseListOrderIndexes(Indexes))
6538 GV = Fn.
UIntVal < NumberedVals.size() ? NumberedVals[Fn.
UIntVal] :
nullptr;
6540 return Error(Fn.
Loc,
"expected function name in uselistorder_bb");
6542 return Error(Fn.
Loc,
"invalid function forward reference in uselistorder_bb");
6545 return Error(Fn.
Loc,
"expected function name in uselistorder_bb");
6547 return Error(Fn.
Loc,
"invalid declaration in uselistorder_bb");
6551 return Error(Label.
Loc,
"invalid numeric label in uselistorder_bb");
6553 return Error(Label.
Loc,
"expected basic block name in uselistorder_bb");
6556 return Error(Label.
Loc,
"invalid basic block in uselistorder_bb");
6557 if (!isa<BasicBlock>(V))
6558 return Error(Label.
Loc,
"expected basic block in uselistorder_bb");
6560 return sortUseListOrder(V, Indexes, Loc);
void setVisibility(VisibilityTypes V)
void sortUseList(Compare Cmp)
Sort the use-list.
void push_back(const T &Elt)
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
static ConstantInt * getFalse(LLVMContext &Context)
SPIR_FUNC - Calling convention for SPIR non-kernel device functions.
const ValueSymbolTable & getValueSymbolTable() const
Get the symbol table of global variable and function identifiers.
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
iterator_range< use_iterator > uses()
static IntegerType * getInt1Ty(LLVMContext &C)
Intel_OCL_BI - Calling conventions for Intel OpenCL built-ins.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Special purpose, only applies to global arrays.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
*p = old <signed v ? old : v
LLVM Argument representation.
uint64_t getZExtValue() const
Get zero extended value.
const char * getPointer() const
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
const APFloat & getAPFloatVal() const
static bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
ARM_APCS - ARM Procedure Calling Standard calling convention (obsolete, but still used on some target...
A Module instance is used to store all the information related to an LLVM module. ...
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static ResumeInst * Create(Value *Exn, Instruction *InsertBefore=nullptr)
An instruction for ordering other memory operations.
Same, but only replaced by something equivalent.
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
static MDString * get(LLVMContext &Context, StringRef Str)
unsigned getUIntVal() const
const GlobalListType & getGlobalList() const
Get the Module's list of global variables (constant).
Available for inspection, not emission.
MSP430_INTR - Calling convention used for MSP430 interrupt routines.
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
Type::subtype_iterator param_iterator
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
enum llvm::ValID::@242 Kind
Type * getValueType() const
uint64_t getAlignment() const
Retrieve the alignment attribute, if it exists.
Calling convention used for Mesa vertex shaders.
void addOperand(MDNode *M)
This class represents a function call, abstracting a target machine's calling convention.
void setGC(std::string Str)
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Calling convention used by HipHop Virtual Machine (HHVM) to perform calls to and from translation cac...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
*p = old <unsigned v ? old : v
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
0 1 0 0 True if ordered and less than
Like Internal, but omit from symbol table.
iterator find(StringRef Key)
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
*p = old >unsigned v ? old : v
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
Externally visible function.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
void setDataLayout(StringRef Desc)
Set the data layout.
1 1 1 0 True if unordered or not equal
The data referenced by the COMDAT must be the same size.
bool isTokenTy() const
Return true if this is 'token'.
AttrBuilder & addDereferenceableAttr(uint64_t Bytes)
This turns the number of dereferenceable bytes into the form used internally in Attribute.
The two locations do not alias at all.
static bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
An instruction for reading from memory.
ELFYAML::ELF_STV Visibility
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
Return the function type for an intrinsic.
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
static bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy, const std::string &Name)
Type * getElementType() const
void setAlignment(unsigned Align)
static bool isStrongerThan(AtomicOrdering ao, AtomicOrdering other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice, which is based on C++'s definition.
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
unsigned getVirtuality(StringRef VirtualityString)
const AliasListType & getAliasList() const
Get the Module's list of aliases (constant).
bool hasAlignmentAttr() const
Return true if the builder has an alignment attribute.
*p = old >signed v ? old : v
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
const IFuncListType & getIFuncList() const
Get the Module's list of ifuncs (constant).
static LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
Tagged DWARF-like metadata node.
static bool isLocalLinkage(LinkageTypes Linkage)
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
DebugEmissionKind getEmissionKind() const
void setAttributes(AttributeSet Attrs)
Set the parameter attributes for this invoke.
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
global Merge global variables
void setCallingConv(CallingConv::ID CC)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
bool Run()
Run: module ::= toplevelentity*.
1 0 0 1 True if unordered or equal
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy)
This method can be used to determine if a cast from S to DstTy using Opcode op is valid or not...
static Type * getTokenTy(LLVMContext &C)
struct fuzzer::@269 Flags
AttrBuilder & addDereferenceableOrNullAttr(uint64_t Bytes)
This turns the number of dereferenceable_or_null bytes into the form used internally in Attribute...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
X86_INTR - x86 hardware interrupt context.
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
param_iterator param_end() const
PTX_Kernel - Call to a PTX kernel.
static Constant * get(ArrayRef< Constant * > V)
void setThreadLocalMode(ThreadLocalMode Val)
static 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...
AttrBuilder & addAllocSizeAttr(unsigned ElemSizeArg, const Optional< unsigned > &NumElemsArg)
This turns one (or two) ints into the form used internally in Attribute.
0 1 0 1 True if ordered and less than or equal
TypeID
Definitions of all of the base types for the Type system.
The linker may choose any COMDAT.
Register calling convention used for parameters transfer optimization.
void setName(const Twine &Name)
Change the name of the value.
static const unsigned MaximumAlignment
void setDLLStorageClass(DLLStorageClassTypes C)
X86_ThisCall - Similar to X86_StdCall.
LLVM_NODISCARD bool empty() const
AtomicOrdering
Atomic ordering for LLVM's memory model.
static bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
void addHandler(BasicBlock *Dest)
Add an entry to the switch instruction...
static 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. ...
llvm::Optional< Function * > remangleIntrinsicFunction(Function *F)
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Class to represent function types.
static Type * getLabelTy(LLVMContext &C)
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Class to represent array types.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
This instruction compares its operands according to the predicate given to the constructor.
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
void setComdat(Comdat *C)
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value. ...
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
X86_FastCall - 'fast' analog of X86_StdCall.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
static bool Verify(FunctionType *Ty, StringRef Constraints)
Verify - This static method can be used by the parser to check to see if the specified constraint str...
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
An instruction for storing to memory.
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isArrayTy() const
True if this is an instance of ArrayType.
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
Type * getScalarType() const LLVM_READONLY
If this is a vector type, return the element type, otherwise return 'this'.
size_t size() const
size - Get the array size.
Class to represent pointers.
void setAttributes(AttributeSet Attrs)
Set the parameter attributes for this call.
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
static const fltSemantics & IEEEsingle()
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
static ChecksumKind getChecksumKind(StringRef CSKindStr)
ExternalWeak linkage description.
static Constant * getInsertValue(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
void setCallingConv(CallingConv::ID CC)
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
StringRef filename(StringRef path)
Get filename.
Same, but only replaced by something equivalent.
No other Module may specify this COMDAT.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
constexpr bool isPowerOf2_32(uint32_t Value)
isPowerOf2_32 - This function returns true if the argument is a power of two > 0. ...
LLVM Basic Block Representation.
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
The instances of the Type class are immutable: once they are created, they are never changed...
Calling convention for AMDGPU code object kernels.
C - The default llvm calling convention, compatible with C.
bool isVectorTy() const
True if this is an instance of VectorType.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, Metadata *TemplateParams)
Build a DICompositeType with the given ODR identifier.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
This function has undefined behavior.
This is an important base class in LLVM.
X86_StdCall - stdcall is the calling conventions mostly used by the Win32 API.
Resume the propagation of an exception.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
unsigned getCallingConvention(StringRef LanguageString)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
param_iterator param_begin() const
Indirect Branch Instruction.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
void setExternallyInitialized(bool Val)
unsigned getOperationEncoding(StringRef OperationEncodingString)
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
StringMap< Type * > NamedTypes
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static const fltSemantics & IEEEhalf()
static bool isValidLinkage(LinkageTypes L)
static Constant * getShuffleVector(Constant *V1, Constant *V2, Constant *Mask, Type *OnlyIfReducedTy=nullptr)
A pair of DIGlobalVariable and DIExpression.
void splice(iterator where, iplist_impl &L2)
const InstListType & getInstList() const
Return the underlying instruction list container.
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
unsigned getBitWidth() const
Return the number of bits in the APInt.
static const unsigned End
DLLStorageClassTypes
Storage classes of global values for PE targets.
0 1 1 1 True if ordered (no nans)
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
Used for AVR interrupt routines.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
The data referenced by the COMDAT must be the same.
void setTailCallKind(TailCallKind TCK)
std::vector< GlobalValue * > GlobalValues
void setConstant(bool Val)
unsigned getLanguage(StringRef LanguageString)
dot regions Print regions of function to dot file(with no function bodies)"
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
1 1 1 1 Always true (always folded)
std::map< unsigned, Type * > Types
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
bool Error(LocTy L, const Twine &Msg) const
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVMContext & getContext() const
All values hold a context through their type.
static bool isAtomic(Instruction *I)
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
1 1 0 1 True if unordered, less than, or equal
Calling convention used for Mesa pixel shaders.
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, Instruction *InsertBefore=nullptr)
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
An imported module (C++ using directive or similar).
unsigned getTag(StringRef TagString)
global_iterator global_end()
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
0 0 1 0 True if ordered and greater than
Iterator for intrusive lists based on ilist_node.
const BasicBlockListType & getBasicBlockList() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
void setSelectionKind(SelectionKind Val)
bool isFunctionTy() const
True if this is an instance of FunctionType.
Calling convention used for Mesa geometry shaders.
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
PTX_Device - Call to a PTX device function.
const std::string & getStrVal() const
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, Instruction *InsertBefore=nullptr)
AttrBuilder & removeAttribute(Attribute::AttrKind Val)
Remove an attribute from the builder.
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
1 1 0 0 True if unordered or less than
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Keep one copy of function when linking (inline)
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
bool isVector(MCInstrInfo const &MCII, MCInst const &MCI)
HHVM calling convention for invoking C/C++ helpers.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
APSInt extOrTrunc(uint32_t width) const
#define GET_OR_DISTINCT(CLASS, ARGS)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
The linker will choose the largest COMDAT.
bool any() const
Whether any flag is set.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
static ConstantInt * getTrue(LLVMContext &Context)
void setLinkage(LinkageTypes LT)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
ValueSymbolTable * getValueSymbolTable()
getSymbolTable() - Return the symbol table if any, otherwise nullptr.
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
AttributeSet removeAttributes(LLVMContext &C, unsigned Index, AttributeSet Attrs) const
Remove the specified attributes at the specified index from this attribute list.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
static DIFlags getFlag(StringRef Flag)
void push_back(pointer val)
static bool isWeak(const MCSymbolELF &Sym)
LinkageTypes
An enumeration for the kinds of linkage for global values.
A (clang) module that has been imported by the compile unit.
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
bool isIntegerTy() const
True if this is an instance of IntegerType.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
void setWeak(bool IsWeak)
unsigned getVectorNumElements() const
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
SPIR_KERNEL - Calling convention for SPIR kernel functions.
The C convention as implemented on Windows/x86-64.
Generic tagged DWARF-like metadata node.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
This struct contains the mappings from the slot numbers to unnamed metadata nodes, global values and types.
void eraseFromParent() override
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
A utility class that uses RAII to save and restore the value of a variable.
AttributeSet removeAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const
Remove the specified attribute at the specified index from this attribute list.
FunctionNumber(functionNumber)
void setAttributes(AttributeSet Attrs)
Set the attribute list for this Function.
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
static const fltSemantics & IEEEdouble()
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the type of the element that would be loaded with a load instruction with the specified param...
Type array for a subprogram.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static std::string getTypeString(Type *T)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Function to be accessible from DLL.
PointerType * getType() const
Global values are always pointers.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void emplace_back(ArgTypes &&...Args)
ValID - Represents a reference of a definition of some sort with no type.
pointer data()
Return a pointer to the vector's buffer, even if empty().
bool isAggregateType() const
Return true if the type is an aggregate type.
void setUnnamedAddr(UnnamedAddr Val)
OperandType
Types of operands to CF instructions.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
unsigned greater or equal
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
void setSourceFileName(StringRef Name)
Set the module's original source file name.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module's symbol table for COMDATs (constant).
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
void setPrologueData(Constant *PrologueData)
void appendModuleInlineAsm(StringRef Asm)
Append to the module-scope inline assembly blocks.
lltok::Kind getKind() const
Deduce function attributes
std::unique_ptr< Constant *[]> ConstantStructElts
0 1 1 0 True if ordered and operands are unequal
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
void setTargetTriple(StringRef T)
Set the target triple.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Keep one copy of named function when linking (weak)
Rename collisions when linking (static functions).
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
1 0 1 0 True if unordered or greater than
Function to be imported from DLL.
Calling convention used for Mesa compute shaders.
unsigned getMacinfo(StringRef MacinfoString)
const APSInt & getAPSIntVal() const
void addDestination(BasicBlock *Dest)
Add a destination.
AttrBuilder & merge(const AttrBuilder &B)
Add the attributes from the builder.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore=nullptr)
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isLabelTy() const
Return true if this is 'label'.
0 0 0 1 True if ordered and equal
LLVM Value Representation.
1 0 1 1 True if unordered, greater than, or equal
bool hasAttributes() const
Return true if the builder has IR-level attributes.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Lightweight error class with error context and mandatory checking.
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, Instruction *InsertBefore=nullptr)
virtual void eraseFromParent()=0
This method unlinks 'this' from the containing module and deletes it.
unsigned getAttributeEncoding(StringRef EncodingString)
AttrBuilder & addStackAlignmentAttr(unsigned Align)
This turns an int stack alignment (which must be a power of 2) into the form used internally in Attri...
This file provides utility classes that use RAII to save and restore values.
void setCallingConv(CallingConv::ID CC)
Calling convention used for AVR signal routines.
#define PARSE_MD_FIELDS()
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Convenience struct for specifying and reasoning about fast-math flags.
StringRef - Represent a constant reference to a string, i.e.
AttrBuilder & addAlignmentAttr(unsigned Align)
This turns an int alignment (which must be a power of 2) into the form used internally in Attribute...
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
void setPersonalityFn(Constant *Fn)
static bool isVolatile(Instruction *Inst)
Represents a location in source code.
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
AttributeSet addAttributes(LLVMContext &C, unsigned Index, AttributeSet Attrs) const
Add attributes to the attribute set at the given index.
0 0 1 1 True if ordered and greater than or equal
unsigned getMDKindID(StringRef Name) const
Return a unique non-zero ID for the specified metadata kind.
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
ARM_AAPCS - ARM Architecture Procedure Calling Standard calling convention (aka EABI).
Fast - This calling convention attempts to make calls as fast as possible (e.g.
static IntegerType * getInt8Ty(LLVMContext &C)
void setSection(StringRef S)
Change the section for this global.
const fltSemantics & getSemantics() const
ARM_AAPCS_VFP - Same as ARM_AAPCS, but uses hard floating point ABI.
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Value * lookup(StringRef Name) const
This method finds the value with the given Name in the the symbol table.
static 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...
iterator_range< arg_iterator > args()
0 0 0 0 Always false (always folded)
bool isVoidTy() const
Return true if this is 'void'.
an instruction to allocate memory on the stack
Basic type, like 'int' or 'float'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static bool parseField(amd_kernel_code_t &C, MCAsmParser &MCParser, raw_ostream &Err)
void setPrefixData(Constant *PrefixData)
AttributeSet getFnAttributes() const
The function attributes are returned.
static 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...