95#include "llvm/IR/IntrinsicsAArch64.h"
96#include "llvm/IR/IntrinsicsAMDGPU.h"
97#include "llvm/IR/IntrinsicsARM.h"
98#include "llvm/IR/IntrinsicsNVPTX.h"
99#include "llvm/IR/IntrinsicsWebAssembly.h"
135 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
136 "scopes are not dominating"));
170 if (isa<Instruction>(V)) {
174 V.printAsOperand(*
OS,
true,
MST);
242 void Write(
const unsigned i) { *
OS << i <<
'\n'; }
248 *
OS <<
A->getAsString() <<
'\n';
268 for (
const T &V : Vs)
272 template <
typename T1,
typename... Ts>
273 void WriteTs(
const T1 &V1,
const Ts &... Vs) {
278 template <
typename... Ts>
void WriteTs() {}
287 *
OS << Message <<
'\n';
295 template <
typename T1,
typename... Ts>
305 *
OS << Message <<
'\n';
311 template <
typename T1,
typename... Ts>
345 Type *LandingPadResultTy;
352 bool HasDebugInfo =
false;
395 SawFrameEscape(
false), TBAAVerifyHelper(this) {
396 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
403 "An instance of this class only works with a specific module!");
415 if (!BB.empty() && BB.back().isTerminator())
419 *
OS <<
"Basic Block in function '" <<
F.getName()
420 <<
"' does not have terminator!\n";
421 BB.printAsOperand(*
OS,
true, MST);
427 auto FailureCB = [
this](
const Twine &Message) {
435 verifySiblingFuncletUnwinds();
438 ConvergenceVerifyHelper.
verify(DT);
440 InstsInThisBlock.
clear();
442 LandingPadResultTy =
nullptr;
443 SawFrameEscape =
false;
444 SiblingFuncletInfo.
clear();
445 verifyNoAliasScopeDecl();
446 NoAliasScopeDecls.
clear();
457 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
462 verifyFrameRecoverIndices();
464 visitGlobalVariable(GV);
467 visitGlobalAlias(GA);
470 visitGlobalIFunc(GI);
473 visitNamedMDNode(NMD);
476 visitComdat(SMEC.getValue());
480 visitModuleCommandLines();
482 verifyCompileUnits();
484 verifyDeoptimizeCallingConvs();
485 DISubprogramAttachments.
clear();
491 enum class AreDebugLocsAllowed {
No,
Yes };
495 enum class RangeLikeMetadataKind {
510 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
514 void visitComdat(
const Comdat &
C);
515 void visitModuleIdents();
516 void visitModuleCommandLines();
517 void visitModuleFlags();
518 void visitModuleFlag(
const MDNode *
Op,
521 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
525 RangeLikeMetadataKind Kind);
530 void visitCallStackMetadata(
MDNode *MD);
535 void visitAnnotationMetadata(
MDNode *Annotation);
536 void visitAliasScopeMetadata(
const MDNode *MD);
537 void visitAliasScopeListMetadata(
const MDNode *MD);
538 void visitAccessGroupMetadata(
const MDNode *MD);
540 template <
class Ty>
bool isValidMetadataArray(
const MDTuple &
N);
541#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
542#include "llvm/IR/Metadata.def"
543 void visitDIScope(
const DIScope &
N);
570 void visitPHINode(
PHINode &PN);
579 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
617 void verifySwiftErrorCall(
CallBase &Call,
const Value *SwiftErrorVal);
618 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
620 void verifyMustTailCall(
CallInst &CI);
621 bool verifyAttributeCount(
AttributeList Attrs,
unsigned Params);
627 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
628 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
630 void visitConstantExprsRecursively(
const Constant *EntryC);
633 void verifyInlineAsmCall(
const CallBase &Call);
634 void verifyStatepoint(
const CallBase &Call);
635 void verifyFrameRecoverIndices();
636 void verifySiblingFuncletUnwinds();
640 template <
typename ValueOrMetadata>
641 void verifyFragmentExpression(
const DIVariable &V,
643 ValueOrMetadata *
Desc);
650 void verifyCompileUnits();
654 void verifyDeoptimizeCallingConvs();
656 void verifyAttachedCallBundle(
const CallBase &Call,
660 void verifyNoAliasScopeDecl();
666#define Check(C, ...) \
669 CheckFailed(__VA_ARGS__); \
676#define CheckDI(C, ...) \
679 DebugInfoCheckFailed(__VA_ARGS__); \
687 CheckDI(
I.DebugMarker->MarkedInstr == &
I,
688 "Instruction has invalid DebugMarker", &
I);
689 CheckDI(!isa<PHINode>(&
I) || !
I.hasDbgRecords(),
690 "PHI Node must not have any attached DbgRecords", &
I);
693 "DbgRecord had invalid DebugMarker", &
I, &DR);
696 visitMDNode(*Loc, AreDebugLocsAllowed::Yes);
697 if (
auto *DVR = dyn_cast<DbgVariableRecord>(&DR)) {
701 verifyFragmentExpression(*DVR);
702 verifyNotEntryValue(*DVR);
703 }
else if (
auto *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
711 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
712 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
725 while (!WorkList.
empty()) {
727 if (!Visited.
insert(Cur).second)
734void Verifier::visitGlobalValue(
const GlobalValue &GV) {
736 "Global is external, but doesn't have external or weak linkage!", &GV);
738 if (
const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
742 "huge alignment values are unsupported", GO);
745 if (
const MDNode *Associated =
746 GO->getMetadata(LLVMContext::MD_associated)) {
747 Check(Associated->getNumOperands() == 1,
748 "associated metadata must have one operand", &GV, Associated);
749 const Metadata *
Op = Associated->getOperand(0).get();
750 Check(
Op,
"associated metadata must have a global value", GO, Associated);
752 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(
Op);
753 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
755 Check(isa<PointerType>(VM->getValue()->getType()),
756 "associated value must be pointer typed", GV, Associated);
759 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
760 "associated metadata must point to a GlobalObject", GO, Stripped);
761 Check(Stripped != GO,
762 "global values should not associate to themselves", GO,
768 if (
const MDNode *AbsoluteSymbol =
769 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
770 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
771 DL.getIntPtrType(GO->getType()),
772 RangeLikeMetadataKind::AbsoluteSymbol);
777 "Only global variables can have appending linkage!", &GV);
782 "Only global arrays can have appending linkage!", GVar);
786 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
790 "dllexport GlobalValue must have default or protected visibility",
795 "dllimport GlobalValue must have default visibility", &GV);
796 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
802 "Global is marked as dllimport, but not external", &GV);
807 "GlobalValue with local linkage or non-default "
808 "visibility must be dso_local!",
812 Check(!GV.
hasSection(),
"tagged GlobalValue must not be in section.", &GV);
817 if (!
I->getParent() || !
I->getParent()->getParent())
818 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
820 else if (
I->getParent()->getParent()->getParent() != &M)
821 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
822 I->getParent()->getParent(),
823 I->getParent()->getParent()->getParent());
825 }
else if (
const Function *
F = dyn_cast<Function>(V)) {
826 if (
F->getParent() != &M)
827 CheckFailed(
"Global is used by function in a different module", &GV, &M,
840 "Global variable initializer type does not match global "
847 "'common' global must have a zero initializer!", &GV);
850 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
855 GV.
getName() ==
"llvm.global_dtors")) {
857 "invalid linkage for intrinsic global variable", &GV);
859 "invalid uses of intrinsic global variable", &GV);
863 if (
ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
864 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
870 "wrong type for intrinsic global variable", &GV);
872 "the third field of the element type is mandatory, "
873 "specify ptr null to migrate from the obsoleted 2-field form");
881 GV.
getName() ==
"llvm.compiler.used")) {
883 "invalid linkage for intrinsic global variable", &GV);
885 "invalid uses of intrinsic global variable", &GV);
887 if (
ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
888 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
889 Check(PTy,
"wrong type for intrinsic global variable", &GV);
893 Check(InitArray,
"wrong initalizer for intrinsic global variable",
897 Check(isa<GlobalVariable>(V) || isa<Function>(V) ||
901 Twine(
"members of ") + GV.
getName() +
" must be named", V);
910 for (
auto *MD : MDs) {
911 if (
auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
912 visitDIGlobalVariableExpression(*GVE);
914 CheckDI(
false,
"!dbg attachment of global variable must be a "
915 "DIGlobalVariableExpression");
925 "Global @" + GV.
getName() +
" has illegal target extension type",
929 visitGlobalValue(GV);
936 visitGlobalValue(GV);
942 visitAliaseeSubExpr(Visited, GA,
C);
948 Check(isa<GlobalValue>(
C) &&
949 cast<GlobalValue>(
C).hasAvailableExternallyLinkage(),
950 "available_externally alias must point to available_externally "
954 if (
const auto *GV = dyn_cast<GlobalValue>(&
C)) {
960 if (
const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
961 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
963 Check(!GA2->isInterposable(),
964 "Alias cannot point to an interposable alias", &GA);
972 if (
const auto *CE = dyn_cast<ConstantExpr>(&
C))
973 visitConstantExprsRecursively(CE);
975 for (
const Use &U :
C.operands()) {
977 if (
const auto *GA2 = dyn_cast<GlobalAlias>(V))
978 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
979 else if (
const auto *C2 = dyn_cast<Constant>(V))
980 visitAliaseeSubExpr(Visited, GA, *C2);
984void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
986 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
987 "weak_odr, external, or available_externally linkage!",
990 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
992 "Alias and aliasee types should match!", &GA);
994 Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
995 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
997 visitAliaseeSubExpr(GA, *Aliasee);
999 visitGlobalValue(GA);
1002void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
1004 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
1005 "weak_odr, or external linkage!",
1010 Check(
Resolver,
"IFunc must have a Function resolver", &GI);
1012 "IFunc resolver must be a definition", &GI);
1018 Check(isa<PointerType>(
Resolver->getFunctionType()->getReturnType()),
1019 "IFunc resolver must return a pointer", &GI);
1022 "IFunc resolver has incorrect type", &GI);
1025void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
1030 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
1032 if (NMD.
getName() ==
"llvm.dbg.cu")
1033 CheckDI(MD && isa<DICompileUnit>(MD),
"invalid compile unit", &NMD, MD);
1038 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
1042void Verifier::visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
1045 if (!MDNodes.
insert(&MD).second)
1049 "MDNode context does not match Module context!", &MD);
1054 case Metadata::MDTupleKind:
1056#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
1057 case Metadata::CLASS##Kind: \
1058 visit##CLASS(cast<CLASS>(MD)); \
1060#include "llvm/IR/Metadata.def"
1066 Check(!isa<LocalAsMetadata>(
Op),
"Invalid operand for global metadata!",
1068 CheckDI(!isa<DILocation>(
Op) || AllowLocs == AreDebugLocsAllowed::Yes,
1069 "DILocation not allowed within this metadata node", &MD,
Op);
1070 if (
auto *
N = dyn_cast<MDNode>(
Op)) {
1071 visitMDNode(*
N, AllowLocs);
1074 if (
auto *V = dyn_cast<ValueAsMetadata>(
Op)) {
1075 visitValueAsMetadata(*V,
nullptr);
1088 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1090 auto *
L = dyn_cast<LocalAsMetadata>(&MD);
1094 Check(
F,
"function-local metadata used outside a function", L);
1099 if (
Instruction *
I = dyn_cast<Instruction>(
L->getValue())) {
1100 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1101 ActualF =
I->getParent()->getParent();
1102 }
else if (
BasicBlock *BB = dyn_cast<BasicBlock>(
L->getValue()))
1104 else if (
Argument *
A = dyn_cast<Argument>(
L->getValue()))
1105 ActualF =
A->getParent();
1106 assert(ActualF &&
"Unimplemented function local metadata case!");
1108 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1113 visitValueAsMetadata(*VAM,
F);
1118 if (
auto *
N = dyn_cast<MDNode>(MD)) {
1119 visitMDNode(*
N, AreDebugLocsAllowed::No);
1125 if (!MDNodes.
insert(MD).second)
1128 if (
auto *V = dyn_cast<ValueAsMetadata>(MD))
1129 visitValueAsMetadata(*V,
F);
1131 if (
auto *AL = dyn_cast<DIArgList>(MD))
1132 visitDIArgList(*AL,
F);
1139void Verifier::visitDILocation(
const DILocation &
N) {
1140 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1141 "location requires a valid scope", &
N,
N.getRawScope());
1142 if (
auto *IA =
N.getRawInlinedAt())
1143 CheckDI(isa<DILocation>(IA),
"inlined-at should be a location", &
N, IA);
1144 if (
auto *SP = dyn_cast<DISubprogram>(
N.getRawScope()))
1145 CheckDI(SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1152void Verifier::visitDIScope(
const DIScope &
N) {
1153 if (
auto *
F =
N.getRawFile())
1154 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1157void Verifier::visitDISubrange(
const DISubrange &
N) {
1158 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1159 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1160 "Subrange can have any one of count or upperBound", &
N);
1161 auto *CBound =
N.getRawCountNode();
1162 CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1163 isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1164 "Count must be signed constant or DIVariable or DIExpression", &
N);
1165 auto Count =
N.getCount();
1166 CheckDI(!Count || !isa<ConstantInt *>(Count) ||
1167 cast<ConstantInt *>(Count)->getSExtValue() >= -1,
1168 "invalid subrange count", &
N);
1169 auto *LBound =
N.getRawLowerBound();
1170 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1171 isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1172 "LowerBound must be signed constant or DIVariable or DIExpression",
1174 auto *UBound =
N.getRawUpperBound();
1175 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1176 isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1177 "UpperBound must be signed constant or DIVariable or DIExpression",
1179 auto *Stride =
N.getRawStride();
1180 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1181 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1182 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1186 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1187 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1188 "GenericSubrange can have any one of count or upperBound", &
N);
1189 auto *CBound =
N.getRawCountNode();
1190 CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1191 "Count must be signed constant or DIVariable or DIExpression", &
N);
1192 auto *LBound =
N.getRawLowerBound();
1193 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1194 CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1195 "LowerBound must be signed constant or DIVariable or DIExpression",
1197 auto *UBound =
N.getRawUpperBound();
1198 CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1199 "UpperBound must be signed constant or DIVariable or DIExpression",
1201 auto *Stride =
N.getRawStride();
1202 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1203 CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1204 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1208 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1212 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1213 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1214 N.getTag() == dwarf::DW_TAG_string_type,
1219 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1220 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1228 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1229 N.getTag() == dwarf::DW_TAG_pointer_type ||
1230 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1231 N.getTag() == dwarf::DW_TAG_reference_type ||
1232 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1233 N.getTag() == dwarf::DW_TAG_const_type ||
1234 N.getTag() == dwarf::DW_TAG_immutable_type ||
1235 N.getTag() == dwarf::DW_TAG_volatile_type ||
1236 N.getTag() == dwarf::DW_TAG_restrict_type ||
1237 N.getTag() == dwarf::DW_TAG_atomic_type ||
1238 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1239 N.getTag() == dwarf::DW_TAG_member ||
1240 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1241 N.getTag() == dwarf::DW_TAG_inheritance ||
1242 N.getTag() == dwarf::DW_TAG_friend ||
1243 N.getTag() == dwarf::DW_TAG_set_type ||
1244 N.getTag() == dwarf::DW_TAG_template_alias,
1246 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1247 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1248 N.getRawExtraData());
1251 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1252 if (
auto *
T =
N.getRawBaseType()) {
1253 auto *
Enum = dyn_cast_or_null<DICompositeType>(
T);
1254 auto *
Basic = dyn_cast_or_null<DIBasicType>(
T);
1256 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1257 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1258 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1259 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1260 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1261 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1262 "invalid set base type", &
N,
T);
1268 N.getRawBaseType());
1270 if (
N.getDWARFAddressSpace()) {
1271 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1272 N.getTag() == dwarf::DW_TAG_reference_type ||
1273 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1274 "DWARF address space only applies to pointer or reference types",
1281 return ((Flags & DINode::FlagLValueReference) &&
1282 (Flags & DINode::FlagRValueReference)) ||
1283 ((Flags & DINode::FlagTypePassByValue) &&
1284 (Flags & DINode::FlagTypePassByReference));
1287void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1288 auto *Params = dyn_cast<MDTuple>(&RawParams);
1289 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1291 CheckDI(
Op && isa<DITemplateParameter>(
Op),
"invalid template parameter",
1300 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1301 N.getTag() == dwarf::DW_TAG_structure_type ||
1302 N.getTag() == dwarf::DW_TAG_union_type ||
1303 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1304 N.getTag() == dwarf::DW_TAG_class_type ||
1305 N.getTag() == dwarf::DW_TAG_variant_part ||
1306 N.getTag() == dwarf::DW_TAG_namelist,
1311 N.getRawBaseType());
1313 CheckDI(!
N.getRawElements() || isa<MDTuple>(
N.getRawElements()),
1314 "invalid composite elements", &
N,
N.getRawElements());
1316 N.getRawVTableHolder());
1318 "invalid reference flags", &
N);
1319 unsigned DIBlockByRefStruct = 1 << 4;
1320 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1321 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1324 const DINodeArray
Elements =
N.getElements();
1326 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1327 "invalid vector, expected one element of type subrange", &
N);
1330 if (
auto *Params =
N.getRawTemplateParams())
1331 visitTemplateParams(
N, *Params);
1333 if (
auto *
D =
N.getRawDiscriminator()) {
1334 CheckDI(isa<DIDerivedType>(
D) &&
N.getTag() == dwarf::DW_TAG_variant_part,
1335 "discriminator can only appear on variant part");
1338 if (
N.getRawDataLocation()) {
1339 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1340 "dataLocation can only appear in array type");
1343 if (
N.getRawAssociated()) {
1344 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1345 "associated can only appear in array type");
1348 if (
N.getRawAllocated()) {
1349 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1350 "allocated can only appear in array type");
1353 if (
N.getRawRank()) {
1354 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1355 "rank can only appear in array type");
1358 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1359 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1364 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1365 if (
auto *Types =
N.getRawTypeArray()) {
1366 CheckDI(isa<MDTuple>(Types),
"invalid composite elements", &
N, Types);
1367 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1368 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1372 "invalid reference flags", &
N);
1375void Verifier::visitDIFile(
const DIFile &
N) {
1376 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1377 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1380 "invalid checksum kind", &
N);
1382 switch (Checksum->Kind) {
1393 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1395 "invalid checksum", &
N);
1400 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1401 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1405 CheckDI(
N.getRawFile() && isa<DIFile>(
N.getRawFile()),
"invalid file", &
N,
1407 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1411 "invalid emission kind", &
N);
1413 if (
auto *Array =
N.getRawEnumTypes()) {
1414 CheckDI(isa<MDTuple>(Array),
"invalid enum list", &
N, Array);
1415 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1416 auto *
Enum = dyn_cast_or_null<DICompositeType>(
Op);
1417 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1418 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1421 if (
auto *Array =
N.getRawRetainedTypes()) {
1422 CheckDI(isa<MDTuple>(Array),
"invalid retained type list", &
N, Array);
1423 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1425 Op && (isa<DIType>(
Op) || (isa<DISubprogram>(
Op) &&
1426 !cast<DISubprogram>(
Op)->isDefinition())),
1427 "invalid retained type", &
N,
Op);
1430 if (
auto *Array =
N.getRawGlobalVariables()) {
1431 CheckDI(isa<MDTuple>(Array),
"invalid global variable list", &
N, Array);
1432 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1433 CheckDI(
Op && (isa<DIGlobalVariableExpression>(
Op)),
1434 "invalid global variable ref", &
N,
Op);
1437 if (
auto *Array =
N.getRawImportedEntities()) {
1438 CheckDI(isa<MDTuple>(Array),
"invalid imported entity list", &
N, Array);
1439 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1440 CheckDI(
Op && isa<DIImportedEntity>(
Op),
"invalid imported entity ref",
1444 if (
auto *Array =
N.getRawMacros()) {
1445 CheckDI(isa<MDTuple>(Array),
"invalid macro list", &
N, Array);
1447 CheckDI(
Op && isa<DIMacroNode>(
Op),
"invalid macro ref", &
N,
Op);
1454 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1456 if (
auto *
F =
N.getRawFile())
1457 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1459 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1460 if (
auto *
T =
N.getRawType())
1461 CheckDI(isa<DISubroutineType>(
T),
"invalid subroutine type", &
N,
T);
1462 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1463 N.getRawContainingType());
1464 if (
auto *Params =
N.getRawTemplateParams())
1465 visitTemplateParams(
N, *Params);
1466 if (
auto *S =
N.getRawDeclaration())
1467 CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1468 "invalid subprogram declaration", &
N, S);
1469 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1470 auto *
Node = dyn_cast<MDTuple>(RawNode);
1471 CheckDI(
Node,
"invalid retained nodes list", &
N, RawNode);
1473 CheckDI(
Op && (isa<DILocalVariable>(
Op) || isa<DILabel>(
Op) ||
1474 isa<DIImportedEntity>(
Op)),
1475 "invalid retained nodes, expected DILocalVariable, DILabel or "
1481 "invalid reference flags", &
N);
1483 auto *Unit =
N.getRawUnit();
1484 if (
N.isDefinition()) {
1486 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1487 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1488 CheckDI(isa<DICompileUnit>(Unit),
"invalid unit type", &
N, Unit);
1491 auto *CT = dyn_cast_or_null<DICompositeType>(
N.getRawScope());
1492 if (CT && CT->getRawIdentifier() &&
1493 M.getContext().isODRUniquingDebugTypes())
1495 "definition subprograms cannot be nested within DICompositeType "
1496 "when enabling ODR",
1500 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1502 "subprogram declaration must not have a declaration field");
1505 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1506 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1507 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1509 CheckDI(
Op && isa<DIType>(
Op),
"invalid thrown type", &
N, ThrownTypes,
1513 if (
N.areAllCallsDescribed())
1515 "DIFlagAllCallsDescribed must be attached to a definition");
1519 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1520 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1521 "invalid local scope", &
N,
N.getRawScope());
1522 if (
auto *SP = dyn_cast<DISubprogram>(
N.getRawScope()))
1523 CheckDI(SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1527 visitDILexicalBlockBase(
N);
1530 "cannot have column info without line info", &
N);
1534 visitDILexicalBlockBase(
N);
1538 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1539 if (
auto *S =
N.getRawScope())
1540 CheckDI(isa<DIScope>(S),
"invalid scope ref", &
N, S);
1541 if (
auto *S =
N.getRawDecl())
1542 CheckDI(isa<DIGlobalVariable>(S),
"invalid declaration", &
N, S);
1546 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1547 if (
auto *S =
N.getRawScope())
1548 CheckDI(isa<DIScope>(S),
"invalid scope ref", &
N, S);
1551void Verifier::visitDIMacro(
const DIMacro &
N) {
1554 "invalid macinfo type", &
N);
1555 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1556 if (!
N.getValue().empty()) {
1557 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1563 "invalid macinfo type", &
N);
1564 if (
auto *
F =
N.getRawFile())
1565 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1567 if (
auto *Array =
N.getRawElements()) {
1568 CheckDI(isa<MDTuple>(Array),
"invalid macro list", &
N, Array);
1569 for (
Metadata *
Op :
N.getElements()->operands()) {
1570 CheckDI(
Op && isa<DIMacroNode>(
Op),
"invalid macro ref", &
N,
Op);
1575void Verifier::visitDIModule(
const DIModule &
N) {
1576 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1577 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1585 visitDITemplateParameter(
N);
1587 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1591void Verifier::visitDITemplateValueParameter(
1593 visitDITemplateParameter(
N);
1595 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1596 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1597 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1601void Verifier::visitDIVariable(
const DIVariable &
N) {
1602 if (
auto *S =
N.getRawScope())
1603 CheckDI(isa<DIScope>(S),
"invalid scope", &
N, S);
1604 if (
auto *
F =
N.getRawFile())
1605 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1612 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1615 if (
N.isDefinition())
1616 CheckDI(
N.getType(),
"missing global variable type", &
N);
1617 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1618 CheckDI(isa<DIDerivedType>(Member),
1619 "invalid static data member declaration", &
N, Member);
1628 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1629 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1630 "local variable requires a valid scope", &
N,
N.getRawScope());
1631 if (
auto Ty =
N.getType())
1632 CheckDI(!isa<DISubroutineType>(Ty),
"invalid type", &
N,
N.getType());
1635void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1636 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1637 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1640void Verifier::visitDILabel(
const DILabel &
N) {
1641 if (
auto *S =
N.getRawScope())
1642 CheckDI(isa<DIScope>(S),
"invalid scope", &
N, S);
1643 if (
auto *
F =
N.getRawFile())
1644 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1646 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1647 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1648 "label requires a valid scope", &
N,
N.getRawScope());
1652 CheckDI(
N.isValid(),
"invalid expression", &
N);
1655void Verifier::visitDIGlobalVariableExpression(
1659 visitDIGlobalVariable(*Var);
1661 visitDIExpression(*Expr);
1662 if (
auto Fragment = Expr->getFragmentInfo())
1663 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1668 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1669 if (
auto *
T =
N.getRawType())
1671 if (
auto *
F =
N.getRawFile())
1672 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1676 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1677 N.getTag() == dwarf::DW_TAG_imported_declaration,
1679 if (
auto *S =
N.getRawScope())
1680 CheckDI(isa<DIScope>(S),
"invalid scope for imported entity", &
N, S);
1685void Verifier::visitComdat(
const Comdat &
C) {
1688 if (
TT.isOSBinFormatCOFF())
1694void Verifier::visitModuleIdents() {
1695 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1702 Check(
N->getNumOperands() == 1,
1703 "incorrect number of operands in llvm.ident metadata",
N);
1704 Check(dyn_cast_or_null<MDString>(
N->getOperand(0)),
1705 (
"invalid value for llvm.ident metadata entry operand"
1706 "(the operand should be a string)"),
1711void Verifier::visitModuleCommandLines() {
1712 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1720 Check(
N->getNumOperands() == 1,
1721 "incorrect number of operands in llvm.commandline metadata",
N);
1722 Check(dyn_cast_or_null<MDString>(
N->getOperand(0)),
1723 (
"invalid value for llvm.commandline metadata entry operand"
1724 "(the operand should be a string)"),
1729void Verifier::visitModuleFlags() {
1739 visitModuleFlag(MDN, SeenIDs, Requirements);
1740 if (MDN->getNumOperands() != 3)
1742 if (
const auto *FlagName = dyn_cast_or_null<MDString>(MDN->getOperand(1))) {
1743 if (FlagName->getString() ==
"aarch64-elf-pauthabi-platform") {
1744 if (
const auto *PAP =
1745 mdconst::dyn_extract_or_null<ConstantInt>(MDN->getOperand(2)))
1746 PAuthABIPlatform = PAP->getZExtValue();
1747 }
else if (FlagName->getString() ==
"aarch64-elf-pauthabi-version") {
1748 if (
const auto *PAV =
1749 mdconst::dyn_extract_or_null<ConstantInt>(MDN->getOperand(2)))
1750 PAuthABIVersion = PAV->getZExtValue();
1755 if ((PAuthABIPlatform ==
uint64_t(-1)) != (PAuthABIVersion ==
uint64_t(-1)))
1756 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
1757 "'aarch64-elf-pauthabi-version' module flags must be present");
1760 for (
const MDNode *Requirement : Requirements) {
1761 const MDString *
Flag = cast<MDString>(Requirement->getOperand(0));
1762 const Metadata *ReqValue = Requirement->getOperand(1);
1766 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1771 if (
Op->getOperand(2) != ReqValue) {
1772 CheckFailed((
"invalid requirement on flag, "
1773 "flag does not have the required value"),
1781Verifier::visitModuleFlag(
const MDNode *
Op,
1787 "incorrect number of operands in module flag",
Op);
1790 Check(mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(0)),
1791 "invalid behavior operand in module flag (expected constant integer)",
1794 "invalid behavior operand in module flag (unexpected constant)",
1797 MDString *
ID = dyn_cast_or_null<MDString>(
Op->getOperand(1));
1798 Check(
ID,
"invalid ID operand in module flag (expected metadata string)",
1810 auto *
V = mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2));
1811 Check(V &&
V->getValue().isNonNegative(),
1812 "invalid value for 'min' module flag (expected constant non-negative "
1819 Check(mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2)),
1820 "invalid value for 'max' module flag (expected constant integer)",
1830 "invalid value for 'require' module flag (expected metadata pair)",
1833 (
"invalid value for 'require' module flag "
1834 "(first value operand should be a string)"),
1835 Value->getOperand(0));
1846 Check(isa<MDNode>(
Op->getOperand(2)),
1847 "invalid value for 'append'-type module flag "
1848 "(expected a metadata node)",
1858 "module flag identifiers must be unique (or of 'require' type)",
ID);
1861 if (
ID->getString() ==
"wchar_size") {
1863 = mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2));
1864 Check(
Value,
"wchar_size metadata requires constant integer argument");
1867 if (
ID->getString() ==
"Linker Options") {
1871 Check(
M.getNamedMetadata(
"llvm.linker.options"),
1872 "'Linker Options' named metadata no longer supported");
1875 if (
ID->getString() ==
"SemanticInterposition") {
1877 mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2));
1879 "SemanticInterposition metadata requires constant integer argument");
1882 if (
ID->getString() ==
"CG Profile") {
1883 for (
const MDOperand &MDO : cast<MDNode>(
Op->getOperand(2))->operands())
1884 visitModuleFlagCGProfileEntry(MDO);
1888void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
1889 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
1892 auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
1893 Check(
F && isa<Function>(
F->getValue()->stripPointerCasts()),
1894 "expected a Function or null", FuncMDO);
1896 auto Node = dyn_cast_or_null<MDNode>(MDO);
1897 Check(
Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
1898 CheckFunction(
Node->getOperand(0));
1899 CheckFunction(
Node->getOperand(1));
1900 auto Count = dyn_cast_or_null<ConstantAsMetadata>(
Node->getOperand(2));
1901 Check(Count && Count->getType()->isIntegerTy(),
1902 "expected an integer constant",
Node->getOperand(2));
1908 if (
A.isStringAttribute()) {
1909#define GET_ATTR_NAMES
1910#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1911#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
1912 if (A.getKindAsString() == #DISPLAY_NAME) { \
1913 auto V = A.getValueAsString(); \
1914 if (!(V.empty() || V == "true" || V == "false")) \
1915 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
1919#include "llvm/IR/Attributes.inc"
1924 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
1935 if (!
Attrs.hasAttributes())
1938 verifyAttributeTypes(Attrs, V);
1941 Check(Attr.isStringAttribute() ||
1943 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
1946 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
1948 "Attribute 'immarg' is incompatible with other attributes", V);
1953 unsigned AttrCount = 0;
1954 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
1955 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
1956 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
1957 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
1958 Attrs.hasAttribute(Attribute::InReg);
1959 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
1960 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
1961 Check(AttrCount <= 1,
1962 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1963 "'byref', and 'sret' are incompatible!",
1966 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
1967 Attrs.hasAttribute(Attribute::ReadOnly)),
1969 "'inalloca and readonly' are incompatible!",
1972 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
1973 Attrs.hasAttribute(Attribute::Returned)),
1975 "'sret and returned' are incompatible!",
1978 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
1979 Attrs.hasAttribute(Attribute::SExt)),
1981 "'zeroext and signext' are incompatible!",
1984 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
1985 Attrs.hasAttribute(Attribute::ReadOnly)),
1987 "'readnone and readonly' are incompatible!",
1990 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
1991 Attrs.hasAttribute(Attribute::WriteOnly)),
1993 "'readnone and writeonly' are incompatible!",
1996 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
1997 Attrs.hasAttribute(Attribute::WriteOnly)),
1999 "'readonly and writeonly' are incompatible!",
2002 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2003 Attrs.hasAttribute(Attribute::AlwaysInline)),
2005 "'noinline and alwaysinline' are incompatible!",
2008 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2009 Attrs.hasAttribute(Attribute::ReadNone)),
2010 "Attributes writable and readnone are incompatible!", V);
2012 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2013 Attrs.hasAttribute(Attribute::ReadOnly)),
2014 "Attributes writable and readonly are incompatible!", V);
2018 if (!Attr.isStringAttribute() &&
2019 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2020 CheckFailed(
"Attribute '" + Attr.getAsString() +
2021 "' applied to incompatible type!", V);
2026 if (isa<PointerType>(Ty)) {
2027 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2028 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2030 "huge alignment values are unsupported", V);
2032 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2036 "Attribute 'byval' does not support unsized types!", V);
2040 "'byval' argument has illegal target extension type", V);
2041 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2042 "huge 'byval' arguments are unsupported", V);
2044 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2046 Check(
Attrs.getByRefType()->isSized(&Visited),
2047 "Attribute 'byref' does not support unsized types!", V);
2048 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2050 "huge 'byref' arguments are unsupported", V);
2052 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2054 Check(
Attrs.getInAllocaType()->isSized(&Visited),
2055 "Attribute 'inalloca' does not support unsized types!", V);
2056 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2058 "huge 'inalloca' arguments are unsupported", V);
2060 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2062 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
2063 "Attribute 'preallocated' does not support unsized types!", V);
2065 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2067 "huge 'preallocated' arguments are unsupported", V);
2071 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2072 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2073 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2076 "Attribute 'initializes' does not support unordered ranges", V);
2079 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2080 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2081 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2084 "Invalid value for 'nofpclass' test mask", V);
2086 if (
Attrs.hasAttribute(Attribute::Range)) {
2088 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2090 "Range bit width must match type bit width!", V);
2096 if (
Attrs.hasFnAttr(Attr)) {
2100 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
2107 const Value *V,
bool IsIntrinsic,
2109 if (
Attrs.isEmpty())
2112 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2114 "Attribute list does not match Module context!", &Attrs, V);
2115 for (
const auto &AttrSet : Attrs) {
2116 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2117 "Attribute set does not match Module context!", &AttrSet, V);
2118 for (
const auto &
A : AttrSet) {
2119 Check(
A.hasParentContext(Context),
2120 "Attribute does not match Module context!", &
A, V);
2125 bool SawNest =
false;
2126 bool SawReturned =
false;
2127 bool SawSRet =
false;
2128 bool SawSwiftSelf =
false;
2129 bool SawSwiftAsync =
false;
2130 bool SawSwiftError =
false;
2137 "Attribute '" +
RetAttr.getAsString() +
2138 "' does not apply to function return values",
2141 unsigned MaxParameterWidth = 0;
2142 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2144 if (
auto *VT = dyn_cast<FixedVectorType>(Ty)) {
2145 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2146 if (
Size > MaxParameterWidth)
2147 MaxParameterWidth =
Size;
2151 GetMaxParameterWidth(FT->getReturnType());
2152 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2155 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2156 Type *Ty = FT->getParamType(i);
2161 "immarg attribute only applies to intrinsics", V);
2164 "Attribute 'elementtype' can only be applied to intrinsics"
2169 verifyParameterAttrs(ArgAttrs, Ty, V);
2170 GetMaxParameterWidth(Ty);
2173 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2178 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2180 "Incompatible argument and return types for 'returned' attribute",
2186 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2187 Check(i == 0 || i == 1,
2188 "Attribute 'sret' is not on first or second parameter!", V);
2193 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2194 SawSwiftSelf =
true;
2198 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2199 SawSwiftAsync =
true;
2203 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2204 SawSwiftError =
true;
2208 Check(i == FT->getNumParams() - 1,
2209 "inalloca isn't on the last parameter!", V);
2213 if (!
Attrs.hasFnAttrs())
2216 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2220 "Attribute '" +
FnAttr.getAsString() +
2221 "' does not apply to functions!",
2224 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2225 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2226 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2228 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2230 "Attribute 'optnone' requires 'noinline'!", V);
2232 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2233 "Attributes 'optsize and optnone' are incompatible!", V);
2236 "Attributes 'minsize and optnone' are incompatible!", V);
2238 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2239 "Attributes 'optdebug and optnone' are incompatible!", V);
2242 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2243 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2245 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2248 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2249 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2250 "Attributes 'optsize and optdebug' are incompatible!", V);
2253 "Attributes 'minsize and optdebug' are incompatible!", V);
2256 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2258 "Attribute writable and memory without argmem: write are incompatible!",
2261 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2262 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2263 "Attributes 'aarch64_pstate_sm_enabled and "
2264 "aarch64_pstate_sm_compatible' are incompatible!",
2268 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2269 Attrs.hasFnAttr(
"aarch64_inout_za") +
2270 Attrs.hasFnAttr(
"aarch64_out_za") +
2271 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2272 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2273 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2274 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2275 "'aarch64_za_state_agnostic' are mutually exclusive",
2279 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2280 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2281 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2282 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2283 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2284 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2285 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2286 "'aarch64_za_state_agnostic' are mutually exclusive",
2289 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2292 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2295 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2297 if (ParamNo >= FT->getNumParams()) {
2298 CheckFailed(
"'allocsize' " +
Name +
" argument is out of bounds", V);
2302 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2303 CheckFailed(
"'allocsize' " +
Name +
2304 " argument must refer to an integer parameter",
2312 if (!CheckParam(
"element size",
Args->first))
2315 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2319 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2327 "'allockind()' requires exactly one of alloc, realloc, and free");
2331 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2332 "or aligned modifiers.");
2334 if ((K & ZeroedUninit) == ZeroedUninit)
2335 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2338 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2339 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2341 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2343 CheckFailed(
"'vscale_range' minimum must be power-of-two value", V);
2344 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2345 if (VScaleMax && VScaleMin > VScaleMax)
2346 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2348 CheckFailed(
"'vscale_range' maximum must be power-of-two value", V);
2351 if (
Attrs.hasFnAttr(
"frame-pointer")) {
2353 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved")
2354 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2358 if (MaxParameterWidth >= 512 &&
Attrs.hasFnAttr(
"target-features") &&
2360 StringRef TF =
Attrs.getFnAttr(
"target-features").getValueAsString();
2362 "512-bit vector arguments require 'evex512' for AVX512", V);
2365 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2366 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2367 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2369 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2371 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2372 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S, V);
2375 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2377 if (S !=
"a_key" && S !=
"b_key")
2378 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2380 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2382 "'sign-return-address-key' present without `sign-return-address`");
2386 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2388 if (S !=
"" && S !=
"true" && S !=
"false")
2390 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2393 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2395 if (S !=
"" && S !=
"true" && S !=
"false")
2397 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2400 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2402 if (S !=
"" && S !=
"true" && S !=
"false")
2403 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2407 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2411 CheckFailed(
"invalid name for a VFABI variant: " + S, V);
2414 if (
auto A =
Attrs.getFnAttr(
"denormal-fp-math");
A.isValid()) {
2417 CheckFailed(
"invalid value for 'denormal-fp-math' attribute: " + S, V);
2420 if (
auto A =
Attrs.getFnAttr(
"denormal-fp-math-f32");
A.isValid()) {
2423 CheckFailed(
"invalid value for 'denormal-fp-math-f32' attribute: " + S,
2428void Verifier::verifyFunctionMetadata(
2429 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2430 for (
const auto &Pair : MDs) {
2431 if (Pair.first == LLVMContext::MD_prof) {
2432 MDNode *MD = Pair.second;
2434 "!prof annotations should have no less than 2 operands", MD);
2437 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2440 "expected string with name of the !prof annotation", MD);
2443 Check(ProfName ==
"function_entry_count" ||
2444 ProfName ==
"synthetic_function_entry_count",
2445 "first operand should be 'function_entry_count'"
2446 " or 'synthetic_function_entry_count'",
2450 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2453 "expected integer argument to function_entry_count", MD);
2454 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2455 MDNode *MD = Pair.second;
2457 "!kcfi_type must have exactly one operand", MD);
2458 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2461 "expected a constant operand for !kcfi_type", MD);
2463 Check(isa<ConstantInt>(
C) && isa<IntegerType>(
C->getType()),
2464 "expected a constant integer operand for !kcfi_type", MD);
2466 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2471void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2472 if (!ConstantExprVisited.
insert(EntryC).second)
2476 Stack.push_back(EntryC);
2478 while (!
Stack.empty()) {
2482 if (
const auto *CE = dyn_cast<ConstantExpr>(
C))
2483 visitConstantExpr(CE);
2485 if (
const auto *CPA = dyn_cast<ConstantPtrAuth>(
C))
2486 visitConstantPtrAuth(CPA);
2488 if (
const auto *GV = dyn_cast<GlobalValue>(
C)) {
2491 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2497 for (
const Use &U :
C->operands()) {
2498 const auto *OpC = dyn_cast<Constant>(U);
2501 if (!ConstantExprVisited.
insert(OpC).second)
2503 Stack.push_back(OpC);
2508void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2509 if (
CE->getOpcode() == Instruction::BitCast)
2512 "Invalid bitcast", CE);
2517 "signed ptrauth constant base pointer must have pointer type");
2520 "signed ptrauth constant must have same type as its base pointer");
2523 "signed ptrauth constant key must be i32 constant integer");
2526 "signed ptrauth constant address discriminator must be a pointer");
2529 "signed ptrauth constant discriminator must be i64 constant integer");
2532bool Verifier::verifyAttributeCount(
AttributeList Attrs,
unsigned Params) {
2535 return Attrs.getNumAttrSets() <= Params + 2;
2538void Verifier::verifyInlineAsmCall(
const CallBase &Call) {
2541 unsigned LabelNo = 0;
2552 if (CI.isIndirect) {
2553 const Value *Arg =
Call.getArgOperand(ArgNo);
2555 "Operand for indirect constraint must have pointer type", &Call);
2558 "Operand for indirect constraint must have elementtype attribute",
2561 Check(!
Call.paramHasAttr(ArgNo, Attribute::ElementType),
2562 "Elementtype attribute can only be applied for indirect "
2570 if (
auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2571 Check(LabelNo == CallBr->getNumIndirectDests(),
2572 "Number of label constraints does not match number of callbr dests",
2575 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
2581void Verifier::verifyStatepoint(
const CallBase &Call) {
2583 Call.getCalledFunction()->getIntrinsicID() ==
2584 Intrinsic::experimental_gc_statepoint);
2586 Check(!
Call.doesNotAccessMemory() && !
Call.onlyReadsMemory() &&
2587 !
Call.onlyAccessesArgMemory(),
2588 "gc.statepoint must read and write all memory to preserve "
2589 "reordering restrictions required by safepoint semantics",
2592 const int64_t NumPatchBytes =
2593 cast<ConstantInt>(
Call.getArgOperand(1))->getSExtValue();
2594 assert(isInt<32>(NumPatchBytes) &&
"NumPatchBytesV is an i32!");
2595 Check(NumPatchBytes >= 0,
2596 "gc.statepoint number of patchable bytes must be "
2600 Type *TargetElemType =
Call.getParamElementType(2);
2601 Check(TargetElemType,
2602 "gc.statepoint callee argument must have elementtype attribute", Call);
2603 FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
2604 Check(TargetFuncType,
2605 "gc.statepoint callee elementtype must be function type", Call);
2607 const int NumCallArgs = cast<ConstantInt>(
Call.getArgOperand(3))->getZExtValue();
2608 Check(NumCallArgs >= 0,
2609 "gc.statepoint number of arguments to underlying call "
2612 const int NumParams = (int)TargetFuncType->getNumParams();
2613 if (TargetFuncType->isVarArg()) {
2614 Check(NumCallArgs >= NumParams,
2615 "gc.statepoint mismatch in number of vararg call args", Call);
2618 Check(TargetFuncType->getReturnType()->isVoidTy(),
2619 "gc.statepoint doesn't support wrapping non-void "
2620 "vararg functions yet",
2623 Check(NumCallArgs == NumParams,
2624 "gc.statepoint mismatch in number of call args", Call);
2627 = cast<ConstantInt>(
Call.getArgOperand(4))->getZExtValue();
2629 "unknown flag used in gc.statepoint flags argument", Call);
2634 for (
int i = 0; i < NumParams; i++) {
2635 Type *ParamType = TargetFuncType->getParamType(i);
2636 Type *ArgType =
Call.getArgOperand(5 + i)->getType();
2637 Check(ArgType == ParamType,
2638 "gc.statepoint call argument does not match wrapped "
2642 if (TargetFuncType->isVarArg()) {
2645 "Attribute 'sret' cannot be used for vararg call arguments!", Call);
2649 const int EndCallArgsInx = 4 + NumCallArgs;
2651 const Value *NumTransitionArgsV =
Call.getArgOperand(EndCallArgsInx + 1);
2652 Check(isa<ConstantInt>(NumTransitionArgsV),
2653 "gc.statepoint number of transition arguments "
2654 "must be constant integer",
2656 const int NumTransitionArgs =
2657 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2658 Check(NumTransitionArgs == 0,
2659 "gc.statepoint w/inline transition bundle is deprecated", Call);
2660 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2662 const Value *NumDeoptArgsV =
Call.getArgOperand(EndTransitionArgsInx + 1);
2663 Check(isa<ConstantInt>(NumDeoptArgsV),
2664 "gc.statepoint number of deoptimization arguments "
2665 "must be constant integer",
2667 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2668 Check(NumDeoptArgs == 0,
2669 "gc.statepoint w/inline deopt operands is deprecated", Call);
2671 const int ExpectedNumArgs = 7 + NumCallArgs;
2672 Check(ExpectedNumArgs == (
int)
Call.arg_size(),
2673 "gc.statepoint too many arguments", Call);
2678 for (
const User *U :
Call.users()) {
2679 const CallInst *UserCall = dyn_cast<const CallInst>(U);
2680 Check(UserCall,
"illegal use of statepoint token", Call, U);
2683 Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
2684 "gc.result or gc.relocate are the only value uses "
2685 "of a gc.statepoint",
2687 if (isa<GCResultInst>(UserCall)) {
2689 "gc.result connected to wrong gc.statepoint", Call, UserCall);
2690 }
else if (isa<GCRelocateInst>(Call)) {
2692 "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
2706void Verifier::verifyFrameRecoverIndices() {
2707 for (
auto &Counts : FrameEscapeInfo) {
2709 unsigned EscapedObjectCount = Counts.second.first;
2710 unsigned MaxRecoveredIndex = Counts.second.second;
2711 Check(MaxRecoveredIndex <= EscapedObjectCount,
2712 "all indices passed to llvm.localrecover must be less than the "
2713 "number of arguments passed to llvm.localescape in the parent "
2721 if (
auto *
II = dyn_cast<InvokeInst>(Terminator))
2722 UnwindDest =
II->getUnwindDest();
2723 else if (
auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2724 UnwindDest = CSI->getUnwindDest();
2726 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
2730void Verifier::verifySiblingFuncletUnwinds() {
2733 for (
const auto &Pair : SiblingFuncletInfo) {
2735 if (Visited.
count(PredPad))
2741 if (Active.
count(SuccPad)) {
2747 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2748 if (CycleTerminator != CyclePad)
2751 }
while (CyclePad != SuccPad);
2752 Check(
false,
"EH pads can't handle each other's exceptions",
2756 if (!Visited.
insert(SuccPad).second)
2760 auto TermI = SiblingFuncletInfo.find(PredPad);
2761 if (TermI == SiblingFuncletInfo.end())
2774void Verifier::visitFunction(
const Function &
F) {
2775 visitGlobalValue(
F);
2779 unsigned NumArgs =
F.arg_size();
2781 Check(&Context == &
F.getContext(),
2782 "Function context does not match Module context!", &
F);
2784 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
2785 Check(FT->getNumParams() == NumArgs,
2786 "# formal arguments must match # of arguments for function type!", &
F,
2788 Check(
F.getReturnType()->isFirstClassType() ||
2789 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
2790 "Functions cannot return aggregate values!", &
F);
2792 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
2793 "Invalid struct return type!", &
F);
2797 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
2798 "Attribute after last parameter!", &
F);
2800 CheckDI(
F.IsNewDbgInfoFormat ==
F.getParent()->IsNewDbgInfoFormat,
2801 "Function debug format should match parent module", &
F,
2802 F.IsNewDbgInfoFormat,
F.getParent(),
2803 F.getParent()->IsNewDbgInfoFormat);
2805 bool IsIntrinsic =
F.isIntrinsic();
2808 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
2814 "Attribute 'builtin' can only be applied to a callsite.", &
F);
2816 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
2817 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
2819 if (
Attrs.hasFnAttr(Attribute::Naked))
2821 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
2826 switch (
F.getCallingConv()) {
2831 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
2832 "Calling convention parameter requires byval", &
F);
2839 Check(
F.getReturnType()->isVoidTy(),
2840 "Calling convention requires void return type", &
F);
2847 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
2849 const unsigned StackAS =
DL.getAllocaAddrSpace();
2852 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
2853 "Calling convention disallows byval", &
F);
2854 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
2855 "Calling convention disallows preallocated", &
F);
2856 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
2857 "Calling convention disallows inalloca", &
F);
2859 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
2862 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
2863 "Calling convention disallows stack byref", &
F);
2877 "Calling convention does not support varargs or "
2878 "perfect forwarding!",
2886 Check(Arg.getType() == FT->getParamType(i),
2887 "Argument value does not match function argument type!", &Arg,
2888 FT->getParamType(i));
2889 Check(Arg.getType()->isFirstClassType(),
2890 "Function arguments must have first-class types!", &Arg);
2892 Check(!Arg.getType()->isMetadataTy(),
2893 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
2894 Check(!Arg.getType()->isTokenTy(),
2895 "Function takes token but isn't an intrinsic", &Arg, &
F);
2896 Check(!Arg.getType()->isX86_AMXTy(),
2897 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
2901 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
2902 verifySwiftErrorValue(&Arg);
2908 Check(!
F.getReturnType()->isTokenTy(),
2909 "Function returns a token but isn't an intrinsic", &
F);
2910 Check(!
F.getReturnType()->isX86_AMXTy(),
2911 "Function returns a x86_amx but isn't an intrinsic", &
F);
2916 F.getAllMetadata(MDs);
2917 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
2918 verifyFunctionMetadata(MDs);
2921 if (
F.hasPersonalityFn()) {
2922 auto *Per = dyn_cast<Function>(
F.getPersonalityFn()->stripPointerCasts());
2924 Check(Per->getParent() ==
F.getParent(),
2925 "Referencing personality function in another module!", &
F,
2926 F.getParent(), Per, Per->getParent());
2930 BlockEHFuncletColors.
clear();
2932 if (
F.isMaterializable()) {
2934 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
2936 }
else if (
F.isDeclaration()) {
2937 for (
const auto &
I : MDs) {
2939 CheckDI(
I.first != LLVMContext::MD_dbg ||
2940 !cast<DISubprogram>(
I.second)->isDistinct(),
2941 "function declaration may only have a unique !dbg attachment",
2943 Check(
I.first != LLVMContext::MD_prof,
2944 "function declaration may not have a !prof attachment", &
F);
2947 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
2949 Check(!
F.hasPersonalityFn(),
2950 "Function declaration shouldn't have a personality routine", &
F);
2954 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
2959 "Entry block to function must not have predecessors!", Entry);
2962 if (
Entry->hasAddressTaken()) {
2964 "blockaddress may not be used with the entry block!", Entry);
2967 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
2968 NumKCFIAttachments = 0;
2970 for (
const auto &
I : MDs) {
2972 auto AllowLocs = AreDebugLocsAllowed::No;
2976 case LLVMContext::MD_dbg: {
2977 ++NumDebugAttachments;
2978 CheckDI(NumDebugAttachments == 1,
2979 "function must have a single !dbg attachment", &
F,
I.second);
2980 CheckDI(isa<DISubprogram>(
I.second),
2981 "function !dbg attachment must be a subprogram", &
F,
I.second);
2982 CheckDI(cast<DISubprogram>(
I.second)->isDistinct(),
2983 "function definition may only have a distinct !dbg attachment",
2986 auto *SP = cast<DISubprogram>(
I.second);
2987 const Function *&AttachedTo = DISubprogramAttachments[SP];
2988 CheckDI(!AttachedTo || AttachedTo == &
F,
2989 "DISubprogram attached to more than one function", SP, &
F);
2991 AllowLocs = AreDebugLocsAllowed::Yes;
2994 case LLVMContext::MD_prof:
2995 ++NumProfAttachments;
2996 Check(NumProfAttachments == 1,
2997 "function must have a single !prof attachment", &
F,
I.second);
2999 case LLVMContext::MD_kcfi_type:
3000 ++NumKCFIAttachments;
3001 Check(NumKCFIAttachments == 1,
3002 "function must have a single !kcfi_type attachment", &
F,
3008 visitMDNode(*
I.second, AllowLocs);
3016 if (
F.isIntrinsic() &&
F.getParent()->isMaterialized()) {
3018 if (
F.hasAddressTaken(&U,
false,
true,
false,
3020 Check(
false,
"Invalid user of intrinsic instruction!", U);
3024 switch (
F.getIntrinsicID()) {
3025 case Intrinsic::experimental_gc_get_pointer_base: {
3027 Check(FT->getNumParams() == 1,
"wrong number of parameters",
F);
3028 Check(isa<PointerType>(
F.getReturnType()),
3029 "gc.get.pointer.base must return a pointer",
F);
3030 Check(FT->getParamType(0) ==
F.getReturnType(),
3031 "gc.get.pointer.base operand and result must be of the same type",
F);
3034 case Intrinsic::experimental_gc_get_pointer_offset: {
3036 Check(FT->getNumParams() == 1,
"wrong number of parameters",
F);
3037 Check(isa<PointerType>(FT->getParamType(0)),
3038 "gc.get.pointer.offset operand must be a pointer",
F);
3039 Check(
F.getReturnType()->isIntegerTy(),
3040 "gc.get.pointer.offset must return integer",
F);
3045 auto *
N =
F.getSubprogram();
3046 HasDebugInfo = (
N !=
nullptr);
3065 CheckDI(Parent && isa<DILocalScope>(Parent),
3066 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3069 Check(Scope,
"Failed to find DILocalScope",
DL);
3071 if (!Seen.
insert(Scope).second)
3078 if (SP && ((Scope != SP) && !Seen.
insert(SP).second))
3082 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3086 for (
auto &
I : BB) {
3087 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3089 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3091 VisitDebugLoc(
I, dyn_cast_or_null<MDNode>(MD->
getOperand(i)));
3092 if (BrokenDebugInfo)
3099void Verifier::visitBasicBlock(
BasicBlock &BB) {
3100 InstsInThisBlock.
clear();
3101 ConvergenceVerifyHelper.
visit(BB);
3108 if (isa<PHINode>(BB.
front())) {
3113 Check(PN.getNumIncomingValues() == Preds.size(),
3114 "PHINode should have one entry for each predecessor of its "
3115 "parent basic block!",
3120 Values.
reserve(PN.getNumIncomingValues());
3121 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3123 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3126 for (
unsigned i = 0, e = Values.
size(); i != e; ++i) {
3131 Check(i == 0 || Values[i].first != Values[i - 1].first ||
3132 Values[i].second == Values[i - 1].second,
3133 "PHI node has multiple entries for the same basic block with "
3134 "different incoming values!",
3135 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
3139 Check(Values[i].first == Preds[i],
3140 "PHI node entries do not match predecessors!", &PN,
3141 Values[i].first, Preds[i]);
3149 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3152 CheckDI(BB.IsNewDbgInfoFormat == BB.getParent()->IsNewDbgInfoFormat,
3153 "BB debug format should match parent function", &BB,
3154 BB.IsNewDbgInfoFormat, BB.getParent(),
3155 BB.getParent()->IsNewDbgInfoFormat);
3158 if (BB.IsNewDbgInfoFormat)
3159 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3165 Check(&
I ==
I.getParent()->getTerminator(),
3166 "Terminator found in the middle of a basic block!",
I.getParent());
3170void Verifier::visitBranchInst(
BranchInst &BI) {
3173 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3178void Verifier::visitReturnInst(
ReturnInst &RI) {
3181 if (
F->getReturnType()->isVoidTy())
3183 "Found return instr that returns non-void in Function of void "
3185 &RI,
F->getReturnType());
3188 "Function return type does not match operand "
3189 "type of return inst!",
3190 &RI,
F->getReturnType());
3197void Verifier::visitSwitchInst(
SwitchInst &SI) {
3198 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3201 Type *SwitchTy =
SI.getCondition()->getType();
3203 for (
auto &Case :
SI.cases()) {
3204 Check(isa<ConstantInt>(
SI.getOperand(Case.getCaseIndex() * 2 + 2)),
3205 "Case value is not a constant integer.", &SI);
3206 Check(Case.getCaseValue()->getType() == SwitchTy,
3207 "Switch constants must all be same type as switch value!", &SI);
3209 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3217 "Indirectbr operand must have pointer type!", &BI);
3220 "Indirectbr destinations must all have pointer type!", &BI);
3225void Verifier::visitCallBrInst(
CallBrInst &CBI) {
3226 Check(CBI.
isInlineAsm(),
"Callbr is currently only used for asm-goto!", &CBI);
3228 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3230 verifyInlineAsmCall(CBI);
3234void Verifier::visitSelectInst(
SelectInst &SI) {
3237 "Invalid operands for select instruction!", &SI);
3239 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3240 "Select values must have same type as select instruction!", &SI);
3248 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3253 Type *SrcTy =
I.getOperand(0)->getType();
3254 Type *DestTy =
I.getType();
3263 "trunc source and destination must both be a vector or neither", &
I);
3264 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3269void Verifier::visitZExtInst(
ZExtInst &
I) {
3271 Type *SrcTy =
I.getOperand(0)->getType();
3272 Type *DestTy =
I.getType();
3278 "zext source and destination must both be a vector or neither", &
I);
3282 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3287void Verifier::visitSExtInst(
SExtInst &
I) {
3289 Type *SrcTy =
I.getOperand(0)->getType();
3290 Type *DestTy =
I.getType();
3299 "sext source and destination must both be a vector or neither", &
I);
3300 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3307 Type *SrcTy =
I.getOperand(0)->getType();
3308 Type *DestTy =
I.getType();
3316 "fptrunc source and destination must both be a vector or neither", &
I);
3317 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3324 Type *SrcTy =
I.getOperand(0)->getType();
3325 Type *DestTy =
I.getType();
3334 "fpext source and destination must both be a vector or neither", &
I);
3335 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3342 Type *SrcTy =
I.getOperand(0)->getType();
3343 Type *DestTy =
I.getType();
3348 Check(SrcVec == DstVec,
3349 "UIToFP source and dest must both be vector or scalar", &
I);
3351 "UIToFP source must be integer or integer vector", &
I);
3355 if (SrcVec && DstVec)
3356 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3357 cast<VectorType>(DestTy)->getElementCount(),
3358 "UIToFP source and dest vector length mismatch", &
I);
3365 Type *SrcTy =
I.getOperand(0)->getType();
3366 Type *DestTy =
I.getType();
3371 Check(SrcVec == DstVec,
3372 "SIToFP source and dest must both be vector or scalar", &
I);
3374 "SIToFP source must be integer or integer vector", &
I);
3378 if (SrcVec && DstVec)
3379 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3380 cast<VectorType>(DestTy)->getElementCount(),
3381 "SIToFP source and dest vector length mismatch", &
I);
3388 Type *SrcTy =
I.getOperand(0)->getType();
3389 Type *DestTy =
I.getType();
3394 Check(SrcVec == DstVec,
3395 "FPToUI source and dest must both be vector or scalar", &
I);
3398 "FPToUI result must be integer or integer vector", &
I);
3400 if (SrcVec && DstVec)
3401 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3402 cast<VectorType>(DestTy)->getElementCount(),
3403 "FPToUI source and dest vector length mismatch", &
I);
3410 Type *SrcTy =
I.getOperand(0)->getType();
3411 Type *DestTy =
I.getType();
3416 Check(SrcVec == DstVec,
3417 "FPToSI source and dest must both be vector or scalar", &
I);
3420 "FPToSI result must be integer or integer vector", &
I);
3422 if (SrcVec && DstVec)
3423 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3424 cast<VectorType>(DestTy)->getElementCount(),
3425 "FPToSI source and dest vector length mismatch", &
I);
3432 Type *SrcTy =
I.getOperand(0)->getType();
3433 Type *DestTy =
I.getType();
3442 auto *VSrc = cast<VectorType>(SrcTy);
3443 auto *VDest = cast<VectorType>(DestTy);
3444 Check(VSrc->getElementCount() == VDest->getElementCount(),
3445 "PtrToInt Vector width mismatch", &
I);
3453 Type *SrcTy =
I.getOperand(0)->getType();
3454 Type *DestTy =
I.getType();
3462 auto *VSrc = cast<VectorType>(SrcTy);
3463 auto *VDest = cast<VectorType>(DestTy);
3464 Check(VSrc->getElementCount() == VDest->getElementCount(),
3465 "IntToPtr Vector width mismatch", &
I);
3473 "Invalid bitcast", &
I);
3478 Type *SrcTy =
I.getOperand(0)->getType();
3479 Type *DestTy =
I.getType();
3486 "AddrSpaceCast must be between different address spaces", &
I);
3487 if (
auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3488 Check(SrcVTy->getElementCount() ==
3489 cast<VectorType>(DestTy)->getElementCount(),
3490 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3496void Verifier::visitPHINode(
PHINode &PN) {
3503 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3512 "PHI node operands are not the same type as the result!", &PN);
3520void Verifier::visitCallBase(
CallBase &Call) {
3521 Check(
Call.getCalledOperand()->getType()->isPointerTy(),
3522 "Called function must be a pointer!", Call);
3526 if (FTy->isVarArg())
3527 Check(
Call.arg_size() >= FTy->getNumParams(),
3528 "Called function requires more parameters than were provided!", Call);
3530 Check(
Call.arg_size() == FTy->getNumParams(),
3531 "Incorrect number of arguments passed to called function!", Call);
3534 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3535 Check(
Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3536 "Call parameter type does not match function signature!",
3537 Call.getArgOperand(i), FTy->getParamType(i), Call);
3541 Check(verifyAttributeCount(Attrs,
Call.arg_size()),
3542 "Attribute after last parameter!", Call);
3545 dyn_cast<Function>(
Call.getCalledOperand()->stripPointerCasts());
3549 "Intrinsic called with incompatible signature", Call);
3553 auto CC =
Call.getCallingConv();
3556 "Direct calls to amdgpu_cs_chain/amdgpu_cs_chain_preserve functions "
3557 "not allowed. Please use the @llvm.amdgpu.cs.chain intrinsic instead.",
3564 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3567 Align ABIAlign =
DL.getABITypeAlign(Ty);
3569 "Incorrect alignment of " + Message +
" to called function!", Call);
3573 VerifyTypeAlign(FTy->getReturnType(),
"return type");
3574 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3575 Type *Ty = FTy->getParamType(i);
3576 VerifyTypeAlign(Ty,
"argument passed");
3580 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
3584 "speculatable attribute may not apply to call sites", Call);
3587 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
3588 Check(
Call.getCalledFunction()->getIntrinsicID() ==
3589 Intrinsic::call_preallocated_arg,
3590 "preallocated as a call site attribute can only be on "
3591 "llvm.call.preallocated.arg");
3595 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic,
Call.isInlineAsm());
3600 if (
Call.hasInAllocaArgument()) {
3601 Value *InAllocaArg =
Call.getArgOperand(FTy->getNumParams() - 1);
3603 Check(AI->isUsedWithInAlloca(),
3604 "inalloca argument for call has mismatched alloca", AI, Call);
3610 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3611 if (
Call.paramHasAttr(i, Attribute::SwiftError)) {
3612 Value *SwiftErrorArg =
Call.getArgOperand(i);
3614 Check(AI->isSwiftError(),
3615 "swifterror argument for call has mismatched alloca", AI, Call);
3618 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
3619 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
3620 SwiftErrorArg, Call);
3621 Check(ArgI->hasSwiftErrorAttr(),
3622 "swifterror argument for call has mismatched parameter", ArgI,
3626 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3629 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
3630 "immarg may not apply only to call sites",
Call.getArgOperand(i),
3634 if (
Call.paramHasAttr(i, Attribute::ImmArg)) {
3636 Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
3637 "immarg operand has non-immediate parameter", ArgVal, Call);
3640 if (
Call.paramHasAttr(i, Attribute::Preallocated)) {
3644 bool isMustTail =
Call.isMustTailCall();
3645 Check(hasOB != isMustTail,
3646 "preallocated operand either requires a preallocated bundle or "
3647 "the call to be musttail (but not both)",
3652 if (FTy->isVarArg()) {
3654 bool SawNest =
false;
3655 bool SawReturned =
false;
3657 for (
unsigned Idx = 0;
Idx < FTy->getNumParams(); ++
Idx) {
3658 if (
Attrs.hasParamAttr(
Idx, Attribute::Nest))
3660 if (
Attrs.hasParamAttr(
Idx, Attribute::Returned))
3665 for (
unsigned Idx = FTy->getNumParams();
Idx <
Call.arg_size(); ++
Idx) {
3668 verifyParameterAttrs(ArgAttrs, Ty, &Call);
3671 Check(!SawNest,
"More than one parameter has attribute nest!", Call);
3676 Check(!SawReturned,
"More than one parameter has attribute returned!",
3679 "Incompatible argument and return types for 'returned' "
3687 if (!
Call.getCalledFunction() ||
3688 Call.getCalledFunction()->getIntrinsicID() !=
3689 Intrinsic::experimental_gc_statepoint)
3691 "Attribute 'sret' cannot be used for vararg call arguments!",
3696 "inalloca isn't on the last argument!", Call);
3702 for (
Type *ParamTy : FTy->params()) {
3703 Check(!ParamTy->isMetadataTy(),
3704 "Function has metadata parameter but isn't an intrinsic", Call);
3705 Check(!ParamTy->isTokenTy(),
3706 "Function has token parameter but isn't an intrinsic", Call);
3711 if (!
Call.getCalledFunction()) {
3712 Check(!FTy->getReturnType()->isTokenTy(),
3713 "Return type cannot be token for indirect call!");
3714 Check(!FTy->getReturnType()->isX86_AMXTy(),
3715 "Return type cannot be x86_amx for indirect call!");
3720 visitIntrinsicCall(
ID, Call);
3725 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
3726 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
3727 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
3728 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
3729 FoundAttachedCallBundle =
false;
3730 for (
unsigned i = 0, e =
Call.getNumOperandBundles(); i < e; ++i) {
3734 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles", Call);
3735 FoundDeoptBundle =
true;
3737 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
3739 FoundGCTransitionBundle =
true;
3741 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles", Call);
3742 FoundFuncletBundle =
true;
3744 "Expected exactly one funclet bundle operand", Call);
3746 "Funclet bundle operands should correspond to a FuncletPadInst",
3749 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
3751 FoundCFGuardTargetBundle =
true;
3753 "Expected exactly one cfguardtarget bundle operand", Call);
3755 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles", Call);
3756 FoundPtrauthBundle =
true;
3758 "Expected exactly two ptrauth bundle operands", Call);
3760 BU.
Inputs[0]->getType()->isIntegerTy(32),
3761 "Ptrauth bundle key operand must be an i32 constant", Call);
3763 "Ptrauth bundle discriminator operand must be an i64", Call);
3765 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles", Call);
3766 FoundKCFIBundle =
true;
3767 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
3770 BU.
Inputs[0]->getType()->isIntegerTy(32),
3771 "Kcfi bundle operand must be an i32 constant", Call);
3773 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
3775 FoundPreallocatedBundle =
true;
3777 "Expected exactly one preallocated bundle operand", Call);
3778 auto Input = dyn_cast<IntrinsicInst>(BU.
Inputs.front());
3780 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
3781 "\"preallocated\" argument must be a token from "
3782 "llvm.call.preallocated.setup",
3785 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles", Call);
3786 FoundGCLiveBundle =
true;
3788 Check(!FoundAttachedCallBundle,
3789 "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3790 FoundAttachedCallBundle =
true;
3791 verifyAttachedCallBundle(Call, BU);
3796 Check(!(
Call.getCalledFunction() && FoundPtrauthBundle),
3797 "Direct call cannot have a ptrauth bundle", Call);
3804 if (
Call.getFunction()->getSubprogram() &&
Call.getCalledFunction() &&
3805 !
Call.getCalledFunction()->isInterposable() &&
3806 !
Call.getCalledFunction()->isDeclaration() &&
3807 Call.getCalledFunction()->getSubprogram())
3809 "inlinable function call in a function with "
3810 "debug info must have a !dbg location",
3813 if (
Call.isInlineAsm())
3814 verifyInlineAsmCall(Call);
3816 ConvergenceVerifyHelper.
visit(Call);
3821void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
3824 Twine(
"inalloca attribute not allowed in ") + Context);
3826 Twine(
"inreg attribute not allowed in ") + Context);
3827 Check(!
Attrs.contains(Attribute::SwiftError),
3828 Twine(
"swifterror attribute not allowed in ") + Context);
3829 Check(!
Attrs.contains(Attribute::Preallocated),
3830 Twine(
"preallocated attribute not allowed in ") + Context);
3832 Twine(
"byref attribute not allowed in ") + Context);
3844 return PL->getAddressSpace() == PR->getAddressSpace();
3849 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
3850 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
3851 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
3854 for (
auto AK : ABIAttrs) {
3855 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
3857 Copy.addAttribute(Attr);
3861 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
3862 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
3863 Attrs.hasParamAttr(
I, Attribute::ByRef)))
3864 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
3868void Verifier::verifyMustTailCall(
CallInst &CI) {
3874 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
3875 "cannot guarantee tail call due to mismatched varargs", &CI);
3877 "cannot guarantee tail call due to mismatched return types", &CI);
3881 "cannot guarantee tail call due to mismatched calling conv", &CI);
3887 Value *RetVal = &CI;
3891 if (
BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
3893 "bitcast following musttail call must use the call", BI);
3900 Check(Ret,
"musttail call must precede a ret with an optional bitcast", &CI);
3901 Check(!
Ret->getReturnValue() ||
Ret->getReturnValue() == RetVal ||
3902 isa<UndefValue>(
Ret->getReturnValue()),
3903 "musttail call result must be returned", Ret);
3914 for (
unsigned I = 0, E = CallerTy->getNumParams();
I != E; ++
I) {
3917 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3919 for (
unsigned I = 0, E = CalleeTy->getNumParams();
I != E; ++
I) {
3922 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3925 Check(!CallerTy->isVarArg(),
Twine(
"cannot guarantee ") + CCName +
3926 " tail call for varargs function");
3934 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
3935 "cannot guarantee tail call due to mismatched parameter counts", &CI);
3936 for (
unsigned I = 0, E = CallerTy->getNumParams();
I != E; ++
I) {
3939 "cannot guarantee tail call due to mismatched parameter types", &CI);
3945 for (
unsigned I = 0, E = CallerTy->getNumParams();
I != E; ++
I) {
3948 Check(CallerABIAttrs == CalleeABIAttrs,
3949 "cannot guarantee tail call due to mismatched ABI impacting "
3950 "function attributes",
3955void Verifier::visitCallInst(
CallInst &CI) {
3959 verifyMustTailCall(CI);
3968 II.getUnwindDest()->isEHPad(),
3969 "The unwind destination does not have an exception handling instruction!",
3978 Check(
U.getType() ==
U.getOperand(0)->getType(),
3979 "Unary operators must have same type for"
3980 "operands and result!",
3983 switch (
U.getOpcode()) {
3986 case Instruction::FNeg:
3987 Check(
U.getType()->isFPOrFPVectorTy(),
3988 "FNeg operator only works with float types!", &U);
4001 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
4002 "Both operands to a binary operator are not of the same type!", &
B);
4004 switch (
B.getOpcode()) {
4007 case Instruction::Add:
4008 case Instruction::Sub:
4009 case Instruction::Mul:
4010 case Instruction::SDiv:
4011 case Instruction::UDiv:
4012 case Instruction::SRem:
4013 case Instruction::URem:
4014 Check(
B.getType()->isIntOrIntVectorTy(),
4015 "Integer arithmetic operators only work with integral types!", &
B);
4016 Check(
B.getType() ==
B.getOperand(0)->getType(),
4017 "Integer arithmetic operators must have same type "
4018 "for operands and result!",
4023 case Instruction::FAdd:
4024 case Instruction::FSub:
4025 case Instruction::FMul:
4026 case Instruction::FDiv:
4027 case Instruction::FRem:
4028 Check(
B.getType()->isFPOrFPVectorTy(),
4029 "Floating-point arithmetic operators only work with "
4030 "floating-point types!",
4032 Check(
B.getType() ==
B.getOperand(0)->getType(),
4033 "Floating-point arithmetic operators must have same type "
4034 "for operands and result!",
4038 case Instruction::And:
4039 case Instruction::Or:
4040 case Instruction::Xor:
4041 Check(
B.getType()->isIntOrIntVectorTy(),
4042 "Logical operators only work with integral types!", &
B);
4043 Check(
B.getType() ==
B.getOperand(0)->getType(),
4044 "Logical operators must have same type for operands and result!", &
B);
4046 case Instruction::Shl:
4047 case Instruction::LShr:
4048 case Instruction::AShr:
4049 Check(
B.getType()->isIntOrIntVectorTy(),
4050 "Shifts only work with integral types!", &
B);
4051 Check(
B.getType() ==
B.getOperand(0)->getType(),
4052 "Shift return type must be same as operands!", &
B);
4061void Verifier::visitICmpInst(
ICmpInst &IC) {
4065 Check(Op0Ty == Op1Ty,
4066 "Both operands to ICmp instruction are not of the same type!", &IC);
4069 "Invalid operand types for ICmp instruction", &IC);
4076void Verifier::visitFCmpInst(
FCmpInst &FC) {
4078 Type *Op0Ty =
FC.getOperand(0)->getType();
4079 Type *Op1Ty =
FC.getOperand(1)->getType();
4080 Check(Op0Ty == Op1Ty,
4081 "Both operands to FCmp instruction are not of the same type!", &FC);
4086 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
4093 "Invalid extractelement operands!", &EI);
4100 "Invalid insertelement operands!", &IE);
4107 "Invalid shufflevector operands!", &SV);
4112 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4114 Check(isa<PointerType>(TargetTy),
4115 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4116 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4118 if (
auto *STy = dyn_cast<StructType>(
GEP.getSourceElementType())) {
4120 "getelementptr cannot target structure that contains scalable vector"
4127 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
4128 "GEP indexes must be integers", &
GEP);
4131 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4133 PointerType *PtrTy = dyn_cast<PointerType>(
GEP.getType()->getScalarType());
4135 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4136 "GEP is not of right type for indices!", &
GEP, ElTy);
4138 if (
auto *GEPVTy = dyn_cast<VectorType>(
GEP.getType())) {
4141 if (
GEP.getPointerOperandType()->isVectorTy())
4144 cast<VectorType>(
GEP.getPointerOperandType())->getElementCount(),
4145 "Vector GEP result width doesn't match operand's", &
GEP);
4147 Type *IndexTy =
Idx->getType();
4148 if (
auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
4150 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4153 "All GEP indices should be of integer type");
4157 Check(
GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4158 "GEP address space doesn't match type", &
GEP);
4164 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4170 Type *Ty, RangeLikeMetadataKind Kind) {
4171 unsigned NumOperands =
Range->getNumOperands();
4172 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4173 unsigned NumRanges = NumOperands / 2;
4174 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4177 for (
unsigned i = 0; i < NumRanges; ++i) {
4179 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(2 * i));
4180 Check(
Low,
"The lower limit must be an integer!",
Low);
4182 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(2 * i + 1));
4185 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4188 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4190 "noalias.addrspace type must be i32!", &
I);
4193 "Range types must match instruction type!", &
I);
4202 "The upper and lower limits cannot be the same value", &
I);
4205 Check(!CurRange.isEmptySet() &&
4206 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4207 !CurRange.isFullSet()),
4208 "Range must not be empty!",
Range);
4210 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4211 "Intervals are overlapping",
Range);
4212 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
4219 if (NumRanges > 2) {
4221 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(0))->getValue();
4223 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(1))->getValue();
4225 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4226 "Intervals are overlapping",
Range);
4234 "precondition violation");
4235 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
4241 "precondition violation");
4242 verifyRangeLikeMetadata(
I,
Range, Ty,
4243 RangeLikeMetadataKind::NoaliasAddrspace);
4247 unsigned Size =
DL.getTypeSizeInBits(Ty);
4248 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
4250 "atomic memory access' operand must have a power-of-two size", Ty,
I);
4253void Verifier::visitLoadInst(
LoadInst &LI) {
4255 Check(PTy,
"Load operand must be a pointer.", &LI);
4259 "huge alignment values are unsupported", &LI);
4261 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4265 "Load cannot have Release ordering", &LI);
4267 "atomic load operand must have integer, pointer, or floating point "
4270 checkAtomicMemAccessSize(ElTy, &LI);
4273 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4279void Verifier::visitStoreInst(
StoreInst &SI) {
4280 PointerType *PTy = dyn_cast<PointerType>(
SI.getOperand(1)->getType());
4281 Check(PTy,
"Store operand must be a pointer.", &SI);
4282 Type *ElTy =
SI.getOperand(0)->getType();
4285 "huge alignment values are unsupported", &SI);
4287 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4288 if (
SI.isAtomic()) {
4291 "Store cannot have Acquire ordering", &SI);
4293 "atomic store operand must have integer, pointer, or floating point "
4296 checkAtomicMemAccessSize(ElTy, &SI);
4299 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4305void Verifier::verifySwiftErrorCall(
CallBase &Call,
4306 const Value *SwiftErrorVal) {
4308 if (
I.value() == SwiftErrorVal) {
4309 Check(
Call.paramHasAttr(
I.index(), Attribute::SwiftError),
4310 "swifterror value when used in a callsite should be marked "
4311 "with swifterror attribute",
4312 SwiftErrorVal, Call);
4317void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4320 for (
const User *U : SwiftErrorVal->
users()) {
4321 Check(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
4323 "swifterror value can only be loaded and stored from, or "
4324 "as a swifterror argument!",
4327 if (
auto StoreI = dyn_cast<StoreInst>(U))
4328 Check(StoreI->getOperand(1) == SwiftErrorVal,
4329 "swifterror value should be the second operand when used "
4332 if (
auto *Call = dyn_cast<CallBase>(U))
4333 verifySwiftErrorCall(*
const_cast<CallBase *
>(Call), SwiftErrorVal);
4337void Verifier::visitAllocaInst(
AllocaInst &AI) {
4340 Check(Ty->
isSized(&Visited),
"Cannot allocate unsized type", &AI);
4344 "Alloca has illegal target extension type", &AI);
4346 "Alloca array size must have integer type", &AI);
4349 "huge alignment values are unsupported", &AI);
4355 "swifterror alloca must not be array allocation", &AI);
4356 verifySwiftErrorValue(&AI);
4365 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4366 checkAtomicMemAccessSize(ElTy, &CXI);
4372 "atomicrmw instructions cannot be unordered.", &RMWI);
4379 " operand must have integer or floating point type!",
4384 " operand must have floating-point or fixed vector of floating-point "
4390 " operand must have integer type!",
4393 checkAtomicMemAccessSize(ElTy, &RMWI);
4395 "Invalid binary operation!", &RMWI);
4399void Verifier::visitFenceInst(
FenceInst &FI) {
4405 "fence instructions may only have acquire, release, acq_rel, or "
4406 "seq_cst ordering.",
4414 "Invalid ExtractValueInst operands!", &EVI);
4423 "Invalid InsertValueInst operands!", &IVI);
4429 if (
auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
4430 return FPI->getParentPad();
4432 return cast<CatchSwitchInst>(EHPad)->getParentPad();
4441 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
4443 if (
auto *LPI = dyn_cast<LandingPadInst>(&
I)) {
4448 const auto *
II = dyn_cast<InvokeInst>(PredBB->getTerminator());
4449 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4450 "Block containing LandingPadInst must be jumped to "
4451 "only by the unwind edge of an invoke.",
4456 if (
auto *CPI = dyn_cast<CatchPadInst>(&
I)) {
4459 "Block containg CatchPadInst must be jumped to "
4460 "only by its catchswitch.",
4462 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4463 "Catchswitch cannot unwind to one of its catchpads",
4464 CPI->getCatchSwitch(), CPI);
4475 if (
auto *
II = dyn_cast<InvokeInst>(TI)) {
4476 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4477 "EH pad must be jumped to via an unwind edge", ToPad,
II);
4479 dyn_cast<Function>(
II->getCalledOperand()->stripPointerCasts());
4480 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
4484 FromPad = Bundle->Inputs[0];
4487 }
else if (
auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
4488 FromPad = CRI->getOperand(0);
4489 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
4490 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4493 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
4499 Check(FromPad != ToPad,
4500 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4501 if (FromPad == ToPadParent) {
4505 Check(!isa<ConstantTokenNone>(FromPad),
4506 "A single unwind edge may only enter one EH pad", TI);
4507 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
4512 Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
4513 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4522 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4524 visitEHPadPredecessors(LPI);
4526 if (!LandingPadResultTy)
4527 LandingPadResultTy = LPI.
getType();
4530 "The landingpad instruction should have a consistent result type "
4531 "inside a function.",
4535 Check(
F->hasPersonalityFn(),
4536 "LandingPadInst needs to be in a function with a personality.", &LPI);
4541 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4547 "Catch operand does not have pointer type!", &LPI);
4549 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
4551 "Filter operand is not an array of constants!", &LPI);
4558void Verifier::visitResumeInst(
ResumeInst &RI) {
4560 "ResumeInst needs to be in a function with a personality.", &RI);
4562 if (!LandingPadResultTy)
4566 "The resume instruction should have a consistent result type "
4567 "inside a function.",
4577 Check(
F->hasPersonalityFn(),
4578 "CatchPadInst needs to be in a function with a personality.", &CPI);
4581 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4587 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4589 visitEHPadPredecessors(CPI);
4595 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,