96#include "llvm/IR/IntrinsicsAArch64.h"
97#include "llvm/IR/IntrinsicsAMDGPU.h"
98#include "llvm/IR/IntrinsicsARM.h"
99#include "llvm/IR/IntrinsicsWebAssembly.h"
130 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
131 "scopes are not dominating"));
159 void Write(
const Value *V) {
164 void Write(
const Value &V) {
165 if (isa<Instruction>(V)) {
169 V.printAsOperand(*
OS,
true,
MST);
192 void Write(
Type *
T) {
204 void Write(
const APInt *AI) {
210 void Write(
const unsigned i) { *
OS << i <<
'\n'; }
216 *
OS <<
A->getAsString() <<
'\n';
236 for (
const T &V : Vs)
240 template <
typename T1,
typename... Ts>
241 void WriteTs(
const T1 &V1,
const Ts &... Vs) {
246 template <
typename... Ts>
void WriteTs() {}
255 *
OS << Message <<
'\n';
263 template <
typename T1,
typename... Ts>
273 *
OS << Message <<
'\n';
279 template <
typename T1,
typename... Ts>
300 static constexpr unsigned ParamMaxAlignment = 1 << 14;
320 Type *LandingPadResultTy;
327 bool HasDebugInfo =
false;
376 SawFrameEscape(
false), TBAAVerifyHelper(this) {
377 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
384 "An instance of this class only works with a specific module!");
396 if (!BB.empty() && BB.back().isTerminator())
400 *
OS <<
"Basic Block in function '" <<
F.getName()
401 <<
"' does not have terminator!\n";
402 BB.printAsOperand(*
OS,
true, MST);
408 auto FailureCB = [
this](
const Twine &Message) {
416 verifySiblingFuncletUnwinds();
419 ConvergenceVerifyHelper.
verify(DT);
421 InstsInThisBlock.
clear();
423 LandingPadResultTy =
nullptr;
424 SawFrameEscape =
false;
425 SiblingFuncletInfo.
clear();
426 verifyNoAliasScopeDecl();
427 NoAliasScopeDecls.
clear();
438 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
443 verifyFrameRecoverIndices();
445 visitGlobalVariable(GV);
448 visitGlobalAlias(GA);
451 visitGlobalIFunc(GI);
454 visitNamedMDNode(NMD);
457 visitComdat(SMEC.getValue());
461 visitModuleCommandLines();
463 verifyCompileUnits();
465 verifyDeoptimizeCallingConvs();
466 DISubprogramAttachments.
clear();
472 enum class AreDebugLocsAllowed {
No,
Yes };
483 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
486 void visitComdat(
const Comdat &
C);
487 void visitModuleIdents();
488 void visitModuleCommandLines();
489 void visitModuleFlags();
490 void visitModuleFlag(
const MDNode *
Op,
493 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
496 void verifyRangeMetadata(
const Value &V,
const MDNode *Range,
Type *Ty,
497 bool IsAbsoluteSymbol);
501 void visitCallStackMetadata(
MDNode *MD);
505 void visitAnnotationMetadata(
MDNode *Annotation);
506 void visitAliasScopeMetadata(
const MDNode *MD);
507 void visitAliasScopeListMetadata(
const MDNode *MD);
508 void visitAccessGroupMetadata(
const MDNode *MD);
510 template <
class Ty>
bool isValidMetadataArray(
const MDTuple &
N);
511#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
512#include "llvm/IR/Metadata.def"
513 void visitDIScope(
const DIScope &
N);
537 void visitPHINode(
PHINode &PN);
546 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
584 void verifySwiftErrorCall(
CallBase &Call,
const Value *SwiftErrorVal);
585 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
587 void verifyMustTailCall(
CallInst &CI);
588 bool verifyAttributeCount(
AttributeList Attrs,
unsigned Params);
594 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
595 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
597 void visitConstantExprsRecursively(
const Constant *EntryC);
599 void verifyInlineAsmCall(
const CallBase &Call);
600 void verifyStatepoint(
const CallBase &Call);
601 void verifyFrameRecoverIndices();
602 void verifySiblingFuncletUnwinds();
605 template <
typename ValueOrMetadata>
606 void verifyFragmentExpression(
const DIVariable &V,
608 ValueOrMetadata *
Desc);
613 void verifyCompileUnits();
617 void verifyDeoptimizeCallingConvs();
619 void verifyAttachedCallBundle(
const CallBase &Call,
626 void verifyNoAliasScopeDecl();
632#define Check(C, ...) \
635 CheckFailed(__VA_ARGS__); \
642#define CheckDI(C, ...) \
645 DebugInfoCheckFailed(__VA_ARGS__); \
651 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
652 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
665 while (!WorkList.
empty()) {
667 if (!Visited.
insert(Cur).second)
674void Verifier::visitGlobalValue(
const GlobalValue &GV) {
676 "Global is external, but doesn't have external or weak linkage!", &GV);
678 if (
const GlobalObject *GO = dyn_cast<GlobalObject>(&GV)) {
682 "huge alignment values are unsupported", GO);
685 if (
const MDNode *Associated =
686 GO->getMetadata(LLVMContext::MD_associated)) {
687 Check(Associated->getNumOperands() == 1,
688 "associated metadata must have one operand", &GV, Associated);
689 const Metadata *
Op = Associated->getOperand(0).get();
690 Check(
Op,
"associated metadata must have a global value", GO, Associated);
692 const auto *VM = dyn_cast_or_null<ValueAsMetadata>(
Op);
693 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
695 Check(isa<PointerType>(VM->getValue()->getType()),
696 "associated value must be pointer typed", GV, Associated);
699 Check(isa<GlobalObject>(Stripped) || isa<Constant>(Stripped),
700 "associated metadata must point to a GlobalObject", GO, Stripped);
701 Check(Stripped != GO,
702 "global values should not associate to themselves", GO,
708 if (
const MDNode *AbsoluteSymbol =
709 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
710 verifyRangeMetadata(*GO, AbsoluteSymbol,
DL.getIntPtrType(GO->getType()),
716 "Only global variables can have appending linkage!", &GV);
721 "Only global arrays can have appending linkage!", GVar);
725 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
729 "dllexport GlobalValue must have default or protected visibility",
734 "dllimport GlobalValue must have default visibility", &GV);
735 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
741 "Global is marked as dllimport, but not external", &GV);
746 "GlobalValue with local linkage or non-default "
747 "visibility must be dso_local!",
752 if (!
I->getParent() || !
I->getParent()->getParent())
753 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
755 else if (
I->getParent()->getParent()->getParent() != &M)
756 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
757 I->getParent()->getParent(),
758 I->getParent()->getParent()->getParent());
760 }
else if (
const Function *
F = dyn_cast<Function>(V)) {
761 if (
F->getParent() != &M)
762 CheckFailed(
"Global is used by function in a different module", &GV, &M,
773 "Global variable initializer type does not match global "
780 "'common' global must have a zero initializer!", &GV);
783 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
788 GV.
getName() ==
"llvm.global_dtors")) {
790 "invalid linkage for intrinsic global variable", &GV);
792 "invalid uses of intrinsic global variable", &GV);
797 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
803 "wrong type for intrinsic global variable", &GV);
805 "the third field of the element type is mandatory, "
806 "specify ptr null to migrate from the obsoleted 2-field form");
814 GV.
getName() ==
"llvm.compiler.used")) {
816 "invalid linkage for intrinsic global variable", &GV);
818 "invalid uses of intrinsic global variable", &GV);
821 if (
ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
822 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
823 Check(PTy,
"wrong type for intrinsic global variable", &GV);
827 Check(InitArray,
"wrong initalizer for intrinsic global variable",
831 Check(isa<GlobalVariable>(V) || isa<Function>(V) ||
835 Twine(
"members of ") + GV.
getName() +
" must be named", V);
844 for (
auto *MD : MDs) {
845 if (
auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
846 visitDIGlobalVariableExpression(*GVE);
848 CheckDI(
false,
"!dbg attachment of global variable must be a "
849 "DIGlobalVariableExpression");
855 "Globals cannot contain scalable types", &GV);
859 if (
auto *TTy = dyn_cast<TargetExtType>(GV.
getValueType()))
861 "Global @" + GV.
getName() +
" has illegal target extension type",
865 visitGlobalValue(GV);
872 visitGlobalValue(GV);
878 visitAliaseeSubExpr(Visited, GA,
C);
884 Check(isa<GlobalValue>(
C) &&
885 cast<GlobalValue>(
C).hasAvailableExternallyLinkage(),
886 "available_externally alias must point to available_externally "
890 if (
const auto *GV = dyn_cast<GlobalValue>(&
C)) {
896 if (
const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
897 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
899 Check(!GA2->isInterposable(),
900 "Alias cannot point to an interposable alias", &GA);
908 if (
const auto *CE = dyn_cast<ConstantExpr>(&
C))
909 visitConstantExprsRecursively(CE);
911 for (
const Use &U :
C.operands()) {
913 if (
const auto *GA2 = dyn_cast<GlobalAlias>(V))
914 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
915 else if (
const auto *C2 = dyn_cast<Constant>(V))
916 visitAliaseeSubExpr(Visited, GA, *C2);
920void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
922 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
923 "weak_odr, external, or available_externally linkage!",
926 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
928 "Alias and aliasee types should match!", &GA);
930 Check(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
931 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
933 visitAliaseeSubExpr(GA, *Aliasee);
935 visitGlobalValue(GA);
938void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
940 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
941 "weak_odr, or external linkage!",
948 "IFunc resolver must be a definition", &GI);
954 Check(isa<PointerType>(
Resolver->getFunctionType()->getReturnType()),
955 "IFunc resolver must return a pointer", &GI);
957 const Type *ResolverFuncTy =
960 "IFunc resolver has incorrect type", &GI);
963void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
968 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
970 if (NMD.
getName() ==
"llvm.dbg.cu")
971 CheckDI(MD && isa<DICompileUnit>(MD),
"invalid compile unit", &NMD, MD);
976 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
980void Verifier::visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
983 if (!MDNodes.
insert(&MD).second)
987 "MDNode context does not match Module context!", &MD);
992 case Metadata::MDTupleKind:
994#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
995 case Metadata::CLASS##Kind: \
996 visit##CLASS(cast<CLASS>(MD)); \
998#include "llvm/IR/Metadata.def"
1004 Check(!isa<LocalAsMetadata>(
Op),
"Invalid operand for global metadata!",
1006 CheckDI(!isa<DILocation>(
Op) || AllowLocs == AreDebugLocsAllowed::Yes,
1007 "DILocation not allowed within this metadata node", &MD,
Op);
1008 if (
auto *
N = dyn_cast<MDNode>(
Op)) {
1009 visitMDNode(*
N, AllowLocs);
1012 if (
auto *V = dyn_cast<ValueAsMetadata>(
Op)) {
1013 visitValueAsMetadata(*V,
nullptr);
1026 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1028 auto *
L = dyn_cast<LocalAsMetadata>(&MD);
1032 Check(
F,
"function-local metadata used outside a function", L);
1037 if (
Instruction *
I = dyn_cast<Instruction>(
L->getValue())) {
1038 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1039 ActualF =
I->getParent()->getParent();
1040 }
else if (
BasicBlock *BB = dyn_cast<BasicBlock>(
L->getValue()))
1042 else if (
Argument *
A = dyn_cast<Argument>(
L->getValue()))
1043 ActualF =
A->getParent();
1044 assert(ActualF &&
"Unimplemented function local metadata case!");
1046 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1051 if (
auto *
N = dyn_cast<MDNode>(MD)) {
1052 visitMDNode(*
N, AreDebugLocsAllowed::No);
1058 if (!MDNodes.
insert(MD).second)
1061 if (
auto *V = dyn_cast<ValueAsMetadata>(MD))
1062 visitValueAsMetadata(*V,
F);
1069void Verifier::visitDILocation(
const DILocation &
N) {
1070 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1071 "location requires a valid scope", &
N,
N.getRawScope());
1072 if (
auto *IA =
N.getRawInlinedAt())
1073 CheckDI(isa<DILocation>(IA),
"inlined-at should be a location", &
N, IA);
1074 if (
auto *SP = dyn_cast<DISubprogram>(
N.getRawScope()))
1075 CheckDI(SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1082void Verifier::visitDIScope(
const DIScope &
N) {
1083 if (
auto *
F =
N.getRawFile())
1084 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1087void Verifier::visitDISubrange(
const DISubrange &
N) {
1088 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1090 CheckDI(HasAssumedSizedArraySupport ||
N.getRawCountNode() ||
1091 N.getRawUpperBound(),
1092 "Subrange must contain count or upperBound", &
N);
1093 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1094 "Subrange can have any one of count or upperBound", &
N);
1095 auto *CBound =
N.getRawCountNode();
1096 CheckDI(!CBound || isa<ConstantAsMetadata>(CBound) ||
1097 isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1098 "Count must be signed constant or DIVariable or DIExpression", &
N);
1099 auto Count =
N.getCount();
1100 CheckDI(!Count || !isa<ConstantInt *>(Count) ||
1101 cast<ConstantInt *>(Count)->getSExtValue() >= -1,
1102 "invalid subrange count", &
N);
1103 auto *LBound =
N.getRawLowerBound();
1104 CheckDI(!LBound || isa<ConstantAsMetadata>(LBound) ||
1105 isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1106 "LowerBound must be signed constant or DIVariable or DIExpression",
1108 auto *UBound =
N.getRawUpperBound();
1109 CheckDI(!UBound || isa<ConstantAsMetadata>(UBound) ||
1110 isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1111 "UpperBound must be signed constant or DIVariable or DIExpression",
1113 auto *Stride =
N.getRawStride();
1114 CheckDI(!Stride || isa<ConstantAsMetadata>(Stride) ||
1115 isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1116 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1120 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1121 CheckDI(
N.getRawCountNode() ||
N.getRawUpperBound(),
1122 "GenericSubrange must contain count or upperBound", &
N);
1123 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1124 "GenericSubrange can have any one of count or upperBound", &
N);
1125 auto *CBound =
N.getRawCountNode();
1126 CheckDI(!CBound || isa<DIVariable>(CBound) || isa<DIExpression>(CBound),
1127 "Count must be signed constant or DIVariable or DIExpression", &
N);
1128 auto *LBound =
N.getRawLowerBound();
1129 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1130 CheckDI(isa<DIVariable>(LBound) || isa<DIExpression>(LBound),
1131 "LowerBound must be signed constant or DIVariable or DIExpression",
1133 auto *UBound =
N.getRawUpperBound();
1134 CheckDI(!UBound || isa<DIVariable>(UBound) || isa<DIExpression>(UBound),
1135 "UpperBound must be signed constant or DIVariable or DIExpression",
1137 auto *Stride =
N.getRawStride();
1138 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1139 CheckDI(isa<DIVariable>(Stride) || isa<DIExpression>(Stride),
1140 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1144 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1148 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1149 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1150 N.getTag() == dwarf::DW_TAG_string_type,
1155 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1156 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1164 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1165 N.getTag() == dwarf::DW_TAG_pointer_type ||
1166 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1167 N.getTag() == dwarf::DW_TAG_reference_type ||
1168 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1169 N.getTag() == dwarf::DW_TAG_const_type ||
1170 N.getTag() == dwarf::DW_TAG_immutable_type ||
1171 N.getTag() == dwarf::DW_TAG_volatile_type ||
1172 N.getTag() == dwarf::DW_TAG_restrict_type ||
1173 N.getTag() == dwarf::DW_TAG_atomic_type ||
1174 N.getTag() == dwarf::DW_TAG_member ||
1175 N.getTag() == dwarf::DW_TAG_inheritance ||
1176 N.getTag() == dwarf::DW_TAG_friend ||
1177 N.getTag() == dwarf::DW_TAG_set_type,
1179 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1180 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1181 N.getRawExtraData());
1184 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1185 if (
auto *
T =
N.getRawBaseType()) {
1186 auto *
Enum = dyn_cast_or_null<DICompositeType>(
T);
1187 auto *
Basic = dyn_cast_or_null<DIBasicType>(
T);
1189 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1190 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1191 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1192 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1193 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1194 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1195 "invalid set base type", &
N,
T);
1201 N.getRawBaseType());
1203 if (
N.getDWARFAddressSpace()) {
1204 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1205 N.getTag() == dwarf::DW_TAG_reference_type ||
1206 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1207 "DWARF address space only applies to pointer or reference types",
1214 return ((Flags & DINode::FlagLValueReference) &&
1215 (Flags & DINode::FlagRValueReference)) ||
1216 ((Flags & DINode::FlagTypePassByValue) &&
1217 (Flags & DINode::FlagTypePassByReference));
1220void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1221 auto *Params = dyn_cast<MDTuple>(&RawParams);
1222 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1224 CheckDI(
Op && isa<DITemplateParameter>(
Op),
"invalid template parameter",
1233 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1234 N.getTag() == dwarf::DW_TAG_structure_type ||
1235 N.getTag() == dwarf::DW_TAG_union_type ||
1236 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1237 N.getTag() == dwarf::DW_TAG_class_type ||
1238 N.getTag() == dwarf::DW_TAG_variant_part ||
1239 N.getTag() == dwarf::DW_TAG_namelist,
1244 N.getRawBaseType());
1246 CheckDI(!
N.getRawElements() || isa<MDTuple>(
N.getRawElements()),
1247 "invalid composite elements", &
N,
N.getRawElements());
1249 N.getRawVTableHolder());
1251 "invalid reference flags", &
N);
1252 unsigned DIBlockByRefStruct = 1 << 4;
1253 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1254 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1257 const DINodeArray
Elements =
N.getElements();
1259 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1260 "invalid vector, expected one element of type subrange", &
N);
1263 if (
auto *Params =
N.getRawTemplateParams())
1264 visitTemplateParams(
N, *Params);
1266 if (
auto *
D =
N.getRawDiscriminator()) {
1267 CheckDI(isa<DIDerivedType>(
D) &&
N.getTag() == dwarf::DW_TAG_variant_part,
1268 "discriminator can only appear on variant part");
1271 if (
N.getRawDataLocation()) {
1272 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1273 "dataLocation can only appear in array type");
1276 if (
N.getRawAssociated()) {
1277 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1278 "associated can only appear in array type");
1281 if (
N.getRawAllocated()) {
1282 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1283 "allocated can only appear in array type");
1286 if (
N.getRawRank()) {
1287 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1288 "rank can only appear in array type");
1293 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1294 if (
auto *Types =
N.getRawTypeArray()) {
1295 CheckDI(isa<MDTuple>(Types),
"invalid composite elements", &
N, Types);
1296 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1297 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1301 "invalid reference flags", &
N);
1304void Verifier::visitDIFile(
const DIFile &
N) {
1305 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1306 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1309 "invalid checksum kind", &
N);
1311 switch (Checksum->Kind) {
1322 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1324 "invalid checksum", &
N);
1329 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1330 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1334 CheckDI(
N.getRawFile() && isa<DIFile>(
N.getRawFile()),
"invalid file", &
N,
1336 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1341 verifySourceDebugInfo(
N, *
N.getFile());
1344 "invalid emission kind", &
N);
1346 if (
auto *Array =
N.getRawEnumTypes()) {
1347 CheckDI(isa<MDTuple>(Array),
"invalid enum list", &
N, Array);
1348 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1349 auto *
Enum = dyn_cast_or_null<DICompositeType>(
Op);
1350 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1351 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1354 if (
auto *Array =
N.getRawRetainedTypes()) {
1355 CheckDI(isa<MDTuple>(Array),
"invalid retained type list", &
N, Array);
1356 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1358 Op && (isa<DIType>(
Op) || (isa<DISubprogram>(
Op) &&
1359 !cast<DISubprogram>(
Op)->isDefinition())),
1360 "invalid retained type", &
N,
Op);
1363 if (
auto *Array =
N.getRawGlobalVariables()) {
1364 CheckDI(isa<MDTuple>(Array),
"invalid global variable list", &
N, Array);
1365 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1366 CheckDI(
Op && (isa<DIGlobalVariableExpression>(
Op)),
1367 "invalid global variable ref", &
N,
Op);
1370 if (
auto *Array =
N.getRawImportedEntities()) {
1371 CheckDI(isa<MDTuple>(Array),
"invalid imported entity list", &
N, Array);
1372 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1373 CheckDI(
Op && isa<DIImportedEntity>(
Op),
"invalid imported entity ref",
1377 if (
auto *Array =
N.getRawMacros()) {
1378 CheckDI(isa<MDTuple>(Array),
"invalid macro list", &
N, Array);
1380 CheckDI(
Op && isa<DIMacroNode>(
Op),
"invalid macro ref", &
N,
Op);
1387 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1389 if (
auto *
F =
N.getRawFile())
1390 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1392 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1393 if (
auto *
T =
N.getRawType())
1394 CheckDI(isa<DISubroutineType>(
T),
"invalid subroutine type", &
N,
T);
1395 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1396 N.getRawContainingType());
1397 if (
auto *Params =
N.getRawTemplateParams())
1398 visitTemplateParams(
N, *Params);
1399 if (
auto *S =
N.getRawDeclaration())
1400 CheckDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1401 "invalid subprogram declaration", &
N, S);
1402 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1403 auto *
Node = dyn_cast<MDTuple>(RawNode);
1404 CheckDI(
Node,
"invalid retained nodes list", &
N, RawNode);
1406 CheckDI(
Op && (isa<DILocalVariable>(
Op) || isa<DILabel>(
Op) ||
1407 isa<DIImportedEntity>(
Op)),
1408 "invalid retained nodes, expected DILocalVariable, DILabel or "
1414 "invalid reference flags", &
N);
1416 auto *Unit =
N.getRawUnit();
1417 if (
N.isDefinition()) {
1419 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1420 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1421 CheckDI(isa<DICompileUnit>(Unit),
"invalid unit type", &
N, Unit);
1424 auto *CT = dyn_cast_or_null<DICompositeType>(
N.getRawScope());
1425 if (CT && CT->getRawIdentifier() &&
1426 M.getContext().isODRUniquingDebugTypes())
1428 "definition subprograms cannot be nested within DICompositeType "
1429 "when enabling ODR",
1432 verifySourceDebugInfo(*
N.getUnit(), *
N.getFile());
1435 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1437 "subprogram declaration must not have a declaration field");
1440 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1441 auto *ThrownTypes = dyn_cast<MDTuple>(RawThrownTypes);
1442 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1444 CheckDI(
Op && isa<DIType>(
Op),
"invalid thrown type", &
N, ThrownTypes,
1448 if (
N.areAllCallsDescribed())
1450 "DIFlagAllCallsDescribed must be attached to a definition");
1454 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1455 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1456 "invalid local scope", &
N,
N.getRawScope());
1457 if (
auto *SP = dyn_cast<DISubprogram>(
N.getRawScope()))
1458 CheckDI(SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1462 visitDILexicalBlockBase(
N);
1465 "cannot have column info without line info", &
N);
1469 visitDILexicalBlockBase(
N);
1473 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1474 if (
auto *S =
N.getRawScope())
1475 CheckDI(isa<DIScope>(S),
"invalid scope ref", &
N, S);
1476 if (
auto *S =
N.getRawDecl())
1477 CheckDI(isa<DIGlobalVariable>(S),
"invalid declaration", &
N, S);
1481 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1482 if (
auto *S =
N.getRawScope())
1483 CheckDI(isa<DIScope>(S),
"invalid scope ref", &
N, S);
1486void Verifier::visitDIMacro(
const DIMacro &
N) {
1489 "invalid macinfo type", &
N);
1490 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1491 if (!
N.getValue().empty()) {
1492 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1498 "invalid macinfo type", &
N);
1499 if (
auto *
F =
N.getRawFile())
1500 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1502 if (
auto *Array =
N.getRawElements()) {
1503 CheckDI(isa<MDTuple>(Array),
"invalid macro list", &
N, Array);
1504 for (
Metadata *
Op :
N.getElements()->operands()) {
1505 CheckDI(
Op && isa<DIMacroNode>(
Op),
"invalid macro ref", &
N,
Op);
1510void Verifier::visitDIArgList(
const DIArgList &
N) {
1512 "DIArgList should have no operands other than a list of "
1517void Verifier::visitDIModule(
const DIModule &
N) {
1518 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1519 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1527 visitDITemplateParameter(
N);
1529 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1533void Verifier::visitDITemplateValueParameter(
1535 visitDITemplateParameter(
N);
1537 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1538 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1539 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1543void Verifier::visitDIVariable(
const DIVariable &
N) {
1544 if (
auto *S =
N.getRawScope())
1545 CheckDI(isa<DIScope>(S),
"invalid scope", &
N, S);
1546 if (
auto *
F =
N.getRawFile())
1547 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1554 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1557 if (
N.isDefinition())
1558 CheckDI(
N.getType(),
"missing global variable type", &
N);
1559 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1560 CheckDI(isa<DIDerivedType>(Member),
1561 "invalid static data member declaration", &
N, Member);
1570 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1571 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1572 "local variable requires a valid scope", &
N,
N.getRawScope());
1573 if (
auto Ty =
N.getType())
1574 CheckDI(!isa<DISubroutineType>(Ty),
"invalid type", &
N,
N.getType());
1577void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1578 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1579 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1582void Verifier::visitDILabel(
const DILabel &
N) {
1583 if (
auto *S =
N.getRawScope())
1584 CheckDI(isa<DIScope>(S),
"invalid scope", &
N, S);
1585 if (
auto *
F =
N.getRawFile())
1586 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1588 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1589 CheckDI(
N.getRawScope() && isa<DILocalScope>(
N.getRawScope()),
1590 "label requires a valid scope", &
N,
N.getRawScope());
1594 CheckDI(
N.isValid(),
"invalid expression", &
N);
1597void Verifier::visitDIGlobalVariableExpression(
1601 visitDIGlobalVariable(*Var);
1603 visitDIExpression(*Expr);
1604 if (
auto Fragment = Expr->getFragmentInfo())
1605 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1610 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1611 if (
auto *
T =
N.getRawType())
1613 if (
auto *
F =
N.getRawFile())
1614 CheckDI(isa<DIFile>(
F),
"invalid file", &
N,
F);
1618 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1619 N.getTag() == dwarf::DW_TAG_imported_declaration,
1621 if (
auto *S =
N.getRawScope())
1622 CheckDI(isa<DIScope>(S),
"invalid scope for imported entity", &
N, S);
1627void Verifier::visitComdat(
const Comdat &
C) {
1630 if (
TT.isOSBinFormatCOFF())
1636void Verifier::visitModuleIdents() {
1637 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1644 Check(
N->getNumOperands() == 1,
1645 "incorrect number of operands in llvm.ident metadata",
N);
1646 Check(dyn_cast_or_null<MDString>(
N->getOperand(0)),
1647 (
"invalid value for llvm.ident metadata entry operand"
1648 "(the operand should be a string)"),
1653void Verifier::visitModuleCommandLines() {
1654 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1662 Check(
N->getNumOperands() == 1,
1663 "incorrect number of operands in llvm.commandline metadata",
N);
1664 Check(dyn_cast_or_null<MDString>(
N->getOperand(0)),
1665 (
"invalid value for llvm.commandline metadata entry operand"
1666 "(the operand should be a string)"),
1671void Verifier::visitModuleFlags() {
1679 visitModuleFlag(MDN, SeenIDs, Requirements);
1682 for (
const MDNode *Requirement : Requirements) {
1683 const MDString *
Flag = cast<MDString>(Requirement->getOperand(0));
1684 const Metadata *ReqValue = Requirement->getOperand(1);
1688 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1693 if (
Op->getOperand(2) != ReqValue) {
1694 CheckFailed((
"invalid requirement on flag, "
1695 "flag does not have the required value"),
1703Verifier::visitModuleFlag(
const MDNode *
Op,
1709 "incorrect number of operands in module flag",
Op);
1712 Check(mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(0)),
1713 "invalid behavior operand in module flag (expected constant integer)",
1716 "invalid behavior operand in module flag (unexpected constant)",
1719 MDString *
ID = dyn_cast_or_null<MDString>(
Op->getOperand(1));
1720 Check(
ID,
"invalid ID operand in module flag (expected metadata string)",
1732 auto *
V = mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2));
1733 Check(V &&
V->getValue().isNonNegative(),
1734 "invalid value for 'min' module flag (expected constant non-negative "
1741 Check(mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2)),
1742 "invalid value for 'max' module flag (expected constant integer)",
1752 "invalid value for 'require' module flag (expected metadata pair)",
1755 (
"invalid value for 'require' module flag "
1756 "(first value operand should be a string)"),
1757 Value->getOperand(0));
1768 Check(isa<MDNode>(
Op->getOperand(2)),
1769 "invalid value for 'append'-type module flag "
1770 "(expected a metadata node)",
1780 "module flag identifiers must be unique (or of 'require' type)",
ID);
1783 if (
ID->getString() ==
"wchar_size") {
1785 = mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2));
1786 Check(
Value,
"wchar_size metadata requires constant integer argument");
1789 if (
ID->getString() ==
"Linker Options") {
1793 Check(
M.getNamedMetadata(
"llvm.linker.options"),
1794 "'Linker Options' named metadata no longer supported");
1797 if (
ID->getString() ==
"SemanticInterposition") {
1799 mdconst::dyn_extract_or_null<ConstantInt>(
Op->getOperand(2));
1801 "SemanticInterposition metadata requires constant integer argument");
1804 if (
ID->getString() ==
"CG Profile") {
1805 for (
const MDOperand &MDO : cast<MDNode>(
Op->getOperand(2))->operands())
1806 visitModuleFlagCGProfileEntry(MDO);
1810void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
1811 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
1814 auto F = dyn_cast<ValueAsMetadata>(FuncMDO);
1815 Check(
F && isa<Function>(
F->getValue()->stripPointerCasts()),
1816 "expected a Function or null", FuncMDO);
1818 auto Node = dyn_cast_or_null<MDNode>(MDO);
1819 Check(
Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
1820 CheckFunction(
Node->getOperand(0));
1821 CheckFunction(
Node->getOperand(1));
1822 auto Count = dyn_cast_or_null<ConstantAsMetadata>(
Node->getOperand(2));
1823 Check(Count && Count->getType()->isIntegerTy(),
1824 "expected an integer constant",
Node->getOperand(2));
1830 if (
A.isStringAttribute()) {
1831#define GET_ATTR_NAMES
1832#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1833#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
1834 if (A.getKindAsString() == #DISPLAY_NAME) { \
1835 auto V = A.getValueAsString(); \
1836 if (!(V.empty() || V == "true" || V == "false")) \
1837 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
1841#include "llvm/IR/Attributes.inc"
1846 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
1857 if (!
Attrs.hasAttributes())
1860 verifyAttributeTypes(Attrs, V);
1863 Check(Attr.isStringAttribute() ||
1865 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
1868 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
1870 "Attribute 'immarg' is incompatible with other attributes", V);
1875 unsigned AttrCount = 0;
1876 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
1877 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
1878 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
1879 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
1880 Attrs.hasAttribute(Attribute::InReg);
1881 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
1882 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
1883 Check(AttrCount <= 1,
1884 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
1885 "'byref', and 'sret' are incompatible!",
1888 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
1889 Attrs.hasAttribute(Attribute::ReadOnly)),
1891 "'inalloca and readonly' are incompatible!",
1894 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
1895 Attrs.hasAttribute(Attribute::Returned)),
1897 "'sret and returned' are incompatible!",
1900 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
1901 Attrs.hasAttribute(Attribute::SExt)),
1903 "'zeroext and signext' are incompatible!",
1906 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
1907 Attrs.hasAttribute(Attribute::ReadOnly)),
1909 "'readnone and readonly' are incompatible!",
1912 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
1913 Attrs.hasAttribute(Attribute::WriteOnly)),
1915 "'readnone and writeonly' are incompatible!",
1918 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
1919 Attrs.hasAttribute(Attribute::WriteOnly)),
1921 "'readonly and writeonly' are incompatible!",
1924 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
1925 Attrs.hasAttribute(Attribute::AlwaysInline)),
1927 "'noinline and alwaysinline' are incompatible!",
1932 if (!Attr.isStringAttribute() &&
1933 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
1934 CheckFailed(
"Attribute '" + Attr.getAsString() +
1935 "' applied to incompatible type!", V);
1940 if (isa<PointerType>(Ty)) {
1941 if (
Attrs.hasAttribute(Attribute::ByVal)) {
1942 if (
Attrs.hasAttribute(Attribute::Alignment)) {
1943 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
1944 Align MaxAlign(ParamMaxAlignment);
1945 Check(AttrAlign <= MaxAlign,
1946 "Attribute 'align' exceed the max size 2^14", V);
1949 Check(
Attrs.getByValType()->isSized(&Visited),
1950 "Attribute 'byval' does not support unsized types!", V);
1952 if (
Attrs.hasAttribute(Attribute::ByRef)) {
1954 Check(
Attrs.getByRefType()->isSized(&Visited),
1955 "Attribute 'byref' does not support unsized types!", V);
1957 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
1959 Check(
Attrs.getInAllocaType()->isSized(&Visited),
1960 "Attribute 'inalloca' does not support unsized types!", V);
1962 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
1964 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
1965 "Attribute 'preallocated' does not support unsized types!", V);
1969 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
1970 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
1971 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
1974 "Invalid value for 'nofpclass' test mask", V);
1980 if (
Attrs.hasFnAttr(Attr)) {
1984 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
1991 const Value *V,
bool IsIntrinsic,
1993 if (
Attrs.isEmpty())
1996 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
1998 "Attribute list does not match Module context!", &Attrs, V);
1999 for (
const auto &AttrSet : Attrs) {
2000 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(Context),
2001 "Attribute set does not match Module context!", &AttrSet, V);
2002 for (
const auto &
A : AttrSet) {
2003 Check(
A.hasParentContext(Context),
2004 "Attribute does not match Module context!", &
A, V);
2009 bool SawNest =
false;
2010 bool SawReturned =
false;
2011 bool SawSRet =
false;
2012 bool SawSwiftSelf =
false;
2013 bool SawSwiftAsync =
false;
2014 bool SawSwiftError =
false;
2021 "Attribute '" +
RetAttr.getAsString() +
2022 "' does not apply to function return values",
2025 unsigned MaxParameterWidth = 0;
2026 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2028 if (
auto *VT = dyn_cast<FixedVectorType>(Ty)) {
2029 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2030 if (
Size > MaxParameterWidth)
2031 MaxParameterWidth =
Size;
2035 GetMaxParameterWidth(FT->getReturnType());
2036 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2039 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2040 Type *Ty = FT->getParamType(i);
2045 "immarg attribute only applies to intrinsics", V);
2048 "Attribute 'elementtype' can only be applied to intrinsics"
2053 verifyParameterAttrs(ArgAttrs, Ty, V);
2054 GetMaxParameterWidth(Ty);
2057 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2062 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2064 "Incompatible argument and return types for 'returned' attribute",
2070 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2071 Check(i == 0 || i == 1,
2072 "Attribute 'sret' is not on first or second parameter!", V);
2077 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2078 SawSwiftSelf =
true;
2082 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2083 SawSwiftAsync =
true;
2087 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2088 SawSwiftError =
true;
2092 Check(i == FT->getNumParams() - 1,
2093 "inalloca isn't on the last parameter!", V);
2097 if (!
Attrs.hasFnAttrs())
2100 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2104 "Attribute '" +
FnAttr.getAsString() +
2105 "' does not apply to functions!",
2108 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2109 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2110 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2112 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2114 "Attribute 'optnone' requires 'noinline'!", V);
2116 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2117 "Attributes 'optsize and optnone' are incompatible!", V);
2120 "Attributes 'minsize and optnone' are incompatible!", V);
2123 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2124 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2125 "Attributes 'aarch64_pstate_sm_enabled and "
2126 "aarch64_pstate_sm_compatible' are incompatible!",
2130 if (
Attrs.hasFnAttr(
"aarch64_pstate_za_new")) {
2131 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_za_preserved"),
2132 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_preserved' "
2133 "are incompatible!",
2136 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_za_shared"),
2137 "Attributes 'aarch64_pstate_za_new and aarch64_pstate_za_shared' "
2138 "are incompatible!",
2142 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2145 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2148 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2150 if (ParamNo >= FT->getNumParams()) {
2151 CheckFailed(
"'allocsize' " +
Name +
" argument is out of bounds", V);
2155 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2156 CheckFailed(
"'allocsize' " +
Name +
2157 " argument must refer to an integer parameter",
2165 if (!CheckParam(
"element size",
Args->first))
2168 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2172 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2180 "'allockind()' requires exactly one of alloc, realloc, and free");
2184 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2185 "or aligned modifiers.");
2187 if ((K & ZeroedUninit) == ZeroedUninit)
2188 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2191 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2192 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2194 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2196 CheckFailed(
"'vscale_range' minimum must be power-of-two value", V);
2197 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2198 if (VScaleMax && VScaleMin > VScaleMax)
2199 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2201 CheckFailed(
"'vscale_range' maximum must be power-of-two value", V);
2204 if (
Attrs.hasFnAttr(
"frame-pointer")) {
2206 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none")
2207 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2211 if (MaxParameterWidth >= 512 &&
Attrs.hasFnAttr(
"target-features")) {
2214 StringRef TF =
Attrs.getFnAttr(
"target-features").getValueAsString();
2216 "512-bit vector arguments require 'evex512' for AVX512", V);
2220 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2221 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2222 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2225void Verifier::verifyFunctionMetadata(
2226 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2227 for (
const auto &Pair : MDs) {
2228 if (Pair.first == LLVMContext::MD_prof) {
2229 MDNode *MD = Pair.second;
2231 "!prof annotations should have no less than 2 operands", MD);
2234 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2237 "expected string with name of the !prof annotation", MD);
2241 ProfName.
equals(
"synthetic_function_entry_count"),
2242 "first operand should be 'function_entry_count'"
2243 " or 'synthetic_function_entry_count'",
2247 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2250 "expected integer argument to function_entry_count", MD);
2251 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2252 MDNode *MD = Pair.second;
2254 "!kcfi_type must have exactly one operand", MD);
2255 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2258 "expected a constant operand for !kcfi_type", MD);
2260 Check(isa<ConstantInt>(
C),
2261 "expected a constant integer operand for !kcfi_type", MD);
2264 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2269void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2270 if (!ConstantExprVisited.
insert(EntryC).second)
2274 Stack.push_back(EntryC);
2276 while (!
Stack.empty()) {
2280 if (
const auto *CE = dyn_cast<ConstantExpr>(
C))
2281 visitConstantExpr(CE);
2283 if (
const auto *GV = dyn_cast<GlobalValue>(
C)) {
2286 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2292 for (
const Use &U :
C->operands()) {
2293 const auto *OpC = dyn_cast<Constant>(U);
2296 if (!ConstantExprVisited.
insert(OpC).second)
2298 Stack.push_back(OpC);
2303void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2304 if (
CE->getOpcode() == Instruction::BitCast)
2307 "Invalid bitcast", CE);
2310bool Verifier::verifyAttributeCount(
AttributeList Attrs,
unsigned Params) {
2313 return Attrs.getNumAttrSets() <= Params + 2;
2316void Verifier::verifyInlineAsmCall(
const CallBase &Call) {
2319 unsigned LabelNo = 0;
2330 if (CI.isIndirect) {
2331 const Value *Arg =
Call.getArgOperand(ArgNo);
2333 "Operand for indirect constraint must have pointer type", &Call);
2336 "Operand for indirect constraint must have elementtype attribute",
2339 Check(!
Call.paramHasAttr(ArgNo, Attribute::ElementType),
2340 "Elementtype attribute can only be applied for indirect "
2348 if (
auto *CallBr = dyn_cast<CallBrInst>(&Call)) {
2349 Check(LabelNo == CallBr->getNumIndirectDests(),
2350 "Number of label constraints does not match number of callbr dests",
2353 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
2359void Verifier::verifyStatepoint(
const CallBase &Call) {
2361 Call.getCalledFunction()->getIntrinsicID() ==
2362 Intrinsic::experimental_gc_statepoint);
2364 Check(!
Call.doesNotAccessMemory() && !
Call.onlyReadsMemory() &&
2365 !
Call.onlyAccessesArgMemory(),
2366 "gc.statepoint must read and write all memory to preserve "
2367 "reordering restrictions required by safepoint semantics",
2370 const int64_t NumPatchBytes =
2371 cast<ConstantInt>(
Call.getArgOperand(1))->getSExtValue();
2372 assert(isInt<32>(NumPatchBytes) &&
"NumPatchBytesV is an i32!");
2373 Check(NumPatchBytes >= 0,
2374 "gc.statepoint number of patchable bytes must be "
2378 Type *TargetElemType =
Call.getParamElementType(2);
2379 Check(TargetElemType,
2380 "gc.statepoint callee argument must have elementtype attribute", Call);
2381 FunctionType *TargetFuncType = dyn_cast<FunctionType>(TargetElemType);
2382 Check(TargetFuncType,
2383 "gc.statepoint callee elementtype must be function type", Call);
2385 const int NumCallArgs = cast<ConstantInt>(
Call.getArgOperand(3))->getZExtValue();
2386 Check(NumCallArgs >= 0,
2387 "gc.statepoint number of arguments to underlying call "
2390 const int NumParams = (int)TargetFuncType->getNumParams();
2391 if (TargetFuncType->isVarArg()) {
2392 Check(NumCallArgs >= NumParams,
2393 "gc.statepoint mismatch in number of vararg call args", Call);
2396 Check(TargetFuncType->getReturnType()->isVoidTy(),
2397 "gc.statepoint doesn't support wrapping non-void "
2398 "vararg functions yet",
2401 Check(NumCallArgs == NumParams,
2402 "gc.statepoint mismatch in number of call args", Call);
2405 = cast<ConstantInt>(
Call.getArgOperand(4))->getZExtValue();
2407 "unknown flag used in gc.statepoint flags argument", Call);
2412 for (
int i = 0; i < NumParams; i++) {
2413 Type *ParamType = TargetFuncType->getParamType(i);
2414 Type *ArgType =
Call.getArgOperand(5 + i)->getType();
2415 Check(ArgType == ParamType,
2416 "gc.statepoint call argument does not match wrapped "
2420 if (TargetFuncType->isVarArg()) {
2423 "Attribute 'sret' cannot be used for vararg call arguments!", Call);
2427 const int EndCallArgsInx = 4 + NumCallArgs;
2429 const Value *NumTransitionArgsV =
Call.getArgOperand(EndCallArgsInx + 1);
2430 Check(isa<ConstantInt>(NumTransitionArgsV),
2431 "gc.statepoint number of transition arguments "
2432 "must be constant integer",
2434 const int NumTransitionArgs =
2435 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2436 Check(NumTransitionArgs == 0,
2437 "gc.statepoint w/inline transition bundle is deprecated", Call);
2438 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2440 const Value *NumDeoptArgsV =
Call.getArgOperand(EndTransitionArgsInx + 1);
2441 Check(isa<ConstantInt>(NumDeoptArgsV),
2442 "gc.statepoint number of deoptimization arguments "
2443 "must be constant integer",
2445 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2446 Check(NumDeoptArgs == 0,
2447 "gc.statepoint w/inline deopt operands is deprecated", Call);
2449 const int ExpectedNumArgs = 7 + NumCallArgs;
2450 Check(ExpectedNumArgs == (
int)
Call.arg_size(),
2451 "gc.statepoint too many arguments", Call);
2456 for (
const User *U :
Call.users()) {
2457 const CallInst *UserCall = dyn_cast<const CallInst>(U);
2458 Check(UserCall,
"illegal use of statepoint token", Call, U);
2461 Check(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
2462 "gc.result or gc.relocate are the only value uses "
2463 "of a gc.statepoint",
2465 if (isa<GCResultInst>(UserCall)) {
2467 "gc.result connected to wrong gc.statepoint", Call, UserCall);
2468 }
else if (isa<GCRelocateInst>(Call)) {
2470 "gc.relocate connected to wrong gc.statepoint", Call, UserCall);
2484void Verifier::verifyFrameRecoverIndices() {
2485 for (
auto &Counts : FrameEscapeInfo) {
2487 unsigned EscapedObjectCount = Counts.second.first;
2488 unsigned MaxRecoveredIndex = Counts.second.second;
2489 Check(MaxRecoveredIndex <= EscapedObjectCount,
2490 "all indices passed to llvm.localrecover must be less than the "
2491 "number of arguments passed to llvm.localescape in the parent "
2499 if (
auto *II = dyn_cast<InvokeInst>(Terminator))
2500 UnwindDest = II->getUnwindDest();
2501 else if (
auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2502 UnwindDest = CSI->getUnwindDest();
2504 UnwindDest = cast<CleanupReturnInst>(Terminator)->getUnwindDest();
2508void Verifier::verifySiblingFuncletUnwinds() {
2511 for (
const auto &Pair : SiblingFuncletInfo) {
2513 if (Visited.
count(PredPad))
2519 if (Active.
count(SuccPad)) {
2525 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2526 if (CycleTerminator != CyclePad)
2529 }
while (CyclePad != SuccPad);
2530 Check(
false,
"EH pads can't handle each other's exceptions",
2534 if (!Visited.
insert(SuccPad).second)
2538 auto TermI = SiblingFuncletInfo.find(PredPad);
2539 if (TermI == SiblingFuncletInfo.end())
2552void Verifier::visitFunction(
const Function &
F) {
2553 visitGlobalValue(
F);
2557 unsigned NumArgs =
F.arg_size();
2559 Check(&Context == &
F.getContext(),
2560 "Function context does not match Module context!", &
F);
2562 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
2563 Check(FT->getNumParams() == NumArgs,
2564 "# formal arguments must match # of arguments for function type!", &
F,
2566 Check(
F.getReturnType()->isFirstClassType() ||
2567 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
2568 "Functions cannot return aggregate values!", &
F);
2570 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
2571 "Invalid struct return type!", &
F);
2575 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
2576 "Attribute after last parameter!", &
F);
2578 bool IsIntrinsic =
F.isIntrinsic();
2581 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
2587 "Attribute 'builtin' can only be applied to a callsite.", &
F);
2589 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
2590 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
2595 switch (
F.getCallingConv()) {
2600 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
2601 "Calling convention parameter requires byval", &
F);
2608 Check(
F.getReturnType()->isVoidTy(),
2609 "Calling convention requires void return type", &
F);
2616 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
2618 const unsigned StackAS =
DL.getAllocaAddrSpace();
2621 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
2622 "Calling convention disallows byval", &
F);
2623 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
2624 "Calling convention disallows preallocated", &
F);
2625 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
2626 "Calling convention disallows inalloca", &
F);
2628 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
2631 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
2632 "Calling convention disallows stack byref", &
F);
2646 "Calling convention does not support varargs or "
2647 "perfect forwarding!",
2655 Check(Arg.getType() == FT->getParamType(i),
2656 "Argument value does not match function argument type!", &Arg,
2657 FT->getParamType(i));
2658 Check(Arg.getType()->isFirstClassType(),
2659 "Function arguments must have first-class types!", &Arg);
2661 Check(!Arg.getType()->isMetadataTy(),
2662 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
2663 Check(!Arg.getType()->isTokenTy(),
2664 "Function takes token but isn't an intrinsic", &Arg, &
F);
2665 Check(!Arg.getType()->isX86_AMXTy(),
2666 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
2670 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
2671 verifySwiftErrorValue(&Arg);
2677 Check(!
F.getReturnType()->isTokenTy(),
2678 "Function returns a token but isn't an intrinsic", &
F);
2679 Check(!
F.getReturnType()->isX86_AMXTy(),
2680 "Function returns a x86_amx but isn't an intrinsic", &
F);
2685 F.getAllMetadata(MDs);
2686 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
2687 verifyFunctionMetadata(MDs);
2690 if (
F.hasPersonalityFn()) {
2691 auto *Per = dyn_cast<Function>(
F.getPersonalityFn()->stripPointerCasts());
2693 Check(Per->getParent() ==
F.getParent(),
2694 "Referencing personality function in another module!", &
F,
2695 F.getParent(), Per, Per->getParent());
2699 BlockEHFuncletColors.
clear();
2701 if (
F.isMaterializable()) {
2703 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
2705 }
else if (
F.isDeclaration()) {
2706 for (
const auto &
I : MDs) {
2708 CheckDI(
I.first != LLVMContext::MD_dbg ||
2709 !cast<DISubprogram>(
I.second)->isDistinct(),
2710 "function declaration may only have a unique !dbg attachment",
2712 Check(
I.first != LLVMContext::MD_prof,
2713 "function declaration may not have a !prof attachment", &
F);
2716 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
2718 Check(!
F.hasPersonalityFn(),
2719 "Function declaration shouldn't have a personality routine", &
F);
2723 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
2728 "Entry block to function must not have predecessors!", Entry);
2731 if (Entry->hasAddressTaken()) {
2733 "blockaddress may not be used with the entry block!", Entry);
2736 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
2737 NumKCFIAttachments = 0;
2739 for (
const auto &
I : MDs) {
2741 auto AllowLocs = AreDebugLocsAllowed::No;
2745 case LLVMContext::MD_dbg: {
2746 ++NumDebugAttachments;
2747 CheckDI(NumDebugAttachments == 1,
2748 "function must have a single !dbg attachment", &
F,
I.second);
2749 CheckDI(isa<DISubprogram>(
I.second),
2750 "function !dbg attachment must be a subprogram", &
F,
I.second);
2751 CheckDI(cast<DISubprogram>(
I.second)->isDistinct(),
2752 "function definition may only have a distinct !dbg attachment",
2755 auto *SP = cast<DISubprogram>(
I.second);
2756 const Function *&AttachedTo = DISubprogramAttachments[SP];
2757 CheckDI(!AttachedTo || AttachedTo == &
F,
2758 "DISubprogram attached to more than one function", SP, &
F);
2760 AllowLocs = AreDebugLocsAllowed::Yes;
2763 case LLVMContext::MD_prof:
2764 ++NumProfAttachments;
2765 Check(NumProfAttachments == 1,
2766 "function must have a single !prof attachment", &
F,
I.second);
2768 case LLVMContext::MD_kcfi_type:
2769 ++NumKCFIAttachments;
2770 Check(NumKCFIAttachments == 1,
2771 "function must have a single !kcfi_type attachment", &
F,
2777 visitMDNode(*
I.second, AllowLocs);
2785 if (
F.isIntrinsic() &&
F.getParent()->isMaterialized()) {
2787 if (
F.hasAddressTaken(&U,
false,
true,
false,
2789 Check(
false,
"Invalid user of intrinsic instruction!", U);
2793 switch (
F.getIntrinsicID()) {
2794 case Intrinsic::experimental_gc_get_pointer_base: {
2796 Check(FT->getNumParams() == 1,
"wrong number of parameters",
F);
2797 Check(isa<PointerType>(
F.getReturnType()),
2798 "gc.get.pointer.base must return a pointer",
F);
2799 Check(FT->getParamType(0) ==
F.getReturnType(),
2800 "gc.get.pointer.base operand and result must be of the same type",
F);
2803 case Intrinsic::experimental_gc_get_pointer_offset: {
2805 Check(FT->getNumParams() == 1,
"wrong number of parameters",
F);
2806 Check(isa<PointerType>(FT->getParamType(0)),
2807 "gc.get.pointer.offset operand must be a pointer",
F);
2808 Check(
F.getReturnType()->isIntegerTy(),
2809 "gc.get.pointer.offset must return integer",
F);
2814 auto *
N =
F.getSubprogram();
2815 HasDebugInfo = (
N !=
nullptr);
2834 CheckDI(Parent && isa<DILocalScope>(Parent),
2835 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
2838 Check(Scope,
"Failed to find DILocalScope",
DL);
2840 if (!Seen.
insert(Scope).second)
2847 if (SP && ((Scope != SP) && !Seen.
insert(SP).second))
2851 "!dbg attachment points at wrong subprogram for function",
N, &
F,
2855 for (
auto &
I : BB) {
2856 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
2858 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
2860 VisitDebugLoc(
I, dyn_cast_or_null<MDNode>(MD->
getOperand(i)));
2861 if (BrokenDebugInfo)
2868void Verifier::visitBasicBlock(
BasicBlock &BB) {
2869 InstsInThisBlock.
clear();
2870 ConvergenceVerifyHelper.
visit(BB);
2877 if (isa<PHINode>(BB.
front())) {
2882 Check(PN.getNumIncomingValues() == Preds.size(),
2883 "PHINode should have one entry for each predecessor of its "
2884 "parent basic block!",
2889 Values.
reserve(PN.getNumIncomingValues());
2890 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2892 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
2895 for (
unsigned i = 0, e = Values.
size(); i != e; ++i) {
2900 Check(i == 0 || Values[i].first != Values[i - 1].first ||
2901 Values[i].second == Values[i - 1].second,
2902 "PHI node has multiple entries for the same basic block with "
2903 "different incoming values!",
2904 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
2908 Check(Values[i].first == Preds[i],
2909 "PHI node entries do not match predecessors!", &PN,
2910 Values[i].first, Preds[i]);
2918 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
2924 Check(&
I ==
I.getParent()->getTerminator(),
2925 "Terminator found in the middle of a basic block!",
I.getParent());
2929void Verifier::visitBranchInst(
BranchInst &BI) {
2932 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
2937void Verifier::visitReturnInst(
ReturnInst &RI) {
2940 if (
F->getReturnType()->isVoidTy())
2942 "Found return instr that returns non-void in Function of void "
2944 &RI,
F->getReturnType());
2947 "Function return type does not match operand "
2948 "type of return inst!",
2949 &RI,
F->getReturnType());
2956void Verifier::visitSwitchInst(
SwitchInst &SI) {
2957 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
2960 Type *SwitchTy =
SI.getCondition()->getType();
2962 for (
auto &Case :
SI.cases()) {
2963 Check(isa<ConstantInt>(
SI.getOperand(Case.getCaseIndex() * 2 + 2)),
2964 "Case value is not a constant integer.", &SI);
2965 Check(Case.getCaseValue()->getType() == SwitchTy,
2966 "Switch constants must all be same type as switch value!", &SI);
2968 "Duplicate integer as switch case", &SI, Case.getCaseValue());
2976 "Indirectbr operand must have pointer type!", &BI);
2979 "Indirectbr destinations must all have pointer type!", &BI);
2984void Verifier::visitCallBrInst(
CallBrInst &CBI) {
2985 Check(CBI.
isInlineAsm(),
"Callbr is currently only used for asm-goto!", &CBI);
2987 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
2989 verifyInlineAsmCall(CBI);
2993void Verifier::visitSelectInst(
SelectInst &SI) {
2996 "Invalid operands for select instruction!", &SI);
2998 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
2999 "Select values must have same type as select instruction!", &SI);
3007 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3012 Type *SrcTy =
I.getOperand(0)->getType();
3013 Type *DestTy =
I.getType();
3022 "trunc source and destination must both be a vector or neither", &
I);
3023 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3028void Verifier::visitZExtInst(
ZExtInst &
I) {
3030 Type *SrcTy =
I.getOperand(0)->getType();
3031 Type *DestTy =
I.getType();
3037 "zext source and destination must both be a vector or neither", &
I);
3041 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3046void Verifier::visitSExtInst(
SExtInst &
I) {
3048 Type *SrcTy =
I.getOperand(0)->getType();
3049 Type *DestTy =
I.getType();
3058 "sext source and destination must both be a vector or neither", &
I);
3059 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3066 Type *SrcTy =
I.getOperand(0)->getType();
3067 Type *DestTy =
I.getType();
3075 "fptrunc source and destination must both be a vector or neither", &
I);
3076 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3083 Type *SrcTy =
I.getOperand(0)->getType();
3084 Type *DestTy =
I.getType();
3093 "fpext source and destination must both be a vector or neither", &
I);
3094 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3101 Type *SrcTy =
I.getOperand(0)->getType();
3102 Type *DestTy =
I.getType();
3107 Check(SrcVec == DstVec,
3108 "UIToFP source and dest must both be vector or scalar", &
I);
3110 "UIToFP source must be integer or integer vector", &
I);
3114 if (SrcVec && DstVec)
3115 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3116 cast<VectorType>(DestTy)->getElementCount(),
3117 "UIToFP source and dest vector length mismatch", &
I);
3124 Type *SrcTy =
I.getOperand(0)->getType();
3125 Type *DestTy =
I.getType();
3130 Check(SrcVec == DstVec,
3131 "SIToFP source and dest must both be vector or scalar", &
I);
3133 "SIToFP source must be integer or integer vector", &
I);
3137 if (SrcVec && DstVec)
3138 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3139 cast<VectorType>(DestTy)->getElementCount(),
3140 "SIToFP source and dest vector length mismatch", &
I);
3147 Type *SrcTy =
I.getOperand(0)->getType();
3148 Type *DestTy =
I.getType();
3153 Check(SrcVec == DstVec,
3154 "FPToUI source and dest must both be vector or scalar", &
I);
3157 "FPToUI result must be integer or integer vector", &
I);
3159 if (SrcVec && DstVec)
3160 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3161 cast<VectorType>(DestTy)->getElementCount(),
3162 "FPToUI source and dest vector length mismatch", &
I);
3169 Type *SrcTy =
I.getOperand(0)->getType();
3170 Type *DestTy =
I.getType();
3175 Check(SrcVec == DstVec,
3176 "FPToSI source and dest must both be vector or scalar", &
I);
3179 "FPToSI result must be integer or integer vector", &
I);
3181 if (SrcVec && DstVec)
3182 Check(cast<VectorType>(SrcTy)->getElementCount() ==
3183 cast<VectorType>(DestTy)->getElementCount(),
3184 "FPToSI source and dest vector length mismatch", &
I);
3191 Type *SrcTy =
I.getOperand(0)->getType();
3192 Type *DestTy =
I.getType();
3201 auto *VSrc = cast<VectorType>(SrcTy);
3202 auto *VDest = cast<VectorType>(DestTy);
3203 Check(VSrc->getElementCount() == VDest->getElementCount(),
3204 "PtrToInt Vector width mismatch", &
I);
3212 Type *SrcTy =
I.getOperand(0)->getType();
3213 Type *DestTy =
I.getType();
3221 auto *VSrc = cast<VectorType>(SrcTy);
3222 auto *VDest = cast<VectorType>(DestTy);
3223 Check(VSrc->getElementCount() == VDest->getElementCount(),
3224 "IntToPtr Vector width mismatch", &
I);
3232 "Invalid bitcast", &
I);
3237 Type *SrcTy =
I.getOperand(0)->getType();
3238 Type *DestTy =
I.getType();
3245 "AddrSpaceCast must be between different address spaces", &
I);
3246 if (
auto *SrcVTy = dyn_cast<VectorType>(SrcTy))
3247 Check(SrcVTy->getElementCount() ==
3248 cast<VectorType>(DestTy)->getElementCount(),
3249 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3255void Verifier::visitPHINode(
PHINode &PN) {
3262 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3271 "PHI node operands are not the same type as the result!", &PN);
3279void Verifier::visitCallBase(
CallBase &Call) {
3280 Check(
Call.getCalledOperand()->getType()->isPointerTy(),
3281 "Called function must be a pointer!", Call);
3285 if (FTy->isVarArg())
3286 Check(
Call.arg_size() >= FTy->getNumParams(),
3287 "Called function requires more parameters than were provided!", Call);
3289 Check(
Call.arg_size() == FTy->getNumParams(),
3290 "Incorrect number of arguments passed to called function!", Call);
3293 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3294 Check(
Call.getArgOperand(i)->getType() == FTy->getParamType(i),
3295 "Call parameter type does not match function signature!",
3296 Call.getArgOperand(i), FTy->getParamType(i), Call);
3300 Check(verifyAttributeCount(Attrs,
Call.arg_size()),
3301 "Attribute after last parameter!", Call);
3304 dyn_cast<Function>(
Call.getCalledOperand()->stripPointerCasts());
3308 "Intrinsic called with incompatible signature", Call);
3312 auto CC =
Call.getCallingConv();
3315 "Direct calls to amdgpu_cs_chain/amdgpu_cs_chain_preserve functions "
3316 "not allowed. Please use the @llvm.amdgpu.cs.chain intrinsic instead.",
3319 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3322 Align ABIAlign =
DL.getABITypeAlign(Ty);
3323 Align MaxAlign(ParamMaxAlignment);
3324 Check(ABIAlign <= MaxAlign,
3325 "Incorrect alignment of " + Message +
" to called function!", Call);
3329 VerifyTypeAlign(FTy->getReturnType(),
"return type");
3330 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3331 Type *Ty = FTy->getParamType(i);
3332 VerifyTypeAlign(Ty,
"argument passed");
3336 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
3340 "speculatable attribute may not apply to call sites", Call);
3343 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
3344 Check(
Call.getCalledFunction()->getIntrinsicID() ==
3345 Intrinsic::call_preallocated_arg,
3346 "preallocated as a call site attribute can only be on "
3347 "llvm.call.preallocated.arg");
3351 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic,
Call.isInlineAsm());
3356 if (
Call.hasInAllocaArgument()) {
3357 Value *InAllocaArg =
Call.getArgOperand(FTy->getNumParams() - 1);
3359 Check(AI->isUsedWithInAlloca(),
3360 "inalloca argument for call has mismatched alloca", AI, Call);
3366 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3367 if (
Call.paramHasAttr(i, Attribute::SwiftError)) {
3368 Value *SwiftErrorArg =
Call.getArgOperand(i);
3370 Check(AI->isSwiftError(),
3371 "swifterror argument for call has mismatched alloca", AI, Call);
3374 auto ArgI = dyn_cast<Argument>(SwiftErrorArg);
3375 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
3376 SwiftErrorArg, Call);
3377 Check(ArgI->hasSwiftErrorAttr(),
3378 "swifterror argument for call has mismatched parameter", ArgI,
3382 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3385 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
3386 "immarg may not apply only to call sites",
Call.getArgOperand(i),
3390 if (
Call.paramHasAttr(i, Attribute::ImmArg)) {
3392 Check(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
3393 "immarg operand has non-immediate parameter", ArgVal, Call);
3396 if (
Call.paramHasAttr(i, Attribute::Preallocated)) {
3400 bool isMustTail =
Call.isMustTailCall();
3401 Check(hasOB != isMustTail,
3402 "preallocated operand either requires a preallocated bundle or "
3403 "the call to be musttail (but not both)",
3408 if (FTy->isVarArg()) {
3410 bool SawNest =
false;
3411 bool SawReturned =
false;
3413 for (
unsigned Idx = 0;
Idx < FTy->getNumParams(); ++
Idx) {
3414 if (
Attrs.hasParamAttr(
Idx, Attribute::Nest))
3416 if (
Attrs.hasParamAttr(
Idx, Attribute::Returned))
3421 for (
unsigned Idx = FTy->getNumParams();
Idx <
Call.arg_size(); ++
Idx) {
3424 verifyParameterAttrs(ArgAttrs, Ty, &Call);
3427 Check(!SawNest,
"More than one parameter has attribute nest!", Call);
3432 Check(!SawReturned,
"More than one parameter has attribute returned!",
3435 "Incompatible argument and return types for 'returned' "
3443 if (!
Call.getCalledFunction() ||
3444 Call.getCalledFunction()->getIntrinsicID() !=
3445 Intrinsic::experimental_gc_statepoint)
3447 "Attribute 'sret' cannot be used for vararg call arguments!",
3452 "inalloca isn't on the last argument!", Call);
3458 for (
Type *ParamTy : FTy->params()) {
3459 Check(!ParamTy->isMetadataTy(),
3460 "Function has metadata parameter but isn't an intrinsic", Call);
3461 Check(!ParamTy->isTokenTy(),
3462 "Function has token parameter but isn't an intrinsic", Call);
3467 if (!
Call.getCalledFunction()) {
3468 Check(!FTy->getReturnType()->isTokenTy(),
3469 "Return type cannot be token for indirect call!");
3470 Check(!FTy->getReturnType()->isX86_AMXTy(),
3471 "Return type cannot be x86_amx for indirect call!");
3476 visitIntrinsicCall(
ID, Call);
3481 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
3482 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
3483 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
3484 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
3485 FoundAttachedCallBundle =
false;
3486 for (
unsigned i = 0, e =
Call.getNumOperandBundles(); i < e; ++i) {
3490 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles", Call);
3491 FoundDeoptBundle =
true;
3493 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
3495 FoundGCTransitionBundle =
true;
3497 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles", Call);
3498 FoundFuncletBundle =
true;
3500 "Expected exactly one funclet bundle operand", Call);
3502 "Funclet bundle operands should correspond to a FuncletPadInst",
3505 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
3507 FoundCFGuardTargetBundle =
true;
3509 "Expected exactly one cfguardtarget bundle operand", Call);
3511 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles", Call);
3512 FoundPtrauthBundle =
true;
3514 "Expected exactly two ptrauth bundle operands", Call);
3516 BU.
Inputs[0]->getType()->isIntegerTy(32),
3517 "Ptrauth bundle key operand must be an i32 constant", Call);
3519 "Ptrauth bundle discriminator operand must be an i64", Call);
3521 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles", Call);
3522 FoundKCFIBundle =
true;
3523 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
3526 BU.
Inputs[0]->getType()->isIntegerTy(32),
3527 "Kcfi bundle operand must be an i32 constant", Call);
3529 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
3531 FoundPreallocatedBundle =
true;
3533 "Expected exactly one preallocated bundle operand", Call);
3534 auto Input = dyn_cast<IntrinsicInst>(BU.
Inputs.front());
3536 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
3537 "\"preallocated\" argument must be a token from "
3538 "llvm.call.preallocated.setup",
3541 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles", Call);
3542 FoundGCLiveBundle =
true;
3544 Check(!FoundAttachedCallBundle,
3545 "Multiple \"clang.arc.attachedcall\" operand bundles", Call);
3546 FoundAttachedCallBundle =
true;
3547 verifyAttachedCallBundle(Call, BU);
3552 Check(!(
Call.getCalledFunction() && FoundPtrauthBundle),
3553 "Direct call cannot have a ptrauth bundle", Call);
3560 if (
Call.getFunction()->getSubprogram() &&
Call.getCalledFunction() &&
3561 !
Call.getCalledFunction()->isInterposable() &&
3562 !
Call.getCalledFunction()->isDeclaration() &&
3563 Call.getCalledFunction()->getSubprogram())
3565 "inlinable function call in a function with "
3566 "debug info must have a !dbg location",
3569 if (
Call.isInlineAsm())
3570 verifyInlineAsmCall(Call);
3572 ConvergenceVerifyHelper.
visit(Call);
3577void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
3580 Twine(
"inalloca attribute not allowed in ") + Context);
3582 Twine(
"inreg attribute not allowed in ") + Context);
3583 Check(!
Attrs.contains(Attribute::SwiftError),
3584 Twine(
"swifterror attribute not allowed in ") + Context);
3585 Check(!
Attrs.contains(Attribute::Preallocated),
3586 Twine(
"preallocated attribute not allowed in ") + Context);
3588 Twine(
"byref attribute not allowed in ") + Context);
3600 return PL->getAddressSpace() == PR->getAddressSpace();
3605 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
3606 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
3607 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
3610 for (
auto AK : ABIAttrs) {
3611 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
3613 Copy.addAttribute(Attr);
3617 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
3618 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
3619 Attrs.hasParamAttr(
I, Attribute::ByRef)))
3620 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
3624void Verifier::verifyMustTailCall(
CallInst &CI) {
3630 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
3631 "cannot guarantee tail call due to mismatched varargs", &CI);
3633 "cannot guarantee tail call due to mismatched return types", &CI);
3637 "cannot guarantee tail call due to mismatched calling conv", &CI);
3643 Value *RetVal = &CI;
3647 if (
BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
3649 "bitcast following musttail call must use the call", BI);
3656 Check(Ret,
"musttail call must precede a ret with an optional bitcast", &CI);
3657 Check(!
Ret->getReturnValue() ||
Ret->getReturnValue() == RetVal ||
3658 isa<UndefValue>(
Ret->getReturnValue()),
3659 "musttail call result must be returned", Ret);
3670 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
3673 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3675 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
3678 verifyTailCCMustTailAttrs(ABIAttrs, Context);
3681 Check(!CallerTy->isVarArg(),
Twine(
"cannot guarantee ") + CCName +
3682 " tail call for varargs function");
3690 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
3691 "cannot guarantee tail call due to mismatched parameter counts", &CI);
3692 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
3695 "cannot guarantee tail call due to mismatched parameter types", &CI);
3701 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
3704 Check(CallerABIAttrs == CalleeABIAttrs,
3705 "cannot guarantee tail call due to mismatched ABI impacting "
3706 "function attributes",
3711void Verifier::visitCallInst(
CallInst &CI) {
3715 verifyMustTailCall(CI);
3718void Verifier::visitInvokeInst(
InvokeInst &II) {
3725 "The unwind destination does not have an exception handling instruction!",
3734 Check(
U.getType() ==
U.getOperand(0)->getType(),
3735 "Unary operators must have same type for"
3736 "operands and result!",
3739 switch (
U.getOpcode()) {
3742 case Instruction::FNeg:
3743 Check(
U.getType()->isFPOrFPVectorTy(),
3744 "FNeg operator only works with float types!", &U);
3757 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
3758 "Both operands to a binary operator are not of the same type!", &
B);
3760 switch (
B.getOpcode()) {
3763 case Instruction::Add:
3764 case Instruction::Sub:
3765 case Instruction::Mul:
3766 case Instruction::SDiv:
3767 case Instruction::UDiv:
3768 case Instruction::SRem:
3769 case Instruction::URem:
3770 Check(
B.getType()->isIntOrIntVectorTy(),
3771 "Integer arithmetic operators only work with integral types!", &
B);
3772 Check(
B.getType() ==
B.getOperand(0)->getType(),
3773 "Integer arithmetic operators must have same type "
3774 "for operands and result!",
3779 case Instruction::FAdd:
3780 case Instruction::FSub:
3781 case Instruction::FMul:
3782 case Instruction::FDiv:
3783 case Instruction::FRem:
3784 Check(
B.getType()->isFPOrFPVectorTy(),
3785 "Floating-point arithmetic operators only work with "
3786 "floating-point types!",
3788 Check(
B.getType() ==
B.getOperand(0)->getType(),
3789 "Floating-point arithmetic operators must have same type "
3790 "for operands and result!",
3794 case Instruction::And:
3795 case Instruction::Or:
3796 case Instruction::Xor:
3797 Check(
B.getType()->isIntOrIntVectorTy(),
3798 "Logical operators only work with integral types!", &
B);
3799 Check(
B.getType() ==
B.getOperand(0)->getType(),
3800 "Logical operators must have same type for operands and result!", &
B);
3802 case Instruction::Shl:
3803 case Instruction::LShr:
3804 case Instruction::AShr:
3805 Check(
B.getType()->isIntOrIntVectorTy(),
3806 "Shifts only work with integral types!", &
B);
3807 Check(
B.getType() ==
B.getOperand(0)->getType(),
3808 "Shift return type must be same as operands!", &
B);
3817void Verifier::visitICmpInst(
ICmpInst &IC) {
3821 Check(Op0Ty == Op1Ty,
3822 "Both operands to ICmp instruction are not of the same type!", &IC);
3825 "Invalid operand types for ICmp instruction", &IC);
3832void Verifier::visitFCmpInst(
FCmpInst &FC) {
3834 Type *Op0Ty =
FC.getOperand(0)->getType();
3835 Type *Op1Ty =
FC.getOperand(1)->getType();
3836 Check(Op0Ty == Op1Ty,
3837 "Both operands to FCmp instruction are not of the same type!", &FC);
3842 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
3849 "Invalid extractelement operands!", &EI);
3856 "Invalid insertelement operands!", &IE);
3863 "Invalid shufflevector operands!", &SV);
3868 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
3870 Check(isa<PointerType>(TargetTy),
3871 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
3872 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
3874 if (
auto *STy = dyn_cast<StructType>(
GEP.getSourceElementType())) {
3877 "getelementptr cannot target structure that contains scalable vector"
3884 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
3885 "GEP indexes must be integers", &
GEP);
3888 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
3890 Check(
GEP.getType()->isPtrOrPtrVectorTy() &&
3891 GEP.getResultElementType() == ElTy,
3892 "GEP is not of right type for indices!", &
GEP, ElTy);
3894 if (
auto *GEPVTy = dyn_cast<VectorType>(
GEP.getType())) {
3897 if (
GEP.getPointerOperandType()->isVectorTy())
3900 cast<VectorType>(
GEP.getPointerOperandType())->getElementCount(),
3901 "Vector GEP result width doesn't match operand's", &
GEP);
3903 Type *IndexTy =
Idx->getType();
3904 if (
auto *IndexVTy = dyn_cast<VectorType>(IndexTy)) {
3906 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
3909 "All GEP indices should be of integer type");
3913 if (
auto *PTy = dyn_cast<PointerType>(
GEP.getType())) {
3914 Check(
GEP.getAddressSpace() == PTy->getAddressSpace(),
3915 "GEP address space doesn't match type", &
GEP);
3922 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
3927void Verifier::verifyRangeMetadata(
const Value &
I,
const MDNode *Range,
3928 Type *Ty,
bool IsAbsoluteSymbol) {
3929 unsigned NumOperands =
Range->getNumOperands();
3930 Check(NumOperands % 2 == 0,
"Unfinished range!", Range);
3931 unsigned NumRanges = NumOperands / 2;
3932 Check(NumRanges >= 1,
"It should have at least one range!", Range);
3935 for (
unsigned i = 0; i < NumRanges; ++i) {
3937 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(2 * i));
3938 Check(
Low,
"The lower limit must be an integer!",
Low);
3940 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(2 * i + 1));
3944 "Range types must match instruction type!", &
I);
3952 "The upper and lower limits cannot be the same value", &
I);
3955 Check(!CurRange.isEmptySet() && (IsAbsoluteSymbol || !CurRange.isFullSet()),
3956 "Range must not be empty!", Range);
3958 Check(CurRange.intersectWith(LastRange).isEmptySet(),
3959 "Intervals are overlapping", Range);
3960 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
3967 if (NumRanges > 2) {
3969 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(0))->getValue();
3971 mdconst::dyn_extract<ConstantInt>(
Range->getOperand(1))->getValue();
3973 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
3974 "Intervals are overlapping", Range);
3981 assert(Range && Range ==
I.getMetadata(LLVMContext::MD_range) &&
3982 "precondition violation");
3983 verifyRangeMetadata(
I, Range, Ty,
false);
3987 unsigned Size =
DL.getTypeSizeInBits(Ty);
3988 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
3990 "atomic memory access' operand must have a power-of-two size", Ty,
I);
3993void Verifier::visitLoadInst(
LoadInst &LI) {
3995 Check(PTy,
"Load operand must be a pointer.", &LI);
3999 "huge alignment values are unsupported", &LI);
4001 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4005 "Load cannot have Release ordering", &LI);
4007 "atomic load operand must have integer, pointer, or floating point "
4010 checkAtomicMemAccessSize(ElTy, &LI);
4013 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4019void Verifier::visitStoreInst(
StoreInst &SI) {
4020 PointerType *PTy = dyn_cast<PointerType>(
SI.getOperand(1)->getType());
4021 Check(PTy,
"Store operand must be a pointer.", &SI);
4022 Type *ElTy =
SI.getOperand(0)->getType();
4025 "huge alignment values are unsupported", &SI);
4027 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4028 if (
SI.isAtomic()) {
4031 "Store cannot have Acquire ordering", &SI);
4033 "atomic store operand must have integer, pointer, or floating point "
4036 checkAtomicMemAccessSize(ElTy, &SI);
4039 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4045void Verifier::verifySwiftErrorCall(
CallBase &Call,
4046 const Value *SwiftErrorVal) {
4048 if (
I.value() == SwiftErrorVal) {
4049 Check(
Call.paramHasAttr(
I.index(), Attribute::SwiftError),
4050 "swifterror value when used in a callsite should be marked "
4051 "with swifterror attribute",
4052 SwiftErrorVal, Call);
4057void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4060 for (
const User *U : SwiftErrorVal->
users()) {
4061 Check(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
4063 "swifterror value can only be loaded and stored from, or "
4064 "as a swifterror argument!",
4067 if (
auto StoreI = dyn_cast<StoreInst>(U))
4068 Check(StoreI->getOperand(1) == SwiftErrorVal,
4069 "swifterror value should be the second operand when used "
4072 if (
auto *Call = dyn_cast<CallBase>(U))
4073 verifySwiftErrorCall(*
const_cast<CallBase *
>(Call), SwiftErrorVal);
4077void Verifier::visitAllocaInst(
AllocaInst &AI) {
4080 "Cannot allocate unsized type", &AI);
4082 "Alloca array size must have integer type", &AI);
4085 "huge alignment values are unsupported", &AI);
4090 "swifterror alloca must have pointer type", &AI);
4092 "swifterror alloca must not be array allocation", &AI);
4093 verifySwiftErrorValue(&AI);
4102 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4103 checkAtomicMemAccessSize(ElTy, &CXI);
4109 "atomicrmw instructions cannot be unordered.", &RMWI);
4116 " operand must have integer or floating point type!",
4121 " operand must have floating point type!",
4126 " operand must have integer type!",
4129 checkAtomicMemAccessSize(ElTy, &RMWI);
4131 "Invalid binary operation!", &RMWI);
4135void Verifier::visitFenceInst(
FenceInst &FI) {
4141 "fence instructions may only have acquire, release, acq_rel, or "
4142 "seq_cst ordering.",
4150 "Invalid ExtractValueInst operands!", &EVI);
4159 "Invalid InsertValueInst operands!", &IVI);
4165 if (
auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
4166 return FPI->getParentPad();
4168 return cast<CatchSwitchInst>(EHPad)->getParentPad();
4177 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
4179 if (
auto *LPI = dyn_cast<LandingPadInst>(&
I)) {
4184 const auto *II = dyn_cast<InvokeInst>(PredBB->getTerminator());
4185 Check(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
4186 "Block containing LandingPadInst must be jumped to "
4187 "only by the unwind edge of an invoke.",
4192 if (
auto *CPI = dyn_cast<CatchPadInst>(&
I)) {
4195 "Block containg CatchPadInst must be jumped to "
4196 "only by its catchswitch.",
4198 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4199 "Catchswitch cannot unwind to one of its catchpads",
4200 CPI->getCatchSwitch(), CPI);
4211 if (
auto *II = dyn_cast<InvokeInst>(TI)) {
4212 Check(II->getUnwindDest() == BB && II->getNormalDest() != BB,
4213 "EH pad must be jumped to via an unwind edge", ToPad, II);
4215 FromPad = Bundle->Inputs[0];
4218 }
else if (
auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
4219 FromPad = CRI->getOperand(0);
4220 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
4221 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4224 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
4230 Check(FromPad != ToPad,
4231 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4232 if (FromPad == ToPadParent) {
4236 Check(!isa<ConstantTokenNone>(FromPad),
4237 "A single unwind edge may only enter one EH pad", TI);
4238 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
4243 Check(isa<FuncletPadInst>(FromPad) || isa<CatchSwitchInst>(FromPad),
4244 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4253 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4255 visitEHPadPredecessors(LPI);
4257 if (!LandingPadResultTy)
4258 LandingPadResultTy = LPI.
getType();
4261 "The landingpad instruction should have a consistent result type "
4262 "inside a function.",
4266 Check(
F->hasPersonalityFn(),
4267 "LandingPadInst needs to be in a function with a personality.", &LPI);
4272 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4278 "Catch operand does not have pointer type!", &LPI);
4280 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
4282 "Filter operand is not an array of constants!", &LPI);
4289void Verifier::visitResumeInst(
ResumeInst &RI) {
4291 "ResumeInst needs to be in a function with a personality.", &RI);
4293 if (!LandingPadResultTy)
4297 "The resume instruction should have a consistent result type "
4298 "inside a function.",
4308 Check(
F->hasPersonalityFn(),
4309 "CatchPadInst needs to be in a function with a personality.", &CPI);
4312 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4318 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4320 visitEHPadPredecessors(CPI);
4326 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4336 Check(
F->hasPersonalityFn(),
4337 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4342 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
4345 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4346 "CleanupPadInst has an invalid parent.", &CPI);
4348 visitEHPadPredecessors(CPI);
4353 User *FirstUser =
nullptr;
4354 Value *FirstUnwindPad =
nullptr;
4358 while (!Worklist.empty()) {
4361 "FuncletPadInst must not be nested within itself", CurrentPad);
4362 Value *UnresolvedAncestorPad =
nullptr;
4365 if (
auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
4366 UnwindDest = CRI->getUnwindDest();
4367 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
4372 if (CSI->unwindsToCaller())
4374 UnwindDest = CSI->getUnwindDest();
4375 }
else if (
auto *II = dyn_cast<InvokeInst>(U)) {
4376 UnwindDest = II->getUnwindDest();
4377 }
else if (isa<CallInst>(U)) {
4382 }
else if (
auto *CPI = dyn_cast<CleanupPadInst>(U)) {
4386 Worklist.push_back(CPI);
4389 Check(isa<CatchReturnInst>(U),
"Bogus funclet pad use", U);
4397 if (!cast<Instruction>(UnwindPad)->isEHPad())
4401 if (UnwindParent == CurrentPad)
4407 Value *ExitedPad = CurrentPad;
4410 if (ExitedPad == &FPI) {
4415 UnresolvedAncestorPad = &FPI;
4419 if (ExitedParent == UnwindParent) {
4423 UnresolvedAncestorPad = ExitedParent;
4426 ExitedPad = ExitedParent;
4427 }
while (!isa<ConstantTokenNone>(ExitedPad));
4432 UnresolvedAncestorPad = &FPI;
4439 Check(UnwindPad == FirstUnwindPad,
4440 "Unwind edges out of a funclet "
4441 "pad must have the same unwind "
4443 &FPI, U, FirstUser);
4446 FirstUnwindPad = UnwindPad;
4448 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
4450 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
4455 if (CurrentPad != &FPI)
4458 if (UnresolvedAncestorPad) {
4459 if (CurrentPad == UnresolvedAncestorPad) {
4463 assert(CurrentPad == &FPI);
4471 Value *ResolvedPad = CurrentPad;
4472 while (!Worklist.empty()) {
4473 Value *UnclePad = Worklist.back();
4477 while (ResolvedPad != AncestorPad) {
4479 if (ResolvedParent == UnresolvedAncestorPad) {
4482 ResolvedPad = ResolvedParent;
4486 if (ResolvedPad != AncestorPad)
4489 Worklist.pop_back();
4494 if (FirstUnwindPad) {
4495 if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.
getParentPad())) {
4496 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
4497 Value *SwitchUnwindPad;
4498 if (SwitchUnwindDest)
4502 Check(SwitchUnwindPad == FirstUnwindPad,
4503 "Unwind edges out of a catch must have the same unwind dest as "
4504 "the parent catchswitch",
4505 &FPI, FirstUser, CatchSwitch);
4516 Check(
F->hasPersonalityFn(),
4517 "CatchSwitchInst needs to be in a function with a personality.",
4523 "CatchSwitchInst not the first non-PHI instruction in the block.",
4527 Check(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
4528 "CatchSwitchInst has an invalid parent.", ParentPad);
4532 Check(
I->isEHPad() && !isa<LandingPadInst>(
I),
4533 "CatchSwitchInst must unwind to an EH block which is not a "
4539 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
4543 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
4546 Check(isa<CatchPadInst>(Handler->getFirstNonPHI()),
4547 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
4550 visitEHPadPredecessors(CatchSwitch);
4556 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
4561 Check(
I->isEHPad() && !isa<LandingPadInst>(
I),
4562 "CleanupReturnInst must unwind to an EH block which is not a "
4570void Verifier::verifyDominatesUse(
Instruction &
I,
unsigned i) {
4576 if (II->getNormalDest() == II->getUnwindDest())
4587 if (!isa<PHINode>(
I) && InstsInThisBlock.
count(
Op))
4590 const Use &
U =
I.getOperandUse(i);
4595 Check(
I.getType()->isPointerTy(),
4596 "dereferenceable, dereferenceable_or_null "
4597 "apply only to pointer types",
4599 Check((isa<LoadInst>(
I) || isa<IntToPtrInst>(
I)),
4600 "dereferenceable, dereferenceable_or_null apply only to load"
4601 " and inttoptr instructions, use attributes for calls or invokes",
4604 "dereferenceable, dereferenceable_or_null "
4605 "take one operand!",
4610 "dereferenceable_or_null metadata value must be an i64!",
4616 "!prof annotations should have no less than 2 operands", MD);
4619 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
4621 "expected string with name of the !prof annotation", MD);
4626 if (ProfName.
equals(
"branch_weights")) {
4627 if (isa<InvokeInst>(&
I)) {
4629 "Wrong number of InvokeInst branch_weights operands", MD);
4631 unsigned ExpectedNumOperands = 0;
4634 else if (
SwitchInst *SI = dyn_cast<SwitchInst>(&
I))
4635 ExpectedNumOperands =
SI->getNumSuccessors();
4636 else if (isa<CallInst>(&
I))
4637 ExpectedNumOperands = 1;
4639 ExpectedNumOperands = IBI->getNumDestinations();
4640 else if (isa<SelectInst>(&
I))
4641 ExpectedNumOperands = 2;
4642 else if (
CallBrInst *CI = dyn_cast<CallBrInst>(&
I))
4645 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
4649 "Wrong number of operands", MD);
4653 Check(MDO,
"second operand should not be null", MD);
4654 Check(mdconst::dyn_extract<ConstantInt>(MDO),
4655 "!prof brunch_weights operand is not a const int");
4661 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
4662 bool ExpectedInstTy =
4663 isa<AllocaInst>(
I) || isa<StoreInst>(
I) || isa<MemIntrinsic>(
I);
4664 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
4671 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
4674 if (
auto *DAI = dyn_cast<DbgAssignIntrinsic>(
User))
4675 CheckDI(DAI->getFunction() ==
I.getFunction(),
4676 "dbg.assign not in same function as inst", DAI, &
I);