89 #include "llvm/IR/IntrinsicsWebAssembly.h" 116 using namespace llvm;
136 : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
137 Context(M.getContext()) {}
140 void Write(
const Module *M) {
144 void Write(
const Value *V) {
149 void Write(
const Value &V) {
150 if (isa<Instruction>(V)) {
162 MD->
print(*OS, MST, &M);
173 NMD->
print(*OS, MST);
177 void Write(
Type *
T) {
189 void Write(
const APInt *AI) {
195 void Write(
const unsigned i) { *OS << i <<
'\n'; }
198 for (
const T &V : Vs)
202 template <
typename T1,
typename... Ts>
203 void WriteTs(
const T1 &V1,
const Ts &... Vs) {
208 template <
typename... Ts>
void WriteTs() {}
217 *OS << Message <<
'\n';
225 template <
typename T1,
typename... Ts>
235 *OS << Message <<
'\n';
237 BrokenDebugInfo =
true;
241 template <
typename T1,
typename... Ts>
276 Type *LandingPadResultTy;
283 bool HasDebugInfo =
false;
319 SawFrameEscape(
false), TBAAVerifyHelper(
this) {
327 "An instance of this class only works with a specific module!");
336 DT.recalculate(const_cast<Function &>(F));
339 if (!BB.empty() && BB.back().isTerminator())
343 *OS <<
"Basic Block in function '" << F.getName()
344 <<
"' does not have terminator!\n";
345 BB.printAsOperand(*OS,
true,
MST);
353 visit(const_cast<Function &>(F));
354 verifySiblingFuncletUnwinds();
355 InstsInThisBlock.
clear();
357 LandingPadResultTy =
nullptr;
358 SawFrameEscape =
false;
359 SiblingFuncletInfo.
clear();
375 verifyFrameRecoverIndices();
377 visitGlobalVariable(GV);
380 visitGlobalAlias(GA);
383 visitNamedMDNode(NMD);
386 visitComdat(SMEC.getValue());
389 visitModuleIdents(M);
390 visitModuleCommandLines(M);
392 verifyCompileUnits();
394 verifyDeoptimizeCallingConvs();
395 DISubprogramAttachments.
clear();
408 void visitMDNode(
const MDNode &MD);
411 void visitComdat(
const Comdat &C);
412 void visitModuleIdents(
const Module &M);
413 void visitModuleCommandLines(
const Module &M);
414 void visitModuleFlags(
const Module &M);
415 void visitModuleFlag(
const MDNode *
Op,
418 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
419 void visitFunction(
const Function &F);
425 template <
class Ty>
bool isValidMetadataArray(
const MDTuple &
N);
426 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N); 427 #include "llvm/IR/Metadata.def" 428 void visitDIScope(
const DIScope &N);
433 void visitTemplateParams(
const MDNode &N,
const Metadata &RawParams);
452 void visitPHINode(
PHINode &PN);
461 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
467 void verifyDominatesUse(
Instruction &I,
unsigned i);
477 void visitUserOp2(
Instruction &I) { visitUserOp1(I); }
499 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
500 void verifyMustTailCall(
CallInst &CI);
502 unsigned ArgNo, std::string &Suffix);
508 const Value *V,
bool IsIntrinsic);
509 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
511 void visitConstantExprsRecursively(
const Constant *EntryC);
514 void verifyFrameRecoverIndices();
515 void verifySiblingFuncletUnwinds();
518 template <
typename ValueOrMetadata>
519 void verifyFragmentExpression(
const DIVariable &V,
521 ValueOrMetadata *Desc);
526 void verifyCompileUnits();
530 void verifyDeoptimizeCallingConvs();
539 #define Assert(C, ...) \ 540 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false) 544 #define AssertDI(C, ...) \ 545 do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false) 559 if (!Visited.
insert(User).second)
562 if (Callback(TheNextUser))
566 void Verifier::visitGlobalValue(
const GlobalValue &GV) {
568 "Global is external, but doesn't have external or weak linkage!", &GV);
571 "huge alignment values are unsupported", &GV);
573 "Only global variables can have appending linkage!", &GV);
578 "Only global arrays can have appending linkage!", GVar);
586 "GlobalValue with DLLImport Storage is dso_local!", &GV);
590 "Global is marked as dllimport, but not external", &GV);
595 "GlobalValue with private or internal linkage must be dso_local!",
600 "GlobalValue with non default visibility must be dso_local!", &GV);
604 if (!
I->getParent() || !
I->getParent()->getParent())
605 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &
M,
607 else if (
I->getParent()->getParent()->getParent() != &
M)
608 CheckFailed(
"Global is referenced in a different module!", &GV, &
M,
I,
609 I->getParent()->getParent(),
610 I->getParent()->getParent()->getParent());
612 }
else if (
const Function *
F = dyn_cast<Function>(V)) {
613 if (
F->getParent() != &
M)
614 CheckFailed(
"Global is used by function in a different module", &GV, &
M,
625 "Global variable initializer type does not match global " 632 "'common' global must have a zero initializer!", &GV);
635 Assert(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
640 GV.
getName() ==
"llvm.global_dtors")) {
642 "invalid linkage for intrinsic global variable", &GV);
654 "wrong type for intrinsic global variable", &GV);
656 "the third field of the element type is mandatory, " 657 "specify i8* null to migrate from the obsoleted 2-field form");
659 Assert(ETy->isPointerTy() &&
660 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
661 "wrong type for intrinsic global variable", &GV);
666 GV.
getName() ==
"llvm.compiler.used")) {
668 "invalid linkage for intrinsic global variable", &GV);
670 if (
ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
672 Assert(PTy,
"wrong type for intrinsic global variable", &GV);
676 Assert(InitArray,
"wrong initalizer for intrinsic global variable",
679 Value *V =
Op->stripPointerCasts();
680 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
682 "invalid llvm.used member", V);
683 Assert(V->
hasName(),
"members of llvm.used must be named", V);
692 for (
auto *MD : MDs) {
693 if (
auto *GVE = dyn_cast<DIGlobalVariableExpression>(MD))
694 visitDIGlobalVariableExpression(*GVE);
696 AssertDI(
false,
"!dbg attachment of global variable must be a " 697 "DIGlobalVariableExpression");
704 if (
auto *VTy = dyn_cast<VectorType>(GV.
getValueType()))
705 Assert(!VTy->isScalable(),
"Globals cannot contain scalable vectors", &GV);
708 visitGlobalValue(GV);
715 visitGlobalValue(GV);
721 visitAliaseeSubExpr(Visited, GA, C);
726 if (
const auto *GV = dyn_cast<GlobalValue>(&C)) {
730 if (
const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
731 Assert(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
733 Assert(!GA2->isInterposable(),
"Alias cannot point to an interposable alias",
742 if (
const auto *CE = dyn_cast<ConstantExpr>(&C))
743 visitConstantExprsRecursively(CE);
747 if (
const auto *GA2 = dyn_cast<GlobalAlias>(V))
748 visitAliaseeSubExpr(Visited, GA, *GA2->
getAliasee());
749 else if (
const auto *C2 = dyn_cast<Constant>(V))
750 visitAliaseeSubExpr(Visited, GA, *C2);
754 void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
756 "Alias should have private, internal, linkonce, weak, linkonce_odr, " 757 "weak_odr, or external linkage!",
760 Assert(Aliasee,
"Aliasee cannot be NULL!", &GA);
762 "Alias and aliasee types should match!", &GA);
764 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
765 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
767 visitAliaseeSubExpr(GA, *Aliasee);
769 visitGlobalValue(GA);
772 void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
777 "unrecognized named metadata node in the llvm.dbg namespace",
780 if (NMD.
getName() ==
"llvm.dbg.cu")
781 AssertDI(MD && isa<DICompileUnit>(MD),
"invalid compile unit", &NMD, MD);
790 void Verifier::visitMDNode(
const MDNode &MD) {
793 if (!MDNodes.insert(&MD).second)
799 case Metadata::MDTupleKind:
801 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \ 802 case Metadata::CLASS##Kind: \ 803 visit##CLASS(cast<CLASS>(MD)); \ 805 #include "llvm/IR/Metadata.def" 811 Assert(!isa<LocalAsMetadata>(
Op),
"Invalid operand for global metadata!",
813 if (
auto *
N = dyn_cast<MDNode>(
Op)) {
817 if (
auto *V = dyn_cast<ValueAsMetadata>(
Op)) {
818 visitValueAsMetadata(*V,
nullptr);
831 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
837 Assert(F,
"function-local metadata used outside a function", L);
842 if (
Instruction *
I = dyn_cast<Instruction>(L->getValue())) {
843 Assert(
I->getParent(),
"function-local metadata not in basic block", L,
I);
844 ActualF =
I->getParent()->getParent();
845 }
else if (
BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
847 else if (
Argument *
A = dyn_cast<Argument>(L->getValue()))
848 ActualF =
A->getParent();
849 assert(ActualF &&
"Unimplemented function local metadata case!");
851 Assert(ActualF == F,
"function-local metadata used in wrong function", L);
856 if (
auto *
N = dyn_cast<MDNode>(MD)) {
863 if (!MDNodes.insert(MD).second)
866 if (
auto *V = dyn_cast<ValueAsMetadata>(MD))
867 visitValueAsMetadata(*V, F);
874 void Verifier::visitDILocation(
const DILocation &
N) {
876 "location requires a valid scope", &N, N.
getRawScope());
878 AssertDI(isa<DILocation>(IA),
"inlined-at should be a location", &
N, IA);
880 AssertDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
887 void Verifier::visitDIScope(
const DIScope &N) {
889 AssertDI(isa<DIFile>(F),
"invalid file", &
N,
F);
892 void Verifier::visitDISubrange(
const DISubrange &N) {
893 AssertDI(N.
getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
895 AssertDI(Count,
"Count must either be a signed constant or a DIVariable",
899 "invalid subrange count", &
N);
902 void Verifier::visitDIEnumerator(
const DIEnumerator &N) {
906 void Verifier::visitDIBasicType(
const DIBasicType &N) {
908 N.
getTag() == dwarf::DW_TAG_unspecified_type,
911 "has conflicting flags", &N);
919 N.
getTag() == dwarf::DW_TAG_pointer_type ||
920 N.
getTag() == dwarf::DW_TAG_ptr_to_member_type ||
921 N.
getTag() == dwarf::DW_TAG_reference_type ||
922 N.
getTag() == dwarf::DW_TAG_rvalue_reference_type ||
923 N.
getTag() == dwarf::DW_TAG_const_type ||
924 N.
getTag() == dwarf::DW_TAG_volatile_type ||
925 N.
getTag() == dwarf::DW_TAG_restrict_type ||
926 N.
getTag() == dwarf::DW_TAG_atomic_type ||
927 N.
getTag() == dwarf::DW_TAG_member ||
928 N.
getTag() == dwarf::DW_TAG_inheritance ||
929 N.
getTag() == dwarf::DW_TAG_friend,
931 if (N.
getTag() == dwarf::DW_TAG_ptr_to_member_type) {
932 AssertDI(
isType(N.getRawExtraData()),
"invalid pointer to member type", &N,
933 N.getRawExtraData());
940 if (N.getDWARFAddressSpace()) {
942 N.
getTag() == dwarf::DW_TAG_reference_type ||
943 N.
getTag() == dwarf::DW_TAG_rvalue_reference_type,
944 "DWARF address space only applies to pointer or reference types",
951 return ((Flags & DINode::FlagLValueReference) &&
952 (Flags & DINode::FlagRValueReference)) ||
953 ((Flags & DINode::FlagTypePassByValue) &&
954 (Flags & DINode::FlagTypePassByReference));
957 void Verifier::visitTemplateParams(
const MDNode &N,
const Metadata &RawParams) {
959 AssertDI(Params,
"invalid template params", &N, &RawParams);
961 AssertDI(
Op && isa<DITemplateParameter>(
Op),
"invalid template parameter",
971 N.
getTag() == dwarf::DW_TAG_structure_type ||
972 N.
getTag() == dwarf::DW_TAG_union_type ||
973 N.
getTag() == dwarf::DW_TAG_enumeration_type ||
974 N.
getTag() == dwarf::DW_TAG_class_type ||
975 N.
getTag() == dwarf::DW_TAG_variant_part,
987 "invalid reference flags", &N);
988 unsigned DIBlockByRefStruct = 1 << 4;
990 "DIBlockByRefStruct on DICompositeType is no longer supported", &N);
995 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
996 "invalid vector, expected one element of type subrange", &
N);
1000 visitTemplateParams(N, *Params);
1002 if (N.
getTag() == dwarf::DW_TAG_class_type ||
1003 N.
getTag() == dwarf::DW_TAG_union_type) {
1005 "class/union requires a filename", &
N, N.
getFile());
1009 AssertDI(isa<DIDerivedType>(
D) && N.
getTag() == dwarf::DW_TAG_variant_part,
1010 "discriminator can only appear on variant part");
1015 AssertDI(N.
getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1017 AssertDI(isa<MDTuple>(Types),
"invalid composite elements", &N, Types);
1019 AssertDI(
isType(Ty),
"invalid subroutine type ref", &N, Types, Ty);
1023 "invalid reference flags", &N);
1026 void Verifier::visitDIFile(
const DIFile &N) {
1030 AssertDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1031 "invalid checksum kind", &N);
1033 switch (Checksum->Kind) {
1041 AssertDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1043 "invalid checksum", &
N);
1049 AssertDI(N.
getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1058 verifySourceDebugInfo(N, *N.
getFile());
1061 "invalid emission kind", &N);
1064 AssertDI(isa<MDTuple>(Array),
"invalid enum list", &N, Array);
1066 auto *Enum = dyn_cast_or_null<DICompositeType>(
Op);
1067 AssertDI(Enum && Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1068 "invalid enum type", &
N, N.getEnumTypes(),
Op);
1072 AssertDI(isa<MDTuple>(Array),
"invalid retained type list", &N, Array);
1075 (isa<DISubprogram>(
Op) &&
1076 !cast<DISubprogram>(
Op)->isDefinition())),
1077 "invalid retained type", &N,
Op);
1081 AssertDI(isa<MDTuple>(Array),
"invalid global variable list", &N, Array);
1084 "invalid global variable ref", &N,
Op);
1088 AssertDI(isa<MDTuple>(Array),
"invalid imported entity list", &N, Array);
1090 AssertDI(
Op && isa<DIImportedEntity>(
Op),
"invalid imported entity ref",
1095 AssertDI(isa<MDTuple>(Array),
"invalid macro list", &N, Array);
1097 AssertDI(
Op && isa<DIMacroNode>(
Op),
"invalid macro ref", &N,
Op);
1100 CUVisited.insert(&N);
1103 void Verifier::visitDISubprogram(
const DISubprogram &N) {
1105 AssertDI(
isScope(N.getRawScope()),
"invalid scope", &N, N.getRawScope());
1107 AssertDI(isa<DIFile>(F),
"invalid file", &
N,
F);
1109 AssertDI(N.getLine() == 0,
"line specified with no file", &
N, N.getLine());
1110 if (
auto *
T = N.getRawType())
1111 AssertDI(isa<DISubroutineType>(
T),
"invalid subroutine type", &
N,
T);
1112 AssertDI(
isType(N.getRawContainingType()),
"invalid containing type", &N,
1113 N.getRawContainingType());
1114 if (
auto *Params = N.getRawTemplateParams())
1115 visitTemplateParams(N, *Params);
1116 if (
auto *S = N.getRawDeclaration())
1117 AssertDI(isa<DISubprogram>(S) && !cast<DISubprogram>(S)->isDefinition(),
1118 "invalid subprogram declaration", &
N, S);
1119 if (
auto *RawNode = N.getRawRetainedNodes()) {
1121 AssertDI(Node,
"invalid retained nodes list", &N, RawNode);
1124 "invalid retained nodes, expected DILocalVariable or DILabel",
1129 "invalid reference flags", &N);
1131 auto *Unit = N.getRawUnit();
1132 if (N.isDefinition()) {
1135 AssertDI(Unit,
"subprogram definitions must have a compile unit", &N);
1136 AssertDI(isa<DICompileUnit>(Unit),
"invalid unit type", &N, Unit);
1138 verifySourceDebugInfo(*N.getUnit(), *N.
getFile());
1141 AssertDI(!Unit,
"subprogram declarations must not have a compile unit", &N);
1144 if (
auto *RawThrownTypes = N.getRawThrownTypes()) {
1146 AssertDI(ThrownTypes,
"invalid thrown types list", &N, RawThrownTypes);
1148 AssertDI(
Op && isa<DIType>(
Op),
"invalid thrown type", &
N, ThrownTypes,
1152 if (N.areAllCallsDescribed())
1154 "DIFlagAllCallsDescribed must be attached to a definition");
1158 AssertDI(N.
getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1162 AssertDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1166 visitDILexicalBlockBase(N);
1169 "cannot have column info without line info", &
N);
1173 visitDILexicalBlockBase(N);
1177 AssertDI(N.
getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1179 AssertDI(isa<DIScope>(S),
"invalid scope ref", &
N, S);
1181 AssertDI(isa<DIGlobalVariable>(S),
"invalid declaration", &
N, S);
1184 void Verifier::visitDINamespace(
const DINamespace &N) {
1187 AssertDI(isa<DIScope>(S),
"invalid scope ref", &
N, S);
1190 void Verifier::visitDIMacro(
const DIMacro &N) {
1193 "invalid macinfo type", &
N);
1200 void Verifier::visitDIMacroFile(
const DIMacroFile &N) {
1202 "invalid macinfo type", &
N);
1204 AssertDI(isa<DIFile>(F),
"invalid file", &
N,
F);
1207 AssertDI(isa<MDTuple>(Array),
"invalid macro list", &N, Array);
1209 AssertDI(
Op && isa<DIMacroNode>(
Op),
"invalid macro ref", &N,
Op);
1214 void Verifier::visitDIModule(
const DIModule &N) {
1224 visitDITemplateParameter(N);
1226 AssertDI(N.
getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1230 void Verifier::visitDITemplateValueParameter(
1232 visitDITemplateParameter(N);
1235 N.
getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1236 N.
getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1240 void Verifier::visitDIVariable(
const DIVariable &N) {
1242 AssertDI(isa<DIScope>(S),
"invalid scope", &
N, S);
1244 AssertDI(isa<DIFile>(F),
"invalid file", &
N,
F);
1255 AssertDI(isa<DIDerivedType>(Member),
1256 "invalid static data member declaration", &N, Member);
1267 "local variable requires a valid scope", &N, N.
getRawScope());
1272 void Verifier::visitDILabel(
const DILabel &N) {
1274 AssertDI(isa<DIScope>(S),
"invalid scope", &
N, S);
1276 AssertDI(isa<DIFile>(F),
"invalid file", &
N,
F);
1280 "label requires a valid scope", &N, N.
getRawScope());
1283 void Verifier::visitDIExpression(
const DIExpression &N) {
1287 void Verifier::visitDIGlobalVariableExpression(
1291 visitDIGlobalVariable(*Var);
1293 visitDIExpression(*Expr);
1294 if (
auto Fragment = Expr->getFragmentInfo())
1295 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1300 AssertDI(N.
getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1304 AssertDI(isa<DIFile>(F),
"invalid file", &
N,
F);
1309 N.
getTag() == dwarf::DW_TAG_imported_declaration,
1312 AssertDI(isa<DIScope>(S),
"invalid scope for imported entity", &
N, S);
1317 void Verifier::visitComdat(
const Comdat &C) {
1323 "comdat global value has private linkage", GV);
1326 void Verifier::visitModuleIdents(
const Module &
M) {
1335 "incorrect number of operands in llvm.ident metadata",
N);
1337 (
"invalid value for llvm.ident metadata entry operand" 1338 "(the operand should be a string)"),
1343 void Verifier::visitModuleCommandLines(
const Module &M) {
1353 "incorrect number of operands in llvm.commandline metadata",
N);
1355 (
"invalid value for llvm.commandline metadata entry operand" 1356 "(the operand should be a string)"),
1361 void Verifier::visitModuleFlags(
const Module &M) {
1369 visitModuleFlag(MDN, SeenIDs, Requirements);
1372 for (
const MDNode *Requirement : Requirements) {
1373 const MDString *
Flag = cast<MDString>(Requirement->getOperand(0));
1374 const Metadata *ReqValue = Requirement->getOperand(1);
1378 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1385 "flag does not have the required value"),
1393 Verifier::visitModuleFlag(
const MDNode *
Op,
1399 "incorrect number of operands in module flag",
Op);
1403 mdconst::dyn_extract_or_null<ConstantInt>(Op->
getOperand(0)),
1404 "invalid behavior operand in module flag (expected constant integer)",
1407 "invalid behavior operand in module flag (unexpected constant)",
1411 Assert(ID,
"invalid ID operand in module flag (expected metadata string)",
1424 "invalid value for 'max' module flag (expected constant integer)",
1434 "invalid value for 'require' module flag (expected metadata pair)",
1437 (
"invalid value for 'require' module flag " 1438 "(first value operand should be a string)"),
1451 "invalid value for 'append'-type module flag " 1452 "(expected a metadata node)",
1460 bool Inserted = SeenIDs.
insert(std::make_pair(ID, Op)).second;
1462 "module flag identifiers must be unique (or of 'require' type)", ID);
1465 if (ID->getString() ==
"wchar_size") {
1467 = mdconst::dyn_extract_or_null<ConstantInt>(Op->
getOperand(2));
1468 Assert(Value,
"wchar_size metadata requires constant integer argument");
1471 if (ID->getString() ==
"Linker Options") {
1476 "'Linker Options' named metadata no longer supported");
1479 if (ID->getString() ==
"CG Profile") {
1481 visitModuleFlagCGProfileEntry(MDO);
1485 void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
1486 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
1490 Assert(F && isa<Function>(F->getValue()),
"expected a Function or null",
1493 auto Node = dyn_cast_or_null<MDNode>(MDO);
1494 Assert(Node && Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
1495 CheckFunction(Node->getOperand(0));
1496 CheckFunction(Node->getOperand(1));
1497 auto Count = dyn_cast_or_null<ConstantAsMetadata>(Node->getOperand(2));
1498 Assert(Count && Count->getType()->isIntegerTy(),
1499 "expected an integer constant", Node->getOperand(2));
1505 case Attribute::NoReturn:
1506 case Attribute::NoSync:
1507 case Attribute::WillReturn:
1508 case Attribute::NoCfCheck:
1509 case Attribute::NoUnwind:
1510 case Attribute::NoInline:
1511 case Attribute::AlwaysInline:
1512 case Attribute::OptimizeForSize:
1513 case Attribute::StackProtect:
1514 case Attribute::StackProtectReq:
1515 case Attribute::StackProtectStrong:
1516 case Attribute::SafeStack:
1517 case Attribute::ShadowCallStack:
1518 case Attribute::NoRedZone:
1519 case Attribute::NoImplicitFloat:
1520 case Attribute::Naked:
1521 case Attribute::InlineHint:
1522 case Attribute::StackAlignment:
1523 case Attribute::UWTable:
1524 case Attribute::NonLazyBind:
1525 case Attribute::ReturnsTwice:
1526 case Attribute::SanitizeAddress:
1527 case Attribute::SanitizeHWAddress:
1528 case Attribute::SanitizeMemTag:
1529 case Attribute::SanitizeThread:
1530 case Attribute::SanitizeMemory:
1531 case Attribute::MinSize:
1532 case Attribute::NoDuplicate:
1533 case Attribute::Builtin:
1534 case Attribute::NoBuiltin:
1536 case Attribute::OptForFuzzing:
1537 case Attribute::OptimizeNone:
1540 case Attribute::ArgMemOnly:
1541 case Attribute::NoRecurse:
1542 case Attribute::InaccessibleMemOnly:
1543 case Attribute::InaccessibleMemOrArgMemOnly:
1544 case Attribute::AllocSize:
1545 case Attribute::SpeculativeLoadHardening:
1546 case Attribute::Speculatable:
1547 case Attribute::StrictFP:
1558 return Kind == Attribute::ReadOnly || Kind == Attribute::WriteOnly ||
1559 Kind == Attribute::ReadNone || Kind == Attribute::NoFree;
1565 if (
A.isStringAttribute())
1571 "' only applies to functions!",
1577 "' does not apply to functions!",
1591 verifyAttributeTypes(Attrs,
false, V);
1595 "Attribute 'immarg' is incompatible with other attributes", V);
1600 unsigned AttrCount = 0;
1603 AttrCount += Attrs.
hasAttribute(Attribute::StructRet) ||
1606 Assert(AttrCount <= 1,
"Attributes 'byval', 'inalloca', 'inreg', 'nest', " 1607 "and 'sret' are incompatible!",
1613 "'inalloca and readonly' are incompatible!",
1619 "'sret and returned' are incompatible!",
1625 "'zeroext and signext' are incompatible!",
1631 "'readnone and readonly' are incompatible!",
1637 "'readnone and writeonly' are incompatible!",
1643 "'readonly and writeonly' are incompatible!",
1649 "'noinline and alwaysinline' are incompatible!",
1654 "Attribute 'byval' type does not match parameter!", V);
1659 "Wrong types for attribute: " +
1663 if (
PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1665 if (!PTy->getElementType()->isSized(&Visited)) {
1668 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1671 if (!isa<PointerType>(PTy->getElementType()))
1673 "Attribute 'swifterror' only applies to parameters " 1674 "with pointer to pointer type!",
1678 "Attribute 'byval' only applies to parameters with pointer type!",
1681 "Attribute 'swifterror' only applies to parameters " 1682 "with pointer type!",
1690 const Value *V,
bool IsIntrinsic) {
1694 bool SawNest =
false;
1695 bool SawReturned =
false;
1696 bool SawSRet =
false;
1697 bool SawSwiftSelf =
false;
1698 bool SawSwiftError =
false;
1711 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', 'nofree'" 1712 "'returned', 'swiftself', and 'swifterror' do not apply to return " 1719 "' does not apply to function returns",
1730 "immarg attribute only applies to intrinsics",V);
1733 verifyParameterAttrs(ArgAttrs, Ty, V);
1736 Assert(!SawNest,
"More than one parameter has attribute nest!", V);
1741 Assert(!SawReturned,
"More than one parameter has attribute returned!",
1744 "Incompatible argument and return types for 'returned' attribute",
1750 Assert(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
1752 "Attribute 'sret' is not on first or second parameter!", V);
1757 Assert(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
1758 SawSwiftSelf =
true;
1762 Assert(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!",
1764 SawSwiftError =
true;
1769 "inalloca isn't on the last parameter!", V);
1780 "Attributes 'readnone and readonly' are incompatible!", V);
1784 "Attributes 'readnone and writeonly' are incompatible!", V);
1788 "Attributes 'readonly and writeonly' are incompatible!", V);
1792 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are " 1798 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V);
1802 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1806 "Attribute 'optnone' requires 'noinline'!", V);
1809 "Attributes 'optsize and optnone' are incompatible!", V);
1812 "Attributes 'minsize and optnone' are incompatible!", V);
1818 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1822 std::pair<unsigned, Optional<unsigned>>
Args =
1827 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds", V);
1833 " argument must refer to an integer parameter",
1841 if (!CheckParam(
"element size", Args.first))
1844 if (Args.second && !CheckParam(
"number of elements", *Args.second))
1851 if (FP !=
"all" && FP !=
"non-leaf" && FP !=
"none")
1852 CheckFailed(
"invalid value for 'frame-pointer' attribute: " + FP, V);
1858 "patchable-function-prefix")
1863 "\"patchable-function-prefix\" takes an unsigned integer: " + S, V);
1868 "patchable-function-entry")
1873 "\"patchable-function-entry\" takes an unsigned integer: " + S, V);
1877 void Verifier::verifyFunctionMetadata(
1878 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
1879 for (
const auto &Pair : MDs) {
1880 if (Pair.first == LLVMContext::MD_prof) {
1881 MDNode *MD = Pair.second;
1883 "!prof annotations should have no less than 2 operands", MD);
1889 "expected string with name of the !prof annotation", MD);
1892 Assert(ProfName.equals(
"function_entry_count") ||
1893 ProfName.equals(
"synthetic_function_entry_count"),
1894 "first operand should be 'function_entry_count'" 1895 " or 'synthetic_function_entry_count'",
1902 "expected integer argument to function_entry_count", MD);
1907 void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
1908 if (!ConstantExprVisited.insert(EntryC).second)
1914 while (!Stack.
empty()) {
1918 if (
const auto *CE = dyn_cast<ConstantExpr>(C))
1919 visitConstantExpr(CE);
1921 if (
const auto *GV = dyn_cast<GlobalValue>(C)) {
1934 if (!ConstantExprVisited.insert(OpC).second)
1941 void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
1942 if (CE->
getOpcode() == Instruction::BitCast)
1945 "Invalid bitcast", CE);
1947 if (CE->
getOpcode() == Instruction::IntToPtr ||
1948 CE->
getOpcode() == Instruction::PtrToInt) {
1949 auto *PtrTy = CE->
getOpcode() == Instruction::IntToPtr
1953 ?
"inttoptr not supported for non-integral pointers" 1954 :
"ptrtoint not supported for non-integral pointers";
1961 bool Verifier::verifyAttributeCount(
AttributeList Attrs,
unsigned Params) {
1968 void Verifier::verifyStatepoint(
const CallBase &
Call) {
1971 Intrinsic::experimental_gc_statepoint);
1975 "gc.statepoint must read and write all memory to preserve " 1976 "reordering restrictions required by safepoint semantics",
1979 const int64_t NumPatchBytes =
1982 Assert(NumPatchBytes >= 0,
1983 "gc.statepoint number of patchable bytes must be " 1989 Assert(PT && PT->getElementType()->isFunctionTy(),
1990 "gc.statepoint callee must be of function pointer type",
Call, Target);
1991 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1993 const int NumCallArgs = cast<ConstantInt>(Call.
getArgOperand(3))->getZExtValue();
1995 "gc.statepoint number of arguments to underlying call " 1998 const int NumParams = (int)TargetFuncType->getNumParams();
1999 if (TargetFuncType->isVarArg()) {
2000 Assert(NumCallArgs >= NumParams,
2001 "gc.statepoint mismatch in number of vararg call args", Call);
2004 Assert(TargetFuncType->getReturnType()->isVoidTy(),
2005 "gc.statepoint doesn't support wrapping non-void " 2006 "vararg functions yet",
2009 Assert(NumCallArgs == NumParams,
2010 "gc.statepoint mismatch in number of call args", Call);
2012 const uint64_t Flags
2015 "unknown flag used in gc.statepoint flags argument", Call);
2020 for (
int i = 0; i < NumParams; i++) {
2021 Type *ParamType = TargetFuncType->getParamType(i);
2023 Assert(ArgType == ParamType,
2024 "gc.statepoint call argument does not match wrapped " 2028 if (TargetFuncType->isVarArg()) {
2031 "Attribute 'sret' cannot be used for vararg call arguments!",
2036 const int EndCallArgsInx = 4 + NumCallArgs;
2039 Assert(isa<ConstantInt>(NumTransitionArgsV),
2040 "gc.statepoint number of transition arguments " 2041 "must be constant integer",
2043 const int NumTransitionArgs =
2044 cast<ConstantInt>(NumTransitionArgsV)->getZExtValue();
2045 Assert(NumTransitionArgs >= 0,
2046 "gc.statepoint number of transition arguments must be positive", Call);
2047 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2050 Assert(isa<ConstantInt>(NumDeoptArgsV),
2051 "gc.statepoint number of deoptimization arguments " 2052 "must be constant integer",
2054 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
2055 Assert(NumDeoptArgs >= 0,
2056 "gc.statepoint number of deoptimization arguments " 2060 const int ExpectedNumArgs =
2061 7 + NumCallArgs + NumTransitionArgs + NumDeoptArgs;
2063 "gc.statepoint too few arguments according to length fields",
Call);
2068 for (
const User *U : Call.
users()) {
2070 Assert(UserCall,
"illegal use of statepoint token", Call, U);
2073 Assert(isa<GCRelocateInst>(UserCall) || isa<GCResultInst>(UserCall),
2074 "gc.result or gc.relocate are the only value uses " 2075 "of a gc.statepoint",
2077 if (isa<GCResultInst>(UserCall)) {
2079 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
2080 }
else if (isa<GCRelocateInst>(Call)) {
2082 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
2096 void Verifier::verifyFrameRecoverIndices() {
2097 for (
auto &Counts : FrameEscapeInfo) {
2099 unsigned EscapedObjectCount = Counts.second.first;
2100 unsigned MaxRecoveredIndex = Counts.second.second;
2101 Assert(MaxRecoveredIndex <= EscapedObjectCount,
2102 "all indices passed to llvm.localrecover must be less than the " 2103 "number of arguments passed to llvm.localescape in the parent " 2111 if (
auto *II = dyn_cast<InvokeInst>(Terminator))
2112 UnwindDest = II->getUnwindDest();
2113 else if (
auto *CSI = dyn_cast<CatchSwitchInst>(Terminator))
2114 UnwindDest = CSI->getUnwindDest();
2116 UnwindDest = cast<CleanupReturnInst>(
Terminator)->getUnwindDest();
2120 void Verifier::verifySiblingFuncletUnwinds() {
2123 for (
const auto &Pair : SiblingFuncletInfo) {
2125 if (Visited.
count(PredPad))
2131 if (Active.
count(SuccPad)) {
2137 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2138 if (CycleTerminator != CyclePad)
2141 }
while (CyclePad != SuccPad);
2142 Assert(
false,
"EH pads can't handle each other's exceptions",
2146 if (!Visited.
insert(SuccPad).second)
2150 auto TermI = SiblingFuncletInfo.find(PredPad);
2151 if (TermI == SiblingFuncletInfo.end())
2153 Terminator = TermI->second;
2164 void Verifier::visitFunction(
const Function &F) {
2165 visitGlobalValue(F);
2172 "Function context does not match Module context!", &
F);
2176 "# formal arguments must match # of arguments for function type!", &
F,
2178 Assert(F.getReturnType()->isFirstClassType() ||
2179 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
2180 "Functions cannot return aggregate values!", &
F);
2182 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
2183 "Invalid struct return type!", &
F);
2188 "Attribute after last parameter!", &F);
2190 bool isLLVMdotName = F.getName().size() >= 5 &&
2191 F.getName().substr(0, 5) ==
"llvm.";
2194 verifyFunctionAttrs(FT, Attrs, &F, isLLVMdotName);
2199 Assert(!Attrs.hasFnAttribute(Attribute::Builtin),
2200 "Attribute 'builtin' can only be applied to a callsite.", &
F);
2205 switch (F.getCallingConv()) {
2211 Assert(F.getReturnType()->isVoidTy(),
2212 "Calling convention requires void return type", &
F);
2219 Assert(!F.hasStructRetAttr(),
2220 "Calling convention does not allow sret", &
F);
2227 Assert(!F.isVarArg(),
"Calling convention does not support varargs or " 2228 "perfect forwarding!",
2237 "Argument value does not match function argument type!", &
Arg,
2239 Assert(
Arg.getType()->isFirstClassType(),
2240 "Function arguments must have first-class types!", &
Arg);
2241 if (!isLLVMdotName) {
2243 "Function takes metadata but isn't an intrinsic", &
Arg, &
F);
2245 "Function takes token but isn't an intrinsic", &
Arg, &
F);
2249 if (Attrs.hasParamAttribute(i, Attribute::SwiftError)) {
2250 verifySwiftErrorValue(&
Arg);
2256 Assert(!F.getReturnType()->isTokenTy(),
2257 "Functions returns a token but isn't an intrinsic", &
F);
2261 F.getAllMetadata(MDs);
2262 assert(F.hasMetadata() != MDs.empty() &&
"Bit out-of-sync");
2263 verifyFunctionMetadata(MDs);
2266 if (F.hasPersonalityFn()) {
2269 Assert(Per->getParent() == F.getParent(),
2270 "Referencing personality function in another module!",
2271 &
F, F.getParent(), Per, Per->getParent());
2274 if (F.isMaterializable()) {
2276 Assert(MDs.empty(),
"unmaterialized function cannot have metadata", &
F,
2277 MDs.empty() ? nullptr : MDs.front().second);
2278 }
else if (F.isDeclaration()) {
2279 for (
const auto &
I : MDs) {
2281 AssertDI(
I.first != LLVMContext::MD_dbg ||
2282 !cast<DISubprogram>(
I.second)->isDistinct(),
2283 "function declaration may only have a unique !dbg attachment",
2285 Assert(
I.first != LLVMContext::MD_prof,
2286 "function declaration may not have a !prof attachment", &F);
2289 visitMDNode(*
I.second);
2291 Assert(!F.hasPersonalityFn(),
2292 "Function declaration shouldn't have a personality routine", &
F);
2296 Assert(!isLLVMdotName,
"llvm intrinsics cannot be defined!", &F);
2301 "Entry block to function must not have predecessors!", Entry);
2306 "blockaddress may not be used with the entry block!", Entry);
2309 unsigned NumDebugAttachments = 0, NumProfAttachments = 0;
2311 for (
const auto &
I : MDs) {
2316 case LLVMContext::MD_dbg: {
2317 ++NumDebugAttachments;
2319 "function must have a single !dbg attachment", &F,
I.second);
2321 "function !dbg attachment must be a subprogram", &F,
I.second);
2322 auto *
SP = cast<DISubprogram>(
I.second);
2323 const Function *&AttachedTo = DISubprogramAttachments[
SP];
2324 AssertDI(!AttachedTo || AttachedTo == &F,
2325 "DISubprogram attached to more than one function",
SP, &F);
2329 case LLVMContext::MD_prof:
2330 ++NumProfAttachments;
2331 Assert(NumProfAttachments == 1,
2332 "function must have a single !prof attachment", &F,
I.second);
2337 visitMDNode(*
I.second);
2345 if (F.getIntrinsicID() && F.getParent()->isMaterialized()) {
2347 if (F.hasAddressTaken(&U))
2348 Assert(
false,
"Invalid user of intrinsic instruction!", U);
2351 auto *N = F.getSubprogram();
2352 HasDebugInfo = (N !=
nullptr);
2365 const DILocation *
DL = dyn_cast_or_null<DILocation>(Node);
2368 if (!Seen.
insert(DL).second)
2372 AssertDI(Parent && isa<DILocalScope>(Parent),
2373 "DILocation's scope must be a DILocalScope", N, &F, &I, DL,
2376 if (Scope && !Seen.
insert(Scope).second)
2383 if (SP && ((Scope != SP) && !Seen.
insert(SP).second))
2388 "!dbg attachment points at wrong subprogram for function",
N, &
F,
2392 for (
auto &I : BB) {
2395 if (
auto MD = I.
getMetadata(LLVMContext::MD_loop))
2396 for (
unsigned i = 1; i < MD->getNumOperands(); ++i)
2397 VisitDebugLoc(I, dyn_cast_or_null<MDNode>(MD->getOperand(i)));
2405 void Verifier::visitBasicBlock(
BasicBlock &BB) {
2406 InstsInThisBlock.clear();
2413 if (isa<PHINode>(BB.
front())) {
2419 Assert(PN.getNumIncomingValues() != 0,
2420 "PHI nodes must have at least one entry. If the block is dead, " 2421 "the PHI should be removed!",
2423 Assert(PN.getNumIncomingValues() == Preds.
size(),
2424 "PHINode should have one entry for each predecessor of its " 2425 "parent basic block!",
2430 Values.
reserve(PN.getNumIncomingValues());
2431 for (
unsigned i = 0,
e = PN.getNumIncomingValues(); i !=
e; ++i)
2433 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
2436 for (
unsigned i = 0,
e = Values.
size(); i !=
e; ++i) {
2443 "PHI node has multiple entries for the same basic block with " 2444 "different incoming values!",
2445 &PN, Values[i].
first, Values[i].
second, Values[i - 1].second);
2449 Assert(Values[i].first == Preds[i],
2450 "PHI node entries do not match predecessors!", &PN,
2451 Values[i].first, Preds[i]);
2459 Assert(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
2466 "Terminator found in the middle of a basic block!", I.
getParent());
2467 visitInstruction(I);
2470 void Verifier::visitBranchInst(
BranchInst &BI) {
2473 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
2475 visitTerminator(BI);
2478 void Verifier::visitReturnInst(
ReturnInst &RI) {
2483 "Found return instr that returns non-void in Function of void " 2488 "Function return type does not match operand " 2489 "type of return inst!",
2494 visitTerminator(RI);
2502 for (
auto &Case : SI.
cases()) {
2503 Assert(Case.getCaseValue()->getType() == SwitchTy,
2504 "Switch constants must all be same type as switch value!", &
SI);
2506 "Duplicate integer as switch case", &SI, Case.getCaseValue());
2509 visitTerminator(SI);
2514 "Indirectbr operand must have pointer type!", &BI);
2517 "Indirectbr destinations must all have pointer type!", &BI);
2519 visitTerminator(BI);
2522 void Verifier::visitCallBrInst(
CallBrInst &CBI) {
2529 "Callbr successors must all have pointer type!", &CBI);
2532 "Using an unescaped label as a callbr argument!", &CBI);
2534 for (
unsigned j = i + 1; j !=
e; ++j)
2536 "Duplicate callbr destination!", &CBI);
2541 if (
auto *BA = dyn_cast<BlockAddress>(V))
2542 ArgBBs.
insert(BA->getBasicBlock());
2545 "Indirect label missing from arglist.", &CBI);
2548 visitTerminator(CBI);
2551 void Verifier::visitSelectInst(
SelectInst &SI) {
2554 "Invalid operands for select instruction!", &SI);
2557 "Select values must have same type as select instruction!", &
SI);
2558 visitInstruction(SI);
2565 Assert(
false,
"User-defined operators should not live outside of a pass!", &I);
2568 void Verifier::visitTruncInst(
TruncInst &I) {
2580 "trunc source and destination must both be a vector or neither", &
I);
2581 Assert(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &I);
2583 visitInstruction(I);
2586 void Verifier::visitZExtInst(
ZExtInst &I) {
2595 "zext source and destination must both be a vector or neither", &
I);
2599 Assert(SrcBitSize < DestBitSize,
"Type too small for ZExt", &I);
2601 visitInstruction(I);
2604 void Verifier::visitSExtInst(
SExtInst &I) {
2616 "sext source and destination must both be a vector or neither", &
I);
2617 Assert(SrcBitSize < DestBitSize,
"Type too small for SExt", &I);
2619 visitInstruction(I);
2633 "fptrunc source and destination must both be a vector or neither", &
I);
2634 Assert(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &I);
2636 visitInstruction(I);
2639 void Verifier::visitFPExtInst(
FPExtInst &I) {
2651 "fpext source and destination must both be a vector or neither", &
I);
2652 Assert(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &I);
2654 visitInstruction(I);
2657 void Verifier::visitUIToFPInst(
UIToFPInst &I) {
2666 "UIToFP source and dest must both be vector or scalar", &I);
2668 "UIToFP source must be integer or integer vector", &
I);
2672 if (SrcVec && DstVec)
2673 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2674 cast<VectorType>(DestTy)->getNumElements(),
2675 "UIToFP source and dest vector length mismatch", &I);
2677 visitInstruction(I);
2680 void Verifier::visitSIToFPInst(
SIToFPInst &I) {
2689 "SIToFP source and dest must both be vector or scalar", &I);
2691 "SIToFP source must be integer or integer vector", &
I);
2695 if (SrcVec && DstVec)
2696 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2697 cast<VectorType>(DestTy)->getNumElements(),
2698 "SIToFP source and dest vector length mismatch", &I);
2700 visitInstruction(I);
2703 void Verifier::visitFPToUIInst(
FPToUIInst &I) {
2712 "FPToUI source and dest must both be vector or scalar", &I);
2716 "FPToUI result must be integer or integer vector", &
I);
2718 if (SrcVec && DstVec)
2719 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2720 cast<VectorType>(DestTy)->getNumElements(),
2721 "FPToUI source and dest vector length mismatch", &I);
2723 visitInstruction(I);
2726 void Verifier::visitFPToSIInst(
FPToSIInst &I) {
2735 "FPToSI source and dest must both be vector or scalar", &I);
2739 "FPToSI result must be integer or integer vector", &
I);
2741 if (SrcVec && DstVec)
2742 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
2743 cast<VectorType>(DestTy)->getNumElements(),
2744 "FPToSI source and dest vector length mismatch", &I);
2746 visitInstruction(I);
2756 if (
auto *PTy = dyn_cast<PointerType>(SrcTy->
getScalarType()))
2758 "ptrtoint not supported for non-integral pointers");
2766 VectorType *VDest = cast<VectorType>(DestTy);
2768 "PtrToInt Vector width mismatch", &
I);
2771 visitInstruction(I);
2780 "IntToPtr source must be an integral", &
I);
2783 if (
auto *PTy = dyn_cast<PointerType>(DestTy->
getScalarType()))
2785 "inttoptr not supported for non-integral pointers");
2791 VectorType *VDest = cast<VectorType>(DestTy);
2793 "IntToPtr Vector width mismatch", &
I);
2795 visitInstruction(I);
2801 "Invalid bitcast", &I);
2802 visitInstruction(I);
2814 "AddrSpaceCast must be between different address spaces", &
I);
2817 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
2818 visitInstruction(I);
2823 void Verifier::visitPHINode(
PHINode &PN) {
2830 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
2839 "PHI node operands are not the same type as the result!", &PN);
2844 visitInstruction(PN);
2847 void Verifier::visitCallBase(
CallBase &Call) {
2849 "Called function must be a pointer!",
Call);
2852 Assert(FPTy->getElementType()->isFunctionTy(),
2853 "Called function is not pointer to function type!",
Call);
2856 "Called function is not the same type as the call!",
Call);
2861 if (FTy->isVarArg())
2863 "Called function requires more parameters than were provided!",
2867 "Incorrect number of arguments passed to called function!",
Call);
2870 for (
unsigned i = 0,
e = FTy->getNumParams(); i !=
e; ++i)
2872 "Call parameter type does not match function signature!",
2878 "Attribute after last parameter!", Call);
2890 "speculatable attribute may not apply to call sites",
Call);
2894 verifyFunctionAttrs(FTy, Attrs, &Call, IsIntrinsic);
2902 Assert(AI->isUsedWithInAlloca(),
2903 "inalloca argument for call has mismatched alloca", AI,
Call);
2909 for (
unsigned i = 0,
e = FTy->getNumParams(); i !=
e; ++i) {
2913 Assert(AI->isSwiftError(),
2914 "swifterror argument for call has mismatched alloca", AI,
Call);
2919 "swifterror argument should come from an alloca or parameter",
2920 SwiftErrorArg, Call);
2921 Assert(ArgI->hasSwiftErrorAttr(),
2922 "swifterror argument for call has mismatched parameter", ArgI,
2930 "immarg may not apply only to call sites",
2936 Assert(isa<ConstantInt>(ArgVal) || isa<ConstantFP>(ArgVal),
2937 "immarg operand has non-immediate parameter", ArgVal, Call);
2941 if (FTy->isVarArg()) {
2943 bool SawNest =
false;
2944 bool SawReturned =
false;
2946 for (
unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
2954 for (
unsigned Idx = FTy->getNumParams(); Idx < Call.
arg_size(); ++Idx) {
2957 verifyParameterAttrs(ArgAttrs, Ty, &Call);
2960 Assert(!SawNest,
"More than one parameter has attribute nest!", Call);
2965 Assert(!SawReturned,
"More than one parameter has attribute returned!",
2968 "Incompatible argument and return types for 'returned' " 2978 Intrinsic::experimental_gc_statepoint)
2980 "Attribute 'sret' cannot be used for vararg call arguments!",
2985 "inalloca isn't on the last argument!",
Call);
2991 for (
Type *ParamTy : FTy->params()) {
2992 Assert(!ParamTy->isMetadataTy(),
2993 "Function has metadata parameter but isn't an intrinsic",
Call);
2994 Assert(!ParamTy->isTokenTy(),
2995 "Function has token parameter but isn't an intrinsic",
Call);
3001 Assert(!FTy->getReturnType()->isTokenTy(),
3002 "Return type cannot be token for indirect call!");
3006 visitIntrinsicCall(
ID, Call);
3010 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
3011 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false;
3016 Assert(!FoundDeoptBundle,
"Multiple deopt operand bundles", Call);
3017 FoundDeoptBundle =
true;
3019 Assert(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
3021 FoundGCTransitionBundle =
true;
3023 Assert(!FoundFuncletBundle,
"Multiple funclet operand bundles", Call);
3024 FoundFuncletBundle =
true;
3026 "Expected exactly one funclet bundle operand",
Call);
3028 "Funclet bundle operands should correspond to a FuncletPadInst",
3031 Assert(!FoundCFGuardTargetBundle,
3032 "Multiple CFGuardTarget operand bundles", Call);
3033 FoundCFGuardTargetBundle =
true;
3035 "Expected exactly one cfguardtarget bundle operand",
Call);
3045 "inlinable function call in a function with " 3046 "debug info must have a !dbg location",
3049 visitInstruction(Call);
3066 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
3067 Attribute::InReg, Attribute::Returned, Attribute::SwiftSelf,
3068 Attribute::SwiftError};
3070 for (
auto AK : ABIAttrs) {
3079 void Verifier::verifyMustTailCall(
CallInst &CI) {
3090 "cannot guarantee tail call due to mismatched parameter counts",
3095 "cannot guarantee tail call due to mismatched parameter types", &CI);
3099 "cannot guarantee tail call due to mismatched varargs", &CI);
3101 "cannot guarantee tail call due to mismatched return types", &CI);
3105 "cannot guarantee tail call due to mismatched calling conv", &CI);
3114 Assert(CallerABIAttrs == CalleeABIAttrs,
3115 "cannot guarantee tail call due to mismatched ABI impacting " 3116 "function attributes",
3124 Value *RetVal = &CI;
3128 if (
BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
3130 "bitcast following musttail call must use the call", BI);
3137 Assert(Ret,
"musttail call must precede a ret with an optional bitcast",
3140 "musttail call result must be returned",
Ret);
3143 void Verifier::visitCallInst(
CallInst &CI) {
3147 verifyMustTailCall(CI);
3150 void Verifier::visitInvokeInst(
InvokeInst &II) {
3157 "The unwind destination does not have an exception handling instruction!",
3160 visitTerminator(II);
3167 "Unary operators must have same type for" 3168 "operands and result!",
3174 case Instruction::FNeg:
3176 "FNeg operator only works with float types!", &U);
3182 visitInstruction(U);
3190 "Both operands to a binary operator are not of the same type!", &
B);
3196 case Instruction::Sub:
3197 case Instruction::Mul:
3198 case Instruction::SDiv:
3199 case Instruction::UDiv:
3200 case Instruction::SRem:
3201 case Instruction::URem:
3203 "Integer arithmetic operators only work with integral types!", &
B);
3205 "Integer arithmetic operators must have same type " 3206 "for operands and result!",
3211 case Instruction::FAdd:
3212 case Instruction::FSub:
3213 case Instruction::FMul:
3214 case Instruction::FDiv:
3215 case Instruction::FRem:
3217 "Floating-point arithmetic operators only work with " 3218 "floating-point types!",
3221 "Floating-point arithmetic operators must have same type " 3222 "for operands and result!",
3226 case Instruction::And:
3227 case Instruction::Or:
3228 case Instruction::Xor:
3230 "Logical operators only work with integral types!", &
B);
3232 "Logical operators must have same type for operands and result!",
3235 case Instruction::Shl:
3236 case Instruction::LShr:
3237 case Instruction::AShr:
3239 "Shifts only work with integral types!", &
B);
3241 "Shift return type must be same as operands!", &
B);
3247 visitInstruction(B);
3250 void Verifier::visitICmpInst(
ICmpInst &IC) {
3255 "Both operands to ICmp instruction are not of the same type!", &IC);
3258 "Invalid operand types for ICmp instruction", &IC);
3261 "Invalid predicate in ICmp instruction!", &IC);
3263 visitInstruction(IC);
3271 "Both operands to FCmp instruction are not of the same type!", &FC);
3274 "Invalid operand types for FCmp instruction", &
FC);
3277 "Invalid predicate in FCmp instruction!", &
FC);
3279 visitInstruction(FC);
3285 "Invalid extractelement operands!", &EI);
3286 visitInstruction(EI);
3292 "Invalid insertelement operands!", &IE);
3293 visitInstruction(IE);
3299 "Invalid shufflevector operands!", &SV);
3300 visitInstruction(SV);
3306 Assert(isa<PointerType>(TargetTy),
3307 "GEP base pointer is not a vector or a vector of pointers", &GEP);
3313 "GEP indexes must be integers", &GEP);
3316 Assert(ElTy,
"Invalid indices for GEP pointer type!", &GEP);
3320 "GEP is not of right type for indices!", &
GEP, ElTy);
3322 if (GEP.getType()->isVectorTy()) {
3324 unsigned GEPWidth = GEP.getType()->getVectorNumElements();
3325 if (GEP.getPointerOperandType()->isVectorTy())
3326 Assert(GEPWidth == GEP.getPointerOperandType()->getVectorNumElements(),
3327 "Vector GEP result width doesn't match operand's", &
GEP);
3328 for (
Value *Idx : Idxs) {
3329 Type *IndexTy = Idx->getType();
3332 Assert(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &GEP);
3335 "All GEP indices should be of integer type");
3339 if (
auto *PTy = dyn_cast<PointerType>(GEP.getType())) {
3340 Assert(GEP.getAddressSpace() == PTy->getAddressSpace(),
3341 "GEP address space doesn't match type", &
GEP);
3344 visitInstruction(GEP);
3353 "precondition violation");
3356 Assert(NumOperands % 2 == 0,
"Unfinished range!", Range);
3357 unsigned NumRanges = NumOperands / 2;
3358 Assert(NumRanges >= 1,
"It should have at least one range!", Range);
3361 for (
unsigned i = 0; i < NumRanges; ++i) {
3363 mdconst::dyn_extract<ConstantInt>(Range->
getOperand(2 * i));
3364 Assert(Low,
"The lower limit must be an integer!", Low);
3366 mdconst::dyn_extract<ConstantInt>(Range->
getOperand(2 * i + 1));
3367 Assert(High,
"The upper limit must be an integer!", High);
3369 "Range types must match instruction type!", &
I);
3375 "Range must not be empty!", Range);
3378 "Intervals are overlapping", Range);
3386 if (NumRanges > 2) {
3388 mdconst::dyn_extract<ConstantInt>(Range->
getOperand(0))->getValue();
3390 mdconst::dyn_extract<ConstantInt>(Range->
getOperand(1))->getValue();
3393 "Intervals are overlapping", Range);
3399 void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *I) {
3401 Assert(Size >= 8,
"atomic memory access' size must be byte-sized", Ty, I);
3402 Assert(!(Size & (Size - 1)),
3403 "atomic memory access' operand must have a power-of-two size", Ty, I);
3406 void Verifier::visitLoadInst(
LoadInst &LI) {
3408 Assert(PTy,
"Load operand must be a pointer.", &LI);
3411 "huge alignment values are unsupported", &LI);
3412 Assert(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
3416 "Load cannot have Release ordering", &LI);
3418 "Atomic load must specify explicit alignment", &LI);
3420 "atomic load operand must have integer, pointer, or floating point " 3423 checkAtomicMemAccessSize(ElTy, &LI);
3426 "Non-atomic load cannot have SynchronizationScope specified", &LI);
3429 visitInstruction(LI);
3432 void Verifier::visitStoreInst(
StoreInst &SI) {
3434 Assert(PTy,
"Store operand must be a pointer.", &SI);
3437 "Stored value type does not match pointer operand type!", &
SI, ElTy);
3439 "huge alignment values are unsupported", &
SI);
3444 "Store cannot have Acquire ordering", &
SI);
3446 "Atomic store must specify explicit alignment", &
SI);
3448 "atomic store operand must have integer, pointer, or floating point " 3451 checkAtomicMemAccessSize(ElTy, &SI);
3454 "Non-atomic store cannot have SynchronizationScope specified", &
SI);
3456 visitInstruction(SI);
3460 void Verifier::verifySwiftErrorCall(
CallBase &Call,
3461 const Value *SwiftErrorVal) {
3464 if (*I == SwiftErrorVal) {
3466 "swifterror value when used in a callsite should be marked " 3467 "with swifterror attribute",
3468 SwiftErrorVal,
Call);
3473 void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
3476 for (
const User *U : SwiftErrorVal->
users()) {
3477 Assert(isa<LoadInst>(U) || isa<StoreInst>(U) || isa<CallInst>(U) ||
3479 "swifterror value can only be loaded and stored from, or " 3480 "as a swifterror argument!",
3483 if (
auto StoreI = dyn_cast<StoreInst>(U))
3484 Assert(StoreI->getOperand(1) == SwiftErrorVal,
3485 "swifterror value should be the second operand when used " 3486 "by stores", SwiftErrorVal, U);
3487 if (
auto *Call = dyn_cast<CallBase>(U))
3488 verifySwiftErrorCall(*const_cast<CallBase *>(Call), SwiftErrorVal);
3492 void Verifier::visitAllocaInst(
AllocaInst &AI) {
3497 "Allocation instruction pointer not in the stack address space!",
3500 "Cannot allocate unsized type", &AI);
3502 "Alloca array size must have integer type", &AI);
3504 "huge alignment values are unsupported", &AI);
3507 verifySwiftErrorValue(&AI);
3510 visitInstruction(AI);
3517 "cmpxchg instructions must be atomic.", &CXI);
3519 "cmpxchg instructions must be atomic.", &CXI);
3521 "cmpxchg instructions cannot be unordered.", &CXI);
3523 "cmpxchg instructions cannot be unordered.", &CXI);
3525 "cmpxchg instructions failure argument shall be no stronger than the " 3530 "cmpxchg failure ordering cannot include release semantics", &CXI);
3533 Assert(PTy,
"First cmpxchg operand must be a pointer.", &CXI);
3534 Type *ElTy = PTy->getElementType();
3536 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
3537 checkAtomicMemAccessSize(ElTy, &CXI);
3539 "Expected value type does not match pointer operand type!", &CXI,
3542 "Stored value type does not match pointer operand type!", &CXI, ElTy);
3543 visitInstruction(CXI);
3548 "atomicrmw instructions must be atomic.", &RMWI);
3550 "atomicrmw instructions cannot be unordered.", &RMWI);
3553 Assert(PTy,
"First atomicrmw operand must be a pointer.", &RMWI);
3558 " operand must have integer or floating point type!",
3563 " operand must have floating point type!",
3568 " operand must have integer type!",
3571 checkAtomicMemAccessSize(ElTy, &RMWI);
3573 "Argument value type does not match pointer operand type!", &RMWI,
3576 "Invalid binary operation!", &RMWI);
3577 visitInstruction(RMWI);
3580 void Verifier::visitFenceInst(
FenceInst &FI) {
3586 "fence instructions may only have acquire, release, acq_rel, or " 3587 "seq_cst ordering.",
3589 visitInstruction(FI);
3595 "Invalid ExtractValueInst operands!", &EVI);
3597 visitInstruction(EVI);
3604 "Invalid InsertValueInst operands!", &IVI);
3606 visitInstruction(IVI);
3610 if (
auto *FPI = dyn_cast<FuncletPadInst>(EHPad))
3611 return FPI->getParentPad();
3616 void Verifier::visitEHPadPredecessors(
Instruction &I) {
3624 if (
auto *LPI = dyn_cast<LandingPadInst>(&I)) {
3631 "Block containing LandingPadInst must be jumped to " 3632 "only by the unwind edge of an invoke.",
3637 if (
auto *CPI = dyn_cast<CatchPadInst>(&I)) {
3639 Assert(BB->getUniquePredecessor() == CPI->getCatchSwitch()->getParent(),
3640 "Block containg CatchPadInst must be jumped to " 3641 "only by its catchswitch.",
3643 Assert(BB != CPI->getCatchSwitch()->getUnwindDest(),
3644 "Catchswitch cannot unwind to one of its catchpads",
3645 CPI->getCatchSwitch(), CPI);
3656 if (
auto *II = dyn_cast<InvokeInst>(TI)) {
3658 "EH pad must be jumped to via an unwind edge", ToPad, II);
3660 FromPad = Bundle->Inputs[0];
3663 }
else if (
auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3664 FromPad = CRI->getOperand(0);
3665 Assert(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
3666 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3669 Assert(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
3676 "EH pad cannot handle exceptions raised within it", FromPad, TI);
3677 if (FromPad == ToPadParent) {
3681 Assert(!isa<ConstantTokenNone>(FromPad),
3682 "A single unwind edge may only enter one EH pad", TI);
3684 "EH pad jumps through a cycle of pads", FromPad);
3693 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
3695 visitEHPadPredecessors(LPI);
3697 if (!LandingPadResultTy)
3698 LandingPadResultTy = LPI.
getType();
3701 "The landingpad instruction should have a consistent result type " 3702 "inside a function.",
3706 Assert(F->hasPersonalityFn(),
3707 "LandingPadInst needs to be in a function with a personality.", &LPI);
3712 "LandingPadInst not the first non-PHI instruction in the block.",
3719 "Catch operand does not have pointer type!", &LPI);
3721 Assert(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
3722 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
3723 "Filter operand is not an array of constants!", &LPI);
3727 visitInstruction(LPI);
3730 void Verifier::visitResumeInst(
ResumeInst &RI) {
3732 "ResumeInst needs to be in a function with a personality.", &RI);
3734 if (!LandingPadResultTy)
3738 "The resume instruction should have a consistent result type " 3739 "inside a function.",
3742 visitTerminator(RI);
3750 "CatchPadInst needs to be in a function with a personality.", &CPI);
3753 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
3759 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
3761 visitEHPadPredecessors(CPI);
3762 visitFuncletPadInst(CPI);
3767 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
3770 visitTerminator(CatchReturn);
3778 "CleanupPadInst needs to be in a function with a personality.", &CPI);
3783 "CleanupPadInst not the first non-PHI instruction in the block.",
3787 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3788 "CleanupPadInst has an invalid parent.", &CPI);
3790 visitEHPadPredecessors(CPI);
3791 visitFuncletPadInst(CPI);
3795 User *FirstUser =
nullptr;
3796 Value *FirstUnwindPad =
nullptr;
3800 while (!Worklist.empty()) {
3803 "FuncletPadInst must not be nested within itself", CurrentPad);
3804 Value *UnresolvedAncestorPad =
nullptr;
3805 for (User *U : CurrentPad->
users()) {
3807 if (
auto *CRI = dyn_cast<CleanupReturnInst>(U)) {
3808 UnwindDest = CRI->getUnwindDest();
3809 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(U)) {
3814 if (CSI->unwindsToCaller())
3816 UnwindDest = CSI->getUnwindDest();
3817 }
else if (
auto *II = dyn_cast<InvokeInst>(U)) {
3819 }
else if (isa<CallInst>(U)) {
3824 }
else if (
auto *CPI = dyn_cast<CleanupPadInst>(U)) {
3828 Worklist.push_back(CPI);
3831 Assert(isa<CatchReturnInst>(U),
"Bogus funclet pad use", U);
3839 if (!cast<Instruction>(UnwindPad)->isEHPad())
3843 if (UnwindParent == CurrentPad)
3849 Value *ExitedPad = CurrentPad;
3852 if (ExitedPad == &FPI) {
3857 UnresolvedAncestorPad = &FPI;
3861 if (ExitedParent == UnwindParent) {
3865 UnresolvedAncestorPad = ExitedParent;
3868 ExitedPad = ExitedParent;
3869 }
while (!isa<ConstantTokenNone>(ExitedPad));
3874 UnresolvedAncestorPad = &FPI;
3881 Assert(UnwindPad == FirstUnwindPad,
"Unwind edges out of a funclet " 3882 "pad must have the same unwind " 3884 &FPI, U, FirstUser);
3887 FirstUnwindPad = UnwindPad;
3889 if (isa<CleanupPadInst>(&FPI) && !isa<ConstantTokenNone>(UnwindPad) &&
3891 SiblingFuncletInfo[&FPI] = cast<Instruction>(U);
3896 if (CurrentPad != &FPI)
3899 if (UnresolvedAncestorPad) {
3900 if (CurrentPad == UnresolvedAncestorPad) {
3904 assert(CurrentPad == &FPI);
3912 Value *ResolvedPad = CurrentPad;
3913 while (!Worklist.empty()) {
3914 Value *UnclePad = Worklist.back();
3918 while (ResolvedPad != AncestorPad) {
3920 if (ResolvedParent == UnresolvedAncestorPad) {
3923 ResolvedPad = ResolvedParent;
3927 if (ResolvedPad != AncestorPad)
3930 Worklist.pop_back();
3935 if (FirstUnwindPad) {
3936 if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FPI.
getParentPad())) {
3937 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
3938 Value *SwitchUnwindPad;
3939 if (SwitchUnwindDest)
3943 Assert(SwitchUnwindPad == FirstUnwindPad,
3944 "Unwind edges out of a catch must have the same unwind dest as " 3945 "the parent catchswitch",
3946 &FPI, FirstUser, CatchSwitch);
3950 visitInstruction(FPI);
3958 "CatchSwitchInst needs to be in a function with a personality.",
3964 "CatchSwitchInst not the first non-PHI instruction in the block.",
3968 Assert(isa<ConstantTokenNone>(ParentPad) || isa<FuncletPadInst>(ParentPad),
3969 "CatchSwitchInst has an invalid parent.", ParentPad);
3974 "CatchSwitchInst must unwind to an EH block which is not a " 3980 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
3984 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
3987 Assert(isa<CatchPadInst>(Handler->getFirstNonPHI()),
3988 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
3991 visitEHPadPredecessors(CatchSwitch);
3992 visitTerminator(CatchSwitch);
3997 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
4003 "CleanupReturnInst must unwind to an EH block which is not a " 4008 visitTerminator(CRI);
4011 void Verifier::verifyDominatesUse(
Instruction &I,
unsigned i) {
4016 if (
InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
4028 if (!isa<PHINode>(I) && InstsInThisBlock.count(Op))
4032 Assert(DT.dominates(Op, U),
4033 "Instruction does not dominate all uses!",
Op, &
I);
4038 "apply only to pointer types", &
I);
4039 Assert((isa<LoadInst>(I) || isa<IntToPtrInst>(I)),
4040 "dereferenceable, dereferenceable_or_null apply only to load" 4041 " and inttoptr instructions, use attributes for calls or invokes", &I);
4043 "take one operand!", &
I);
4045 Assert(CI && CI->getType()->isIntegerTy(64),
"dereferenceable, " 4046 "dereferenceable_or_null metadata value must be an i64!", &
I);
4051 "!prof annotations should have no less than 2 operands", MD);
4054 Assert(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
4056 "expected string with name of the !prof annotation", MD);
4061 if (ProfName.equals(
"branch_weights")) {
4062 unsigned ExpectedNumOperands = 0;
4063 if (
BranchInst *BI = dyn_cast<BranchInst>(&I))
4065 else if (
SwitchInst *SI = dyn_cast<SwitchInst>(&I))
4067 else if (isa<CallInst>(&I) || isa<InvokeInst>(&I))
4068 ExpectedNumOperands = 1;
4070 ExpectedNumOperands = IBI->getNumDestinations();
4071 else if (isa<SelectInst>(&I))
4072 ExpectedNumOperands = 2;
4074 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
4078 "Wrong number of operands", MD);
4081 Assert(MDO,
"second operand should not be null", MD);
4082 Assert(mdconst::dyn_extract<ConstantInt>(MDO),
4083 "!prof brunch_weights operand is not a const int");
4092 Assert(BB,
"Instruction not embedded in basic block!", &I);
4094 if (!isa<PHINode>(I)) {
4095 for (User *U : I.
users()) {
4096 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
4097 "Only PHI nodes may reference their own value!", &
I);
4103 "Instruction has a name, but provides a void value!", &
I);
4108 "Instruction returns a non-scalar type!", &
I);
4113 "Invalid use of metadata!", &
I);
4119 if (
Instruction *Used = dyn_cast<Instruction>(U.getUser()))
4120 Assert(Used->getParent() !=
nullptr,
4121 "Instruction referencing" 4122 " instruction not embedded in a basic block!",
4125 CheckFailed(
"Use of instruction is not an instruction!", U);
4140 Assert(
false,
"Instruction operands must be first-class values!", &I);
4148 "Cannot take the address of an intrinsic!", &I);
4154 F->
getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
4158 "Cannot invoke an intrinsic other than donothing, patchpoint, " 4159 "statepoint, coro_resume or coro_destroy",
4162 &
I, &
M,
F, F->getParent());
4165 "Referring to a basic block in another function!", &
I);
4168 "Referring to an argument in another function!", &
I);
4172 }
else if (isa<Instruction>(I.
getOperand(i))) {
4173 verifyDominatesUse(I, i);
4174 }
else if (isa<InlineAsm>(I.
getOperand(i))) {
4176 "Cannot take the address of an inline asm!", &
I);
4184 visitConstantExprsRecursively(CE);
4191 "fpmath requires a floating point result!", &
I);
4194 mdconst::dyn_extract_or_null<ConstantFP>(MD->
getOperand(0))) {
4195 const APFloat &Accuracy = CFP0->getValueAPF();
4197 "fpmath accuracy must have float type", &
I);
4199 "fpmath accuracy not a positive number!", &
I);
4201 Assert(
false,
"invalid fpmath accuracy!", &I);
4206 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
4207 "Ranges are only for loads, calls and invokes!", &I);
4208 visitRangeMetadata(I, Range, I.
getType());
4215 "nonnull applies only to load instructions, use attributes" 4216 " for calls or invokes",
4221 visitDereferenceableMetadata(I, MD);
4224 visitDereferenceableMetadata(I, MD);
4227 TBAAVerifyHelper.visitTBAAMetadata(I, TBAA);
4232 Assert(isa<LoadInst>(I),
"align applies only to load instructions, " 4233 "use attributes for calls or invokes", &I);
4234 Assert(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
4235 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(AlignMD->getOperand(0));
4236 Assert(CI && CI->getType()->isIntegerTy(64),
4237 "align metadata value must be an i64!", &
I);
4238 uint64_t
Align = CI->getZExtValue();
4240 "align metadata value must be a power of 2!", &I);
4242 "alignment is larger that implementation defined limit", &I);
4246 visitProfMetadata(I, MD);
4249 AssertDI(isa<DILocation>(N),
"invalid !dbg metadata attachment", &I, N);
4253 if (
auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) {
4254 verifyFragmentExpression(*DII);
4255 verifyNotEntryValue(*DII);
4258 InstsInThisBlock.insert(&I);
4281 "Intrinsic has incorrect return type!", IF);
4283 "Intrinsic has incorrect argument type!", IF);
4288 "Intrinsic was not defined with variable arguments!", IF);
4291 "Callsite was not defined with variable arguments!", IF);
4294 Assert(TableRef.
empty(),
"Intrinsic has too few arguments!",
IF);
4302 "Intrinsic name not mangled correctly for type arguments! " 4310 if (
auto *MD = dyn_cast<MetadataAsValue>(V))
4311 visitMetadataAsValue(*MD, Call.
getCaller());
4316 case Intrinsic::coro_id: {
4318 if (isa<ConstantPointerNull>(InfoArg))
4322 "info argument of llvm.coro.begin must refer to an initialized " 4325 Assert(isa<ConstantStruct>(Init) || isa<ConstantArray>(Init),
4326 "info argument of llvm.coro.begin must refer to either a struct or " 4330 #define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC, DAGN) \ 4331 case Intrinsic::INTRINSIC: 4332 #include "llvm/IR/ConstrainedOps.def" 4333 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(Call));
4335 case Intrinsic::dbg_declare:
4337 "invalid llvm.dbg.declare intrinsic call 1", Call);
4338 visitDbgIntrinsic(
"declare", cast<DbgVariableIntrinsic>(Call));
4340 case Intrinsic::dbg_addr:
4341 visitDbgIntrinsic(
"addr", cast<DbgVariableIntrinsic>(Call));
4343 case Intrinsic::dbg_value:
4344 visitDbgIntrinsic(
"value", cast<DbgVariableIntrinsic>(Call));
4346 case Intrinsic::dbg_label:
4347 visitDbgLabelIntrinsic(
"label", cast<DbgLabelInst>(Call));
4349 case Intrinsic::memcpy:
4350 case Intrinsic::memmove:
4351 case Intrinsic::memset: {
4352 const auto *
MI = cast<MemIntrinsic>(&
Call);
4353 auto IsValidAlignment = [&](
unsigned Alignment) ->
bool {
4356 Assert(IsValidAlignment(
MI->getDestAlignment()),
4357 "alignment of arg 0 of memory intrinsic must be 0 or a power of 2",
4359 if (
const auto *MTI = dyn_cast<MemTransferInst>(
MI)) {
4360 Assert(IsValidAlignment(MTI->getSourceAlignment()),
4361 "alignment of arg 1 of memory intrinsic must be 0 or a power of 2",
4367 case Intrinsic::memcpy_element_unordered_atomic:
4368 case Intrinsic::memmove_element_unordered_atomic:
4369 case Intrinsic::memset_element_unordered_atomic: {
4370 const auto *AMI = cast<AtomicMemIntrinsic>(&
Call);
4373 cast<ConstantInt>(AMI->getRawElementSizeInBytes());
4374 const APInt &ElementSizeVal = ElementSizeCI->getValue();
4375 Assert(ElementSizeVal.isPowerOf2(),
4376 "element size of the element-wise atomic memory intrinsic " 4377 "must be a power of 2",
4380 if (
auto *LengthCI = dyn_cast<ConstantInt>(AMI->getLength())) {
4381 uint64_t Length = LengthCI->getZExtValue();
4382 uint64_t ElementSize = AMI->getElementSizeInBytes();
4383 Assert((Length % ElementSize) == 0,
4384 "constant length must be a multiple of the element size in the " 4385 "element-wise atomic memory intrinsic",
4389 auto IsValidAlignment = [&](uint64_t Alignment) {
4390 return isPowerOf2_64(Alignment) && ElementSizeVal.ule(Alignment);
4392 uint64_t DstAlignment = AMI->getDestAlignment();
4393 Assert(IsValidAlignment(DstAlignment),
4394 "incorrect alignment of the destination argument", Call);
4395 if (
const auto *AMT = dyn_cast<AtomicMemTransferInst>(AMI)) {
4396 uint64_t SrcAlignment = AMT->getSourceAlignment();
4397 Assert(IsValidAlignment(SrcAlignment),
4398 "incorrect alignment of the source argument", Call);
4402 case Intrinsic::gcroot:
4403 case Intrinsic::gcwrite:
4404 case Intrinsic::gcread:
4405 if (ID == Intrinsic::gcroot) {
4408 Assert(AI,
"llvm.gcroot parameter #1 must be an alloca.", Call);
4410 "llvm.gcroot parameter #2 must be a constant.", Call);
4413 "llvm.gcroot parameter #1 must either be a pointer alloca, " 4414 "or argument #2 must be a non-null constant.",
4420 "Enclosing function does not use GC.",
Call);
4422 case Intrinsic::init_trampoline:
4424 "llvm.init_trampoline parameter #2 must resolve to a function.",
4429 cast<ConstantInt>(Call.
getArgOperand(2))->getZExtValue() < 4,
4430 "invalid arguments to llvm.prefetch",
Call);
4432 case Intrinsic::stackprotector:
4434 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call);
4436 case Intrinsic::localescape: {
4439 "llvm.localescape used outside of entry block",
Call);
4441 "multiple calls to llvm.localescape in one function", Call);
4443 if (isa<ConstantPointerNull>(
Arg))
4447 "llvm.localescape only accepts static allocas",
Call);
4450 SawFrameEscape =
true;
4453 case Intrinsic::localrecover: {
4457 "llvm.localrecover first " 4458 "argument must be function defined in this module",
4461 auto &
Entry = FrameEscapeInfo[Fn];
4463 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
4467 case Intrinsic::experimental_gc_statepoint:
4468 if (
auto *CI = dyn_cast<CallInst>(&Call))
4470 "gc.statepoint support for inline assembly unimplemented", CI);
4472 "Enclosing function does not use GC.",
Call);
4474 verifyStatepoint(Call);
4476 case Intrinsic::experimental_gc_result: {
4478 "Enclosing function does not use GC.",
Call);
4482 StatepointCall ? StatepointCall->getCalledFunction() :
nullptr;
4483 Assert(StatepointFn && StatepointFn->isDeclaration() &&
4484 StatepointFn->getIntrinsicID() ==
4485 Intrinsic::experimental_gc_statepoint,
4486 "gc.result operand #1 must be from a statepoint",
Call,
4487 Call.getArgOperand(0));
4490 const Value *
Target = StatepointCall->getArgOperand(2);
4491 auto *PT = cast<PointerType>(Target->getType());
4492 auto *TargetFuncType = cast<FunctionType>(PT->getElementType());
4493 Assert(Call.getType() == TargetFuncType->getReturnType(),
4494 "gc.result result type does not match wrapped callee",
Call);
4497 case Intrinsic::experimental_gc_relocate: {
4501 "gc.relocate must return a pointer or a vector of pointers", Call);
4510 LandingPad->
getParent()->getUniquePredecessor();
4514 Assert(InvokeBB,
"safepoints should have unique landingpads",
4519 "gc relocate should be linked to a statepoint", InvokeBB);
4526 "gc relocate is incorrectly tied to the statepoint", Call, Token);
4531 *cast<CallBase>(cast<GCRelocateInst>(
Call).getStatepoint());
4535 Assert(isa<ConstantInt>(Base),
4536 "gc.relocate operand #2 must be integer offset", Call);
4539 Assert(isa<ConstantInt>(Derived),
4540 "gc.relocate operand #3 must be integer offset", Call);
4542 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
4543 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
4545 Assert(0 <= BaseIndex && BaseIndex < (
int)StatepointCall.
arg_size(),
4546 "gc.relocate: statepoint base index out of bounds",
Call);
4547 Assert(0 <= DerivedIndex && DerivedIndex < (
int)StatepointCall.
arg_size(),
4548 "gc.relocate: statepoint derived index out of bounds",
Call);
4553 "gc.statepoint: insufficient arguments");
4555 "gc.statement: number of call arguments must be constant integer");
4556 const unsigned NumCallArgs =
4557 cast<ConstantInt>(StatepointCall.
getArgOperand(3))->getZExtValue();
4559 "gc.statepoint: mismatch in number of call arguments");
4561 "gc.statepoint: number of transition arguments must be " 4562 "a constant integer");
4563 const int NumTransitionArgs =
4564 cast<ConstantInt>(StatepointCall.
getArgOperand(NumCallArgs + 5))
4566 const int DeoptArgsStart = 4 + NumCallArgs + 1 + NumTransitionArgs + 1;
4568 "gc.statepoint: number of deoptimization arguments must be " 4569 "a constant integer");
4570 const int NumDeoptArgs =
4571 cast<ConstantInt>(StatepointCall.
getArgOperand(DeoptArgsStart))
4573 const int GCParamArgsStart = DeoptArgsStart + 1 + NumDeoptArgs;
4574 const int GCParamArgsEnd = StatepointCall.
arg_size();
4575 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
4576 "gc.relocate: statepoint base index doesn't fall within the " 4577 "'gc parameters' section of the statepoint call",
4579 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
4580 "gc.relocate: statepoint derived index doesn't fall within the " 4581 "'gc parameters' section of the statepoint call",
4590 "gc.relocate: relocated value must be a gc pointer",
Call);
4592 auto ResultType = Call.
getType();
4594 Assert(ResultType->isVectorTy() == DerivedType->isVectorTy(),
4595 "gc.relocate: vector relocates to vector and pointer to pointer",
4598 ResultType->getPointerAddressSpace() ==
4599 DerivedType->getPointerAddressSpace(),
4600 "gc.relocate: relocating a pointer shouldn't change its address space",
4604 case Intrinsic::eh_exceptioncode:
4605 case Intrinsic::eh_exceptionpointer: {
4607 "eh.exceptionpointer argument must be a catchpad", Call);
4610 case Intrinsic::masked_load: {
4618 Assert(Mask->getType()->isVectorTy(),
"masked_load: mask must be vector",
4621 "masked_load: alignment must be a power of 2",
Call);
4624 Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
4626 "masked_load: return must match pointer type",
Call);
4628 "masked_load: pass through and data type must match",
Call);
4629 Assert(Mask->getType()->getVectorNumElements() ==
4630 DataTy->getVectorNumElements(),
4631 "masked_load: vector mask must be same length as data",
Call);
4634 case Intrinsic::masked_store: {
4639 Assert(Mask->getType()->isVectorTy(),
"masked_store: mask must be vector",
4642 "masked_store: alignment must be a power of 2",
Call);
4645 Type *DataTy = cast<PointerType>(Ptr->
getType())->getElementType();
4647 "masked_store: storee must match pointer type",
Call);
4648 Assert(Mask->getType()->getVectorNumElements() ==
4649 DataTy->getVectorNumElements(),
4650 "masked_store: vector mask must be same length as data",
Call);
4654 case Intrinsic::experimental_guard: {
4655 Assert(isa<CallInst>(Call),
"experimental_guard cannot be invoked", Call);
4657 "experimental_guard must have exactly one " 4658 "\"deopt\" operand bundle");
4662 case Intrinsic::experimental_deoptimize: {
4663 Assert(isa<CallInst>(Call),
"experimental_deoptimize cannot be invoked",
4666 "experimental_deoptimize must have exactly one " 4667 "\"deopt\" operand bundle");
4669 "experimental_deoptimize return type must match caller return type");
4671 if (isa<CallInst>(Call)) {
4674 "calls to experimental_deoptimize must be followed by a return");
4678 "calls to experimental_deoptimize must be followed by a return " 4679 "of the value computed by experimental_deoptimize");
4684 case Intrinsic::sadd_sat:
4685 case Intrinsic::uadd_sat:
4686 case Intrinsic::ssub_sat:
4687 case Intrinsic::usub_sat: {
4691 "first operand of [us][add|sub]_sat must be an int type or vector " 4694 "second operand of [us][add|sub]_sat must be an int type or vector " 4698 case Intrinsic::smul_fix:
4699 case Intrinsic::smul_fix_sat:
4700 case Intrinsic::umul_fix:
4701 case Intrinsic::umul_fix_sat:
4702 case Intrinsic::sdiv_fix:
4703 case Intrinsic::udiv_fix: {
4707 "first operand of [us][mul|div]_fix[_sat] must be an int type or " 4710 "second operand of [us][mul|div]_fix[_sat] must be an int type or " 4714 Assert(Op3->getType()->getBitWidth() <= 32,
4715 "third argument of [us][mul|div]_fix[_sat] must fit within 32 bits");
4717 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
4718 ID == Intrinsic::sdiv_fix) {
4721 "the scale of s[mul|div]_fix[_sat] must be less than the width of " 4725 "the scale of u[mul|div]_fix[_sat] must be less than or equal " 4726 "to the width of the operands");
4730 case Intrinsic::lround:
4731 case Intrinsic::llround:
4732 case Intrinsic::lrint:
4733 case Intrinsic::llrint: {
4737 "Intrinsic does not support vectors", &
Call);
4751 if (
auto *
SP = dyn_cast<DISubprogram>(LocalScope))
4754 if (
auto *LB = dyn_cast<DILexicalBlockBase>(LocalScope))
4758 assert(!isa<DILocalScope>(LocalScope) &&
"Unknown type of local scope");
4763 unsigned NumOperands;
4766 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 4767 case Intrinsic::INTRINSIC: \ 4768 NumOperands = NARG; \ 4769 HasRoundingMD = ROUND_MODE; \ 4771 #include "llvm/IR/ConstrainedOps.def" 4775 NumOperands += (1 + HasRoundingMD);
4777 if (isa<ConstrainedFPCmpIntrinsic>(FPI))
4780 "invalid arguments for constrained FP intrinsic", &FPI);
4783 case Intrinsic::experimental_constrained_lrint:
4784 case Intrinsic::experimental_constrained_llrint: {
4788 "Intrinsic does not support vectors", &FPI);
4792 case Intrinsic::experimental_constrained_lround:
4793 case Intrinsic::experimental_constrained_llround: {
4797 "Intrinsic does not support vectors", &FPI);
4801 case Intrinsic::experimental_constrained_fcmp:
4802 case Intrinsic::experimental_constrained_fcmps: {
4803 auto Pred = cast<ConstrainedFPCmpIntrinsic>(&FPI)->
getPredicate();
4805 "invalid predicate for constrained FP comparison intrinsic", &FPI);
4809 case Intrinsic::experimental_constrained_fptosi:
4810 case Intrinsic::experimental_constrained_fptoui: {
4812 uint64_t NumSrcElem = 0;
4814 "Intrinsic first argument must be floating point", &FPI);
4815 if (
auto *OperandT = dyn_cast<VectorType>(Operand->
getType())) {
4816 NumSrcElem = OperandT->getNumElements();
4821 "Intrinsic first argument and result disagree on vector use", &FPI);
4823 "Intrinsic result must be an integer", &FPI);
4824 if (
auto *OperandT = dyn_cast<VectorType>(Operand->
getType())) {
4825 Assert(NumSrcElem == OperandT->getNumElements(),
4826 "Intrinsic first argument and result vector lengths must be equal",
4832 case Intrinsic::experimental_constrained_sitofp:
4833 case Intrinsic::experimental_constrained_uitofp: {
4835 uint64_t NumSrcElem = 0;
4837 "Intrinsic first argument must be integer", &FPI);
4838 if (
auto *OperandT = dyn_cast<VectorType>(Operand->
getType())) {
4839 NumSrcElem = OperandT->getNumElements();
4844 "Intrinsic first argument and result disagree on vector use", &FPI);
4846 "Intrinsic result must be a floating point", &FPI);
4847 if (
auto *OperandT = dyn_cast<VectorType>(Operand->
getType())) {
4848 Assert(NumSrcElem == OperandT->getNumElements(),
4849 "Intrinsic first argument and result vector lengths must be equal",
4854 case Intrinsic::experimental_constrained_fptrunc:
4855 case Intrinsic::experimental_constrained_fpext: {
4858 Value *Result = &FPI;
4861 "Intrinsic first argument must be FP or FP vector", &FPI);
4863 "Intrinsic result must be FP or FP vector", &FPI);
4865 "Intrinsic first argument and result disagree on vector use", &FPI);
4867 auto *OperandVecTy = cast<VectorType>(OperandTy);
4868 auto *ResultVecTy = cast<VectorType>(ResultTy);
4869 Assert(OperandVecTy->getNumElements() == ResultVecTy->getNumElements(),
4870 "Intrinsic first argument and result vector lengths must be equal",
4873 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
4875 "Intrinsic first argument's type must be larger than result type",
4879 "Intrinsic first argument's type must be smaller than result type",
4895 "invalid exception behavior argument", &FPI);
4896 if (HasRoundingMD) {
4898 "invalid rounding mode argument", &FPI);
4903 auto *MD = cast<MetadataAsValue>(DII.
getArgOperand(0))->getMetadata();
4904 AssertDI(isa<ValueAsMetadata>(MD) ||
4905 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
4906 "invalid llvm.dbg." + Kind +
" intrinsic address/value", &DII, MD);
4908 "invalid llvm.dbg." + Kind +
" intrinsic variable", &DII,
4911 "invalid llvm.dbg." + Kind +
" intrinsic expression", &DII,
4916 if (!isa<DILocation>(N))
4925 AssertDI(Loc,
"llvm.dbg." + Kind +
" intrinsic requires a !dbg attachment",
4930 if (!VarSP || !LocSP)
4933 AssertDI(VarSP == LocSP,
"mismatched subprogram between llvm.dbg." + Kind +
4934 " variable and !dbg attachment",
4936 Loc->getScope()->getSubprogram());
4946 "invalid llvm.dbg." + Kind +
" intrinsic variable", &DLI,
4951 if (!isa<DILocation>(N))
4960 Assert(Loc,
"llvm.dbg." + Kind +
" intrinsic requires a !dbg attachment",
4965 if (!LabelSP || !LocSP)
4968 AssertDI(LabelSP == LocSP,
"mismatched subprogram between llvm.dbg." + Kind +
4969 " label and !dbg attachment",
4971 Loc->getScope()->getSubprogram());
4979 if (!V || !E || !E->isValid())
4983 auto Fragment = E->getFragmentInfo();
4996 verifyFragmentExpression(*V, *Fragment, &I);
4999 template <
typename ValueOrMetadata>
5000 void Verifier::verifyFragmentExpression(
const DIVariable &V,
5002 ValueOrMetadata *Desc) {
5011 AssertDI(FragSize + FragOffset <= *VarSize,
5012 "fragment is larger than or outside of variable", Desc, &V);
5013 AssertDI(FragSize != *VarSize,
"fragment covers entire variable", Desc, &V);
5028 AssertDI(Var,
"dbg intrinsic without variable");
5030 unsigned ArgNo = Var->
getArg();
5036 if (DebugFnArgs.size() < ArgNo)
5037 DebugFnArgs.resize(ArgNo,
nullptr);
5039 auto *Prev = DebugFnArgs[ArgNo - 1];
5040 DebugFnArgs[ArgNo - 1] = Var;
5041 AssertDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &I,
5055 void Verifier::verifyCompileUnits() {
5064 Listed.
insert(CUs->op_begin(), CUs->op_end());
5065 for (
auto *
CU : CUVisited)
5070 void Verifier::verifyDeoptimizeCallingConvs() {
5071 if (DeoptimizeDeclarations.empty())
5074 const Function *First = DeoptimizeDeclarations[0];
5075 for (
auto *F :
makeArrayRef(DeoptimizeDeclarations).slice(1)) {
5077 "All llvm.experimental.deoptimize declarations must have the same " 5078 "calling convention",
5084 bool HasSource = F.
getSource().hasValue();
5085 if (!HasSourceDebugInfo.count(&U))
5086 HasSourceDebugInfo[&U] = HasSource;
5087 AssertDI(HasSource == HasSourceDebugInfo[&U],
5088 "inconsistent use of embedded source");
5103 return !V.verify(F);
5109 Verifier V(OS, !BrokenDebugInfo, M);
5113 Broken |= !V.verify(F);
5115 Broken |= !V.verify();
5116 if (BrokenDebugInfo)
5117 *BrokenDebugInfo = V.hasBrokenDebugInfo();
5128 std::unique_ptr<Verifier> V;
5129 bool FatalErrors =
true;
5134 explicit VerifierLegacyPass(
bool FatalErrors)
5136 FatalErrors(FatalErrors) {
5140 bool doInitialization(
Module &M)
override {
5141 V = std::make_unique<Verifier>(
5147 if (!V->verify(F) && FatalErrors) {
5154 bool doFinalization(
Module &M)
override {
5155 bool HasErrors =
false;
5158 HasErrors |= !V->verify(F);
5160 HasErrors |= !V->verify();
5161 if (FatalErrors && (HasErrors || V->hasBrokenDebugInfo()))
5174 template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&...
Args) {
5176 return Diagnostic->CheckFailed(
Args...);
5179 #define AssertTBAA(C, ...) \ 5182 CheckFailed(__VA_ARGS__); \ 5190 TBAAVerifier::TBAABaseNodeSummary
5194 CheckFailed(
"Base nodes must have at least two operands", &I, BaseNode);
5198 auto Itr = TBAABaseNodes.find(BaseNode);
5199 if (Itr != TBAABaseNodes.end())
5202 auto Result = verifyTBAABaseNodeImpl(I, BaseNode, IsNewFormat);
5203 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
5205 assert(InsertResult.second &&
"We just checked!");
5209 TBAAVerifier::TBAABaseNodeSummary
5212 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0u};
5216 return isValidScalarTBAANode(BaseNode)
5217 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
5223 CheckFailed(
"Access tag nodes must have the number of operands that is a " 5224 "multiple of 3!", BaseNode);
5229 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
5237 auto *TypeSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
5239 if (!TypeSizeNode) {
5240 CheckFailed(
"Type size nodes must be constants!", &I, BaseNode);
5246 if (!IsNewFormat && !isa<MDString>(BaseNode->
getOperand(0))) {
5247 CheckFailed(
"Struct tag nodes have a string as their first operand",
5255 unsigned BitWidth = ~0u;
5259 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
5260 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
5261 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
5262 Idx += NumOpsPerField) {
5265 if (!isa<MDNode>(FieldTy)) {
5266 CheckFailed(
"Incorrect field entry in struct type node!", &I, BaseNode);
5271 auto *OffsetEntryCI =
5272 mdconst::dyn_extract_or_null<ConstantInt>(FieldOffset);
5273 if (!OffsetEntryCI) {
5274 CheckFailed(
"Offset entries must be constants!", &I, BaseNode);
5279 if (BitWidth == ~0u)
5280 BitWidth = OffsetEntryCI->getBitWidth();
5282 if (OffsetEntryCI->getBitWidth() != BitWidth) {
5284 "Bitwidth between the offsets and struct type entries must match", &I,
5296 !PrevOffset || PrevOffset->
ule(OffsetEntryCI->getValue());
5299 CheckFailed(
"Offsets must be increasing!", &I, BaseNode);
5303 PrevOffset = OffsetEntryCI->getValue();
5306 auto *MemberSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
5308 if (!MemberSizeNode) {
5309 CheckFailed(
"Member size entries must be constants!", &I, BaseNode);
5316 return Failed ? InvalidNode
5317 : TBAAVerifier::TBAABaseNodeSummary(
false, BitWidth);
5338 auto *Parent = dyn_cast_or_null<MDNode>(MD->
getOperand(1));
5339 return Parent && Visited.
insert(Parent).second &&
5343 bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
5344 auto ResultIt = TBAAScalarNodes.find(MD);
5345 if (ResultIt != TBAAScalarNodes.end())
5346 return ResultIt->second;
5350 auto InsertResult = TBAAScalarNodes.insert({MD, Result});
5352 assert(InsertResult.second &&
"Just checked!");
5371 return cast<MDNode>(BaseNode->
getOperand(1));
5373 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
5374 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
5375 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
5376 Idx += NumOpsPerField) {
5377 auto *OffsetEntryCI =
5378 mdconst::extract<ConstantInt>(BaseNode->
getOperand(Idx + 1));
5379 if (OffsetEntryCI->getValue().ugt(Offset)) {
5380 if (Idx == FirstFieldOpNo) {
5381 CheckFailed(
"Could not find TBAA parent in struct type node", &I,
5386 unsigned PrevIdx = Idx - NumOpsPerField;
5387 auto *PrevOffsetEntryCI =
5388 mdconst::extract<ConstantInt>(BaseNode->
getOperand(PrevIdx + 1));
5389 Offset -= PrevOffsetEntryCI->getValue();
5390 return cast<MDNode>(BaseNode->
getOperand(PrevIdx));
5395 auto *LastOffsetEntryCI = mdconst::extract<ConstantInt>(
5397 Offset -= LastOffsetEntryCI->getValue();
5398 return cast<MDNode>(BaseNode->
getOperand(LastIdx));
5415 AssertTBAA(isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
5416 isa<VAArgInst>(I) || isa<AtomicRMWInst>(I) ||
5417 isa<AtomicCmpXchgInst>(I),
5418 "This instruction shall not have a TBAA access tag!", &I);
5420 bool IsStructPathTBAA =
5425 "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I);
5434 "Access tag metadata must have either 4 or 5 operands", &
I, MD);
5437 "Struct tag metadata must have either 3 or 4 operands", &
I, MD);
5442 auto *AccessSizeNode = mdconst::dyn_extract_or_null<ConstantInt>(
5444 AssertTBAA(AccessSizeNode,
"Access size field must be a constant", &I, MD);
5448 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
5450 auto *IsImmutableCI = mdconst::dyn_extract_or_null<ConstantInt>(
5453 "Immutability tag on struct tag metadata must be a constant",
5456 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
5457 "Immutability part of the struct tag metadata must be either 0 or 1",
5462 "Malformed struct tag metadata: base and access-type " 5463 "should be non-null and point to Metadata nodes",
5464 &I, MD, BaseNode, AccessType);
5467 AssertTBAA(isValidScalarTBAANode(AccessType),
5468 "Access type node must be a valid scalar type", &I, MD,
5472 auto *OffsetCI = mdconst::dyn_extract_or_null<ConstantInt>(MD->
getOperand(2));
5473 AssertTBAA(OffsetCI,
"Offset must be constant integer", &I, MD);
5475 APInt Offset = OffsetCI->getValue();
5476 bool SeenAccessTypeInPath =
false;
5481 BaseNode = getFieldNodeFromTBAABaseNode(I, BaseNode, Offset,
5483 if (!StructPath.
insert(BaseNode).second) {
5484 CheckFailed(
"Cycle detected in struct path", &I, MD);
5489 unsigned BaseNodeBitWidth;
5490 std::tie(Invalid, BaseNodeBitWidth) = verifyTBAABaseNode(I, BaseNode,
5498 SeenAccessTypeInPath |= BaseNode == AccessType;
5500 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
5501 AssertTBAA(Offset == 0,
"Offset not zero at the point of scalar access",
5505 (BaseNodeBitWidth == 0 && Offset == 0) ||
5506 (IsNewFormat && BaseNodeBitWidth == ~0u),
5507 "Access bit-width not the same as description bit-width", &
I, MD,
5510 if (IsNewFormat && SeenAccessTypeInPath)
5514 AssertTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
5520 INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
5523 return new VerifierLegacyPass(FatalErrors);
5541 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
5549 if (res.IRBroken && FatalErrors)
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface ...
bool isFPPredicate() const
bool isDeclarationForLinker() const
Metadata * getRawRetainedTypes() const
Return a value (possibly void), from a function.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
static bool isScope(const Metadata *MD)
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
A parsed version of the target data layout string in and methods for querying it. ...
MaybeAlign getParamAlignment(unsigned ArgNo) const
Return the alignment for the specified function parameter.
Tracking metadata reference owned by Metadata.
Calling convention used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
static Value * getParentPad(Value *EHPad)
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
iterator_range< use_iterator > uses()
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool hasLocalLinkage() const
bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
This class represents an incoming formal argument to a Function.
bool doesNotAccessMemory(unsigned OpNo) const
Base class for instruction visitors.
Value * getAggregateOperand()
bool isSpeculatable() const
Determine if the call has sideeffects.
const Value * stripInBoundsOffsets() const
Strip off pointer casts and inbounds GEPs.
This represents the llvm.dbg.label instruction.
Atomic ordering constants.
Takes the max of the two values, which are required to be integers.
StringRef getName() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
bool hasPrivateLinkage() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
bool isMetadataTy() const
Return true if this is 'metadata'.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
MatchIntrinsicTypesResult
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
BinaryOps getOpcode() const
const APInt & getUpper() const
Return the upper value for this range.
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
Type * getParamType(unsigned i) const
Parameter type accessors.
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
static bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
Metadata * getRawGlobalVariables() const
Metadata * getRawVTableHolder() const
A Module instance is used to store all the information related to an LLVM module. ...
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Result run(Module &M, ModuleAnalysisManager &)
An instruction for ordering other memory operations.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
An instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Function * getCaller()
Helper to get the caller (the parent function).
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
This class represents zero extension of integer types.
unsigned getNumElements() const
Random access to the elements.
void push_back(const T &Elt)
Metadata * getRawFile() const
Return the raw underlying file.
This class represents a function call, abstracting a target machine's calling convention.
bool hasAvailableExternallyLinkage() const
Metadata * getRawInlinedAt() const
Value * getCondition() const
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this store instruction.
FunctionPass * createVerifierPass(bool FatalErrors=true)
const Value * getTrueValue() const
An efficient, type-erasing, non-owning reference to a callable.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
This instruction constructs a fixed permutation of two input vectors.
LLVMContext & getContext() const
All values hold a context through their type.
DICompositeTypeArray getEnumTypes() const
bool sgt(const APInt &RHS) const
Signed greater than comparison.
const Use & getOperandUse(unsigned i) const
This class implements a map that also provides access to all stored values in a deterministic order...
bool hasDLLImportStorageClass() const
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
C - The default llvm calling convention, compatible with C.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
static Instruction * getSuccPad(Instruction *Terminator)
Metadata * getRawScope() const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
const fltSemantics & getSemantics() const
const MDOperand & getOperand(unsigned I) const
This class represents a sign extension of integer types.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
Manage lifetime of a slot tracker for printing IR.
bool hasExternalWeakLinkage() const
void CheckFailed(const Twine &Message)
A check failed, so printout out the condition and the message.
Typed, array-like tuple of metadata.
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Value * getCondition() const
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
BasicBlock * getUnwindDest() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isVectorTy() const
True if this is an instance of VectorType.
This is the common base class for constrained floating point intrinsics.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
This defines the Use class.
void reserve(size_type N)
bool isMustTailCall() const
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
Calling convention used for Mesa/AMDPAL geometry shaders.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
unsigned getBitWidth() const
Return the number of bits in the APInt.
DINodeArray getElements() const
Check a module for errors, and report separate error states for IR and debug info errors...
iterator_range< user_iterator > materialized_users()
AtomicOrdering getFailureOrdering() const
Returns the failure ordering constraint of this cmpxchg instruction.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Adds a requirement that another module flag be present and have a specified value after linking is pe...
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Value * getArgOperand(unsigned i) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Appends the two values, which are required to be metadata nodes.
unsigned getAllocaAddrSpace() const
Metadata * getRawTypeArray() const
This class represents a conversion between pointers from one address space to another.
static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy)
This method can be used to determine if a cast from S to DstTy using Opcode op is valid or not...
SPIR_KERNEL - Calling convention for SPIR kernel functions.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
This class represents the LLVM 'select' instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
PointerType * getType() const
Overload to return most specific pointer type.
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
unsigned getNumSuccessors() const
bool isStrongerThan(AtomicOrdering ao, AtomicOrdering other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice, which is based on C++'s definition.
bool isResolved() const
Check if node is fully resolved.
DIGlobalVariable * getVariable() const
Class to represent struct types.
LLVMContext & getContext() const
Get the global data context.
A Use represents the edge between a Value definition and its users.
DILabel * getLabel() const
iterator find(ConstPtrType Ptr) const
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
BinOp getOperation() const
Value * getDerivedPtr() const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
bool isArtificial() const
bool isIntegerTy() const
True if this is an instance of IntegerType.
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
This file contains the simple types necessary to represent the attributes associated with functions a...
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
unsigned getNumHandlers() const
return the number of 'handlers' in this catchswitch instruction, except the default handler ...
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
check if an attributes is in the list of attributes.
static bool isNewFormatTBAATypeNode(llvm::MDNode *Type)
bool hasAttributes(unsigned Index) const
Return true if attribute exists at the given index.
Metadata * getRawType() const
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
static const unsigned MaximumAlignment
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Type * getSourceElementType() const
StringRef getFilename() const
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
This file implements a class to represent arbitrary precision integral constant values and operations...
bool hasCommonLinkage() const
This class represents a cast from a pointer to an integer.
AtomicOrdering
Atomic ordering for LLVM's memory model.
static bool IsRootTBAANode(const MDNode *MD)
static bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
bool hasValidDeclarationLinkage() const
static StringRef getOperationName(BinOp Op)
void visit(Iterator Start, Iterator End)
bool hasExternalLinkage() const
Metadata * getRawImportedEntities() const
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
A constant value that is initialized with an expression using other constant values.
Class to represent function types.
Type * getType() const
All values are typed, get the type of this value.
static bool isTypeCongruent(Type *L, Type *R)
Two types are "congruent" if they are identical, or if they are both pointer types with different poi...
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value. ...
Holds the characteristics of one fragment of a larger variable.
op_range operands() const
bool isStatepoint(const CallBase *Call)
AtomicOrdering getSuccessOrdering() const
Returns the success ordering constraint of this cmpxchg instruction.
ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
#define Assert(C,...)
We know that cond should be true, if not print an error message.
Class to represent array types.
This is the common base class for debug info intrinsics for variables.
AttributeSet getParamAttributes(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
This instruction compares its operands according to the predicate given to the constructor.
DIMacroNodeArray getElements() const
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
This class represents a no-op cast from one type to another.
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
const APInt & getValue() const
Return the constant as an APInt value reference.
An instruction for storing to memory.
bool hasPersonalityFn() const
Check whether this function has a personality function.
Metadata * getRawEntity() const
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
LinkageTypes getLinkage() const
This class represents a cast from floating point to signed integer.
unsigned getAlignment() const
Value * getParentPad() const
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
PTX_Kernel - Call to a PTX kernel.
handler_range handlers()
iteration adapter for range-for loops.
iterator_range< op_iterator > operands()
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
This class represents a truncation of integer types.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
Class to represent pointers.
Metadata * getRawFile() const
Optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
bool hasAppendingLinkage() const
Calling convention used for Mesa/AMDPAL compute shaders.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
StringRef getString() const
DIMacroNodeArray getMacros() const
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static bool runOnFunction(Function &F, bool PostInlining)
static bool isFPOperation(BinOp Op)
Intel_OCL_BI - Calling conventions for Intel OpenCL built-ins.
Type * getReturnType() const
Returns the type of the ret val.
void getModuleFlagsMetadata(SmallVectorImpl< ModuleFlagEntry > &Flags) const
Returns the module flags in the provided vector.
This instruction inserts a single (scalar) element into a VectorType value.
StringRef getName() const
unsigned getColumn() const
static bool isIntPredicate(Predicate P)
bool isLabelTy() const
Return true if this is 'label'.
Optional< fp::ExceptionBehavior > getExceptionBehavior() const
The landingpad instruction holds all of the information necessary to generate correct exception handl...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Emits an error if two values disagree, otherwise the resulting value is that of the operands...
Metadata * getRawExpression() const
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
Metadata * getRawDiscriminator() const
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
unsigned arg_size() const
Value * getCalledValue() const
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
bool isOSBinFormatCOFF() const
Tests whether the OS uses the COFF binary format.
This is an important class for using LLVM in a threaded context.
DISubprogram * getSubprogram() const
Get the attached subprogram.
Conditional or Unconditional Branch instruction.
bool isHexDigit(char C)
Checks if character C is a hexadecimal numeric character.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
bool isInlineAsm() const
Check if this call is an inline asm statement.
Resume the propagation of an exception.
CountType getCount() const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
bool hasInAllocaArgument() const
Determine if there are is an inalloca argument.
const Instruction & front() const
Indirect Branch Instruction.
void print(raw_ostream &ROS, bool IsForDebug=false) const
FunctionType * getFunctionType() const
Base class for template parameters.
ModFlagBehavior
This enumeration defines the supported behaviors of module flags.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
ConstantFP - Floating Point Values [float, double].
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
DIExpression * getExpression() const
unsigned getNumAttributes() const
Return the number of attributes in this set.
bool isODRUniquingDebugTypes() const
Whether there is a string map for uniquing debug info identifiers across the context.
Metadata * getRawLabel() const
static bool isValidLinkage(LinkageTypes L)
A pair of DIGlobalVariable and DIExpression.
Represent the analysis usage information of a pass.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
static Type * getVoidTy(LLVMContext &C)
static bool isFuncOnlyAttr(Attribute::AttrKind Kind)
Return true if this attribute kind only applies to functions.
bool visitTBAAMetadata(Instruction &I, const MDNode *MD)
Visit an instruction and return true if it is valid, return false if an invalid TBAA is attached...
DIImportedEntityArray getImportedEntities() const
AttrBuilder & addAlignmentAttr(MaybeAlign Align)
This turns an alignment into the form used internally in Attribute.
This instruction compares its operands according to the predicate given to the constructor.
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
FunctionPass class - This class is used to implement most global optimizations.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Interval::pred_iterator pred_end(Interval *I)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Base class for variables.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type. ...
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
bool pred_empty(const BasicBlock *BB)
const Function * getFunction() const
Return the function this instruction belongs to.
This class represents a cast from an integer to a pointer.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Type * getPointerOperandType() const
Method to return the pointer operand as a PointerType.
static DISubprogram * getSubprogram(Metadata *LocalScope)
Carefully grab the subprogram from a local scope.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Attribute getAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return the attribute object that exists at the given index.
const Value * getArraySize() const
Get the number of elements allocated.
PTX_Device - Call to a PTX device function.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
Metadata * getRawType() const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Triple - Helper class for working with autoconf configuration names.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
An imported module (C++ using directive or similar).
Synchronized with respect to all concurrently executing threads.
Base class for scope-like contexts.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Value * getParentPad() const
Convenience accessors.
void sort(IteratorTy Start, IteratorTy End)
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Metadata * getRawElements() const
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
bool isEmptySet() const
Return true if this set contains no members.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
bool isLittleEndian() const
BasicBlock * getNormalDest() const
Metadata * getRawScope() const
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
static const fltSemantics & IEEEsingle() LLVM_READNONE
#define AssertDI(C,...)
We know that a debug info condition should be true, if not print an error message.
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
unsigned getNumOperands() const
std::string getAsString(bool InAttrGrp=false) const
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
Equivalent to hasAttribute(ArgNo + FirstArgIndex, Kind).
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
bool matchIntrinsicVarArg(bool isVarArg, ArrayRef< IITDescriptor > &Infos)
Verify if the intrinsic has variable arguments.
This is the shared class of boolean and integer constants.
constexpr bool isInt< 32 >(int64_t x)
VerifierSupport(raw_ostream *OS, const Module &M)
Align max(MaybeAlign Lhs, Align Rhs)
Metadata * getRawTemplateParams() const
static Optional< DebugEmissionKind > getEmissionKind(StringRef Str)
testing::Matcher< const detail::ErrorHolder & > Failed()
Optional< uint64_t > getSizeInBits() const
Determines the size of the variable's type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
BasicBlock * getSuccessor(unsigned i) const
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
void getIntrinsicInfoTableEntries(ID id, SmallVectorImpl< IITDescriptor > &T)
Return the IIT table descriptor for the specified intrinsic into an array of IITDescriptors.
Calling convention used for Mesa/AMDPAL pixel shaders.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Metadata * getRawVariable() const
bool isFiniteNonZero() const
static bool isDINode(const Metadata *MD)
std::pair< unsigned, Optional< unsigned > > getAllocSizeArgs(unsigned Index) const
Get the allocsize argument numbers (or pair(0, 0) if unknown).
static bool isFuncOrArgAttr(Attribute::AttrKind Kind)
Return true if this is a function attribute that can also appear on arguments.
static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB)
Checks if Metadata represents a valid ModFlagBehavior, and stores the converted result in MFB...
This class represents a range of values.
BasicBlock * getUnwindDest() const
MatchIntrinsicTypesResult matchIntrinsicSignature(FunctionType *FTy, ArrayRef< IITDescriptor > &Infos, SmallVectorImpl< Type *> &ArgTys)
Match the specified function type with the type constraints specified by the .td file.
Type * getReturnType() const
MDNode * getAsMDNode() const
Return this as a bar MDNode.
This class represents a cast from floating point to unsigned integer.
LLVM_NODISCARD T pop_back_val()
unsigned getProgramAddressSpace() const
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
bool isConditional() const
pred_range predecessors(BasicBlock *BB)
bool hasGlobalUnnamedAddr() const
Metadata * getRawElements() const
Metadata * getRawFile() const
static AttrBuilder getParameterABIAttributes(int I, AttributeList Attrs)
AttributeList getAttributes() const
Return the parameter attributes for this call.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Uses the specified value, regardless of the behavior or value of the other module.
static BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
DISubprogram * getSubprogram() const
Get the subprogram for this scope.
unsigned getVectorNumElements() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Optional< fp::RoundingMode > getRoundingMode() const
Class to represent vector types.
This file contains constants used for implementing Dwarf debug support.
Target - Wrapper for Target specific information.
ConstantArray - Constant Array Declarations.
Class for arbitrary precision integers.
unsigned getNumAttrSets() const
Metadata * getRawFile() const
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
amdgpu Simplify well known AMD library false FunctionCallee Callee
A (clang) module that has been imported by the compile unit.
StringRef getName() const
static bool isFPPredicate(Predicate P)
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
Emits a warning if two values disagree.
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
A lightweight accessor for an operand bundle meant to be passed around by value.
iterator_range< user_iterator > users()
SmallVector< BasicBlock *, 16 > getIndirectDests() const
InstListType::iterator iterator
Instruction iterators...
DIGlobalVariableExpressionArray getGlobalVariables() const
Generic tagged DWARF-like metadata node.
iterator insert(iterator I, T &&Elt)
Metadata * getRawFile() const
bool isNonIntegralPointerType(PointerType *PT) const
bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
Metadata * getRawBaseType() const
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Type array for a subprogram.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
bool hasGC() const
hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm to use during code generatio...
unsigned getNumArgOperands() const
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Metadata * getRawEnumTypes() const
Appends the two values, which are required to be metadata nodes.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
static Type * getIndexedType(Type *Ty, ArrayRef< Value *> IdxList)
Returns the type of the element that would be loaded with a load instruction with the specified param...
LLVM_NODISCARD bool empty() const
bool BrokenDebugInfo
Broken debug info can be "recovered" from by stripping the debug info.
StringRef getValueAsString() const
Return the attribute's value as a string.
UnaryOps getOpcode() const
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
Metadata * getRawScope() const
Metadata * getRawScope() const
bool isTokenTy() const
Return true if this is 'token'.
CallingConv::ID getCallingConv() const
verify safepoint Safepoint IR Verifier
bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'. ...
StringRef getName() const
Return a constant reference to the value's name.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
const Function * getParent() const
Return the enclosing method, or null if none.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
Calling convention used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (ve...
void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A check failed (with values to print).
void DebugInfoCheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A debug info check failed (with values to print).
bool onlyReadsMemory(unsigned OpNo) const
const APInt & getLower() const
Return the lower value for this range.
Value * getValue() const
Convenience accessor.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
void initializeVerifierLegacyPassPass(PassRegistry &)
This class represents a cast unsigned integer to floating point.
Type * getResultElementType() const
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
Optional< StringRef > getSource() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
static ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
unsigned getMacinfoType() const
DILocalVariable * getVariable() const
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
ArrayRef< unsigned > getNonIntegralAddressSpaces() const
Return the address spaces containing non-integral pointers.
Type * getByValType() const
StringRef getValue() const
unsigned getAlignment() const
Return the alignment of the access that is being performed FIXME: Remove this function once transitio...
void DebugInfoCheckFailed(const Twine &Message)
A debug info check failed.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Metadata * getRawStaticDataMemberDeclaration() const
DIScopeArray getRetainedTypes() const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
static bool IsScalarTBAANodeImpl(const MDNode *MD, SmallPtrSetImpl< const MDNode *> &Visited)
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
This class represents a cast from signed integer to floating point.
DILocalScope * getScope() const
Get the local scope for this label.
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
bool hasFnAttribute(Attribute::AttrKind Kind) const
Equivalent to hasAttribute(AttributeList::FunctionIndex, Kind) but may be faster. ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static void forEachUser(const Value *User, SmallPtrSet< const Value *, 32 > &Visited, llvm::function_ref< bool(const Value *)> Callback)
const BasicBlock & front() const
bool hasAttributes() const
Return true if attributes exists in this set.
bool isEHPad() const
Return true if this basic block is an exception handling block.
This class represents a truncation of floating point types.
BasicBlock * getUnwindDest() const
Represents calls to the gc.relocate intrinsic.
ArrayRef< unsigned > getIndices() const
Module * getParent()
Get the module that this global value is contained inside of...
Verify that the TBAA Metadatas are valid.
LLVM Value Representation.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
bool hasInitializer() const
Definitions have initializers, declarations don't.
Metadata * getRawMacros() const
Metadata * getRawScope() const
static bool hasConflictingReferenceFlags(unsigned Flags)
Detect mutually exclusive flags.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
bool TreatBrokenDebugInfoAsError
Whether to treat broken debug info as an error.
AttrBuilder typeIncompatible(Type *Ty)
Which attributes cannot be applied to a type.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
AttributeSet getFnAttributes() const
The function attributes are returned.
DITypeRefArray getTypeArray() const
This class implements an extremely fast bulk output stream that can only output to a stream...
bool hasDefaultVisibility() const
Metadata * getRawScope() const
bool Broken
Track the brokenness of the module while recursively visiting.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
static bool isContiguous(const ConstantRange &A, const ConstantRange &B)
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Metadata * getRawType() const
Metadata * getRawScope() const
const Use & getCalledOperandUse() const
This header defines various interfaces for pass management in LLVM.
DILocalScope * getScope() const
Get the local scope for this variable.
unsigned getNumOperands() const
Return number of MDNode operands.
op_range incoming_values()
This class represents an extension of floating point types.
unsigned getNumSuccessors() const
bool isEmpty() const
Return true if there are no attributes.
A bitmask that includes all valid flags.
#define AssertTBAA(C,...)
Calling convention for AMDGPU code object kernels.
Metadata * getRawDecl() const
A special type used by analysis passes to provide an address that identifies that particular analysis...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Type * getElementType() const
PointerType * getType() const
Global values are always pointers.
Metadata * getRawScope() const
bool empty() const
empty - Check if the array is empty.
bool isArrayTy() const
True if this is an instance of ArrayType.
StringRef getName() const
Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
This instruction inserts a struct field of array element value into an aggregate value.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results...
static bool isType(const Metadata *MD)
Basic type, like 'int' or 'float'.
static const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null...
const Constant * getAliasee() const