96#include "llvm/IR/IntrinsicsAArch64.h"
97#include "llvm/IR/IntrinsicsAMDGPU.h"
98#include "llvm/IR/IntrinsicsARM.h"
99#include "llvm/IR/IntrinsicsNVPTX.h"
100#include "llvm/IR/IntrinsicsWebAssembly.h"
138 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
139 "scopes are not dominating"));
162 *
OS <<
"; ModuleID = '" << M->getModuleIdentifier() <<
"'\n";
175 V.printAsOperand(*
OS,
true,
MST);
180 void Write(
const DbgRecord *DR) {
196 *
OS <<
"declare_value";
217 template <
class T>
void Write(
const MDTupleTypedArrayWrapper<T> &MD) {
221 void Write(
const NamedMDNode *NMD) {
234 void Write(
const Comdat *
C) {
240 void Write(
const APInt *AI) {
246 void Write(
const unsigned i) { *
OS << i <<
'\n'; }
252 *
OS <<
A->getAsString() <<
'\n';
256 void Write(
const AttributeSet *AS) {
263 void Write(
const AttributeList *AL) {
269 void Write(Printable
P) { *
OS <<
P <<
'\n'; }
271 template <
typename T>
void Write(ArrayRef<T> Vs) {
272 for (
const T &V : Vs)
276 template <
typename T1,
typename... Ts>
277 void WriteTs(
const T1 &V1,
const Ts &... Vs) {
282 template <
typename... Ts>
void WriteTs() {}
291 *
OS << Message <<
'\n';
299 template <
typename T1,
typename... Ts>
309 *
OS << Message <<
'\n';
315 template <
typename T1,
typename... Ts>
347 Type *LandingPadResultTy;
354 bool HasDebugInfo =
false;
397 SawFrameEscape(
false), TBAAVerifyHelper(this) {
398 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
401 bool hasBrokenDebugInfo()
const {
return BrokenDebugInfo; }
403 bool verify(
const Function &
F) {
404 llvm::TimeTraceScope timeScope(
"Verifier");
406 "An instance of this class only works with a specific module!");
415 DT.recalculate(
const_cast<Function &
>(
F));
417 for (
const BasicBlock &BB :
F) {
418 if (!BB.empty() && BB.back().isTerminator())
422 *OS <<
"Basic Block in function '" <<
F.getName()
423 <<
"' does not have terminator!\n";
424 BB.printAsOperand(*OS,
true, MST);
430 auto FailureCB = [
this](
const Twine &Message) {
431 this->CheckFailed(Message);
433 ConvergenceVerifyHelper.initialize(OS, FailureCB,
F);
438 verifySiblingFuncletUnwinds();
440 if (ConvergenceVerifyHelper.sawTokens())
441 ConvergenceVerifyHelper.verify(DT);
443 InstsInThisBlock.clear();
445 LandingPadResultTy =
nullptr;
446 SawFrameEscape =
false;
447 SiblingFuncletInfo.clear();
448 verifyNoAliasScopeDecl();
449 NoAliasScopeDecls.clear();
459 for (
const Function &
F : M)
460 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
461 DeoptimizeDeclarations.push_back(&
F);
465 verifyFrameRecoverIndices();
466 for (
const GlobalVariable &GV :
M.globals())
467 visitGlobalVariable(GV);
469 for (
const GlobalAlias &GA :
M.aliases())
470 visitGlobalAlias(GA);
472 for (
const GlobalIFunc &GI :
M.ifuncs())
473 visitGlobalIFunc(GI);
475 for (
const NamedMDNode &NMD :
M.named_metadata())
476 visitNamedMDNode(NMD);
478 for (
const StringMapEntry<Comdat> &SMEC :
M.getComdatSymbolTable())
479 visitComdat(SMEC.getValue());
483 visitModuleCommandLines();
484 visitModuleErrnoTBAA();
486 verifyCompileUnits();
488 verifyDeoptimizeCallingConvs();
489 DISubprogramAttachments.clear();
495 enum class AreDebugLocsAllowed {
No,
Yes };
499 enum class RangeLikeMetadataKind {
506 void visitGlobalValue(
const GlobalValue &GV);
507 void visitGlobalVariable(
const GlobalVariable &GV);
508 void visitGlobalAlias(
const GlobalAlias &GA);
509 void visitGlobalIFunc(
const GlobalIFunc &GI);
510 void visitAliaseeSubExpr(
const GlobalAlias &
A,
const Constant &
C);
511 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
512 const GlobalAlias &
A,
const Constant &
C);
513 void visitNamedMDNode(
const NamedMDNode &NMD);
514 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
515 void visitMetadataAsValue(
const MetadataAsValue &MD, Function *
F);
516 void visitValueAsMetadata(
const ValueAsMetadata &MD, Function *
F);
517 void visitDIArgList(
const DIArgList &AL, Function *
F);
518 void visitComdat(
const Comdat &
C);
519 void visitModuleIdents();
520 void visitModuleCommandLines();
521 void visitModuleErrnoTBAA();
522 void visitModuleFlags();
523 void visitModuleFlag(
const MDNode *
Op,
524 DenseMap<const MDString *, const MDNode *> &SeenIDs,
525 SmallVectorImpl<const MDNode *> &Requirements);
526 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
527 void visitFunction(
const Function &
F);
528 void visitBasicBlock(BasicBlock &BB);
529 void verifyRangeLikeMetadata(
const Value &V,
const MDNode *
Range,
Type *Ty,
530 RangeLikeMetadataKind Kind);
531 void visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
532 void visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
533 void visitDereferenceableMetadata(Instruction &
I, MDNode *MD);
534 void visitNofreeMetadata(Instruction &
I, MDNode *MD);
535 void visitProfMetadata(Instruction &
I, MDNode *MD);
536 void visitCallStackMetadata(MDNode *MD);
537 void visitMemProfMetadata(Instruction &
I, MDNode *MD);
538 void visitCallsiteMetadata(Instruction &
I, MDNode *MD);
539 void visitCalleeTypeMetadata(Instruction &
I, MDNode *MD);
540 void visitDIAssignIDMetadata(Instruction &
I, MDNode *MD);
541 void visitMMRAMetadata(Instruction &
I, MDNode *MD);
542 void visitAnnotationMetadata(MDNode *Annotation);
543 void visitAliasScopeMetadata(
const MDNode *MD);
544 void visitAliasScopeListMetadata(
const MDNode *MD);
545 void visitAccessGroupMetadata(
const MDNode *MD);
546 void visitCapturesMetadata(Instruction &
I,
const MDNode *Captures);
547 void visitAllocTokenMetadata(Instruction &
I, MDNode *MD);
549 template <
class Ty>
bool isValidMetadataArray(
const MDTuple &
N);
550#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
551#include "llvm/IR/Metadata.def"
552 void visitDIScope(
const DIScope &
N);
576 void checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V);
581 void visitPHINode(
PHINode &PN);
590 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
591 void visitCallInst(CallInst &CI);
592 void visitInvokeInst(InvokeInst &
II);
593 void visitGetElementPtrInst(GetElementPtrInst &
GEP);
594 void visitLoadInst(LoadInst &LI);
595 void visitStoreInst(StoreInst &SI);
596 void verifyDominatesUse(Instruction &
I,
unsigned i);
597 void visitInstruction(Instruction &
I);
598 void visitTerminator(Instruction &
I);
599 void visitBranchInst(BranchInst &BI);
600 void visitReturnInst(ReturnInst &RI);
601 void visitSwitchInst(SwitchInst &SI);
602 void visitIndirectBrInst(IndirectBrInst &BI);
603 void visitCallBrInst(CallBrInst &CBI);
604 void visitSelectInst(SelectInst &SI);
605 void visitUserOp1(Instruction &
I);
606 void visitUserOp2(Instruction &
I) { visitUserOp1(
I); }
608 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
609 void visitVPIntrinsic(VPIntrinsic &VPI);
610 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
611 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
612 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
613 void visitFenceInst(FenceInst &FI);
614 void visitAllocaInst(AllocaInst &AI);
615 void visitExtractValueInst(ExtractValueInst &EVI);
616 void visitInsertValueInst(InsertValueInst &IVI);
617 void visitEHPadPredecessors(Instruction &
I);
618 void visitLandingPadInst(LandingPadInst &LPI);
619 void visitResumeInst(ResumeInst &RI);
620 void visitCatchPadInst(CatchPadInst &CPI);
621 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
622 void visitCleanupPadInst(CleanupPadInst &CPI);
623 void visitFuncletPadInst(FuncletPadInst &FPI);
624 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
625 void visitCleanupReturnInst(CleanupReturnInst &CRI);
627 void verifySwiftErrorCall(CallBase &
Call,
const Value *SwiftErrorVal);
628 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
629 void verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs, StringRef
Context);
630 void verifyMustTailCall(CallInst &CI);
631 bool verifyAttributeCount(AttributeList Attrs,
unsigned Params);
632 void verifyAttributeTypes(AttributeSet Attrs,
const Value *V);
633 void verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
const Value *V);
634 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
636 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
637 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
638 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
639 void verifyUnknownProfileMetadata(MDNode *MD);
640 void visitConstantExprsRecursively(
const Constant *EntryC);
641 void visitConstantExpr(
const ConstantExpr *CE);
642 void visitConstantPtrAuth(
const ConstantPtrAuth *CPA);
643 void verifyInlineAsmCall(
const CallBase &
Call);
644 void verifyStatepoint(
const CallBase &
Call);
645 void verifyFrameRecoverIndices();
646 void verifySiblingFuncletUnwinds();
648 void verifyFragmentExpression(
const DbgVariableRecord &
I);
649 template <
typename ValueOrMetadata>
650 void verifyFragmentExpression(
const DIVariable &V,
652 ValueOrMetadata *
Desc);
653 void verifyFnArgs(
const DbgVariableRecord &DVR);
654 void verifyNotEntryValue(
const DbgVariableRecord &
I);
657 void verifyCompileUnits();
661 void verifyDeoptimizeCallingConvs();
663 void verifyAttachedCallBundle(
const CallBase &
Call,
664 const OperandBundleUse &BU);
667 void verifyNoAliasScopeDecl();
673#define Check(C, ...) \
676 CheckFailed(__VA_ARGS__); \
683#define CheckDI(C, ...) \
686 DebugInfoCheckFailed(__VA_ARGS__); \
694 CheckDI(
I.DebugMarker->MarkedInstr == &
I,
695 "Instruction has invalid DebugMarker", &
I);
697 "PHI Node must not have any attached DbgRecords", &
I);
700 "DbgRecord had invalid DebugMarker", &
I, &DR);
703 visitMDNode(*
Loc, AreDebugLocsAllowed::Yes);
708 verifyFragmentExpression(*DVR);
709 verifyNotEntryValue(*DVR);
716void Verifier::visit(Instruction &
I) {
718 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
719 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
731 while (!WorkList.
empty()) {
733 if (!Visited.
insert(Cur).second)
740void Verifier::visitGlobalValue(
const GlobalValue &GV) {
742 "Global is external, but doesn't have external or weak linkage!", &GV);
745 if (
const MDNode *Associated =
746 GO->getMetadata(LLVMContext::MD_associated)) {
747 Check(Associated->getNumOperands() == 1,
748 "associated metadata must have one operand", &GV, Associated);
749 const Metadata *
Op = Associated->getOperand(0).get();
750 Check(
Op,
"associated metadata must have a global value", GO, Associated);
753 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
756 "associated value must be pointer typed", GV, Associated);
758 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
760 "associated metadata must point to a GlobalObject", GO, Stripped);
761 Check(Stripped != GO,
762 "global values should not associate to themselves", GO,
768 if (
const MDNode *AbsoluteSymbol =
769 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
770 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
771 DL.getIntPtrType(GO->getType()),
772 RangeLikeMetadataKind::AbsoluteSymbol);
775 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
776 Check(!GO->isDeclaration(),
777 "ref metadata must not be placed on a declaration", GO);
780 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
781 for (
const MDNode *MD : MDs) {
782 Check(MD->getNumOperands() == 1,
"ref metadata must have one operand",
786 Check(VM,
"ref metadata must be ValueAsMetadata", GO, MD);
789 "ref value must be pointer typed", GV, MD);
793 "ref metadata must point to a GlobalObject", GO, Stripped);
794 Check(Stripped != GO,
"values should not reference themselves", GO,
802 "Only global variables can have appending linkage!", &GV);
807 "Only global arrays can have appending linkage!", GVar);
811 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
815 "dllexport GlobalValue must have default or protected visibility",
820 "dllimport GlobalValue must have default visibility", &GV);
821 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
827 "Global is marked as dllimport, but not external", &GV);
832 "GlobalValue with local linkage or non-default "
833 "visibility must be dso_local!",
838 if (!
I->getParent() || !
I->getParent()->getParent())
839 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
841 else if (
I->getParent()->getParent()->getParent() != &M)
842 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
843 I->getParent()->getParent(),
844 I->getParent()->getParent()->getParent());
847 if (
F->getParent() != &M)
848 CheckFailed(
"Global is used by function in a different module", &GV, &M,
856void Verifier::visitGlobalVariable(
const GlobalVariable &GV) {
860 Check(
A->value() <= Value::MaximumAlignment,
861 "huge alignment values are unsupported", &GV);
866 "Global variable initializer type does not match global "
870 "Global variable initializer must be sized", &GV);
876 "'common' global must have a zero initializer!", &GV);
879 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
884 GV.
getName() ==
"llvm.global_dtors")) {
886 "invalid linkage for intrinsic global variable", &GV);
888 "invalid uses of intrinsic global variable", &GV);
895 PointerType::get(
Context,
DL.getProgramAddressSpace());
899 "wrong type for intrinsic global variable", &GV);
901 "the third field of the element type is mandatory, "
902 "specify ptr null to migrate from the obsoleted 2-field form");
910 GV.
getName() ==
"llvm.compiler.used")) {
912 "invalid linkage for intrinsic global variable", &GV);
914 "invalid uses of intrinsic global variable", &GV);
918 Check(PTy,
"wrong type for intrinsic global variable", &GV);
922 Check(InitArray,
"wrong initializer for intrinsic global variable",
928 Twine(
"invalid ") + GV.
getName() +
" member", V);
930 Twine(
"members of ") + GV.
getName() +
" must be named", V);
939 for (
auto *MD : MDs) {
941 visitDIGlobalVariableExpression(*GVE);
943 CheckDI(
false,
"!dbg attachment of global variable must be a "
944 "DIGlobalVariableExpression");
954 "Global @" + GV.
getName() +
" has illegal target extension type",
958 visitGlobalValue(GV);
965 visitGlobalValue(GV);
968void Verifier::visitAliaseeSubExpr(
const GlobalAlias &GA,
const Constant &
C) {
969 SmallPtrSet<const GlobalAlias*, 4> Visited;
971 visitAliaseeSubExpr(Visited, GA,
C);
974void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
975 const GlobalAlias &GA,
const Constant &
C) {
979 "available_externally alias must point to available_externally "
990 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
992 Check(!GA2->isInterposable(),
993 "Alias cannot point to an interposable alias", &GA);
1002 visitConstantExprsRecursively(CE);
1004 for (
const Use &U :
C.operands()) {
1007 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
1009 visitAliaseeSubExpr(Visited, GA, *C2);
1013void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
1015 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
1016 "weak_odr, external, or available_externally linkage!",
1019 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
1021 "Alias and aliasee types should match!", &GA);
1024 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
1026 visitAliaseeSubExpr(GA, *Aliasee);
1028 visitGlobalValue(GA);
1031void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
1032 visitGlobalValue(GI);
1036 for (
const auto &
I : MDs) {
1037 CheckDI(
I.first != LLVMContext::MD_dbg,
1038 "an ifunc may not have a !dbg attachment", &GI);
1039 Check(
I.first != LLVMContext::MD_prof,
1040 "an ifunc may not have a !prof attachment", &GI);
1041 visitMDNode(*
I.second, AreDebugLocsAllowed::No);
1045 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
1046 "weak_odr, or external linkage!",
1051 Check(Resolver,
"IFunc must have a Function resolver", &GI);
1053 "IFunc resolver must be a definition", &GI);
1060 "IFunc resolver must return a pointer", &GI);
1063 "IFunc resolver has incorrect type", &GI);
1066void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
1071 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
1072 for (
const MDNode *MD : NMD.
operands()) {
1073 if (NMD.
getName() ==
"llvm.dbg.cu")
1079 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
1083void Verifier::visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs) {
1086 if (!MDNodes.
insert(&MD).second)
1090 "MDNode context does not match Module context!", &MD);
1095 case Metadata::MDTupleKind:
1097#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
1098 case Metadata::CLASS##Kind: \
1099 visit##CLASS(cast<CLASS>(MD)); \
1101#include "llvm/IR/Metadata.def"
1110 "DILocation not allowed within this metadata node", &MD,
Op);
1112 visitMDNode(*
N, AllowLocs);
1116 visitValueAsMetadata(*V,
nullptr);
1128 "Expected second operand to be an integer constant of type i32 or "
1138void Verifier::visitValueAsMetadata(
const ValueAsMetadata &MD, Function *
F) {
1141 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1147 Check(
F,
"function-local metadata used outside a function", L);
1153 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1159 assert(ActualF &&
"Unimplemented function local metadata case!");
1161 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1164void Verifier::visitDIArgList(
const DIArgList &AL, Function *
F) {
1165 for (
const ValueAsMetadata *VAM :
AL.getArgs())
1166 visitValueAsMetadata(*VAM,
F);
1169void Verifier::visitMetadataAsValue(
const MetadataAsValue &MDV, Function *
F) {
1172 visitMDNode(*
N, AreDebugLocsAllowed::No);
1178 if (!MDNodes.
insert(MD).second)
1182 visitValueAsMetadata(*V,
F);
1185 visitDIArgList(*AL,
F);
1193void Verifier::visitDILocation(
const DILocation &
N) {
1195 "location requires a valid scope", &
N,
N.getRawScope());
1196 if (
auto *IA =
N.getRawInlinedAt())
1199 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1202void Verifier::visitGenericDINode(
const GenericDINode &
N) {
1206void Verifier::visitDIScope(
const DIScope &
N) {
1207 if (
auto *
F =
N.getRawFile())
1211void Verifier::visitDISubrangeType(
const DISubrangeType &
N) {
1212 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1215 auto *LBound =
N.getRawLowerBound();
1219 "LowerBound must be signed constant or DIVariable or DIExpression or "
1222 auto *UBound =
N.getRawUpperBound();
1226 "UpperBound must be signed constant or DIVariable or DIExpression or "
1229 auto *Stride =
N.getRawStride();
1232 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1233 auto *Bias =
N.getRawBias();
1236 "Bias must be signed constant or DIVariable or DIExpression", &
N);
1238 auto *
Size =
N.getRawSizeInBits();
1240 "SizeInBits must be a constant");
1243void Verifier::visitDISubrange(
const DISubrange &
N) {
1244 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1245 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1246 "Subrange can have any one of count or upperBound", &
N);
1247 auto *CBound =
N.getRawCountNode();
1250 "Count must be signed constant or DIVariable or DIExpression", &
N);
1251 auto Count =
N.getCount();
1254 "invalid subrange count", &
N);
1255 auto *LBound =
N.getRawLowerBound();
1258 "LowerBound must be signed constant or DIVariable or DIExpression",
1260 auto *UBound =
N.getRawUpperBound();
1263 "UpperBound must be signed constant or DIVariable or DIExpression",
1265 auto *Stride =
N.getRawStride();
1268 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1271void Verifier::visitDIGenericSubrange(
const DIGenericSubrange &
N) {
1272 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1273 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1274 "GenericSubrange can have any one of count or upperBound", &
N);
1275 auto *CBound =
N.getRawCountNode();
1277 "Count must be signed constant or DIVariable or DIExpression", &
N);
1278 auto *LBound =
N.getRawLowerBound();
1279 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1281 "LowerBound must be signed constant or DIVariable or DIExpression",
1283 auto *UBound =
N.getRawUpperBound();
1285 "UpperBound must be signed constant or DIVariable or DIExpression",
1287 auto *Stride =
N.getRawStride();
1288 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1290 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1293void Verifier::visitDIEnumerator(
const DIEnumerator &
N) {
1294 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1297void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1298 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1299 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1300 N.getTag() == dwarf::DW_TAG_string_type,
1303 auto *
Size =
N.getRawSizeInBits();
1305 "SizeInBits must be a constant");
1308void Verifier::visitDIFixedPointType(
const DIFixedPointType &
N) {
1309 visitDIBasicType(
N);
1311 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type,
"invalid tag", &
N);
1312 CheckDI(
N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1313 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1314 "invalid encoding", &
N);
1318 "invalid kind", &
N);
1320 N.getFactorRaw() == 0,
1321 "factor should be 0 for rationals", &
N);
1323 (
N.getNumeratorRaw() == 0 &&
N.getDenominatorRaw() == 0),
1324 "numerator and denominator should be 0 for non-rationals", &
N);
1327void Verifier::visitDIStringType(
const DIStringType &
N) {
1328 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1329 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1333void Verifier::visitDIDerivedType(
const DIDerivedType &
N) {
1337 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1338 N.getTag() == dwarf::DW_TAG_pointer_type ||
1339 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1340 N.getTag() == dwarf::DW_TAG_reference_type ||
1341 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1342 N.getTag() == dwarf::DW_TAG_const_type ||
1343 N.getTag() == dwarf::DW_TAG_immutable_type ||
1344 N.getTag() == dwarf::DW_TAG_volatile_type ||
1345 N.getTag() == dwarf::DW_TAG_restrict_type ||
1346 N.getTag() == dwarf::DW_TAG_atomic_type ||
1347 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1348 N.getTag() == dwarf::DW_TAG_member ||
1349 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1350 N.getTag() == dwarf::DW_TAG_inheritance ||
1351 N.getTag() == dwarf::DW_TAG_friend ||
1352 N.getTag() == dwarf::DW_TAG_set_type ||
1353 N.getTag() == dwarf::DW_TAG_template_alias,
1355 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1356 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1357 N.getRawExtraData());
1358 }
else if (
N.getTag() == dwarf::DW_TAG_template_alias) {
1360 N.getRawExtraData());
1361 }
else if (
N.getTag() == dwarf::DW_TAG_inheritance ||
1362 N.getTag() == dwarf::DW_TAG_member ||
1363 N.getTag() == dwarf::DW_TAG_variable) {
1364 auto *ExtraData =
N.getRawExtraData();
1365 auto IsValidExtraData = [&]() {
1366 if (ExtraData ==
nullptr)
1372 if (Tuple->getNumOperands() != 1)
1379 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1380 "or MDTuple with single ConstantAsMetadata operand",
1384 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1385 if (
auto *
T =
N.getRawBaseType()) {
1390 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1391 (Subrange &&
Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1392 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1393 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1394 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1395 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1396 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1397 "invalid set base type", &
N,
T);
1403 N.getRawBaseType());
1405 if (
N.getDWARFAddressSpace()) {
1406 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1407 N.getTag() == dwarf::DW_TAG_reference_type ||
1408 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1409 "DWARF address space only applies to pointer or reference types",
1413 auto *
Size =
N.getRawSizeInBits();
1416 "SizeInBits must be a constant or DIVariable or DIExpression");
1421 return ((Flags & DINode::FlagLValueReference) &&
1422 (Flags & DINode::FlagRValueReference)) ||
1423 ((Flags & DINode::FlagTypePassByValue) &&
1424 (Flags & DINode::FlagTypePassByReference));
1427void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1429 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1436void Verifier::visitDICompositeType(
const DICompositeType &
N) {
1440 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1441 N.getTag() == dwarf::DW_TAG_structure_type ||
1442 N.getTag() == dwarf::DW_TAG_union_type ||
1443 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1444 N.getTag() == dwarf::DW_TAG_class_type ||
1445 N.getTag() == dwarf::DW_TAG_variant_part ||
1446 N.getTag() == dwarf::DW_TAG_variant ||
1447 N.getTag() == dwarf::DW_TAG_namelist,
1452 N.getRawBaseType());
1455 "invalid composite elements", &
N,
N.getRawElements());
1457 N.getRawVTableHolder());
1459 "invalid reference flags", &
N);
1460 unsigned DIBlockByRefStruct = 1 << 4;
1461 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1462 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1464 "DISubprogram contains null entry in `elements` field", &
N);
1467 const DINodeArray
Elements =
N.getElements();
1469 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1470 "invalid vector, expected one element of type subrange", &
N);
1473 if (
auto *Params =
N.getRawTemplateParams())
1474 visitTemplateParams(
N, *Params);
1476 if (
auto *
D =
N.getRawDiscriminator()) {
1478 "discriminator can only appear on variant part");
1481 if (
N.getRawDataLocation()) {
1482 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1483 "dataLocation can only appear in array type");
1486 if (
N.getRawAssociated()) {
1487 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1488 "associated can only appear in array type");
1491 if (
N.getRawAllocated()) {
1492 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1493 "allocated can only appear in array type");
1496 if (
N.getRawRank()) {
1497 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1498 "rank can only appear in array type");
1501 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1502 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1505 auto *
Size =
N.getRawSizeInBits();
1508 "SizeInBits must be a constant or DIVariable or DIExpression");
1511void Verifier::visitDISubroutineType(
const DISubroutineType &
N) {
1512 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1513 if (
auto *Types =
N.getRawTypeArray()) {
1515 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1516 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1520 "invalid reference flags", &
N);
1523void Verifier::visitDIFile(
const DIFile &
N) {
1524 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1525 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1527 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1528 "invalid checksum kind", &
N);
1530 switch (Checksum->Kind) {
1541 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1543 "invalid checksum", &
N);
1547void Verifier::visitDICompileUnit(
const DICompileUnit &
N) {
1548 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1549 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1555 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1559 "invalid emission kind", &
N);
1561 if (
auto *Array =
N.getRawEnumTypes()) {
1563 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1565 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1566 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1569 if (
auto *Array =
N.getRawRetainedTypes()) {
1571 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1575 "invalid retained type", &
N,
Op);
1578 if (
auto *Array =
N.getRawGlobalVariables()) {
1580 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1582 "invalid global variable ref", &
N,
Op);
1585 if (
auto *Array =
N.getRawImportedEntities()) {
1587 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1592 if (
auto *Array =
N.getRawMacros()) {
1601void Verifier::visitDISubprogram(
const DISubprogram &
N) {
1602 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1604 if (
auto *
F =
N.getRawFile())
1607 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1608 if (
auto *
T =
N.getRawType())
1610 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1611 N.getRawContainingType());
1612 if (
auto *Params =
N.getRawTemplateParams())
1613 visitTemplateParams(
N, *Params);
1614 if (
auto *S =
N.getRawDeclaration())
1616 "invalid subprogram declaration", &
N, S);
1617 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1619 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1621 CheckDI(
Op,
"nullptr in retained nodes", &
N, Node);
1623 auto True = [](
const Metadata *) {
return true; };
1624 auto False = [](
const Metadata *) {
return false; };
1625 bool IsTypeCorrect =
1626 DISubprogram::visitRetainedNode<bool>(
Op, True, True, True, False);
1628 "invalid retained nodes, expected DILocalVariable, DILabel or "
1636 "invalid retained nodes, retained node is not local", &
N, Node,
1639 RetainedNodeScope->getSubprogram() == &
N,
1640 "invalid retained nodes, retained node does not belong to subprogram",
1641 &
N, Node, RetainedNode, RetainedNodeScope);
1645 "invalid reference flags", &
N);
1647 auto *
Unit =
N.getRawUnit();
1648 if (
N.isDefinition()) {
1650 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1651 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1656 if (CT && CT->getRawIdentifier() &&
1657 M.getContext().isODRUniquingDebugTypes())
1659 "definition subprograms cannot be nested within DICompositeType "
1660 "when enabling ODR",
1664 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1666 "subprogram declaration must not have a declaration field");
1669 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1671 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1677 if (
N.areAllCallsDescribed())
1679 "DIFlagAllCallsDescribed must be attached to a definition");
1682void Verifier::visitDILexicalBlockBase(
const DILexicalBlockBase &
N) {
1683 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1685 "invalid local scope", &
N,
N.getRawScope());
1687 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1690void Verifier::visitDILexicalBlock(
const DILexicalBlock &
N) {
1691 visitDILexicalBlockBase(
N);
1694 "cannot have column info without line info", &
N);
1697void Verifier::visitDILexicalBlockFile(
const DILexicalBlockFile &
N) {
1698 visitDILexicalBlockBase(
N);
1701void Verifier::visitDICommonBlock(
const DICommonBlock &
N) {
1702 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1703 if (
auto *S =
N.getRawScope())
1705 if (
auto *S =
N.getRawDecl())
1709void Verifier::visitDINamespace(
const DINamespace &
N) {
1710 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1711 if (
auto *S =
N.getRawScope())
1715void Verifier::visitDIMacro(
const DIMacro &
N) {
1718 "invalid macinfo type", &
N);
1719 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1720 if (!
N.getValue().empty()) {
1721 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1725void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1727 "invalid macinfo type", &
N);
1728 if (
auto *
F =
N.getRawFile())
1731 if (
auto *Array =
N.getRawElements()) {
1733 for (
Metadata *
Op :
N.getElements()->operands()) {
1739void Verifier::visitDIModule(
const DIModule &
N) {
1740 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1741 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1744void Verifier::visitDITemplateParameter(
const DITemplateParameter &
N) {
1748void Verifier::visitDITemplateTypeParameter(
const DITemplateTypeParameter &
N) {
1749 visitDITemplateParameter(
N);
1751 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1755void Verifier::visitDITemplateValueParameter(
1756 const DITemplateValueParameter &
N) {
1757 visitDITemplateParameter(
N);
1759 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1760 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1761 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1765void Verifier::visitDIVariable(
const DIVariable &
N) {
1766 if (
auto *S =
N.getRawScope())
1768 if (
auto *
F =
N.getRawFile())
1772void Verifier::visitDIGlobalVariable(
const DIGlobalVariable &
N) {
1776 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1779 if (
N.isDefinition())
1780 CheckDI(
N.getType(),
"missing global variable type", &
N);
1781 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1783 "invalid static data member declaration", &
N, Member);
1787void Verifier::visitDILocalVariable(
const DILocalVariable &
N) {
1792 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1794 "local variable requires a valid scope", &
N,
N.getRawScope());
1795 if (
auto Ty =
N.getType())
1799void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1800 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1801 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1804void Verifier::visitDILabel(
const DILabel &
N) {
1805 if (
auto *S =
N.getRawScope())
1807 if (
auto *
F =
N.getRawFile())
1810 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1812 "label requires a valid scope", &
N,
N.getRawScope());
1815void Verifier::visitDIExpression(
const DIExpression &
N) {
1816 CheckDI(
N.isValid(),
"invalid expression", &
N);
1819void Verifier::visitDIGlobalVariableExpression(
1820 const DIGlobalVariableExpression &GVE) {
1823 visitDIGlobalVariable(*Var);
1825 visitDIExpression(*Expr);
1826 if (
auto Fragment = Expr->getFragmentInfo())
1827 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1831void Verifier::visitDIObjCProperty(
const DIObjCProperty &
N) {
1832 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1833 if (
auto *
T =
N.getRawType())
1835 if (
auto *
F =
N.getRawFile())
1839void Verifier::visitDIImportedEntity(
const DIImportedEntity &
N) {
1840 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1841 N.getTag() == dwarf::DW_TAG_imported_declaration,
1843 if (
auto *S =
N.getRawScope())
1849void Verifier::visitComdat(
const Comdat &
C) {
1852 if (
TT.isOSBinFormatCOFF())
1853 if (
const GlobalValue *GV =
M.getNamedValue(
C.getName()))
1858void Verifier::visitModuleIdents() {
1859 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1865 for (
const MDNode *
N : Idents->
operands()) {
1866 Check(
N->getNumOperands() == 1,
1867 "incorrect number of operands in llvm.ident metadata",
N);
1869 (
"invalid value for llvm.ident metadata entry operand"
1870 "(the operand should be a string)"),
1875void Verifier::visitModuleCommandLines() {
1876 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1883 for (
const MDNode *
N : CommandLines->
operands()) {
1884 Check(
N->getNumOperands() == 1,
1885 "incorrect number of operands in llvm.commandline metadata",
N);
1887 (
"invalid value for llvm.commandline metadata entry operand"
1888 "(the operand should be a string)"),
1893void Verifier::visitModuleErrnoTBAA() {
1894 const NamedMDNode *ErrnoTBAA =
M.getNamedMetadata(
"llvm.errno.tbaa");
1899 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1901 for (
const MDNode *
N : ErrnoTBAA->
operands())
1905void Verifier::visitModuleFlags() {
1906 const NamedMDNode *
Flags =
M.getModuleFlagsMetadata();
1910 DenseMap<const MDString*, const MDNode*> SeenIDs;
1912 uint64_t PAuthABIPlatform = -1;
1913 uint64_t PAuthABIVersion = -1;
1914 for (
const MDNode *MDN :
Flags->operands()) {
1915 visitModuleFlag(MDN, SeenIDs, Requirements);
1916 if (MDN->getNumOperands() != 3)
1919 if (FlagName->getString() ==
"aarch64-elf-pauthabi-platform") {
1920 if (
const auto *PAP =
1922 PAuthABIPlatform = PAP->getZExtValue();
1923 }
else if (FlagName->getString() ==
"aarch64-elf-pauthabi-version") {
1924 if (
const auto *PAV =
1926 PAuthABIVersion = PAV->getZExtValue();
1931 if ((PAuthABIPlatform == uint64_t(-1)) != (PAuthABIVersion == uint64_t(-1)))
1932 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
1933 "'aarch64-elf-pauthabi-version' module flags must be present");
1936 for (
const MDNode *Requirement : Requirements) {
1938 const Metadata *ReqValue = Requirement->getOperand(1);
1940 const MDNode *
Op = SeenIDs.
lookup(Flag);
1942 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1947 if (
Op->getOperand(2) != ReqValue) {
1948 CheckFailed((
"invalid requirement on flag, "
1949 "flag does not have the required value"),
1957Verifier::visitModuleFlag(
const MDNode *
Op,
1958 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1959 SmallVectorImpl<const MDNode *> &Requirements) {
1963 "incorrect number of operands in module flag",
Op);
1964 Module::ModFlagBehavior MFB;
1965 if (!Module::isValidModFlagBehavior(
Op->getOperand(0), MFB)) {
1967 "invalid behavior operand in module flag (expected constant integer)",
1970 "invalid behavior operand in module flag (unexpected constant)",
1974 Check(
ID,
"invalid ID operand in module flag (expected metadata string)",
1980 case Module::Warning:
1981 case Module::Override:
1987 Check(V &&
V->getValue().isNonNegative(),
1988 "invalid value for 'min' module flag (expected constant non-negative "
1996 "invalid value for 'max' module flag (expected constant integer)",
2001 case Module::Require: {
2006 "invalid value for 'require' module flag (expected metadata pair)",
2009 (
"invalid value for 'require' module flag "
2010 "(first value operand should be a string)"),
2011 Value->getOperand(0));
2019 case Module::Append:
2020 case Module::AppendUnique: {
2023 "invalid value for 'append'-type module flag "
2024 "(expected a metadata node)",
2031 if (MFB != Module::Require) {
2034 "module flag identifiers must be unique (or of 'require' type)",
ID);
2037 if (
ID->getString() ==
"wchar_size") {
2040 Check(
Value,
"wchar_size metadata requires constant integer argument");
2043 if (
ID->getString() ==
"Linker Options") {
2047 Check(
M.getNamedMetadata(
"llvm.linker.options"),
2048 "'Linker Options' named metadata no longer supported");
2051 if (
ID->getString() ==
"SemanticInterposition") {
2052 ConstantInt *
Value =
2055 "SemanticInterposition metadata requires constant integer argument");
2058 if (
ID->getString() ==
"CG Profile") {
2059 for (
const MDOperand &MDO :
cast<MDNode>(
Op->getOperand(2))->operands())
2060 visitModuleFlagCGProfileEntry(MDO);
2064void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
2065 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
2070 "expected a Function or null", FuncMDO);
2073 Check(Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
2074 CheckFunction(
Node->getOperand(0));
2075 CheckFunction(
Node->getOperand(1));
2078 "expected an integer constant",
Node->getOperand(2));
2081void Verifier::verifyAttributeTypes(AttributeSet Attrs,
const Value *V) {
2084 if (
A.isStringAttribute()) {
2085#define GET_ATTR_NAMES
2086#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2087#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2088 if (A.getKindAsString() == #DISPLAY_NAME) { \
2089 auto V = A.getValueAsString(); \
2090 if (!(V.empty() || V == "true" || V == "false")) \
2091 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2095#include "llvm/IR/Attributes.inc"
2099 if (
A.isIntAttribute() != Attribute::isIntAttrKind(
A.getKindAsEnum())) {
2100 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
2109void Verifier::verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
2111 if (!
Attrs.hasAttributes())
2114 verifyAttributeTypes(Attrs, V);
2117 Check(Attr.isStringAttribute() ||
2118 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2119 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
2122 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
2123 unsigned AttrCount =
2124 Attrs.getNumAttributes() -
Attrs.hasAttribute(Attribute::Range);
2125 Check(AttrCount == 1,
2126 "Attribute 'immarg' is incompatible with other attributes except the "
2127 "'range' attribute",
2133 unsigned AttrCount = 0;
2134 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
2135 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
2136 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
2137 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
2138 Attrs.hasAttribute(Attribute::InReg);
2139 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
2140 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
2141 Check(AttrCount <= 1,
2142 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2143 "'byref', and 'sret' are incompatible!",
2146 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
2147 Attrs.hasAttribute(Attribute::ReadOnly)),
2149 "'inalloca and readonly' are incompatible!",
2152 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
2153 Attrs.hasAttribute(Attribute::Returned)),
2155 "'sret and returned' are incompatible!",
2158 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
2159 Attrs.hasAttribute(Attribute::SExt)),
2161 "'zeroext and signext' are incompatible!",
2164 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2165 Attrs.hasAttribute(Attribute::ReadOnly)),
2167 "'readnone and readonly' are incompatible!",
2170 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2171 Attrs.hasAttribute(Attribute::WriteOnly)),
2173 "'readnone and writeonly' are incompatible!",
2176 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
2177 Attrs.hasAttribute(Attribute::WriteOnly)),
2179 "'readonly and writeonly' are incompatible!",
2182 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2183 Attrs.hasAttribute(Attribute::AlwaysInline)),
2185 "'noinline and alwaysinline' are incompatible!",
2188 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2189 Attrs.hasAttribute(Attribute::ReadNone)),
2190 "Attributes writable and readnone are incompatible!", V);
2192 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2193 Attrs.hasAttribute(Attribute::ReadOnly)),
2194 "Attributes writable and readonly are incompatible!", V);
2196 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2198 if (!Attr.isStringAttribute() &&
2199 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2200 CheckFailed(
"Attribute '" + Attr.getAsString() +
2201 "' applied to incompatible type!", V);
2207 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2208 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2209 Check(AttrAlign.
value() <= Value::MaximumAlignment,
2210 "huge alignment values are unsupported", V);
2212 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2214 SmallPtrSet<Type *, 4> Visited;
2216 "Attribute 'byval' does not support unsized types!", V);
2220 "'byval' argument has illegal target extension type", V);
2221 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2222 "huge 'byval' arguments are unsupported", V);
2224 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2225 SmallPtrSet<Type *, 4> Visited;
2226 Check(
Attrs.getByRefType()->isSized(&Visited),
2227 "Attribute 'byref' does not support unsized types!", V);
2228 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2230 "huge 'byref' arguments are unsupported", V);
2232 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2233 SmallPtrSet<Type *, 4> Visited;
2234 Check(
Attrs.getInAllocaType()->isSized(&Visited),
2235 "Attribute 'inalloca' does not support unsized types!", V);
2236 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2238 "huge 'inalloca' arguments are unsupported", V);
2240 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2241 SmallPtrSet<Type *, 4> Visited;
2242 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
2243 "Attribute 'preallocated' does not support unsized types!", V);
2245 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2247 "huge 'preallocated' arguments are unsupported", V);
2251 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2252 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2253 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2256 "Attribute 'initializes' does not support unordered ranges", V);
2259 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2260 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2261 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2264 "Invalid value for 'nofpclass' test mask", V);
2266 if (
Attrs.hasAttribute(Attribute::Range)) {
2267 const ConstantRange &CR =
2268 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2270 "Range bit width must match type bit width!", V);
2274void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2276 if (
Attrs.hasFnAttr(Attr)) {
2277 StringRef S =
Attrs.getFnAttr(Attr).getValueAsString();
2280 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
2286void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2287 const Value *V,
bool IsIntrinsic,
2289 if (
Attrs.isEmpty())
2292 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2294 "Attribute list does not match Module context!", &Attrs, V);
2295 for (
const auto &AttrSet : Attrs) {
2296 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
2297 "Attribute set does not match Module context!", &AttrSet, V);
2298 for (
const auto &
A : AttrSet) {
2300 "Attribute does not match Module context!", &
A, V);
2305 bool SawNest =
false;
2306 bool SawReturned =
false;
2307 bool SawSRet =
false;
2308 bool SawSwiftSelf =
false;
2309 bool SawSwiftAsync =
false;
2310 bool SawSwiftError =
false;
2313 AttributeSet RetAttrs =
Attrs.getRetAttrs();
2316 Attribute::canUseAsRetAttr(
RetAttr.getKindAsEnum()),
2317 "Attribute '" +
RetAttr.getAsString() +
2318 "' does not apply to function return values",
2321 unsigned MaxParameterWidth = 0;
2322 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2325 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2326 if (
Size > MaxParameterWidth)
2327 MaxParameterWidth =
Size;
2331 GetMaxParameterWidth(FT->getReturnType());
2332 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2335 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2336 Type *Ty = FT->getParamType(i);
2337 AttributeSet ArgAttrs =
Attrs.getParamAttrs(i);
2341 "immarg attribute only applies to intrinsics", V);
2344 "Attribute 'elementtype' can only be applied to intrinsics"
2349 verifyParameterAttrs(ArgAttrs, Ty, V);
2350 GetMaxParameterWidth(Ty);
2353 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2358 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2360 "Incompatible argument and return types for 'returned' attribute",
2366 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2367 Check(i == 0 || i == 1,
2368 "Attribute 'sret' is not on first or second parameter!", V);
2373 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2374 SawSwiftSelf =
true;
2378 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2379 SawSwiftAsync =
true;
2383 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2384 SawSwiftError =
true;
2388 Check(i == FT->getNumParams() - 1,
2389 "inalloca isn't on the last parameter!", V);
2393 if (!
Attrs.hasFnAttrs())
2396 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2399 Attribute::canUseAsFnAttr(
FnAttr.getKindAsEnum()),
2400 "Attribute '" +
FnAttr.getAsString() +
2401 "' does not apply to functions!",
2404 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2405 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2406 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2408 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2410 "Attribute 'optnone' requires 'noinline'!", V);
2412 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2413 "Attributes 'optsize and optnone' are incompatible!", V);
2416 "Attributes 'minsize and optnone' are incompatible!", V);
2418 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2419 "Attributes 'optdebug and optnone' are incompatible!", V);
2422 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2423 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2425 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2428 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2429 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2430 "Attributes 'optsize and optdebug' are incompatible!", V);
2433 "Attributes 'minsize and optdebug' are incompatible!", V);
2436 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2437 isModSet(
Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2438 "Attribute writable and memory without argmem: write are incompatible!",
2441 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2442 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2443 "Attributes 'aarch64_pstate_sm_enabled and "
2444 "aarch64_pstate_sm_compatible' are incompatible!",
2448 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2449 Attrs.hasFnAttr(
"aarch64_inout_za") +
2450 Attrs.hasFnAttr(
"aarch64_out_za") +
2451 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2452 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2453 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2454 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2455 "'aarch64_za_state_agnostic' are mutually exclusive",
2459 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2460 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2461 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2462 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2463 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2464 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2465 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2466 "'aarch64_za_state_agnostic' are mutually exclusive",
2469 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2472 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2475 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2476 auto CheckParam = [&](StringRef
Name,
unsigned ParamNo) {
2477 if (ParamNo >= FT->getNumParams()) {
2478 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds", V);
2482 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2483 CheckFailed(
"'allocsize' " + Name +
2484 " argument must refer to an integer parameter",
2492 if (!CheckParam(
"element size",
Args->first))
2495 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2499 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2502 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2504 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2507 "'allockind()' requires exactly one of alloc, realloc, and free");
2508 if ((
Type == AllocFnKind::Free) &&
2509 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2510 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2511 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2512 "or aligned modifiers.");
2513 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2514 if ((K & ZeroedUninit) == ZeroedUninit)
2515 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2519 StringRef S =
A.getValueAsString();
2520 Check(!S.
empty(),
"'alloc-variant-zeroed' must not be empty");
2528 "'alloc-variant-zeroed' must name a function belonging to the "
2529 "same 'alloc-family'");
2532 (
Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2533 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2534 "'alloc-variant-zeroed' must name a function with "
2535 "'allockind(\"zeroed\")'");
2538 "'alloc-variant-zeroed' must name a function with the same "
2543 "'alloc-variant-zeroed' must name a function with the same "
2544 "calling convention");
2548 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2549 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2551 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2553 CheckFailed(
"'vscale_range' minimum must be power-of-two value", V);
2554 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2555 if (VScaleMax && VScaleMin > VScaleMax)
2556 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2558 CheckFailed(
"'vscale_range' maximum must be power-of-two value", V);
2561 if (
Attribute FPAttr =
Attrs.getFnAttr(
"frame-pointer"); FPAttr.isValid()) {
2562 StringRef
FP = FPAttr.getValueAsString();
2563 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved" &&
2564 FP !=
"non-leaf-no-reserve")
2565 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2568 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2569 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2570 if (
Attrs.hasFnAttr(
"patchable-function-entry-section"))
2571 Check(!
Attrs.getFnAttr(
"patchable-function-entry-section")
2574 "\"patchable-function-entry-section\" must not be empty");
2575 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2577 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2578 StringRef S =
A.getValueAsString();
2579 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2580 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S, V);
2583 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2584 StringRef S =
A.getValueAsString();
2585 if (S !=
"a_key" && S !=
"b_key")
2586 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2588 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2590 "'sign-return-address-key' present without `sign-return-address`");
2594 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2595 StringRef S =
A.getValueAsString();
2596 if (S !=
"" && S !=
"true" && S !=
"false")
2598 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2601 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2602 StringRef S =
A.getValueAsString();
2603 if (S !=
"" && S !=
"true" && S !=
"false")
2605 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2608 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2609 StringRef S =
A.getValueAsString();
2610 if (S !=
"" && S !=
"true" && S !=
"false")
2611 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2615 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2616 StringRef S =
A.getValueAsString();
2619 CheckFailed(
"invalid name for a VFABI variant: " + S, V);
2622 if (
auto A =
Attrs.getFnAttr(
"denormal-fp-math");
A.isValid()) {
2623 StringRef S =
A.getValueAsString();
2625 CheckFailed(
"invalid value for 'denormal-fp-math' attribute: " + S, V);
2628 if (
auto A =
Attrs.getFnAttr(
"denormal-fp-math-f32");
A.isValid()) {
2629 StringRef S =
A.getValueAsString();
2631 CheckFailed(
"invalid value for 'denormal-fp-math-f32' attribute: " + S,
2635 if (
auto A =
Attrs.getFnAttr(
"modular-format");
A.isValid()) {
2636 StringRef S =
A.getValueAsString();
2640 "modular-format attribute requires at least 5 arguments", V);
2641 unsigned FirstArgIdx;
2642 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2643 "modular-format attribute first arg index is not an integer", V);
2644 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2645 Check(FirstArgIdx > 0 && FirstArgIdx <= UpperBound,
2646 "modular-format attribute first arg index is out of bounds", V);
2649 if (
auto A =
Attrs.getFnAttr(
"target-features");
A.isValid()) {
2650 StringRef S =
A.getValueAsString();
2652 for (
auto FeatureFlag :
split(S,
',')) {
2653 if (FeatureFlag.empty())
2655 "target-features attribute should not contain an empty string");
2657 Check(FeatureFlag[0] ==
'+' || FeatureFlag[0] ==
'-',
2658 "target feature '" + FeatureFlag +
2659 "' must start with a '+' or '-'",
2665void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2667 "'unknown' !prof should have a single additional operand", MD);
2670 "'unknown' !prof should have an additional operand of type "
2673 "the 'unknown' !prof operand should not be an empty string");
2676void Verifier::verifyFunctionMetadata(
2677 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2678 for (
const auto &Pair : MDs) {
2679 if (Pair.first == LLVMContext::MD_prof) {
2680 MDNode *MD = Pair.second;
2682 "!prof annotations should have no less than 2 operands", MD);
2687 verifyUnknownProfileMetadata(MD);
2692 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2695 "expected string with name of the !prof annotation", MD);
2700 "first operand should be 'function_entry_count'"
2701 " or 'synthetic_function_entry_count'",
2705 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2708 "expected integer argument to function_entry_count", MD);
2709 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2710 MDNode *MD = Pair.second;
2712 "!kcfi_type must have exactly one operand", MD);
2713 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2716 "expected a constant operand for !kcfi_type", MD);
2719 "expected a constant integer operand for !kcfi_type", MD);
2721 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2726void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2730 if (!ConstantExprVisited.
insert(EntryC).second)
2734 Stack.push_back(EntryC);
2736 while (!
Stack.empty()) {
2741 visitConstantExpr(CE);
2744 visitConstantPtrAuth(CPA);
2749 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2755 for (
const Use &U :
C->operands()) {
2759 if (!ConstantExprVisited.
insert(OpC).second)
2761 Stack.push_back(OpC);
2766void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2767 if (
CE->getOpcode() == Instruction::BitCast)
2770 "Invalid bitcast", CE);
2771 else if (
CE->getOpcode() == Instruction::PtrToAddr)
2772 checkPtrToAddr(
CE->getOperand(0)->getType(),
CE->getType(), *CE);
2775void Verifier::visitConstantPtrAuth(
const ConstantPtrAuth *CPA) {
2777 "signed ptrauth constant base pointer must have pointer type");
2780 "signed ptrauth constant must have same type as its base pointer");
2783 "signed ptrauth constant key must be i32 constant integer");
2786 "signed ptrauth constant address discriminator must be a pointer");
2789 "signed ptrauth constant discriminator must be i64 constant integer");
2792 "signed ptrauth constant deactivation symbol must be a pointer");
2796 "signed ptrauth constant deactivation symbol must be a global value "
2800bool Verifier::verifyAttributeCount(AttributeList Attrs,
unsigned Params) {
2803 return Attrs.getNumAttrSets() <= Params + 2;
2806void Verifier::verifyInlineAsmCall(
const CallBase &
Call) {
2809 unsigned LabelNo = 0;
2810 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
2820 if (CI.isIndirect) {
2823 "Operand for indirect constraint must have pointer type", &
Call);
2826 "Operand for indirect constraint must have elementtype attribute",
2830 "Elementtype attribute can only be applied for indirect "
2839 Check(LabelNo == CallBr->getNumIndirectDests(),
2840 "Number of label constraints does not match number of callbr dests",
2843 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
2849void Verifier::verifyStatepoint(
const CallBase &
Call) {
2854 "gc.statepoint must read and write all memory to preserve "
2855 "reordering restrictions required by safepoint semantics",
2858 const int64_t NumPatchBytes =
2861 Check(NumPatchBytes >= 0,
2862 "gc.statepoint number of patchable bytes must be "
2867 Check(TargetElemType,
2868 "gc.statepoint callee argument must have elementtype attribute",
Call);
2870 Check(TargetFuncType,
2871 "gc.statepoint callee elementtype must be function type",
Call);
2874 Check(NumCallArgs >= 0,
2875 "gc.statepoint number of arguments to underlying call "
2878 const int NumParams = (int)TargetFuncType->getNumParams();
2879 if (TargetFuncType->isVarArg()) {
2880 Check(NumCallArgs >= NumParams,
2881 "gc.statepoint mismatch in number of vararg call args",
Call);
2884 Check(TargetFuncType->getReturnType()->isVoidTy(),
2885 "gc.statepoint doesn't support wrapping non-void "
2886 "vararg functions yet",
2889 Check(NumCallArgs == NumParams,
2890 "gc.statepoint mismatch in number of call args",
Call);
2892 const uint64_t
Flags
2894 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2895 "unknown flag used in gc.statepoint flags argument",
Call);
2900 for (
int i = 0; i < NumParams; i++) {
2901 Type *ParamType = TargetFuncType->getParamType(i);
2903 Check(ArgType == ParamType,
2904 "gc.statepoint call argument does not match wrapped "
2908 if (TargetFuncType->isVarArg()) {
2909 AttributeSet ArgAttrs =
Attrs.getParamAttrs(5 + i);
2911 "Attribute 'sret' cannot be used for vararg call arguments!",
Call);
2915 const int EndCallArgsInx = 4 + NumCallArgs;
2919 "gc.statepoint number of transition arguments "
2920 "must be constant integer",
2922 const int NumTransitionArgs =
2924 Check(NumTransitionArgs == 0,
2925 "gc.statepoint w/inline transition bundle is deprecated",
Call);
2926 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2930 "gc.statepoint number of deoptimization arguments "
2931 "must be constant integer",
2934 Check(NumDeoptArgs == 0,
2935 "gc.statepoint w/inline deopt operands is deprecated",
Call);
2937 const int ExpectedNumArgs = 7 + NumCallArgs;
2939 "gc.statepoint too many arguments",
Call);
2946 Check(UserCall,
"illegal use of statepoint token",
Call, U);
2950 "gc.result or gc.relocate are the only value uses "
2951 "of a gc.statepoint",
2955 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
2958 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
2972void Verifier::verifyFrameRecoverIndices() {
2973 for (
auto &Counts : FrameEscapeInfo) {
2975 unsigned EscapedObjectCount = Counts.second.first;
2976 unsigned MaxRecoveredIndex = Counts.second.second;
2977 Check(MaxRecoveredIndex <= EscapedObjectCount,
2978 "all indices passed to llvm.localrecover must be less than the "
2979 "number of arguments passed to llvm.localescape in the parent "
2988 UnwindDest =
II->getUnwindDest();
2990 UnwindDest = CSI->getUnwindDest();
2996void Verifier::verifySiblingFuncletUnwinds() {
2997 llvm::TimeTraceScope timeScope(
"Verifier verify sibling funclet unwinds");
2998 SmallPtrSet<Instruction *, 8> Visited;
2999 SmallPtrSet<Instruction *, 8>
Active;
3000 for (
const auto &Pair : SiblingFuncletInfo) {
3002 if (Visited.
count(PredPad))
3008 if (
Active.count(SuccPad)) {
3011 SmallVector<Instruction *, 8> CycleNodes;
3014 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3015 if (CycleTerminator != CyclePad)
3018 }
while (CyclePad != SuccPad);
3019 Check(
false,
"EH pads can't handle each other's exceptions",
3023 if (!Visited.
insert(SuccPad).second)
3027 auto TermI = SiblingFuncletInfo.find(PredPad);
3028 if (TermI == SiblingFuncletInfo.end())
3041void Verifier::visitFunction(
const Function &
F) {
3042 visitGlobalValue(
F);
3045 FunctionType *FT =
F.getFunctionType();
3046 unsigned NumArgs =
F.arg_size();
3049 "Function context does not match Module context!", &
F);
3051 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
3052 Check(FT->getNumParams() == NumArgs,
3053 "# formal arguments must match # of arguments for function type!", &
F,
3055 Check(
F.getReturnType()->isFirstClassType() ||
3056 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
3057 "Functions cannot return aggregate values!", &
F);
3059 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
3060 "Invalid struct return type!", &
F);
3062 if (MaybeAlign
A =
F.getAlign()) {
3063 Check(
A->value() <= Value::MaximumAlignment,
3064 "huge alignment values are unsupported", &
F);
3067 AttributeList
Attrs =
F.getAttributes();
3069 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3070 "Attribute after last parameter!", &
F);
3072 bool IsIntrinsic =
F.isIntrinsic();
3075 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
3081 "Attribute 'builtin' can only be applied to a callsite.", &
F);
3083 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
3084 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
3087 "Attribute 'aarch64_zt0_undef' can only be applied to a callsite.");
3089 if (
Attrs.hasFnAttr(Attribute::Naked))
3090 for (
const Argument &Arg :
F.args())
3091 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
3096 switch (
F.getCallingConv()) {
3098 case CallingConv::C:
3100 case CallingConv::X86_INTR: {
3101 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
3102 "Calling convention parameter requires byval", &
F);
3105 case CallingConv::AMDGPU_KERNEL:
3106 case CallingConv::SPIR_KERNEL:
3107 case CallingConv::AMDGPU_CS_Chain:
3108 case CallingConv::AMDGPU_CS_ChainPreserve:
3109 Check(
F.getReturnType()->isVoidTy(),
3110 "Calling convention requires void return type", &
F);
3112 case CallingConv::AMDGPU_VS:
3113 case CallingConv::AMDGPU_HS:
3114 case CallingConv::AMDGPU_GS:
3115 case CallingConv::AMDGPU_PS:
3116 case CallingConv::AMDGPU_CS:
3117 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
3118 if (
F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3119 const unsigned StackAS =
DL.getAllocaAddrSpace();
3121 for (
const Argument &Arg :
F.args()) {
3122 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
3123 "Calling convention disallows byval", &
F);
3124 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
3125 "Calling convention disallows preallocated", &
F);
3126 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
3127 "Calling convention disallows inalloca", &
F);
3129 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
3132 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3133 "Calling convention disallows stack byref", &
F);
3141 case CallingConv::Fast:
3142 case CallingConv::Cold:
3143 case CallingConv::Intel_OCL_BI:
3144 case CallingConv::PTX_Kernel:
3145 case CallingConv::PTX_Device:
3147 "Calling convention does not support varargs or "
3148 "perfect forwarding!",
3151 case CallingConv::AMDGPU_Gfx_WholeWave:
3152 Check(!
F.arg_empty() &&
F.arg_begin()->getType()->isIntegerTy(1),
3153 "Calling convention requires first argument to be i1", &
F);
3154 Check(!
F.arg_begin()->hasInRegAttr(),
3155 "Calling convention requires first argument to not be inreg", &
F);
3157 "Calling convention does not support varargs or "
3158 "perfect forwarding!",
3165 for (
const Argument &Arg :
F.args()) {
3166 Check(Arg.getType() == FT->getParamType(i),
3167 "Argument value does not match function argument type!", &Arg,
3168 FT->getParamType(i));
3169 Check(Arg.getType()->isFirstClassType(),
3170 "Function arguments must have first-class types!", &Arg);
3172 Check(!Arg.getType()->isMetadataTy(),
3173 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
3174 Check(!Arg.getType()->isTokenLikeTy(),
3175 "Function takes token but isn't an intrinsic", &Arg, &
F);
3176 Check(!Arg.getType()->isX86_AMXTy(),
3177 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
3181 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3182 verifySwiftErrorValue(&Arg);
3188 Check(!
F.getReturnType()->isTokenLikeTy(),
3189 "Function returns a token but isn't an intrinsic", &
F);
3190 Check(!
F.getReturnType()->isX86_AMXTy(),
3191 "Function returns a x86_amx but isn't an intrinsic", &
F);
3196 F.getAllMetadata(MDs);
3197 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
3198 verifyFunctionMetadata(MDs);
3201 if (
F.hasPersonalityFn()) {
3204 Check(Per->getParent() ==
F.getParent(),
3205 "Referencing personality function in another module!", &
F,
3206 F.getParent(), Per, Per->getParent());
3210 BlockEHFuncletColors.
clear();
3212 if (
F.isMaterializable()) {
3214 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
3216 }
else if (
F.isDeclaration()) {
3217 for (
const auto &
I : MDs) {
3219 CheckDI(
I.first != LLVMContext::MD_dbg ||
3221 "function declaration may only have a unique !dbg attachment",
3223 Check(
I.first != LLVMContext::MD_prof,
3224 "function declaration may not have a !prof attachment", &
F);
3227 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
3229 Check(!
F.hasPersonalityFn(),
3230 "Function declaration shouldn't have a personality routine", &
F);
3234 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
3239 "Entry block to function must not have predecessors!", Entry);
3242 if (
Entry->hasAddressTaken()) {
3244 "blockaddress may not be used with the entry block!", Entry);
3247 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3248 NumKCFIAttachments = 0;
3250 for (
const auto &
I : MDs) {
3252 auto AllowLocs = AreDebugLocsAllowed::No;
3256 case LLVMContext::MD_dbg: {
3257 ++NumDebugAttachments;
3258 CheckDI(NumDebugAttachments == 1,
3259 "function must have a single !dbg attachment", &
F,
I.second);
3261 "function !dbg attachment must be a subprogram", &
F,
I.second);
3263 "function definition may only have a distinct !dbg attachment",
3267 const Function *&AttachedTo = DISubprogramAttachments[
SP];
3268 CheckDI(!AttachedTo || AttachedTo == &
F,
3269 "DISubprogram attached to more than one function", SP, &
F);
3271 AllowLocs = AreDebugLocsAllowed::Yes;
3274 case LLVMContext::MD_prof:
3275 ++NumProfAttachments;
3276 Check(NumProfAttachments == 1,
3277 "function must have a single !prof attachment", &
F,
I.second);
3279 case LLVMContext::MD_kcfi_type:
3280 ++NumKCFIAttachments;
3281 Check(NumKCFIAttachments == 1,
3282 "function must have a single !kcfi_type attachment", &
F,
3288 visitMDNode(*
I.second, AllowLocs);
3296 if (
F.isIntrinsic() &&
F.getParent()->isMaterialized()) {
3298 if (
F.hasAddressTaken(&U,
false,
true,
false,
3300 Check(
false,
"Invalid user of intrinsic instruction!", U);
3304 switch (
F.getIntrinsicID()) {
3305 case Intrinsic::experimental_gc_get_pointer_base: {
3306 FunctionType *FT =
F.getFunctionType();
3307 Check(FT->getNumParams() == 1,
"wrong number of parameters",
F);
3309 "gc.get.pointer.base must return a pointer",
F);
3310 Check(FT->getParamType(0) ==
F.getReturnType(),
3311 "gc.get.pointer.base operand and result must be of the same type",
F);
3314 case Intrinsic::experimental_gc_get_pointer_offset: {
3315 FunctionType *FT =
F.getFunctionType();
3316 Check(FT->getNumParams() == 1,
"wrong number of parameters",
F);
3318 "gc.get.pointer.offset operand must be a pointer",
F);
3319 Check(
F.getReturnType()->isIntegerTy(),
3320 "gc.get.pointer.offset must return integer",
F);
3325 auto *
N =
F.getSubprogram();
3326 HasDebugInfo = (
N !=
nullptr);
3334 SmallPtrSet<const MDNode *, 32> Seen;
3346 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3348 DILocalScope *
Scope =
DL->getInlinedAtScope();
3349 Check(Scope,
"Failed to find DILocalScope",
DL);
3351 if (!Seen.
insert(Scope).second)
3354 DISubprogram *
SP =
Scope->getSubprogram();
3358 if ((Scope != SP) && !Seen.
insert(SP).second)
3362 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3366 for (
auto &
I : BB) {
3367 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3369 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3372 if (BrokenDebugInfo)
3379void Verifier::visitBasicBlock(BasicBlock &BB) {
3380 InstsInThisBlock.
clear();
3381 ConvergenceVerifyHelper.
visit(BB);
3392 for (
const PHINode &PN : BB.
phis()) {
3393 Check(PN.getNumIncomingValues() == Preds.size(),
3394 "PHINode should have one entry for each predecessor of its "
3395 "parent basic block!",
3400 Values.
reserve(PN.getNumIncomingValues());
3401 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3403 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3406 for (
unsigned i = 0, e = Values.
size(); i != e; ++i) {
3411 Check(i == 0 || Values[i].first != Values[i - 1].first ||
3412 Values[i].second == Values[i - 1].second,
3413 "PHI node has multiple entries for the same basic block with "
3414 "different incoming values!",
3415 &PN, Values[i].first, Values[i].second, Values[i - 1].second);
3419 Check(Values[i].first == Preds[i],
3420 "PHI node entries do not match predecessors!", &PN,
3421 Values[i].first, Preds[i]);
3429 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3433 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3437void Verifier::visitTerminator(Instruction &
I) {
3439 Check(&
I ==
I.getParent()->getTerminator(),
3440 "Terminator found in the middle of a basic block!",
I.getParent());
3441 visitInstruction(
I);
3444void Verifier::visitBranchInst(BranchInst &BI) {
3447 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3449 visitTerminator(BI);
3452void Verifier::visitReturnInst(ReturnInst &RI) {
3455 if (
F->getReturnType()->isVoidTy())
3457 "Found return instr that returns non-void in Function of void "
3459 &RI,
F->getReturnType());
3462 "Function return type does not match operand "
3463 "type of return inst!",
3464 &RI,
F->getReturnType());
3468 visitTerminator(RI);
3471void Verifier::visitSwitchInst(SwitchInst &SI) {
3472 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3475 Type *SwitchTy =
SI.getCondition()->getType();
3476 SmallPtrSet<ConstantInt*, 32>
Constants;
3477 for (
auto &Case :
SI.cases()) {
3479 "Case value is not a constant integer.", &SI);
3480 Check(Case.getCaseValue()->getType() == SwitchTy,
3481 "Switch constants must all be same type as switch value!", &SI);
3483 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3486 visitTerminator(SI);
3489void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3491 "Indirectbr operand must have pointer type!", &BI);
3494 "Indirectbr destinations must all have pointer type!", &BI);
3496 visitTerminator(BI);
3499void Verifier::visitCallBrInst(CallBrInst &CBI) {
3502 "Callbr: indirect function / invalid signature");
3504 "Callbr for intrinsics currently doesn't support operand bundles");
3507 case Intrinsic::amdgcn_kill: {
3509 "Callbr amdgcn_kill only supports one indirect dest");
3513 Intrinsic::amdgcn_unreachable),
3514 "Callbr amdgcn_kill indirect dest needs to be unreachable");
3519 "Callbr currently only supports asm-goto and selected intrinsics");
3524 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3526 verifyInlineAsmCall(CBI);
3528 visitTerminator(CBI);
3531void Verifier::visitSelectInst(SelectInst &SI) {
3534 "Invalid operands for select instruction!", &SI);
3536 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3537 "Select values must have same type as select instruction!", &SI);
3538 visitInstruction(SI);
3544void Verifier::visitUserOp1(Instruction &
I) {
3545 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3548void Verifier::visitTruncInst(TruncInst &
I) {
3550 Type *SrcTy =
I.getOperand(0)->getType();
3551 Type *DestTy =
I.getType();
3560 "trunc source and destination must both be a vector or neither", &
I);
3561 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3563 visitInstruction(
I);
3566void Verifier::visitZExtInst(ZExtInst &
I) {
3568 Type *SrcTy =
I.getOperand(0)->getType();
3569 Type *DestTy =
I.getType();
3575 "zext source and destination must both be a vector or neither", &
I);
3579 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3581 visitInstruction(
I);
3584void Verifier::visitSExtInst(SExtInst &
I) {
3586 Type *SrcTy =
I.getOperand(0)->getType();
3587 Type *DestTy =
I.getType();
3596 "sext source and destination must both be a vector or neither", &
I);
3597 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3599 visitInstruction(
I);
3602void Verifier::visitFPTruncInst(FPTruncInst &
I) {
3604 Type *SrcTy =
I.getOperand(0)->getType();
3605 Type *DestTy =
I.getType();
3613 "fptrunc source and destination must both be a vector or neither", &
I);
3614 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3616 visitInstruction(
I);
3619void Verifier::visitFPExtInst(FPExtInst &
I) {
3621 Type *SrcTy =
I.getOperand(0)->getType();
3622 Type *DestTy =
I.getType();
3631 "fpext source and destination must both be a vector or neither", &
I);
3632 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3634 visitInstruction(
I);
3637void Verifier::visitUIToFPInst(UIToFPInst &
I) {
3639 Type *SrcTy =
I.getOperand(0)->getType();
3640 Type *DestTy =
I.getType();
3645 Check(SrcVec == DstVec,
3646 "UIToFP source and dest must both be vector or scalar", &
I);
3648 "UIToFP source must be integer or integer vector", &
I);
3652 if (SrcVec && DstVec)
3655 "UIToFP source and dest vector length mismatch", &
I);
3657 visitInstruction(
I);
3660void Verifier::visitSIToFPInst(SIToFPInst &
I) {
3662 Type *SrcTy =
I.getOperand(0)->getType();
3663 Type *DestTy =
I.getType();
3668 Check(SrcVec == DstVec,
3669 "SIToFP source and dest must both be vector or scalar", &
I);
3671 "SIToFP source must be integer or integer vector", &
I);
3675 if (SrcVec && DstVec)
3678 "SIToFP source and dest vector length mismatch", &
I);
3680 visitInstruction(
I);
3683void Verifier::visitFPToUIInst(FPToUIInst &
I) {
3685 Type *SrcTy =
I.getOperand(0)->getType();
3686 Type *DestTy =
I.getType();
3691 Check(SrcVec == DstVec,
3692 "FPToUI source and dest must both be vector or scalar", &
I);
3695 "FPToUI result must be integer or integer vector", &
I);
3697 if (SrcVec && DstVec)
3700 "FPToUI source and dest vector length mismatch", &
I);
3702 visitInstruction(
I);
3705void Verifier::visitFPToSIInst(FPToSIInst &
I) {
3707 Type *SrcTy =
I.getOperand(0)->getType();
3708 Type *DestTy =
I.getType();
3713 Check(SrcVec == DstVec,
3714 "FPToSI source and dest must both be vector or scalar", &
I);
3717 "FPToSI result must be integer or integer vector", &
I);
3719 if (SrcVec && DstVec)
3722 "FPToSI source and dest vector length mismatch", &
I);
3724 visitInstruction(
I);
3727void Verifier::checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V) {
3736 Check(VSrc->getElementCount() == VDest->getElementCount(),
3737 "PtrToAddr vector length mismatch", V);
3740 Type *AddrTy =
DL.getAddressType(SrcTy);
3741 Check(AddrTy == DestTy,
"PtrToAddr result must be address width", V);
3744void Verifier::visitPtrToAddrInst(PtrToAddrInst &
I) {
3745 checkPtrToAddr(
I.getOperand(0)->getType(),
I.getType(),
I);
3746 visitInstruction(
I);
3749void Verifier::visitPtrToIntInst(PtrToIntInst &
I) {
3751 Type *SrcTy =
I.getOperand(0)->getType();
3752 Type *DestTy =
I.getType();
3763 Check(VSrc->getElementCount() == VDest->getElementCount(),
3764 "PtrToInt Vector length mismatch", &
I);
3767 visitInstruction(
I);
3770void Verifier::visitIntToPtrInst(IntToPtrInst &
I) {
3772 Type *SrcTy =
I.getOperand(0)->getType();
3773 Type *DestTy =
I.getType();
3783 Check(VSrc->getElementCount() == VDest->getElementCount(),
3784 "IntToPtr Vector length mismatch", &
I);
3786 visitInstruction(
I);
3789void Verifier::visitBitCastInst(BitCastInst &
I) {
3792 "Invalid bitcast", &
I);
3793 visitInstruction(
I);
3796void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
3797 Type *SrcTy =
I.getOperand(0)->getType();
3798 Type *DestTy =
I.getType();
3805 "AddrSpaceCast must be between different address spaces", &
I);
3807 Check(SrcVTy->getElementCount() ==
3809 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3810 visitInstruction(
I);
3815void Verifier::visitPHINode(PHINode &PN) {
3822 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3831 "PHI node operands are not the same type as the result!", &PN);
3836 visitInstruction(PN);
3839void Verifier::visitCallBase(CallBase &
Call) {
3841 "Called function must be a pointer!",
Call);
3845 if (FTy->isVarArg())
3847 "Called function requires more parameters than were provided!",
Call);
3850 "Incorrect number of arguments passed to called function!",
Call);
3853 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3855 "Call parameter type does not match function signature!",
3861 "Attribute after last parameter!",
Call);
3868 "Intrinsic called with incompatible signature",
Call);
3872 "calling convention does not permit calls",
Call);
3878 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3881 Align ABIAlign =
DL.getABITypeAlign(Ty);
3882 Check(ABIAlign.
value() <= Value::MaximumAlignment,
3883 "Incorrect alignment of " + Message +
" to called function!",
Call);
3887 VerifyTypeAlign(FTy->getReturnType(),
"return type");
3888 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3889 Type *Ty = FTy->getParamType(i);
3890 VerifyTypeAlign(Ty,
"argument passed");
3894 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
3898 "speculatable attribute may not apply to call sites",
Call);
3901 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
3903 "preallocated as a call site attribute can only be on "
3904 "llvm.call.preallocated.arg");
3916 Check(AI->isUsedWithInAlloca(),
3917 "inalloca argument for call has mismatched alloca", AI,
Call);
3923 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3927 Check(AI->isSwiftError(),
3928 "swifterror argument for call has mismatched alloca", AI,
Call);
3932 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
3933 SwiftErrorArg,
Call);
3934 Check(ArgI->hasSwiftErrorAttr(),
3935 "swifterror argument for call has mismatched parameter", ArgI,
3939 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3942 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
3950 "immarg operand has non-immediate parameter", ArgVal,
Call);
3956 const ConstantRange &CR =
3959 "immarg value " + Twine(CI->getValue().getSExtValue()) +
3972 Check(hasOB != isMustTail,
3973 "preallocated operand either requires a preallocated bundle or "
3974 "the call to be musttail (but not both)",
3979 if (FTy->isVarArg()) {
3981 bool SawNest =
false;
3982 bool SawReturned =
false;
3984 for (
unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3985 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
3987 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
3992 for (
unsigned Idx = FTy->getNumParams(); Idx <
Call.
arg_size(); ++Idx) {
3994 AttributeSet ArgAttrs =
Attrs.getParamAttrs(Idx);
3995 verifyParameterAttrs(ArgAttrs, Ty, &
Call);
3998 Check(!SawNest,
"More than one parameter has attribute nest!",
Call);
4003 Check(!SawReturned,
"More than one parameter has attribute returned!",
4006 "Incompatible argument and return types for 'returned' "
4016 "Attribute 'sret' cannot be used for vararg call arguments!",
4021 "inalloca isn't on the last argument!",
Call);
4027 for (
Type *ParamTy : FTy->params()) {
4028 Check(!ParamTy->isMetadataTy(),
4029 "Function has metadata parameter but isn't an intrinsic",
Call);
4030 Check(!ParamTy->isTokenLikeTy(),
4031 "Function has token parameter but isn't an intrinsic",
Call);
4037 Check(!FTy->getReturnType()->isTokenLikeTy(),
4038 "Return type cannot be token for indirect call!");
4039 Check(!FTy->getReturnType()->isX86_AMXTy(),
4040 "Return type cannot be x86_amx for indirect call!");
4044 visitIntrinsicCall(
ID,
Call);
4049 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
4050 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
4051 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
4052 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
4053 FoundAttachedCallBundle =
false;
4058 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles",
Call);
4059 FoundDeoptBundle =
true;
4061 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
4063 FoundGCTransitionBundle =
true;
4065 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles",
Call);
4066 FoundFuncletBundle =
true;
4068 "Expected exactly one funclet bundle operand",
Call);
4070 "Funclet bundle operands should correspond to a FuncletPadInst",
4073 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
4075 FoundCFGuardTargetBundle =
true;
4077 "Expected exactly one cfguardtarget bundle operand",
Call);
4079 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles",
Call);
4080 FoundPtrauthBundle =
true;
4082 "Expected exactly two ptrauth bundle operands",
Call);
4084 BU.
Inputs[0]->getType()->isIntegerTy(32),
4085 "Ptrauth bundle key operand must be an i32 constant",
Call);
4087 "Ptrauth bundle discriminator operand must be an i64",
Call);
4089 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles",
Call);
4090 FoundKCFIBundle =
true;
4091 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
4094 BU.
Inputs[0]->getType()->isIntegerTy(32),
4095 "Kcfi bundle operand must be an i32 constant",
Call);
4097 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
4099 FoundPreallocatedBundle =
true;
4101 "Expected exactly one preallocated bundle operand",
Call);
4104 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4105 "\"preallocated\" argument must be a token from "
4106 "llvm.call.preallocated.setup",
4109 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles",
Call);
4110 FoundGCLiveBundle =
true;
4112 Check(!FoundAttachedCallBundle,
4113 "Multiple \"clang.arc.attachedcall\" operand bundles",
Call);
4114 FoundAttachedCallBundle =
true;
4115 verifyAttachedCallBundle(
Call, BU);
4121 "Direct call cannot have a ptrauth bundle",
Call);
4133 "inlinable function call in a function with "
4134 "debug info must have a !dbg location",
4138 verifyInlineAsmCall(
Call);
4142 visitInstruction(
Call);
4145void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
4148 Twine(
"inalloca attribute not allowed in ") +
Context);
4150 Twine(
"inreg attribute not allowed in ") +
Context);
4151 Check(!
Attrs.contains(Attribute::SwiftError),
4152 Twine(
"swifterror attribute not allowed in ") +
Context);
4153 Check(!
Attrs.contains(Attribute::Preallocated),
4154 Twine(
"preallocated attribute not allowed in ") +
Context);
4156 Twine(
"byref attribute not allowed in ") +
Context);
4168 return PL->getAddressSpace() == PR->getAddressSpace();
4173 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4174 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4175 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4177 AttrBuilder Copy(
C);
4178 for (
auto AK : ABIAttrs) {
4179 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
4181 Copy.addAttribute(Attr);
4185 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
4186 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
4187 Attrs.hasParamAttr(
I, Attribute::ByRef)))
4188 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
4192void Verifier::verifyMustTailCall(CallInst &CI) {
4196 FunctionType *CallerTy =
F->getFunctionType();
4198 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4199 "cannot guarantee tail call due to mismatched varargs", &CI);
4201 "cannot guarantee tail call due to mismatched return types", &CI);
4205 "cannot guarantee tail call due to mismatched calling conv", &CI);
4211 Value *RetVal = &CI;
4217 "bitcast following musttail call must use the call", BI);
4224 Check(Ret,
"musttail call must precede a ret with an optional bitcast", &CI);
4227 "musttail call result must be returned", Ret);
4229 AttributeList CallerAttrs =
F->getAttributes();
4234 CI.
getCallingConv() == CallingConv::Tail ?
"tailcc" :
"swifttailcc";
4238 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4240 SmallString<32>
Context{CCName, StringRef(
" musttail caller")};
4241 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4243 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
4245 SmallString<32>
Context{CCName, StringRef(
" musttail callee")};
4246 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4249 Check(!CallerTy->isVarArg(), Twine(
"cannot guarantee ") + CCName +
4250 " tail call for varargs function");
4258 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4259 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4260 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4263 "cannot guarantee tail call due to mismatched parameter types", &CI);
4269 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4272 Check(CallerABIAttrs == CalleeABIAttrs,
4273 "cannot guarantee tail call due to mismatched ABI impacting "
4274 "function attributes",
4279void Verifier::visitCallInst(CallInst &CI) {
4283 verifyMustTailCall(CI);
4286void Verifier::visitInvokeInst(InvokeInst &
II) {
4292 II.getUnwindDest()->isEHPad(),
4293 "The unwind destination does not have an exception handling instruction!",
4296 visitTerminator(
II);
4301void Verifier::visitUnaryOperator(UnaryOperator &U) {
4302 Check(
U.getType() ==
U.getOperand(0)->getType(),
4303 "Unary operators must have same type for"
4304 "operands and result!",
4307 switch (
U.getOpcode()) {
4310 case Instruction::FNeg:
4311 Check(
U.getType()->isFPOrFPVectorTy(),
4312 "FNeg operator only works with float types!", &U);
4318 visitInstruction(U);
4324void Verifier::visitBinaryOperator(BinaryOperator &
B) {
4325 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
4326 "Both operands to a binary operator are not of the same type!", &
B);
4328 switch (
B.getOpcode()) {
4331 case Instruction::Add:
4332 case Instruction::Sub:
4333 case Instruction::Mul:
4334 case Instruction::SDiv:
4335 case Instruction::UDiv:
4336 case Instruction::SRem:
4337 case Instruction::URem:
4338 Check(
B.getType()->isIntOrIntVectorTy(),
4339 "Integer arithmetic operators only work with integral types!", &
B);
4340 Check(
B.getType() ==
B.getOperand(0)->getType(),
4341 "Integer arithmetic operators must have same type "
4342 "for operands and result!",
4347 case Instruction::FAdd:
4348 case Instruction::FSub:
4349 case Instruction::FMul:
4350 case Instruction::FDiv:
4351 case Instruction::FRem:
4352 Check(
B.getType()->isFPOrFPVectorTy(),
4353 "Floating-point arithmetic operators only work with "
4354 "floating-point types!",
4356 Check(
B.getType() ==
B.getOperand(0)->getType(),
4357 "Floating-point arithmetic operators must have same type "
4358 "for operands and result!",
4362 case Instruction::And:
4363 case Instruction::Or:
4364 case Instruction::Xor:
4365 Check(
B.getType()->isIntOrIntVectorTy(),
4366 "Logical operators only work with integral types!", &
B);
4367 Check(
B.getType() ==
B.getOperand(0)->getType(),
4368 "Logical operators must have same type for operands and result!", &
B);
4370 case Instruction::Shl:
4371 case Instruction::LShr:
4372 case Instruction::AShr:
4373 Check(
B.getType()->isIntOrIntVectorTy(),
4374 "Shifts only work with integral types!", &
B);
4375 Check(
B.getType() ==
B.getOperand(0)->getType(),
4376 "Shift return type must be same as operands!", &
B);
4382 visitInstruction(
B);
4385void Verifier::visitICmpInst(ICmpInst &IC) {
4389 Check(Op0Ty == Op1Ty,
4390 "Both operands to ICmp instruction are not of the same type!", &IC);
4393 "Invalid operand types for ICmp instruction", &IC);
4397 visitInstruction(IC);
4400void Verifier::visitFCmpInst(FCmpInst &FC) {
4402 Type *Op0Ty =
FC.getOperand(0)->getType();
4403 Type *Op1Ty =
FC.getOperand(1)->getType();
4404 Check(Op0Ty == Op1Ty,
4405 "Both operands to FCmp instruction are not of the same type!", &FC);
4410 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
4412 visitInstruction(FC);
4415void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4417 "Invalid extractelement operands!", &EI);
4418 visitInstruction(EI);
4421void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4424 "Invalid insertelement operands!", &IE);
4425 visitInstruction(IE);
4428void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4431 "Invalid shufflevector operands!", &SV);
4432 visitInstruction(SV);
4435void Verifier::visitGetElementPtrInst(GetElementPtrInst &
GEP) {
4436 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4439 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4440 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4444 "getelementptr cannot target structure that contains scalable vector"
4449 SmallVector<Value *, 16> Idxs(
GEP.indices());
4451 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
4452 "GEP indexes must be integers", &
GEP);
4455 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4459 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4460 "GEP is not of right type for indices!", &
GEP, ElTy);
4464 ElementCount GEPWidth = GEPVTy->getElementCount();
4465 if (
GEP.getPointerOperandType()->isVectorTy())
4469 "Vector GEP result width doesn't match operand's", &
GEP);
4470 for (
Value *Idx : Idxs) {
4471 Type *IndexTy = Idx->getType();
4473 ElementCount IndexWidth = IndexVTy->getElementCount();
4474 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4477 "All GEP indices should be of integer type");
4484 GTI != GTE; ++GTI) {
4485 if (GTI.isVector()) {
4486 Type *ElemTy = GTI.getIndexedType();
4487 Check(
DL.typeSizeEqualsStoreSize(ElemTy),
4488 "GEP into vector with non-byte-addressable element type", &
GEP);
4492 Check(
GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4493 "GEP address space doesn't match type", &
GEP);
4495 visitInstruction(
GEP);
4499 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4504void Verifier::verifyRangeLikeMetadata(
const Value &
I,
const MDNode *
Range,
4505 Type *Ty, RangeLikeMetadataKind Kind) {
4506 unsigned NumOperands =
Range->getNumOperands();
4507 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4508 unsigned NumRanges = NumOperands / 2;
4509 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4511 ConstantRange LastRange(1,
true);
4512 for (
unsigned i = 0; i < NumRanges; ++i) {
4515 Check(
Low,
"The lower limit must be an integer!",
Low);
4520 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4523 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4525 "noalias.addrspace type must be i32!", &
I);
4528 "Range types must match instruction type!", &
I);
4531 APInt HighV =
High->getValue();
4532 APInt LowV =
Low->getValue();
4537 "The upper and lower limits cannot be the same value", &
I);
4539 ConstantRange CurRange(LowV, HighV);
4540 Check(!CurRange.isEmptySet() &&
4541 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4542 !CurRange.isFullSet()),
4543 "Range must not be empty!",
Range);
4545 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4546 "Intervals are overlapping",
Range);
4547 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
4552 LastRange = ConstantRange(LowV, HighV);
4554 if (NumRanges > 2) {
4559 ConstantRange FirstRange(FirstLow, FirstHigh);
4560 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4561 "Intervals are overlapping",
Range);
4567void Verifier::visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty) {
4569 "precondition violation");
4570 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
4573void Verifier::visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
4576 "precondition violation");
4577 verifyRangeLikeMetadata(
I,
Range, Ty,
4578 RangeLikeMetadataKind::NoaliasAddrspace);
4581void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I) {
4582 unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
4583 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
4585 "atomic memory access' operand must have a power-of-two size", Ty,
I);
4588void Verifier::visitLoadInst(LoadInst &LI) {
4590 Check(PTy,
"Load operand must be a pointer.", &LI);
4593 Check(
A->value() <= Value::MaximumAlignment,
4594 "huge alignment values are unsupported", &LI);
4596 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4599 LI.
getOrdering() != AtomicOrdering::AcquireRelease,
4600 "Load cannot have Release ordering", &LI);
4603 "atomic load operand must have integer, pointer, floating point, "
4607 checkAtomicMemAccessSize(ElTy, &LI);
4610 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4613 visitInstruction(LI);
4616void Verifier::visitStoreInst(StoreInst &SI) {
4618 Check(PTy,
"Store operand must be a pointer.", &SI);
4619 Type *ElTy =
SI.getOperand(0)->getType();
4620 if (MaybeAlign
A =
SI.getAlign()) {
4621 Check(
A->value() <= Value::MaximumAlignment,
4622 "huge alignment values are unsupported", &SI);
4624 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4625 if (
SI.isAtomic()) {
4626 Check(
SI.getOrdering() != AtomicOrdering::Acquire &&
4627 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4628 "Store cannot have Acquire ordering", &SI);
4631 "atomic store operand must have integer, pointer, floating point, "
4634 checkAtomicMemAccessSize(ElTy, &SI);
4637 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4639 visitInstruction(SI);
4643void Verifier::verifySwiftErrorCall(CallBase &
Call,
4644 const Value *SwiftErrorVal) {
4646 if (
I.value() == SwiftErrorVal) {
4648 "swifterror value when used in a callsite should be marked "
4649 "with swifterror attribute",
4650 SwiftErrorVal,
Call);
4655void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4658 for (
const User *U : SwiftErrorVal->
users()) {
4661 "swifterror value can only be loaded and stored from, or "
4662 "as a swifterror argument!",
4666 Check(StoreI->getOperand(1) == SwiftErrorVal,
4667 "swifterror value should be the second operand when used "
4671 verifySwiftErrorCall(*
const_cast<CallBase *
>(
Call), SwiftErrorVal);
4675void Verifier::visitAllocaInst(AllocaInst &AI) {
4677 SmallPtrSet<Type*, 4> Visited;
4678 Check(Ty->
isSized(&Visited),
"Cannot allocate unsized type", &AI);
4682 "Alloca has illegal target extension type", &AI);
4684 "Alloca array size must have integer type", &AI);
4686 Check(
A->value() <= Value::MaximumAlignment,
4687 "huge alignment values are unsupported", &AI);
4693 "swifterror alloca must not be array allocation", &AI);
4694 verifySwiftErrorValue(&AI);
4697 if (
TT.isAMDGPU()) {
4699 "alloca on amdgpu must be in addrspace(5)", &AI);
4702 visitInstruction(AI);
4705void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4708 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4709 checkAtomicMemAccessSize(ElTy, &CXI);
4710 visitInstruction(CXI);
4713void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4715 "atomicrmw instructions cannot be unordered.", &RMWI);
4722 " operand must have integer or floating point type!",
4727 " operand must have floating-point or fixed vector of floating-point "
4733 " operand must have integer type!",
4736 checkAtomicMemAccessSize(ElTy, &RMWI);
4738 "Invalid binary operation!", &RMWI);
4739 visitInstruction(RMWI);
4742void Verifier::visitFenceInst(FenceInst &FI) {
4744 Check(Ordering == AtomicOrdering::Acquire ||
4745 Ordering == AtomicOrdering::Release ||
4746 Ordering == AtomicOrdering::AcquireRelease ||
4747 Ordering == AtomicOrdering::SequentiallyConsistent,
4748 "fence instructions may only have acquire, release, acq_rel, or "
4749 "seq_cst ordering.",
4751 visitInstruction(FI);
4754void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4757 "Invalid ExtractValueInst operands!", &EVI);
4759 visitInstruction(EVI);
4762void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4766 "Invalid InsertValueInst operands!", &IVI);
4768 visitInstruction(IVI);
4773 return FPI->getParentPad();
4778void Verifier::visitEHPadPredecessors(Instruction &
I) {
4784 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
4792 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4793 "Block containing LandingPadInst must be jumped to "
4794 "only by the unwind edge of an invoke.",
4802 "Block containg CatchPadInst must be jumped to "
4803 "only by its catchswitch.",
4805 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4806 "Catchswitch cannot unwind to one of its catchpads",
4807 CPI->getCatchSwitch(), CPI);
4819 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4820 "EH pad must be jumped to via an unwind edge", ToPad,
II);
4823 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
4827 FromPad = Bundle->Inputs[0];
4831 FromPad = CRI->getOperand(0);
4832 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
4836 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
4840 SmallPtrSet<Value *, 8> Seen;
4842 Check(FromPad != ToPad,
4843 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4844 if (FromPad == ToPadParent) {
4849 "A single unwind edge may only enter one EH pad", TI);
4850 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
4856 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4861void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4865 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4867 visitEHPadPredecessors(LPI);
4869 if (!LandingPadResultTy)
4870 LandingPadResultTy = LPI.
getType();
4873 "The landingpad instruction should have a consistent result type "
4874 "inside a function.",
4878 Check(
F->hasPersonalityFn(),
4879 "LandingPadInst needs to be in a function with a personality.", &LPI);
4884 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4890 "Catch operand does not have pointer type!", &LPI);
4892 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
4894 "Filter operand is not an array of constants!", &LPI);
4898 visitInstruction(LPI);
4901void Verifier::visitResumeInst(ResumeInst &RI) {
4903 "ResumeInst needs to be in a function with a personality.", &RI);
4905 if (!LandingPadResultTy)
4909 "The resume instruction should have a consistent result type "
4910 "inside a function.",
4913 visitTerminator(RI);
4916void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4920 Check(
F->hasPersonalityFn(),
4921 "CatchPadInst needs to be in a function with a personality.", &CPI);
4924 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4930 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4932 visitEHPadPredecessors(CPI);
4933 visitFuncletPadInst(CPI);
4936void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4938 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4941 visitTerminator(CatchReturn);
4944void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4948 Check(
F->hasPersonalityFn(),
4949 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4954 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
4958 "CleanupPadInst has an invalid parent.", &CPI);
4960 visitEHPadPredecessors(CPI);
4961 visitFuncletPadInst(CPI);
4964void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4965 User *FirstUser =
nullptr;
4966 Value *FirstUnwindPad =
nullptr;
4968 SmallPtrSet<FuncletPadInst *, 8> Seen;
4970 while (!Worklist.empty()) {
4971 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
4973 "FuncletPadInst must not be nested within itself", CurrentPad);
4974 Value *UnresolvedAncestorPad =
nullptr;
4975 for (User *U : CurrentPad->
users()) {
4978 UnwindDest = CRI->getUnwindDest();
4984 if (CSI->unwindsToCaller())
4986 UnwindDest = CSI->getUnwindDest();
4988 UnwindDest =
II->getUnwindDest();
4998 Worklist.push_back(CPI);
5013 if (UnwindParent == CurrentPad)
5019 Value *ExitedPad = CurrentPad;
5022 if (ExitedPad == &FPI) {
5027 UnresolvedAncestorPad = &FPI;
5031 if (ExitedParent == UnwindParent) {
5035 UnresolvedAncestorPad = ExitedParent;
5038 ExitedPad = ExitedParent;
5044 UnresolvedAncestorPad = &FPI;
5051 Check(UnwindPad == FirstUnwindPad,
5052 "Unwind edges out of a funclet "
5053 "pad must have the same unwind "
5055 &FPI, U, FirstUser);
5058 FirstUnwindPad = UnwindPad;
5067 if (CurrentPad != &FPI)
5070 if (UnresolvedAncestorPad) {
5071 if (CurrentPad == UnresolvedAncestorPad) {
5075 assert(CurrentPad == &FPI);
5083 Value *ResolvedPad = CurrentPad;
5084 while (!Worklist.empty()) {
5085 Value *UnclePad = Worklist.back();
5089 while (ResolvedPad != AncestorPad) {
5091 if (ResolvedParent == UnresolvedAncestorPad) {
5094 ResolvedPad = ResolvedParent;
5098 if (ResolvedPad != AncestorPad)
5101 Worklist.pop_back();
5106 if (FirstUnwindPad) {
5108 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5109 Value *SwitchUnwindPad;
5110 if (SwitchUnwindDest)
5114 Check(SwitchUnwindPad == FirstUnwindPad,
5115 "Unwind edges out of a catch must have the same unwind dest as "
5116 "the parent catchswitch",
5117 &FPI, FirstUser, CatchSwitch);
5121 visitInstruction(FPI);
5124void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5128 Check(
F->hasPersonalityFn(),
5129 "CatchSwitchInst needs to be in a function with a personality.",
5135 "CatchSwitchInst not the first non-PHI instruction in the block.",
5140 "CatchSwitchInst has an invalid parent.", ParentPad);
5145 "CatchSwitchInst must unwind to an EH block which is not a "
5151 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5155 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5157 for (BasicBlock *Handler : CatchSwitch.
handlers()) {
5159 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5162 visitEHPadPredecessors(CatchSwitch);
5163 visitTerminator(CatchSwitch);
5166void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5168 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5174 "CleanupReturnInst must unwind to an EH block which is not a "
5179 visitTerminator(CRI);
5182void Verifier::verifyDominatesUse(Instruction &
I,
unsigned i) {
5188 if (
II->getNormalDest() ==
II->getUnwindDest())
5202 const Use &
U =
I.getOperandUse(i);
5203 Check(DT.dominates(
Op, U),
"Instruction does not dominate all uses!",
Op, &
I);
5206void Verifier::visitDereferenceableMetadata(Instruction&
I, MDNode* MD) {
5207 Check(
I.getType()->isPointerTy(),
5208 "dereferenceable, dereferenceable_or_null "
5209 "apply only to pointer types",
5212 "dereferenceable, dereferenceable_or_null apply only to load"
5213 " and inttoptr instructions, use attributes for calls or invokes",
5216 "dereferenceable, dereferenceable_or_null "
5217 "take one operand!",
5222 "dereferenceable_or_null metadata value must be an i64!",
5226void Verifier::visitNofreeMetadata(Instruction &
I, MDNode *MD) {
5227 Check(
I.getType()->isPointerTy(),
"nofree applies only to pointer types", &
I);
5233void Verifier::visitProfMetadata(Instruction &
I, MDNode *MD) {
5234 auto GetBranchingTerminatorNumOperands = [&]() {
5235 unsigned ExpectedNumOperands = 0;
5239 ExpectedNumOperands =
SI->getNumSuccessors();
5241 ExpectedNumOperands = 1;
5243 ExpectedNumOperands = IBI->getNumDestinations();
5245 ExpectedNumOperands = 2;
5248 return ExpectedNumOperands;
5251 "!prof annotations should have at least 1 operand", MD);
5253 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
5255 "expected string with name of the !prof annotation", MD);
5261 "'unknown' !prof should only appear on instructions on which "
5262 "'branch_weights' would",
5264 verifyUnknownProfileMetadata(MD);
5269 "!prof annotations should have no less than 2 operands", MD);
5275 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5276 "Wrong number of InvokeInst branch_weights operands", MD);
5278 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5279 if (ExpectedNumOperands == 0)
5280 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
5283 Check(NumBranchWeights == ExpectedNumOperands,
"Wrong number of operands",
5289 Check(MDO,
"second operand should not be null", MD);
5291 "!prof brunch_weights operand is not a const int");
5296 Check(KindInt,
"VP !prof missing kind argument", MD);
5299 Check(Kind >= InstrProfValueKind::IPVK_First &&
5300 Kind <= InstrProfValueKind::IPVK_Last,
5301 "Invalid VP !prof kind", MD);
5303 "VP !prof should have an even number "
5304 "of arguments after 'VP'",
5306 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5307 Kind == InstrProfValueKind::IPVK_MemOPSize)
5309 "VP !prof indirect call or memop size expected to be applied to "
5310 "CallBase instructions only",
5313 CheckFailed(
"expected either branch_weights or VP profile name", MD);
5317void Verifier::visitDIAssignIDMetadata(Instruction &
I, MDNode *MD) {
5318 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
5323 bool ExpectedInstTy =
5325 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
5330 for (
auto *User : AsValue->users()) {
5332 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5336 CheckDI(DAI->getFunction() ==
I.getFunction(),
5337 "dbg.assign not in same function as inst", DAI, &
I);
5340 for (DbgVariableRecord *DVR :
5343 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5344 CheckDI(DVR->getFunction() ==
I.getFunction(),
5345 "DVRAssign not in same function as inst", DVR, &
I);
5349void Verifier::visitMMRAMetadata(Instruction &
I, MDNode *MD) {
5351 "!mmra metadata attached to unexpected instruction kind",
I, MD);
5362 for (
const MDOperand &MDOp : MD->
operands())
5364 "!mmra metadata tuple operand is not an MMRA tag",
I, MDOp.get());
5367void Verifier::visitCallStackMetadata(MDNode *MD) {
5371 "call stack metadata should have at least 1 operand", MD);
5375 "call stack metadata operand should be constant integer",
Op);
5378void Verifier::visitMemProfMetadata(Instruction &
I, MDNode *MD) {
5381 "!memprof annotations should have at least 1 metadata operand "
5386 for (
auto &MIBOp : MD->
operands()) {
5392 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5396 "!memprof MemInfoBlock first operand should not be null", MIB);
5398 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5400 visitCallStackMetadata(StackMD);
5404 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5409 Check(OpNode,
"Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5412 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5417 [](
const MDOperand &
Op) {
5418 return mdconst::hasa<ConstantInt>(Op);
5420 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5421 "ConstantInt operands",
5427void Verifier::visitCallsiteMetadata(Instruction &
I, MDNode *MD) {
5431 visitCallStackMetadata(MD);
5440void Verifier::visitCalleeTypeMetadata(Instruction &
I, MDNode *MD) {
5445 "The callee_type metadata must be a list of type metadata nodes",
Op);
5447 Check(TypeMD->getNumOperands() == 2,
5448 "Well-formed generalized type metadata must contain exactly two "
5453 "The first operand of type metadata for functions must be zero",
Op);
5454 Check(TypeMD->hasGeneralizedMDString(),
5455 "Only generalized type metadata can be part of the callee_type "
5461void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5464 "annotation must have at least one operand");
5466 bool TupleOfStrings =
5472 "operands must be a string or a tuple of strings");
5476void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
5481 "first scope operand must be self-referential or string", MD);
5484 "third scope operand must be string (if used)", MD);
5487 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
5489 unsigned NumDomainOps =
Domain->getNumOperands();
5490 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5491 "domain must have one or two operands",
Domain);
5494 "first domain operand must be self-referential or string",
Domain);
5495 if (NumDomainOps == 2)
5497 "second domain operand must be string (if used)",
Domain);
5500void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
5503 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
5504 visitAliasScopeMetadata(OpMD);
5508void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
5509 auto IsValidAccessScope = [](
const MDNode *MD) {
5514 if (IsValidAccessScope(MD))
5520 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
5521 Check(IsValidAccessScope(OpMD),
5522 "Access scope list contains invalid access scope", MD);
5526void Verifier::visitCapturesMetadata(Instruction &
I,
const MDNode *Captures) {
5527 static const char *ValidArgs[] = {
"address_is_null",
"address",
5528 "read_provenance",
"provenance"};
5531 Check(SI,
"!captures metadata can only be applied to store instructions", &
I);
5532 Check(
SI->getValueOperand()->getType()->isPointerTy(),
5533 "!captures metadata can only be applied to store with value operand of "
5541 Check(Str,
"!captures metadata must be a list of strings", &
I);
5543 "invalid entry in !captures metadata", &
I, Str);
5547void Verifier::visitAllocTokenMetadata(Instruction &
I, MDNode *MD) {
5552 "expected integer constant", MD);
5557void Verifier::visitInstruction(Instruction &
I) {
5559 Check(BB,
"Instruction not embedded in basic block!", &
I);
5562 for (User *U :
I.users()) {
5563 Check(U != (User *)&
I || !DT.isReachableFromEntry(BB),
5564 "Only PHI nodes may reference their own value!", &
I);
5569 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
5570 "Instruction has a name, but provides a void value!", &
I);
5574 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
5575 "Instruction returns a non-scalar type!", &
I);
5580 "Invalid use of metadata!", &
I);
5585 for (Use &U :
I.uses()) {
5588 "Instruction referencing"
5589 " instruction not embedded in a basic block!",
5592 CheckFailed(
"Use of instruction is not an instruction!", U);
5601 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i) {
5602 Check(
I.getOperand(i) !=
nullptr,
"Instruction has null operand!", &
I);
5606 if (!
I.getOperand(i)->getType()->isFirstClassType()) {
5607 Check(
false,
"Instruction operands must be first-class values!", &
I);
5613 auto IsAttachedCallOperand = [](
Function *
F,
const CallBase *CBI,
5615 return CBI && CBI->isOperandBundleOfType(
5623 Check((!
F->isIntrinsic() ||
5624 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i)) ||
5625 IsAttachedCallOperand(
F, CBI, i)),
5626 "Cannot take the address of an intrinsic!", &
I);
5628 F->getIntrinsicID() == Intrinsic::donothing ||
5629 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5630 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5631 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5632 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5633 F->getIntrinsicID() == Intrinsic::coro_resume ||
5634 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5635 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5636 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5637 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5638 F->getIntrinsicID() ==
5639 Intrinsic::experimental_patchpoint_void ||
5640 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5641 F->getIntrinsicID() == Intrinsic::fake_use ||
5642 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5643 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5644 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5645 IsAttachedCallOperand(
F, CBI, i),
5646 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5647 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5650 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
5651 &M,
F,
F->getParent());
5654 "Referring to a basic block in another function!", &
I);
5657 "Referring to an argument in another function!", &
I);
5659 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
5663 "Referring to an instruction in another function!", &
I);
5664 verifyDominatesUse(
I, i);
5666 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i),
5667 "Cannot take the address of an inline asm!", &
I);
5669 visitConstantExprsRecursively(
C);
5673 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_fpmath)) {
5674 Check(
I.getType()->isFPOrFPVectorTy(),
5675 "fpmath requires a floating point result!", &
I);
5677 if (ConstantFP *CFP0 =
5679 const APFloat &Accuracy = CFP0->getValueAPF();
5681 "fpmath accuracy must have float type", &
I);
5683 "fpmath accuracy not a positive number!", &
I);
5685 Check(
false,
"invalid fpmath accuracy!", &
I);
5689 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_range)) {
5691 "Ranges are only for loads, calls and invokes!", &
I);
5692 visitRangeMetadata(
I,
Range,
I.getType());
5695 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5698 "noalias.addrspace are only for memory operations!", &
I);
5699 visitNoaliasAddrspaceMetadata(
I,
Range,
I.getType());
5702 if (
I.hasMetadata(LLVMContext::MD_invariant_group)) {
5704 "invariant.group metadata is only for loads and stores", &
I);
5707 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nonnull)) {
5708 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
5711 "nonnull applies only to load instructions, use attributes"
5712 " for calls or invokes",
5717 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable))
5718 visitDereferenceableMetadata(
I, MD);
5720 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
5721 visitDereferenceableMetadata(
I, MD);
5723 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofree))
5724 visitNofreeMetadata(
I, MD);
5726 if (MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa))
5729 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noalias))
5730 visitAliasScopeListMetadata(MD);
5731 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alias_scope))
5732 visitAliasScopeListMetadata(MD);
5734 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_access_group))
5735 visitAccessGroupMetadata(MD);
5737 if (MDNode *AlignMD =
I.getMetadata(LLVMContext::MD_align)) {
5738 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
5741 "align applies only to load instructions, "
5742 "use attributes for calls or invokes",
5744 Check(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
5747 "align metadata value must be an i64!", &
I);
5751 Check(Align <= Value::MaximumAlignment,
5752 "alignment is larger that implementation defined limit", &
I);
5755 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_prof))
5756 visitProfMetadata(
I, MD);
5758 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_memprof))
5759 visitMemProfMetadata(
I, MD);
5761 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callsite))
5762 visitCallsiteMetadata(
I, MD);
5764 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callee_type))
5765 visitCalleeTypeMetadata(
I, MD);
5767 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_DIAssignID))
5768 visitDIAssignIDMetadata(
I, MD);
5770 if (MDNode *MMRA =
I.getMetadata(LLVMContext::MD_mmra))
5771 visitMMRAMetadata(
I, MMRA);
5773 if (MDNode *Annotation =
I.getMetadata(LLVMContext::MD_annotation))
5774 visitAnnotationMetadata(Annotation);
5776 if (MDNode *Captures =
I.getMetadata(LLVMContext::MD_captures))
5777 visitCapturesMetadata(
I, Captures);
5779 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alloc_token))
5780 visitAllocTokenMetadata(
I, MD);
5782 if (MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
5784 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
5787 if (
DL->getAtomGroup()) {
5788 CheckDI(
DL->getScope()->getSubprogram()->getKeyInstructionsEnabled(),
5789 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
5790 "Instructions enabled",
5791 DL,
DL->getScope()->getSubprogram());
5797 I.getAllMetadata(MDs);
5798 for (
auto Attachment : MDs) {
5799 unsigned Kind = Attachment.first;
5801 (
Kind == LLVMContext::MD_dbg ||
Kind == LLVMContext::MD_loop)
5802 ? AreDebugLocsAllowed::Yes
5803 : AreDebugLocsAllowed::
No;
5804 visitMDNode(*Attachment.second, AllowLocs);
5819 bool IsVarArg = IFTy->isVarArg();
5830 "Intrinsic has incorrect return type!", IF);
5832 "Intrinsic has incorrect argument type!", IF);
5837 "Intrinsic was not defined with variable arguments!", IF);
5840 "Callsite was not defined with variable arguments!", IF);
5849 const std::string ExpectedName =
5852 "Intrinsic name not mangled correctly for type arguments! "
5864 "const x86_amx is not allowed in argument!");
5870 case Intrinsic::assume: {
5874 "assume with operand bundles must have i1 true condition",
Call);
5877 unsigned ArgCount = Elem.End - Elem.Begin;
5880 if (Elem.Tag->getKey() ==
"separate_storage") {
5881 Check(ArgCount == 2,
5882 "separate_storage assumptions should have 2 arguments",
Call);
5885 "arguments to separate_storage assumptions should be pointers",
5889 Check(Elem.Tag->getKey() ==
"ignore" ||
5890 Attribute::isExistingAttribute(Elem.Tag->getKey()),
5891 "tags must be valid attribute names",
Call);
5892 Attribute::AttrKind
Kind =
5893 Attribute::getAttrKindFromName(Elem.Tag->getKey());
5894 if (Kind == Attribute::Alignment) {
5895 Check(ArgCount <= 3 && ArgCount >= 2,
5896 "alignment assumptions should have 2 or 3 arguments",
Call);
5898 "first argument should be a pointer",
Call);
5900 "second argument should be an integer",
Call);
5903 "third argument should be an integer if present",
Call);
5906 if (Kind == Attribute::Dereferenceable) {
5907 Check(ArgCount == 2,
5908 "dereferenceable assumptions should have 2 arguments",
Call);
5910 "first argument should be a pointer",
Call);
5912 "second argument should be an integer",
Call);
5915 Check(ArgCount <= 2,
"too many arguments",
Call);
5916 if (Kind == Attribute::None)
5918 if (Attribute::isIntAttrKind(Kind)) {
5919 Check(ArgCount == 2,
"this attribute should have 2 arguments",
Call);
5921 "the second argument should be a constant integral value",
Call);
5922 }
else if (Attribute::canUseAsParamAttr(Kind)) {
5923 Check((ArgCount) == 1,
"this attribute should have one argument",
Call);
5924 }
else if (Attribute::canUseAsFnAttr(Kind)) {
5925 Check((ArgCount) == 0,
"this attribute has no argument",
Call);
5930 case Intrinsic::ucmp:
5931 case Intrinsic::scmp: {
5936 "result type must be at least 2 bits wide",
Call);
5938 bool IsDestTypeVector = DestTy->
isVectorTy();
5940 "ucmp/scmp argument and result types must both be either vector or "
5943 if (IsDestTypeVector) {
5946 Check(SrcVecLen == DestVecLen,
5947 "return type and arguments must have the same number of "
5953 case Intrinsic::coro_id: {
5959 "info argument of llvm.coro.id must refer to an initialized "
5963 "info argument of llvm.coro.id must refer to either a struct or "
5967 case Intrinsic::is_fpclass: {
5970 "unsupported bits for llvm.is.fpclass test mask");
5973 case Intrinsic::fptrunc_round: {
5978 MD = MAV->getMetadata();
5980 Check(MD !=
nullptr,
"missing rounding mode argument",
Call);
5983 (
"invalid value for llvm.fptrunc.round metadata operand"
5984 " (the operand should be a string)"),
5987 std::optional<RoundingMode> RoundMode =
5989 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
5990 "unsupported rounding mode argument",
Call);
5993 case Intrinsic::convert_to_arbitrary_fp: {
6001 "if floating-point operand is a vector, integer operand must also "
6004 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6005 "floating-point and integer vector operands must have the same "
6012 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6014 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6015 StringRef Interp = InterpStr->getString();
6017 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6022 "unsupported interpretation metadata string",
Call);
6026 Check(RoundingMAV,
"missing rounding mode metadata operand",
Call);
6028 Check(RoundingStr,
"rounding mode metadata operand must be a string",
Call);
6030 std::optional<RoundingMode>
RM =
6032 Check(RM && *RM != RoundingMode::Dynamic,
6033 "unsupported rounding mode argument",
Call);
6036 case Intrinsic::convert_from_arbitrary_fp: {
6044 "if floating-point operand is a vector, integer operand must also "
6047 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6048 "floating-point and integer vector operands must have the same "
6055 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6057 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6058 StringRef Interp = InterpStr->getString();
6060 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6065 "unsupported interpretation metadata string",
Call);
6068#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6069#include "llvm/IR/VPIntrinsics.def"
6070#undef BEGIN_REGISTER_VP_INTRINSIC
6073#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6074 case Intrinsic::INTRINSIC:
6075#include "llvm/IR/ConstrainedOps.def"
6079 case Intrinsic::dbg_declare:
6080 case Intrinsic::dbg_value:
6081 case Intrinsic::dbg_assign:
6082 case Intrinsic::dbg_label:
6089 case Intrinsic::memcpy:
6090 case Intrinsic::memcpy_inline:
6091 case Intrinsic::memmove:
6092 case Intrinsic::memset:
6093 case Intrinsic::memset_inline:
6095 case Intrinsic::experimental_memset_pattern: {
6097 Check(Memset->getValue()->getType()->isSized(),
6098 "unsized types cannot be used as memset patterns",
Call);
6101 case Intrinsic::memcpy_element_unordered_atomic:
6102 case Intrinsic::memmove_element_unordered_atomic:
6103 case Intrinsic::memset_element_unordered_atomic: {
6106 ConstantInt *ElementSizeCI =
6108 const APInt &ElementSizeVal = ElementSizeCI->
getValue();
6110 "element size of the element-wise atomic memory intrinsic "
6111 "must be a power of 2",
6114 auto IsValidAlignment = [&](MaybeAlign Alignment) {
6115 return Alignment && ElementSizeVal.
ule(Alignment->value());
6117 Check(IsValidAlignment(AMI->getDestAlign()),
6118 "incorrect alignment of the destination argument",
Call);
6120 Check(IsValidAlignment(AMT->getSourceAlign()),
6121 "incorrect alignment of the source argument",
Call);
6125 case Intrinsic::call_preallocated_setup: {
6127 bool FoundCall =
false;
6130 Check(UseCall !=
nullptr,
6131 "Uses of llvm.call.preallocated.setup must be calls");
6133 if (IID == Intrinsic::call_preallocated_arg) {
6135 Check(AllocArgIndex !=
nullptr,
6136 "llvm.call.preallocated.alloc arg index must be a constant");
6137 auto AllocArgIndexInt = AllocArgIndex->getValue();
6138 Check(AllocArgIndexInt.sge(0) &&
6139 AllocArgIndexInt.slt(NumArgs->getValue()),
6140 "llvm.call.preallocated.alloc arg index must be between 0 and "
6142 "llvm.call.preallocated.setup's argument count");
6143 }
else if (IID == Intrinsic::call_preallocated_teardown) {
6146 Check(!FoundCall,
"Can have at most one call corresponding to a "
6147 "llvm.call.preallocated.setup");
6149 size_t NumPreallocatedArgs = 0;
6150 for (
unsigned i = 0; i < UseCall->arg_size(); i++) {
6151 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6152 ++NumPreallocatedArgs;
6155 Check(NumPreallocatedArgs != 0,
6156 "cannot use preallocated intrinsics on a call without "
6157 "preallocated arguments");
6158 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6159 "llvm.call.preallocated.setup arg size must be equal to number "
6160 "of preallocated arguments "
6170 auto PreallocatedBundle =
6172 Check(PreallocatedBundle,
6173 "Use of llvm.call.preallocated.setup outside intrinsics "
6174 "must be in \"preallocated\" operand bundle");
6175 Check(PreallocatedBundle->Inputs.front().get() == &
Call,
6176 "preallocated bundle must have token from corresponding "
6177 "llvm.call.preallocated.setup");
6182 case Intrinsic::call_preallocated_arg: {
6185 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6186 "llvm.call.preallocated.arg token argument must be a "
6187 "llvm.call.preallocated.setup");
6189 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6190 "call site attribute");
6193 case Intrinsic::call_preallocated_teardown: {
6196 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6197 "llvm.call.preallocated.teardown token argument must be a "
6198 "llvm.call.preallocated.setup");
6201 case Intrinsic::gcroot:
6202 case Intrinsic::gcwrite:
6203 case Intrinsic::gcread:
6204 if (
ID == Intrinsic::gcroot) {
6207 Check(AI,
"llvm.gcroot parameter #1 must be an alloca.",
Call);
6209 "llvm.gcroot parameter #2 must be a constant.",
Call);
6212 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6213 "or argument #2 must be a non-null constant.",
6219 "Enclosing function does not use GC.",
Call);
6221 case Intrinsic::init_trampoline:
6223 "llvm.init_trampoline parameter #2 must resolve to a function.",
6226 case Intrinsic::prefetch:
6228 "rw argument to llvm.prefetch must be 0-1",
Call);
6230 "locality argument to llvm.prefetch must be 0-3",
Call);
6232 "cache type argument to llvm.prefetch must be 0-1",
Call);
6234 case Intrinsic::reloc_none: {
6237 "llvm.reloc.none argument must be a metadata string", &
Call);
6240 case Intrinsic::stackprotector:
6242 "llvm.stackprotector parameter #2 must resolve to an alloca.",
Call);
6244 case Intrinsic::localescape: {
6248 Check(!SawFrameEscape,
"multiple calls to llvm.localescape in one function",
6255 "llvm.localescape only accepts static allocas",
Call);
6258 SawFrameEscape =
true;
6261 case Intrinsic::localrecover: {
6265 "llvm.localrecover first "
6266 "argument must be function defined in this module",
6269 auto &
Entry = FrameEscapeInfo[Fn];
6270 Entry.second = unsigned(
6271 std::max(uint64_t(
Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6275 case Intrinsic::experimental_gc_statepoint:
6277 Check(!CI->isInlineAsm(),
6278 "gc.statepoint support for inline assembly unimplemented", CI);
6280 "Enclosing function does not use GC.",
Call);
6282 verifyStatepoint(
Call);
6284 case Intrinsic::experimental_gc_result: {
6286 "Enclosing function does not use GC.",
Call);
6294 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6295 Intrinsic::experimental_gc_statepoint,
6296 "gc.result operand #1 must be from a statepoint",
Call,
6300 auto *TargetFuncType =
6303 "gc.result result type does not match wrapped callee",
Call);
6306 case Intrinsic::experimental_gc_relocate: {
6310 "gc.relocate must return a pointer or a vector of pointers",
Call);
6315 if (LandingPadInst *LandingPad =
6319 LandingPad->getParent()->getUniquePredecessor();
6323 Check(InvokeBB,
"safepoints should have unique landingpads",
6324 LandingPad->getParent());
6328 "gc relocate should be linked to a statepoint", InvokeBB);
6335 "gc relocate is incorrectly tied to the statepoint",
Call, Token);
6344 "gc.relocate operand #2 must be integer offset",
Call);
6348 "gc.relocate operand #3 must be integer offset",
Call);
6358 Check(BaseIndex < Opt->Inputs.size(),
6359 "gc.relocate: statepoint base index out of bounds",
Call);
6360 Check(DerivedIndex < Opt->Inputs.size(),
6361 "gc.relocate: statepoint derived index out of bounds",
Call);
6374 "gc.relocate: relocated value must be a pointer",
Call);
6375 Check(DerivedType->isPtrOrPtrVectorTy(),
6376 "gc.relocate: relocated value must be a pointer",
Call);
6378 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6379 "gc.relocate: vector relocates to vector and pointer to pointer",
6382 ResultType->getPointerAddressSpace() ==
6383 DerivedType->getPointerAddressSpace(),
6384 "gc.relocate: relocating a pointer shouldn't change its address space",
6388 Check(GC,
"gc.relocate: calling function must have GCStrategy",
6391 auto isGCPtr = [&
GC](
Type *PTy) {
6392 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(
true);
6394 Check(isGCPtr(ResultType),
"gc.relocate: must return gc pointer",
Call);
6396 "gc.relocate: relocated value must be a gc pointer",
Call);
6397 Check(isGCPtr(DerivedType),
6398 "gc.relocate: relocated value must be a gc pointer",
Call);
6402 case Intrinsic::experimental_patchpoint: {
6405 "patchpoint: invalid return type used with anyregcc",
Call);
6409 case Intrinsic::eh_exceptioncode:
6410 case Intrinsic::eh_exceptionpointer: {
6412 "eh.exceptionpointer argument must be a catchpad",
Call);
6415 case Intrinsic::get_active_lane_mask: {
6417 "get_active_lane_mask: must return a "
6421 Check(ElemTy->isIntegerTy(1),
6422 "get_active_lane_mask: element type is not "
6427 case Intrinsic::experimental_get_vector_length: {
6430 "get_vector_length: VF must be positive",
Call);
6433 case Intrinsic::masked_load: {
6439 Check(
Mask->getType()->isVectorTy(),
"masked_load: mask must be vector",
6442 "masked_load: pass through and return type must match",
Call);
6445 "masked_load: vector mask must be same length as return",
Call);
6448 case Intrinsic::masked_store: {
6451 Check(
Mask->getType()->isVectorTy(),
"masked_store: mask must be vector",
6455 "masked_store: vector mask must be same length as value",
Call);
6459 case Intrinsic::experimental_guard: {
6462 "experimental_guard must have exactly one "
6463 "\"deopt\" operand bundle");
6467 case Intrinsic::experimental_deoptimize: {
6471 "experimental_deoptimize must have exactly one "
6472 "\"deopt\" operand bundle");
6474 "experimental_deoptimize return type must match caller return type");
6479 "calls to experimental_deoptimize must be followed by a return");
6483 "calls to experimental_deoptimize must be followed by a return "
6484 "of the value computed by experimental_deoptimize");
6489 case Intrinsic::vastart: {
6491 "va_start called in a non-varargs function");
6494 case Intrinsic::get_dynamic_area_offset: {
6496 Check(IntTy &&
DL.getPointerSizeInBits(
DL.getAllocaAddrSpace()) ==
6497 IntTy->getBitWidth(),
6498 "get_dynamic_area_offset result type must be scalar integer matching "
6499 "alloca address space width",
6503 case Intrinsic::vector_reduce_and:
6504 case Intrinsic::vector_reduce_or:
6505 case Intrinsic::vector_reduce_xor:
6506 case Intrinsic::vector_reduce_add:
6507 case Intrinsic::vector_reduce_mul:
6508 case Intrinsic::vector_reduce_smax:
6509 case Intrinsic::vector_reduce_smin:
6510 case Intrinsic::vector_reduce_umax:
6511 case Intrinsic::vector_reduce_umin: {
6514 "Intrinsic has incorrect argument type!");
6517 case Intrinsic::vector_reduce_fmax:
6518 case Intrinsic::vector_reduce_fmin: {
6521 "Intrinsic has incorrect argument type!");
6524 case Intrinsic::vector_reduce_fadd:
6525 case Intrinsic::vector_reduce_fmul: {
6530 "Intrinsic has incorrect argument type!");
6533 case Intrinsic::smul_fix:
6534 case Intrinsic::smul_fix_sat:
6535 case Intrinsic::umul_fix:
6536 case Intrinsic::umul_fix_sat:
6537 case Intrinsic::sdiv_fix:
6538 case Intrinsic::sdiv_fix_sat:
6539 case Intrinsic::udiv_fix:
6540 case Intrinsic::udiv_fix_sat: {
6544 "first operand of [us][mul|div]_fix[_sat] must be an int type or "
6547 "second operand of [us][mul|div]_fix[_sat] must be an int type or "
6551 Check(Op3->getType()->isIntegerTy(),
6552 "third operand of [us][mul|div]_fix[_sat] must be an int type");
6553 Check(Op3->getBitWidth() <= 32,
6554 "third operand of [us][mul|div]_fix[_sat] must fit within 32 bits");
6556 if (
ID == Intrinsic::smul_fix ||
ID == Intrinsic::smul_fix_sat ||
6557 ID == Intrinsic::sdiv_fix ||
ID == Intrinsic::sdiv_fix_sat) {
6559 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6563 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6564 "to the width of the operands");
6568 case Intrinsic::lrint:
6569 case Intrinsic::llrint:
6570 case Intrinsic::lround:
6571 case Intrinsic::llround: {
6577 ExpectedName +
": argument must be floating-point or vector "
6578 "of floating-points, and result must be integer or "
6579 "vector of integers",
6582 ExpectedName +
": argument and result disagree on vector use", &
Call);
6584 Check(VTy->getElementCount() == RTy->getElementCount(),
6585 ExpectedName +
": argument must be same length as result", &
Call);
6589 case Intrinsic::bswap: {
6592 Check(
Size % 16 == 0,
"bswap must be an even number of bytes", &
Call);
6595 case Intrinsic::invariant_start: {
6597 Check(InvariantSize &&
6599 "invariant_start parameter must be -1, 0 or a positive number",
6603 case Intrinsic::matrix_multiply:
6604 case Intrinsic::matrix_transpose:
6605 case Intrinsic::matrix_column_major_load:
6606 case Intrinsic::matrix_column_major_store: {
6608 ConstantInt *Stride =
nullptr;
6609 ConstantInt *NumRows;
6610 ConstantInt *NumColumns;
6612 Type *Op0ElemTy =
nullptr;
6613 Type *Op1ElemTy =
nullptr;
6615 case Intrinsic::matrix_multiply: {
6620 ->getNumElements() ==
6622 "First argument of a matrix operation does not match specified "
6625 ->getNumElements() ==
6627 "Second argument of a matrix operation does not match specified "
6637 case Intrinsic::matrix_transpose:
6644 case Intrinsic::matrix_column_major_load: {
6651 case Intrinsic::matrix_column_major_store: {
6664 Check(ResultTy->getElementType()->isIntegerTy() ||
6665 ResultTy->getElementType()->isFloatingPointTy(),
6666 "Result type must be an integer or floating-point type!", IF);
6669 Check(ResultTy->getElementType() == Op0ElemTy,
6670 "Vector element type mismatch of the result and first operand "
6675 Check(ResultTy->getElementType() == Op1ElemTy,
6676 "Vector element type mismatch of the result and second operand "
6682 "Result of a matrix operation does not fit in the returned vector!");
6688 "Stride must be greater or equal than the number of rows!", IF);
6693 case Intrinsic::vector_splice_left:
6694 case Intrinsic::vector_splice_right: {
6697 uint64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
6701 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
6702 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
6704 if (
ID == Intrinsic::vector_splice_left)
6705 Check(Idx < KnownMinNumElements,
6706 "The splice index exceeds the range [0, VL-1] where VL is the "
6707 "known minimum number of elements in the vector. For scalable "
6708 "vectors the minimum number of elements is determined from "
6712 Check(Idx <= KnownMinNumElements,
6713 "The splice index exceeds the range [0, VL] where VL is the "
6714 "known minimum number of elements in the vector. For scalable "
6715 "vectors the minimum number of elements is determined from "
6720 case Intrinsic::stepvector: {
6722 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6723 VecTy->getScalarSizeInBits() >= 8,
6724 "stepvector only supported for vectors of integers "
6725 "with a bitwidth of at least 8.",
6729 case Intrinsic::experimental_vector_match: {
6738 Check(Op1Ty && Op2Ty && MaskTy,
"Operands must be vectors.", &
Call);
6740 "Second operand must be a fixed length vector.", &
Call);
6741 Check(Op1Ty->getElementType()->isIntegerTy(),
6742 "First operand must be a vector of integers.", &
Call);
6743 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6744 "First two operands must have the same element type.", &
Call);
6745 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6746 "First operand and mask must have the same number of elements.",
6748 Check(MaskTy->getElementType()->isIntegerTy(1),
6749 "Mask must be a vector of i1's.", &
Call);
6754 case Intrinsic::vector_insert: {
6763 ElementCount VecEC = VecTy->getElementCount();
6764 ElementCount SubVecEC = SubVecTy->getElementCount();
6765 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6766 "vector_insert parameters must have the same element "
6770 "vector_insert index must be a constant multiple of "
6771 "the subvector's known minimum vector length.");
6779 "subvector operand of vector_insert would overrun the "
6780 "vector being inserted into.");
6784 case Intrinsic::vector_extract: {
6792 ElementCount VecEC = VecTy->getElementCount();
6793 ElementCount ResultEC = ResultTy->getElementCount();
6795 Check(ResultTy->getElementType() == VecTy->getElementType(),
6796 "vector_extract result must have the same element "
6797 "type as the input vector.",
6800 "vector_extract index must be a constant multiple of "
6801 "the result type's known minimum vector length.");
6809 "vector_extract would overrun.");
6813 case Intrinsic::vector_partial_reduce_fadd:
6814 case Intrinsic::vector_partial_reduce_add: {
6818 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
6819 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
6821 Check((VecWidth % AccWidth) == 0,
6822 "Invalid vector widths for partial "
6823 "reduction. The width of the input vector "
6824 "must be a positive integer multiple of "
6825 "the width of the accumulator vector.");
6828 case Intrinsic::experimental_noalias_scope_decl: {
6832 case Intrinsic::preserve_array_access_index:
6833 case Intrinsic::preserve_struct_access_index:
6834 case Intrinsic::aarch64_ldaxr:
6835 case Intrinsic::aarch64_ldxr:
6836 case Intrinsic::arm_ldaex:
6837 case Intrinsic::arm_ldrex: {
6839 Check(ElemTy,
"Intrinsic requires elementtype attribute on first argument.",
6843 case Intrinsic::aarch64_stlxr:
6844 case Intrinsic::aarch64_stxr:
6845 case Intrinsic::arm_stlex:
6846 case Intrinsic::arm_strex: {
6849 "Intrinsic requires elementtype attribute on second argument.",
6853 case Intrinsic::aarch64_prefetch: {
6855 "write argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6857 "target argument to llvm.aarch64.prefetch must be 0-3",
Call);
6859 "stream argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6861 "isdata argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6864 case Intrinsic::aarch64_range_prefetch: {
6866 "write argument to llvm.aarch64.range.prefetch must be 0 or 1",
Call);
6868 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
6872 case Intrinsic::callbr_landingpad: {
6874 Check(CBR,
"intrinstic requires callbr operand", &
Call);
6881 CheckFailed(
"Intrinsic in block must have 1 unique predecessor", &
Call);
6885 CheckFailed(
"Intrinsic must have corresponding callbr in predecessor",
6890 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
6891 "block in indirect destination list",
6894 Check(&
First == &
Call,
"No other instructions may proceed intrinsic",
6898 case Intrinsic::amdgcn_cs_chain: {
6901 case CallingConv::AMDGPU_CS:
6902 case CallingConv::AMDGPU_CS_Chain:
6903 case CallingConv::AMDGPU_CS_ChainPreserve:
6904 case CallingConv::AMDGPU_ES:
6905 case CallingConv::AMDGPU_GS:
6906 case CallingConv::AMDGPU_HS:
6907 case CallingConv::AMDGPU_LS:
6908 case CallingConv::AMDGPU_VS:
6911 CheckFailed(
"Intrinsic cannot be called from functions with this "
6912 "calling convention",
6918 "SGPR arguments must have the `inreg` attribute", &
Call);
6920 "VGPR arguments must not have the `inreg` attribute", &
Call);
6925 Intrinsic::amdgcn_unreachable;
6927 "llvm.amdgcn.cs.chain must be followed by unreachable", &
Call);
6930 case Intrinsic::amdgcn_init_exec_from_input: {
6933 "only inreg arguments to the parent function are valid as inputs to "
6938 case Intrinsic::amdgcn_set_inactive_chain_arg: {
6941 case CallingConv::AMDGPU_CS_Chain:
6942 case CallingConv::AMDGPU_CS_ChainPreserve:
6945 CheckFailed(
"Intrinsic can only be used from functions with the "
6946 "amdgpu_cs_chain or amdgpu_cs_chain_preserve "
6947 "calling conventions",
6952 unsigned InactiveIdx = 1;
6954 "Value for inactive lanes must not have the `inreg` attribute",
6957 "Value for inactive lanes must be a function argument", &
Call);
6959 "Value for inactive lanes must be a VGPR function argument", &
Call);
6962 case Intrinsic::amdgcn_call_whole_wave: {
6964 Check(
F,
"Indirect whole wave calls are not allowed", &
Call);
6966 CallingConv::ID CC =
F->getCallingConv();
6967 Check(CC == CallingConv::AMDGPU_Gfx_WholeWave,
6968 "Callee must have the amdgpu_gfx_whole_wave calling convention",
6971 Check(!
F->isVarArg(),
"Variadic whole wave calls are not allowed", &
Call);
6974 "Call argument count must match callee argument count", &
Call);
6978 Check(
F->arg_begin()->getType()->isIntegerTy(1),
6979 "Callee must have i1 as its first argument", &
Call);
6980 for (
auto [CallArg, FuncArg] :
6982 Check(CallArg->getType() == FuncArg.getType(),
6983 "Argument types must match", &
Call);
6987 FuncArg.hasInRegAttr(),
6988 "Argument inreg attributes must match", &
Call);
6992 case Intrinsic::amdgcn_s_prefetch_data: {
6996 "llvm.amdgcn.s.prefetch.data only supports global or constant memory");
6999 case Intrinsic::amdgcn_mfma_scale_f32_16x16x128_f8f6f4:
7000 case Intrinsic::amdgcn_mfma_scale_f32_32x32x64_f8f6f4: {
7006 Check(CBSZ <= 4,
"invalid value for cbsz format",
Call,
7008 Check(BLGP <= 4,
"invalid value for blgp format",
Call,
7012 auto getFormatNumRegs = [](
unsigned FormatVal) {
7013 switch (FormatVal) {
7027 auto isValidSrcASrcBVector = [](FixedVectorType *Ty) {
7028 if (!Ty || !Ty->getElementType()->
isIntegerTy(32))
7030 unsigned NumElts = Ty->getNumElements();
7031 return NumElts == 4 || NumElts == 6 || NumElts == 8;
7036 Check(isValidSrcASrcBVector(Src0Ty),
7037 "operand 0 must be 4, 6 or 8 element i32 vector", &
Call, Src0);
7038 Check(isValidSrcASrcBVector(Src1Ty),
7039 "operand 1 must be 4, 6 or 8 element i32 vector", &
Call, Src1);
7042 Check(Src0Ty->getNumElements() >= getFormatNumRegs(CBSZ),
7044 Check(Src1Ty->getNumElements() >= getFormatNumRegs(BLGP),
7048 case Intrinsic::amdgcn_wmma_f32_16x16x128_f8f6f4:
7049 case Intrinsic::amdgcn_wmma_scale_f32_16x16x128_f8f6f4:
7050 case Intrinsic::amdgcn_wmma_scale16_f32_16x16x128_f8f6f4: {
7056 Check(FmtA <= 4,
"invalid value for matrix format",
Call,
7058 Check(FmtB <= 4,
"invalid value for matrix format",
Call,
7062 auto getFormatNumRegs = [](
unsigned FormatVal) {
7063 switch (FormatVal) {
7077 auto isValidSrcASrcBVector = [](FixedVectorType *Ty) {
7078 if (!Ty || !Ty->getElementType()->
isIntegerTy(32))
7080 unsigned NumElts = Ty->getNumElements();
7081 return NumElts == 16 || NumElts == 12 || NumElts == 8;
7086 Check(isValidSrcASrcBVector(Src0Ty),
7087 "operand 1 must be 8, 12 or 16 element i32 vector", &
Call, Src0);
7088 Check(isValidSrcASrcBVector(Src1Ty),
7089 "operand 3 must be 8, 12 or 16 element i32 vector", &
Call, Src1);
7092 Check(Src0Ty->getNumElements() >= getFormatNumRegs(FmtA),
7094 Check(Src1Ty->getNumElements() >= getFormatNumRegs(FmtB),
7098 case Intrinsic::amdgcn_cooperative_atomic_load_32x4B:
7099 case Intrinsic::amdgcn_cooperative_atomic_load_16x8B:
7100 case Intrinsic::amdgcn_cooperative_atomic_load_8x16B:
7101 case Intrinsic::amdgcn_cooperative_atomic_store_32x4B:
7102 case Intrinsic::amdgcn_cooperative_atomic_store_16x8B:
7103 case Intrinsic::amdgcn_cooperative_atomic_store_8x16B: {
7108 "cooperative atomic intrinsics require a generic or global pointer",
7115 "cooperative atomic intrinsics require that the last argument is a "
7120 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7121 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7124 Check(RegCount % 8 == 0,
7125 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7128 case Intrinsic::experimental_convergence_entry:
7129 case Intrinsic::experimental_convergence_anchor:
7131 case Intrinsic::experimental_convergence_loop:
7133 case Intrinsic::ptrmask: {
7137 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7142 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
7147 "llvm.ptrmask intrinsic arguments must have the same number of "
7151 "llvm.ptrmask intrinsic second argument bitwidth must match "
7152 "pointer index type size of first argument",
7156 case Intrinsic::thread_pointer: {
7158 DL.getDefaultGlobalsAddressSpace(),
7159 "llvm.thread.pointer intrinsic return type must be for the globals "
7164 case Intrinsic::threadlocal_address: {
7167 "llvm.threadlocal.address first argument must be a GlobalValue");
7169 "llvm.threadlocal.address operand isThreadLocal() must be true");
7172 case Intrinsic::lifetime_start:
7173 case Intrinsic::lifetime_end: {
7176 "llvm.lifetime.start/end can only be used on alloca or poison",
7185 if (
F->hasPersonalityFn() &&
7189 if (BlockEHFuncletColors.
empty())
7193 bool InEHFunclet =
false;
7197 for (BasicBlock *ColorFirstBB : CV)
7198 if (
auto It = ColorFirstBB->getFirstNonPHIIt();
7199 It != ColorFirstBB->end())
7204 bool HasToken =
false;
7211 Check(HasToken,
"Missing funclet token on intrinsic call", &
Call);
7235void Verifier::visit(DbgLabelRecord &DLR) {
7237 "invalid #dbg_label intrinsic variable", &DLR, DLR.
getRawLabel());
7250 CheckDI(Loc,
"#dbg_label record requires a !dbg attachment", &DLR, BB,
F);
7254 if (!LabelSP || !LocSP)
7258 "mismatched subprogram between #dbg_label label and !dbg attachment",
7259 &DLR, BB,
F, Label,
Label->getScope()->getSubprogram(), Loc,
7260 Loc->getScope()->getSubprogram());
7263void Verifier::visit(DbgVariableRecord &DVR) {
7267 CheckDI(DVR.
getType() == DbgVariableRecord::LocationType::Value ||
7268 DVR.
getType() == DbgVariableRecord::LocationType::Declare ||
7269 DVR.
getType() == DbgVariableRecord::LocationType::DeclareValue ||
7270 DVR.
getType() == DbgVariableRecord::LocationType::Assign,
7271 "invalid #dbg record type", &DVR, DVR.
getType(), BB,
F);
7279 "invalid #dbg record address/value", &DVR, MD, BB,
F);
7281 visitValueAsMetadata(*VAM,
F);
7284 Type *Ty = VAM->getValue()->getType();
7286 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7290 visitDIArgList(*AL,
F);
7304 "invalid #dbg_assign DIAssignID", &DVR, DVR.
getRawAssignID(), BB,
7307 AreDebugLocsAllowed::No);
7316 "invalid #dbg_assign address", &DVR, DVR.
getRawAddress(), BB,
F);
7318 visitValueAsMetadata(*VAM,
F);
7321 "invalid #dbg_assign address expression", &DVR,
7328 "inst not in same function as #dbg_assign",
I, &DVR, BB,
F);
7338 &DVR, DLNode, BB,
F);
7344 if (!VarSP || !LocSP)
7348 "mismatched subprogram between #dbg record variable and DILocation",
7350 Loc->getScope()->getSubprogram(), BB,
F);
7355void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7359 Check(RetTy->getElementCount() == ValTy->getElementCount(),
7360 "VP cast intrinsic first argument and result vector lengths must be "
7364 switch (VPCast->getIntrinsicID()) {
7367 case Intrinsic::vp_trunc:
7369 "llvm.vp.trunc intrinsic first argument and result element type "
7373 "llvm.vp.trunc intrinsic the bit size of first argument must be "
7374 "larger than the bit size of the return type",
7377 case Intrinsic::vp_zext:
7378 case Intrinsic::vp_sext:
7380 "llvm.vp.zext or llvm.vp.sext intrinsic first argument and result "
7381 "element type must be integer",
7384 "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
7385 "argument must be smaller than the bit size of the return type",
7388 case Intrinsic::vp_fptoui:
7389 case Intrinsic::vp_fptosi:
7390 case Intrinsic::vp_lrint:
7391 case Intrinsic::vp_llrint:
7394 "llvm.vp.fptoui, llvm.vp.fptosi, llvm.vp.lrint or llvm.vp.llrint" "intrinsic first argument element "
7395 "type must be floating-point and result element type must be integer",
7398 case Intrinsic::vp_uitofp:
7399 case Intrinsic::vp_sitofp:
7402 "llvm.vp.uitofp or llvm.vp.sitofp intrinsic first argument element "
7403 "type must be integer and result element type must be floating-point",
7406 case Intrinsic::vp_fptrunc:
7408 "llvm.vp.fptrunc intrinsic first argument and result element type "
7409 "must be floating-point",
7412 "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
7413 "larger than the bit size of the return type",
7416 case Intrinsic::vp_fpext:
7418 "llvm.vp.fpext intrinsic first argument and result element type "
7419 "must be floating-point",
7422 "llvm.vp.fpext intrinsic the bit size of first argument must be "
7423 "smaller than the bit size of the return type",
7426 case Intrinsic::vp_ptrtoint:
7428 "llvm.vp.ptrtoint intrinsic first argument element type must be "
7429 "pointer and result element type must be integer",
7432 case Intrinsic::vp_inttoptr:
7434 "llvm.vp.inttoptr intrinsic first argument element type must be "
7435 "integer and result element type must be pointer",
7442 case Intrinsic::vp_fcmp: {
7445 "invalid predicate for VP FP comparison intrinsic", &VPI);
7448 case Intrinsic::vp_icmp: {
7451 "invalid predicate for VP integer comparison intrinsic", &VPI);
7454 case Intrinsic::vp_is_fpclass: {
7457 "unsupported bits for llvm.vp.is.fpclass test mask");
7460 case Intrinsic::experimental_vp_splice: {
7463 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7465 AttributeList
Attrs = VPI.
getParent()->getParent()->getAttributes();
7466 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
7467 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
7469 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7470 (Idx >= 0 && Idx < KnownMinNumElements),
7471 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7472 "known minimum number of elements in the vector. For scalable "
7473 "vectors the minimum number of elements is determined from "
7481void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7483 bool HasRoundingMD =
7487 NumOperands += (1 + HasRoundingMD);
7493 "invalid arguments for constrained FP intrinsic", &FPI);
7496 case Intrinsic::experimental_constrained_lrint:
7497 case Intrinsic::experimental_constrained_llrint: {
7501 "Intrinsic does not support vectors", &FPI);
7505 case Intrinsic::experimental_constrained_lround:
7506 case Intrinsic::experimental_constrained_llround: {
7510 "Intrinsic does not support vectors", &FPI);
7514 case Intrinsic::experimental_constrained_fcmp:
7515 case Intrinsic::experimental_constrained_fcmps: {
7518 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7522 case Intrinsic::experimental_constrained_fptosi:
7523 case Intrinsic::experimental_constrained_fptoui: {
7527 "Intrinsic first argument must be floating point", &FPI);
7534 "Intrinsic first argument and result disagree on vector use", &FPI);
7536 "Intrinsic result must be an integer", &FPI);
7539 "Intrinsic first argument and result vector lengths must be equal",
7545 case Intrinsic::experimental_constrained_sitofp:
7546 case Intrinsic::experimental_constrained_uitofp: {
7550 "Intrinsic first argument must be integer", &FPI);
7557 "Intrinsic first argument and result disagree on vector use", &FPI);
7559 "Intrinsic result must be a floating point", &FPI);
7562 "Intrinsic first argument and result vector lengths must be equal",
7568 case Intrinsic::experimental_constrained_fptrunc:
7569 case Intrinsic::experimental_constrained_fpext: {
7575 "Intrinsic first argument must be FP or FP vector", &FPI);
7577 "Intrinsic result must be FP or FP vector", &FPI);
7579 "Intrinsic first argument and result disagree on vector use", &FPI);
7583 "Intrinsic first argument and result vector lengths must be equal",
7586 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7588 "Intrinsic first argument's type must be larger than result type",
7592 "Intrinsic first argument's type must be smaller than result type",
7608 "invalid exception behavior argument", &FPI);
7609 if (HasRoundingMD) {
7615void Verifier::verifyFragmentExpression(
const DbgVariableRecord &DVR) {
7620 if (!V || !
E || !
E->isValid())
7624 auto Fragment =
E->getFragmentInfo();
7634 if (
V->isArtificial())
7637 verifyFragmentExpression(*V, *Fragment, &DVR);
7640template <
typename ValueOrMetadata>
7641void Verifier::verifyFragmentExpression(
const DIVariable &V,
7643 ValueOrMetadata *
Desc) {
7646 auto VarSize =
V.getSizeInBits();
7652 CheckDI(FragSize + FragOffset <= *VarSize,
7653 "fragment is larger than or outside of variable",
Desc, &V);
7654 CheckDI(FragSize != *VarSize,
"fragment covers entire variable",
Desc, &V);
7657void Verifier::verifyFnArgs(
const DbgVariableRecord &DVR) {
7669 CheckDI(Var,
"#dbg record without variable");
7671 unsigned ArgNo = Var->
getArg();
7677 if (DebugFnArgs.
size() < ArgNo)
7678 DebugFnArgs.
resize(ArgNo,
nullptr);
7680 auto *Prev = DebugFnArgs[ArgNo - 1];
7681 DebugFnArgs[ArgNo - 1] = Var;
7682 CheckDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &DVR,
7686void Verifier::verifyNotEntryValue(
const DbgVariableRecord &DVR) {
7690 if (!
E || !
E->isValid())
7700 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7705 "Entry values are only allowed in MIR unless they target a "
7706 "swiftasync Argument",
7710void Verifier::verifyCompileUnits() {
7714 if (
M.getContext().isODRUniquingDebugTypes())
7716 auto *CUs =
M.getNamedMetadata(
"llvm.dbg.cu");
7717 SmallPtrSet<const Metadata *, 2> Listed;
7720 for (
const auto *CU : CUVisited)
7721 CheckDI(Listed.
count(CU),
"DICompileUnit not listed in llvm.dbg.cu", CU);
7725void Verifier::verifyDeoptimizeCallingConvs() {
7726 if (DeoptimizeDeclarations.
empty())
7730 for (
const auto *
F :
ArrayRef(DeoptimizeDeclarations).slice(1)) {
7731 Check(
First->getCallingConv() ==
F->getCallingConv(),
7732 "All llvm.experimental.deoptimize declarations must have the same "
7733 "calling convention",
7738void Verifier::verifyAttachedCallBundle(
const CallBase &
Call,
7739 const OperandBundleUse &BU) {
7742 Check((FTy->getReturnType()->isPointerTy() ||
7744 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7745 "function returning a pointer or a non-returning function that has a "
7750 "operand bundle \"clang.arc.attachedcall\" requires one function as "
7758 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7759 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
7760 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7761 "invalid function argument",
Call);
7763 StringRef FnName = Fn->
getName();
7764 Check((FnName ==
"objc_retainAutoreleasedReturnValue" ||
7765 FnName ==
"objc_claimAutoreleasedReturnValue" ||
7766 FnName ==
"objc_unsafeClaimAutoreleasedReturnValue"),
7767 "invalid function argument",
Call);
7771void Verifier::verifyNoAliasScopeDecl() {
7772 if (NoAliasScopeDecls.
empty())
7776 for (
auto *
II : NoAliasScopeDecls) {
7777 assert(
II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7778 "Not a llvm.experimental.noalias.scope.decl ?");
7781 Check(ScopeListMV !=
nullptr,
7782 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7787 Check(ScopeListMD !=
nullptr,
"!id.scope.list must point to an MDNode",
II);
7788 Check(ScopeListMD->getNumOperands() == 1,
7789 "!id.scope.list must point to a list with a single scope",
II);
7790 visitAliasScopeListMetadata(ScopeListMD);
7800 auto GetScope = [](IntrinsicInst *
II) {
7803 return &
cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7808 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7809 return GetScope(Lhs) < GetScope(Rhs);
7816 auto ItCurrent = NoAliasScopeDecls.begin();
7817 while (ItCurrent != NoAliasScopeDecls.end()) {
7818 auto CurScope = GetScope(*ItCurrent);
7819 auto ItNext = ItCurrent;
7822 }
while (ItNext != NoAliasScopeDecls.end() &&
7823 GetScope(*ItNext) == CurScope);
7828 if (ItNext - ItCurrent < 32)
7832 Check(!DT.dominates(
I, J),
7833 "llvm.experimental.noalias.scope.decl dominates another one "
7834 "with the same scope",
7848 Verifier V(OS,
true, *f.getParent());
7852 return !V.verify(
F);
7856 bool *BrokenDebugInfo) {
7858 Verifier V(OS, !BrokenDebugInfo, M);
7860 bool Broken =
false;
7862 Broken |= !V.verify(
F);
7864 Broken |= !V.verify();
7865 if (BrokenDebugInfo)
7866 *BrokenDebugInfo = V.hasBrokenDebugInfo();
7877 std::unique_ptr<Verifier> V;
7878 bool FatalErrors =
true;
7883 explicit VerifierLegacyPass(
bool FatalErrors)
7885 FatalErrors(FatalErrors) {
7889 bool doInitialization(
Module &M)
override {
7890 V = std::make_unique<Verifier>(
7896 if (!
V->verify(
F) && FatalErrors) {
7897 errs() <<
"in function " <<
F.getName() <<
'\n';
7903 bool doFinalization(
Module &M)
override {
7904 bool HasErrors =
false;
7905 for (Function &
F : M)
7906 if (
F.isDeclaration())
7907 HasErrors |= !
V->verify(
F);
7909 HasErrors |= !
V->verify();
7910 if (FatalErrors && (HasErrors ||
V->hasBrokenDebugInfo()))
7915 void getAnalysisUsage(AnalysisUsage &AU)
const override {
7923template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&... Args) {
7925 return Diagnostic->CheckFailed(
Args...);
7928#define CheckTBAA(C, ...) \
7931 CheckFailed(__VA_ARGS__); \
7939TBAAVerifier::TBAABaseNodeSummary
7943 CheckFailed(
"Base nodes must have at least two operands",
I, BaseNode);
7947 auto Itr = TBAABaseNodes.find(BaseNode);
7948 if (Itr != TBAABaseNodes.end())
7951 auto Result = verifyTBAABaseNodeImpl(
I, BaseNode, IsNewFormat);
7952 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
7954 assert(InsertResult.second &&
"We just checked!");
7958TBAAVerifier::TBAABaseNodeSummary
7959TBAAVerifier::verifyTBAABaseNodeImpl(
const Instruction *
I,
7960 const MDNode *BaseNode,
bool IsNewFormat) {
7961 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0
u};
7965 return isValidScalarTBAANode(BaseNode)
7966 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
7972 CheckFailed(
"Access tag nodes must have the number of operands that is a "
7973 "multiple of 3!", BaseNode);
7978 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
7988 if (!TypeSizeNode) {
7989 CheckFailed(
"Type size nodes must be constants!",
I, BaseNode);
7996 CheckFailed(
"Struct tag nodes have a string as their first operand",
8003 std::optional<APInt> PrevOffset;
8008 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8009 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8010 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
8011 Idx += NumOpsPerField) {
8012 const MDOperand &FieldTy = BaseNode->
getOperand(Idx);
8013 const MDOperand &FieldOffset = BaseNode->
getOperand(Idx + 1);
8015 CheckFailed(
"Incorrect field entry in struct type node!",
I, BaseNode);
8020 auto *OffsetEntryCI =
8022 if (!OffsetEntryCI) {
8023 CheckFailed(
"Offset entries must be constants!",
I, BaseNode);
8029 BitWidth = OffsetEntryCI->getBitWidth();
8031 if (OffsetEntryCI->getBitWidth() !=
BitWidth) {
8033 "Bitwidth between the offsets and struct type entries must match",
I,
8045 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
8048 CheckFailed(
"Offsets must be increasing!",
I, BaseNode);
8052 PrevOffset = OffsetEntryCI->getValue();
8057 if (!MemberSizeNode) {
8058 CheckFailed(
"Member size entries must be constants!",
I, BaseNode);
8065 return Failed ? InvalidNode
8066 : TBAAVerifier::TBAABaseNodeSummary(
false,
BitWidth);
8088 return Parent && Visited.
insert(Parent).second &&
8092bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
8093 auto ResultIt = TBAAScalarNodes.find(MD);
8094 if (ResultIt != TBAAScalarNodes.end())
8095 return ResultIt->second;
8097 SmallPtrSet<const MDNode *, 4> Visited;
8099 auto InsertResult = TBAAScalarNodes.insert({MD,
Result});
8101 assert(InsertResult.second &&
"Just checked!");
8110MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(
const Instruction *
I,
8111 const MDNode *BaseNode,
8122 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8123 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8124 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
8125 Idx += NumOpsPerField) {
8126 auto *OffsetEntryCI =
8128 if (OffsetEntryCI->getValue().ugt(
Offset)) {
8129 if (Idx == FirstFieldOpNo) {
8130 CheckFailed(
"Could not find TBAA parent in struct type node",
I,
8135 unsigned PrevIdx = Idx - NumOpsPerField;
8136 auto *PrevOffsetEntryCI =
8138 Offset -= PrevOffsetEntryCI->getValue();
8146 Offset -= LastOffsetEntryCI->getValue();
8151 if (!
Type ||
Type->getNumOperands() < 3)
8167 "This instruction shall not have a TBAA access tag!",
I);
8169 bool IsStructPathTBAA =
8173 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8183 "Access tag metadata must have either 4 or 5 operands",
I, MD);
8186 "Struct tag metadata must have either 3 or 4 operands",
I, MD);
8193 CheckTBAA(AccessSizeNode,
"Access size field must be a constant",
I, MD);
8197 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8202 "Immutability tag on struct tag metadata must be a constant",
I,
8205 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8206 "Immutability part of the struct tag metadata must be either 0 or 1",
I,
8211 "Malformed struct tag metadata: base and access-type "
8212 "should be non-null and point to Metadata nodes",
8213 I, MD, BaseNode, AccessType);
8216 CheckTBAA(isValidScalarTBAANode(AccessType),
8217 "Access type node must be a valid scalar type",
I, MD,
8222 CheckTBAA(OffsetCI,
"Offset must be constant integer",
I, MD);
8225 bool SeenAccessTypeInPath =
false;
8231 getFieldNodeFromTBAABaseNode(
I, BaseNode,
Offset, IsNewFormat)) {
8232 if (!StructPath.
insert(BaseNode).second) {
8233 CheckFailed(
"Cycle detected in struct path",
I, MD);
8238 unsigned BaseNodeBitWidth;
8239 std::tie(
Invalid, BaseNodeBitWidth) =
8240 verifyTBAABaseNode(
I, BaseNode, IsNewFormat);
8247 SeenAccessTypeInPath |= BaseNode == AccessType;
8249 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8254 (BaseNodeBitWidth == 0 &&
Offset == 0) ||
8255 (IsNewFormat && BaseNodeBitWidth == ~0u),
8256 "Access bit-width not the same as description bit-width",
I, MD,
8257 BaseNodeBitWidth,
Offset.getBitWidth());
8259 if (IsNewFormat && SeenAccessTypeInPath)
8263 CheckTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
I,
8268char VerifierLegacyPass::ID = 0;
8269INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
8272 return new VerifierLegacyPass(FatalErrors);
8290 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8298 if (res.IRBroken && FatalErrors)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU address space definition.
ArrayRef< TableEntry > TableRef
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericConvergenceVerifier template.
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
static bool runOnFunction(Function &F, bool PostInlining)
This file contains the declarations of entities that describe floating point environment and related ...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
static unsigned getNumElements(Type *Ty)
void visit(MachineFunction &MF, MachineBasicBlock &Start, std::function< void(MachineBasicBlock *)> op)
verify safepoint Safepoint IR Verifier
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool IsScalarTBAANodeImpl(const MDNode *MD, SmallPtrSetImpl< const MDNode * > &Visited)
static bool isType(const Metadata *MD)
static Instruction * getSuccPad(Instruction *Terminator)
static bool isMDTuple(const Metadata *MD)
static bool isNewFormatTBAATypeNode(llvm::MDNode *Type)
#define CheckDI(C,...)
We know that a debug info condition should be true, if not print an error message.
static void forEachUser(const Value *User, SmallPtrSet< const Value *, 32 > &Visited, llvm::function_ref< bool(const Value *)> Callback)
static bool isDINode(const Metadata *MD)
static bool isScope(const Metadata *MD)
static cl::opt< bool > VerifyNoAliasScopeDomination("verify-noalias-scope-decl-dom", cl::Hidden, cl::init(false), cl::desc("Ensure that llvm.experimental.noalias.scope.decl for identical " "scopes are not dominating"))
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...
static bool isConstantIntMetadataOperand(const Metadata *MD)
static bool IsRootTBAANode(const MDNode *MD)
static Value * getParentPad(Value *EHPad)
static bool hasConflictingReferenceFlags(unsigned Flags)
Detect mutually exclusive flags.
static AttrBuilder getParameterABIAttributes(LLVMContext &C, unsigned I, AttributeList Attrs)
static const char PassName[]
static LLVM_ABI bool isValidArbitraryFPFormat(StringRef Format)
Returns true if the given string is a valid arbitrary floating-point format interpretation for llvm....
bool isFiniteNonZero() const
const fltSemantics & getSemantics() const
Class for arbitrary precision integers.
bool sgt(const APInt &RHS) const
Signed greater than comparison.
bool isMinValue() const
Determine if this is the smallest unsigned value.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
int64_t getSExtValue() const
Get sign extended value.
bool isMaxValue() const
Determine if this is the largest unsigned value.
This class represents a conversion between pointers from one address space to another.
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void setPreservesAll()
Set by analyses that do not transform their input at all.
LLVM_ABI bool hasInRegAttr() const
Return true if this argument has the inreg attribute.
bool empty() const
empty - Check if the array is empty.
static bool isFPOperation(BinOp Op)
BinOp getOperation() const
static LLVM_ABI StringRef getOperationName(BinOp Op)
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM_ABI std::string getAsString(bool InAttrGrp=false) const
Functions, function parameters, and return types can have attributes to indicate how they should be t...
LLVM_ABI const ConstantRange & getValueAsConstantRange() const
Return the attribute's value as a ConstantRange.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
bool isValid() const
Return true if the attribute is any kind of attribute.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction & front() const
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
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...
This class represents a no-op cast from one type to another.
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
bool isConditional() const
Value * getCondition() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
bool hasInAllocaArgument() const
Determine if there are is an inalloca argument.
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
Attribute getParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Get the attribute of a given kind from a given arg.
iterator_range< bundle_op_iterator > bundle_op_infos()
Return the range [bundle_op_info_begin, bundle_op_info_end).
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Type * getParamElementType(unsigned ArgNo) const
Extract the elementtype type for a parameter.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
bool doesNotReturn() const
Determine if the call cannot return.
LLVM_ABI bool onlyAccessesArgMemory() const
Determine if the call can access memmory only using pointers based on its arguments.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
BasicBlock * getIndirectDest(unsigned i) const
unsigned getNumIndirectDests() const
Return the number of callbr indirect dest labels.
bool isMustTailCall() const
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
unsigned getNumHandlers() const
return the number of 'handlers' in this catchswitch instruction, except the default handler
Value * getParentPad() const
BasicBlock * getUnwindDest() const
handler_range handlers()
iteration adapter for range-for loops.
BasicBlock * getUnwindDest() const
bool isFPPredicate() const
bool isIntPredicate() const
static bool isIntPredicate(Predicate P)
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const APInt & getValue() const
Return the constant as an APInt value reference.
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Constant * getPointer() const
The pointer that is signed in this ptrauth signed pointer.
ConstantInt * getKey() const
The Key ID, an i32 constant.
Constant * getDeactivationSymbol() const
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DbgVariableFragmentInfo FragmentInfo
@ FixedPointBinary
Scale factor 2^Factor.
@ FixedPointDecimal
Scale factor 10^Factor.
@ FixedPointRational
Arbitrary rational scale factor.
DIGlobalVariable * getVariable() const
DIExpression * getExpression() const
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
DILocalScope * getScope() const
Get the local scope for this variable.
Metadata * getRawScope() const
Base class for scope-like contexts.
Subprogram description. Uses SubclassData1.
static const DIScope * getRawRetainedNodeScope(const MDNode *N)
Base class for template parameters.
Base class for variables.
Metadata * getRawType() const
Metadata * getRawScope() const
uint64_t getNumOperands() const
A parsed version of the target data layout string in and methods for querying it.
Records a position in IR for a source label (DILabel).
MDNode * getRawLabel() const
DILabel * getLabel() const
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
DebugLoc getDebugLoc() const
LLVM_ABI const BasicBlock * getParent() const
LLVM_ABI Function * getFunction()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LocationType getType() const
MDNode * getRawExpression() const
MDNode * getRawAddressExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
Metadata * getRawAssignID() const
MDNode * getRawVariable() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
bool isDbgDeclare() const
Metadata * getRawAddress() const
@ End
Marks the end of the concrete types.
@ Any
To indicate all LocationTypes in searches.
DIExpression * getAddressExpression() const
MDNode * getAsMDNode() const
Return this as a bar MDNode.
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...
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
This instruction compares its operands according to the predicate given to the constructor.
This class represents an extension of floating point types.
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
This class represents a truncation of floating point types.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this fence instruction.
Value * getParentPad() const
Convenience accessors.
FunctionPass class - This class is used to implement most global optimizations.
Type * getReturnType() const
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
DISubprogram * getSubprogram() const
Get the attached subprogram.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
bool hasPersonalityFn() const
Check whether this function has a personality function.
const Function & getFunction() const
const std::string & getGC() const
Type * getReturnType() const
Returns the type of the ret val.
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
LLVM_ABI Value * getBasePtr() const
LLVM_ABI Value * getDerivedPtr() const
void visit(const BlockT &BB)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
const Constant * getAliasee() const
LLVM_ABI const Function * getResolverFunction() const
static bool isValidLinkage(LinkageTypes L)
const Constant * getResolver() const
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
bool hasExternalLinkage() const
bool isImplicitDSOLocal() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool hasValidDeclarationLinkage() const
LinkageTypes getLinkage() const
bool hasDefaultVisibility() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
bool hasDLLExportStorageClass() const
bool isDeclarationForLinker() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
LLVM_ABI bool isInterposable() const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
unsigned getNumSuccessors() const
This instruction inserts a single (scalar) element into a VectorType value.
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
Value * getAggregateOperand()
ArrayRef< unsigned > getIndices() const
Base class for instruction visitors.
void visit(Iterator Start, Iterator End)
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
This class represents a cast from an integer to a pointer.
static LLVM_ABI bool mayLowerToFunctionCall(Intrinsic::ID IID)
Check if the intrinsic might lower into a regular function call in the course of IR transformations.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This is an important class for using LLVM in a threaded context.
@ OB_clang_arc_attachedcall
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
bool isFilter(unsigned Idx) const
Return 'true' if the clause and index Idx is a filter clause.
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
bool isResolved() const
Check if node is fully resolved.
LLVMContext & getContext() const
bool equalsStr(StringRef Str) const
LLVM_ABI StringRef getString() const
This class implements a map that also provides access to all stored values in a deterministic order.
Manage lifetime of a slot tracker for printing IR.
A Module instance is used to store all the information related to an LLVM module.
LLVM_ABI StringRef getName() const
LLVM_ABI void print(raw_ostream &ROS, bool IsForDebug=false) const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
op_range incoming_values()
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This class represents a cast from a pointer to an address (non-capturing ptrtoint).
This class represents a cast from a pointer to an integer.
Value * getValue() const
Convenience accessor.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
static constexpr size_t npos
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
empty - Check if the string is empty.
unsigned getNumElements() const
Random access to the elements.
LLVM_ABI Type * getTypeAtIndex(const Value *V) const
Given an index value into the type, return the type of the element.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Verify that the TBAA Metadatas are valid.
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
Triple - Helper class for working with autoconf configuration names.
This class represents a truncation of integer types.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
LLVM_ABI bool containsNonGlobalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a global...
bool isArrayTy() const
True if this is an instance of ArrayType.
LLVM_ABI bool containsNonLocalTargetExtType(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this type is or contains a target extension type that disallows being used as a local.
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
LLVM_ABI bool canLosslesslyBitCastTo(Type *Ty) const
Return true if this type could be converted with a lossless BitCast to type 'Ty'.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
This class represents a cast unsigned integer to floating point.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
iterator_range< user_iterator > materialized_users()
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
iterator_range< user_iterator > users()
bool materialized_use_empty() const
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Check a module for errors, and report separate error states for IR and debug info errors.
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class represents zero extension of integer types.
constexpr bool isNonZero() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
This class implements an extremely fast bulk output stream that can only output to a stream.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ FLAT_ADDRESS
Address space for flat memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
bool isFlatGlobalAddrSpace(unsigned AS)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
@ BasicBlock
Various leaf nodes.
LLVM_ABI MatchIntrinsicTypesResult matchIntrinsicSignature(FunctionType *FTy, ArrayRef< IITDescriptor > &Infos, SmallVectorImpl< Type * > &ArgTys)
Match the specified function type with the type constraints specified by the .td file.
LLVM_ABI void getIntrinsicInfoTableEntries(ID id, SmallVectorImpl< IITDescriptor > &T)
Return the IIT table descriptor for the specified intrinsic into an array of IITDescriptors.
MatchIntrinsicTypesResult
@ MatchIntrinsicTypes_NoMatchRet
@ MatchIntrinsicTypes_NoMatchArg
LLVM_ABI bool hasConstrainedFPRoundingModeOperand(ID QID)
Returns true if the intrinsic ID is for one of the "ConstrainedFloating-Point Intrinsics" that take r...
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
static const int NoAliasScopeDeclScopeArg
LLVM_ABI bool matchIntrinsicVarArg(bool isVarArg, ArrayRef< IITDescriptor > &Infos)
Verify if the intrinsic has variable arguments.
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ System
Synchronized with respect to all concurrently executing threads.
LLVM_ABI std::optional< VFInfo > tryDemangleForVFABI(StringRef MangledName, const FunctionType *FTy)
Function to construct a VFInfo out of a mangled names in the following format:
@ CE
Windows NT (Windows on ARM)
LLVM_ABI AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
initializer< Ty > init(const Ty &Val)
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
FunctionAddr VTableAddr Value
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool canInstructionHaveMMRAs(const Instruction &I)
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
testing::Matcher< const detail::ErrorHolder & > Failed()
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
gep_type_iterator gep_type_end(const User *GEP)
bool isa_and_nonnull(const Y &Val)
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
auto dyn_cast_or_null(const Y &Val)
GenericConvergenceVerifier< SSAContext > ConvergenceVerifier
LLVM_ABI void initializeVerifierLegacyPassPass(PassRegistry &)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
bool isModSet(const ModRefInfo MRI)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
generic_gep_type_iterator<> gep_type_iterator
FunctionAddr VTableAddr Count
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI unsigned getNumBranchWeights(const MDNode &ProfileData)
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
LLVM_ABI FunctionPass * createVerifierPass(bool FatalErrors=true)
FunctionAddr VTableAddr Next
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
TinyPtrVector< BasicBlock * > ColorVector
LLVM_ABI const char * LLVMLoopEstimatedTripCount
Profile-based loop metadata that should be accessed only by using llvm::getLoopEstimatedTripCount and...
DenormalMode parseDenormalFPAttribute(StringRef Str)
Returns the denormal mode to use for inputs and outputs.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI std::unique_ptr< GCStrategy > getGCStrategy(const StringRef Name)
Lookup the GCStrategy object associated with the given gc name.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool pred_empty(const BasicBlock *BB)
bool isHexDigit(char C)
Checks if character C is a hexadecimal numeric character.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
constexpr bool isCallableCC(CallingConv::ID CC)
LLVM_ABI bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
A special type used by analysis passes to provide an address that identifies that particular analysis...
static LLVM_ABI const char * SyntheticFunctionEntryCount
static LLVM_ABI const char * UnknownBranchWeightsMarker
static LLVM_ABI const char * ValueProfile
static LLVM_ABI const char * FunctionEntryCount
static LLVM_ABI const char * BranchWeights
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
void DebugInfoCheckFailed(const Twine &Message)
A debug info check failed.
VerifierSupport(raw_ostream *OS, const Module &M)
bool Broken
Track the brokenness of the module while recursively visiting.
void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A check failed (with values to print).
bool BrokenDebugInfo
Broken debug info can be "recovered" from by stripping the debug info.
bool TreatBrokenDebugInfoAsError
Whether to treat broken debug info as an error.
void CheckFailed(const Twine &Message)
A check failed, so printout out the condition and the message.
void DebugInfoCheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs)
A debug info check failed (with values to print).