98#include "llvm/IR/IntrinsicsAArch64.h"
99#include "llvm/IR/IntrinsicsARM.h"
100#include "llvm/IR/IntrinsicsNVPTX.h"
101#include "llvm/IR/IntrinsicsWebAssembly.h"
143 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
144 "scopes are not dominating"));
169 Type *LandingPadResultTy;
176 bool HasDebugInfo =
false;
219 SawFrameEscape(
false), TBAAVerifyHelper(this) {
220 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
223 bool hasBrokenDebugInfo()
const {
return BrokenDebugInfo; }
225 bool verify(
const Function &
F) {
226 llvm::TimeTraceScope timeScope(
"Verifier");
228 "An instance of this class only works with a specific module!");
238 for (
const BasicBlock &BB :
F) {
239 if (!BB.empty() && BB.back().isTerminator())
243 *OS <<
"Basic Block in function '" <<
F.getName()
244 <<
"' does not have terminator!\n";
245 BB.printAsOperand(*OS,
true, MST);
253 DT.recalculate(
const_cast<Function &
>(
F));
255 auto FailureCB = [
this](
const Twine &Message) {
256 this->CheckFailed(Message);
258 ConvergenceVerifyHelper.initialize(OS, FailureCB,
F);
263 verifySiblingFuncletUnwinds();
265 if (ConvergenceVerifyHelper.sawTokens())
266 ConvergenceVerifyHelper.verify(DT);
268 InstsInThisBlock.clear();
270 LandingPadResultTy =
nullptr;
271 SawFrameEscape =
false;
272 SiblingFuncletInfo.clear();
273 verifyNoAliasScopeDecl();
274 NoAliasScopeDecls.clear();
284 for (
const Function &
F : M)
285 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
286 DeoptimizeDeclarations.push_back(&
F);
290 verifyFrameRecoverIndices();
291 for (
const GlobalVariable &GV :
M.globals())
292 visitGlobalVariable(GV);
294 for (
const GlobalAlias &GA :
M.aliases())
295 visitGlobalAlias(GA);
297 for (
const GlobalIFunc &GI :
M.ifuncs())
298 visitGlobalIFunc(GI);
300 for (
const NamedMDNode &NMD :
M.named_metadata())
301 visitNamedMDNode(NMD);
303 for (
const StringMapEntry<Comdat> &SMEC :
M.getComdatSymbolTable())
304 visitComdat(SMEC.getValue());
308 visitModuleCommandLines();
309 visitModuleErrnoTBAA();
311 verifyCompileUnits();
313 verifyDeoptimizeCallingConvs();
314 DISubprogramAttachments.clear();
320 enum class AreDebugLocsAllowed {
No,
Yes };
324 enum class RangeLikeMetadataKind {
331 void visitGlobalValue(
const GlobalValue &GV);
332 void visitGlobalVariable(
const GlobalVariable &GV);
333 void visitGlobalAlias(
const GlobalAlias &GA);
334 void visitGlobalIFunc(
const GlobalIFunc &GI);
335 void visitAliaseeSubExpr(
const GlobalAlias &
A,
const Constant &
C);
336 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
337 const GlobalAlias &
A,
const Constant &
C);
338 void visitNamedMDNode(
const NamedMDNode &NMD);
339 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
340 void visitMetadataAsValue(
const MetadataAsValue &MD, Function *
F);
341 void visitValueAsMetadata(
const ValueAsMetadata &MD, Function *
F);
342 void visitDIArgList(
const DIArgList &AL, Function *
F);
343 void visitComdat(
const Comdat &
C);
344 void visitModuleIdents();
345 void visitModuleCommandLines();
346 void visitModuleErrnoTBAA();
347 void visitModuleFlags();
348 void visitModuleFlag(
const MDNode *
Op,
349 DenseMap<const MDString *, const MDNode *> &SeenIDs,
350 SmallVectorImpl<const MDNode *> &Requirements);
351 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
352 void visitFunction(
const Function &
F);
353 void visitBasicBlock(BasicBlock &BB);
354 void verifyRangeLikeMetadata(
const Value &V,
const MDNode *
Range,
Type *Ty,
355 RangeLikeMetadataKind Kind);
356 void visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
357 void visitNoFPClassMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
358 void visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
359 void visitDereferenceableMetadata(Instruction &
I, MDNode *MD);
360 void visitNofreeMetadata(Instruction &
I, MDNode *MD);
361 void visitProfMetadata(Instruction &
I, MDNode *MD);
362 void visitCallStackMetadata(MDNode *MD);
363 void visitMemProfMetadata(Instruction &
I, MDNode *MD);
364 void visitCallsiteMetadata(Instruction &
I, MDNode *MD);
365 void visitCalleeTypeMetadata(Instruction &
I, MDNode *MD);
366 void visitDIAssignIDMetadata(Instruction &
I, MDNode *MD);
367 void visitMMRAMetadata(Instruction &
I, MDNode *MD);
368 void visitAnnotationMetadata(MDNode *Annotation);
369 void visitAliasScopeMetadata(
const MDNode *MD);
370 void visitAliasScopeListMetadata(
const MDNode *MD);
371 void visitAccessGroupMetadata(
const MDNode *MD);
372 void visitCapturesMetadata(Instruction &
I,
const MDNode *Captures);
373 void visitAllocTokenMetadata(Instruction &
I, MDNode *MD);
374 void visitInlineHistoryMetadata(Instruction &
I, MDNode *MD);
375 void visitMemCacheHintMetadata(Instruction &
I, MDNode *MD);
377#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
378#include "llvm/IR/Metadata.def"
379 void visitDIType(
const DIType &
N);
380 void visitDIScope(
const DIScope &
N);
404 void checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V);
409 void visitPHINode(
PHINode &PN);
418 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
419 void visitCallInst(CallInst &CI);
420 void visitInvokeInst(InvokeInst &
II);
421 void visitGetElementPtrInst(GetElementPtrInst &
GEP);
422 void visitLoadInst(LoadInst &LI);
423 void visitStoreInst(StoreInst &SI);
424 void verifyDominatesUse(Instruction &
I,
unsigned i);
425 void visitInstruction(Instruction &
I);
426 void visitTerminator(Instruction &
I);
427 void visitCondBrInst(CondBrInst &BI);
428 void visitReturnInst(ReturnInst &RI);
429 void visitSwitchInst(SwitchInst &SI);
430 void visitIndirectBrInst(IndirectBrInst &BI);
431 void visitCallBrInst(CallBrInst &CBI);
432 void visitSelectInst(SelectInst &SI);
433 void visitUserOp1(Instruction &
I);
434 void visitUserOp2(Instruction &
I) { visitUserOp1(
I); }
436 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
437 void visitVPIntrinsic(VPIntrinsic &VPI);
438 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
439 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
440 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
441 void visitFenceInst(FenceInst &FI);
442 void visitAllocaInst(AllocaInst &AI);
443 void visitExtractValueInst(ExtractValueInst &EVI);
444 void visitInsertValueInst(InsertValueInst &IVI);
445 void visitEHPadPredecessors(Instruction &
I);
446 void visitLandingPadInst(LandingPadInst &LPI);
447 void visitResumeInst(ResumeInst &RI);
448 void visitCatchPadInst(CatchPadInst &CPI);
449 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
450 void visitCleanupPadInst(CleanupPadInst &CPI);
451 void visitFuncletPadInst(FuncletPadInst &FPI);
452 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
453 void visitCleanupReturnInst(CleanupReturnInst &CRI);
455 void verifySwiftErrorCall(CallBase &
Call,
const Value *SwiftErrorVal);
456 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
457 void verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs, StringRef
Context);
458 void verifyMustTailCall(CallInst &CI);
459 bool verifyAttributeCount(AttributeList Attrs,
unsigned Params);
460 void verifyAttributeTypes(AttributeSet Attrs,
const Value *V);
461 void verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
const Value *V);
462 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
464 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
465 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
466 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
467 void verifyUnknownProfileMetadata(MDNode *MD);
468 void visitConstantExprsRecursively(
const Constant *EntryC);
469 void visitConstantExpr(
const ConstantExpr *CE);
470 void visitConstantPtrAuth(
const ConstantPtrAuth *CPA);
471 void verifyInlineAsmCall(
const CallBase &
Call);
472 void verifyStatepoint(
const CallBase &
Call);
473 void verifyFrameRecoverIndices();
474 void verifySiblingFuncletUnwinds();
476 void verifyFragmentExpression(
const DbgVariableRecord &
I);
477 template <
typename ValueOrMetadata>
478 void verifyFragmentExpression(
const DIVariable &V,
480 ValueOrMetadata *
Desc);
481 void verifyFnArgs(
const DbgVariableRecord &DVR);
482 void verifyNotEntryValue(
const DbgVariableRecord &
I);
485 void verifyCompileUnits();
489 void verifyDeoptimizeCallingConvs();
491 void verifyAttachedCallBundle(
const CallBase &
Call,
492 const OperandBundleUse &BU);
495 void verifyNoAliasScopeDecl();
501#define Check(C, ...) \
504 CheckFailed(__VA_ARGS__); \
511#define CheckDI(C, ...) \
514 DebugInfoCheckFailed(__VA_ARGS__); \
522 CheckDI(
I.DebugMarker->MarkedInstr == &
I,
523 "Instruction has invalid DebugMarker", &
I);
525 "PHI Node must not have any attached DbgRecords", &
I);
527 CheckDI(DR.getMarker() ==
I.DebugMarker,
528 "DbgRecord had invalid DebugMarker", &
I, &DR);
531 visitMDNode(*
Loc, AreDebugLocsAllowed::Yes);
536 verifyFragmentExpression(*DVR);
537 verifyNotEntryValue(*DVR);
544void Verifier::visit(Instruction &
I) {
546 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
547 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
559 while (!WorkList.
empty()) {
561 if (!Visited.
insert(Cur).second)
568void Verifier::visitGlobalValue(
const GlobalValue &GV) {
570 "Global is external, but doesn't have external or weak linkage!", &GV);
573 if (
const MDNode *Associated =
574 GO->getMetadata(LLVMContext::MD_associated)) {
575 Check(Associated->getNumOperands() == 1,
576 "associated metadata must have one operand", &GV, Associated);
577 const Metadata *
Op = Associated->getOperand(0).get();
578 Check(
Op,
"associated metadata must have a global value", GO, Associated);
581 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
584 "associated value must be pointer typed", GV, Associated);
586 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
588 "associated metadata must point to a GlobalObject", GO, Stripped);
589 Check(Stripped != GO,
590 "global values should not associate to themselves", GO,
596 if (
const MDNode *AbsoluteSymbol =
597 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
598 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
599 DL.getIntPtrType(GO->getType()),
600 RangeLikeMetadataKind::AbsoluteSymbol);
603 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
604 Check(!GO->isDeclaration(),
605 "ref metadata must not be placed on a declaration", GO);
608 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
609 for (
const MDNode *MD : MDs) {
610 Check(MD->getNumOperands() == 1,
"ref metadata must have one operand",
614 Check(VM,
"ref metadata must be ValueAsMetadata", GO, MD);
617 "ref value must be pointer typed", GV, MD);
621 "ref metadata must point to a GlobalObject", GO, Stripped);
622 Check(Stripped != GO,
"values should not reference themselves", GO,
628 if (
auto *Props = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
629 Check(Props->getNumOperands() == 2,
630 "elf_section_properties metadata must have two operands", GO,
632 if (Props->getNumOperands() == 2) {
634 Check(
Type,
"type field must be ConstantAsMetadata", GO, Props);
636 Check(TypeInt,
"type field must be ConstantInt", GO, Props);
639 Check(Entsize,
"entsize field must be ConstantAsMetadata", GO, Props);
641 Check(EntsizeInt,
"entsize field must be ConstantInt", GO, Props);
647 "Only global variables can have appending linkage!", &GV);
651 Check(GVar && GVar->getValueType()->isArrayTy(),
652 "Only global arrays can have appending linkage!", GVar);
656 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
660 "dllexport GlobalValue must have default or protected visibility",
665 "dllimport GlobalValue must have default visibility", &GV);
666 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
672 "Global is marked as dllimport, but not external", &GV);
677 "GlobalValue with local linkage or non-default "
678 "visibility must be dso_local!",
683 if (!
I->getParent() || !
I->getParent()->getParent())
684 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
686 else if (
I->getParent()->getParent()->getParent() != &M)
687 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
688 I->getParent()->getParent(),
689 I->getParent()->getParent()->getParent());
692 if (
F->getParent() != &M)
693 CheckFailed(
"Global is used by function in a different module", &GV, &M,
701void Verifier::visitGlobalVariable(
const GlobalVariable &GV) {
705 Check(
A->value() <= Value::MaximumAlignment,
706 "huge alignment values are unsupported", &GV);
711 "Global variable initializer type does not match global "
715 "Global variable initializer must be sized", &GV);
721 "'common' global must have a zero initializer!", &GV);
724 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
729 GV.
getName() ==
"llvm.global_dtors")) {
731 "invalid linkage for intrinsic global variable", &GV);
733 "invalid uses of intrinsic global variable", &GV);
740 PointerType::get(
Context,
DL.getProgramAddressSpace());
741 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
742 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
743 STy->getTypeAtIndex(1) == FuncPtrTy,
744 "wrong type for intrinsic global variable", &GV);
745 Check(STy->getNumElements() == 3,
746 "the third field of the element type is mandatory, "
747 "specify ptr null to migrate from the obsoleted 2-field form");
748 Type *ETy = STy->getTypeAtIndex(2);
755 GV.
getName() ==
"llvm.compiler.used")) {
757 "invalid linkage for intrinsic global variable", &GV);
759 "invalid uses of intrinsic global variable", &GV);
763 Check(PTy,
"wrong type for intrinsic global variable", &GV);
767 Check(InitArray,
"wrong initializer for intrinsic global variable",
769 for (
Value *
Op : InitArray->operands()) {
773 Twine(
"invalid ") + GV.
getName() +
" member", V);
775 Twine(
"members of ") + GV.
getName() +
" must be named", V);
784 for (MDNode *MD : MDs) {
786 visitDIGlobalVariableExpression(*GVE);
788 CheckDI(
false,
"!dbg attachment of global variable must be a "
789 "DIGlobalVariableExpression");
799 "Global @" + GV.
getName() +
" has illegal target extension type",
808 "Global variable is too large to fit into the address space", &GV,
812 visitGlobalValue(GV);
819 visitGlobalValue(GV);
822void Verifier::visitAliaseeSubExpr(
const GlobalAlias &GA,
const Constant &
C) {
823 SmallPtrSet<const GlobalAlias*, 4> Visited;
825 visitAliaseeSubExpr(Visited, GA,
C);
828void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
829 const GlobalAlias &GA,
const Constant &
C) {
833 "available_externally alias must point to available_externally "
844 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
846 Check(!GA2->isInterposable(),
847 "Alias cannot point to an interposable alias", &GA);
856 visitConstantExprsRecursively(CE);
858 for (
const Use &U :
C.operands()) {
861 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
863 visitAliaseeSubExpr(Visited, GA, *C2);
867void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
869 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
870 "weak_odr, external, or available_externally linkage!",
873 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
875 "Alias and aliasee types should match!", &GA);
878 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
880 visitAliaseeSubExpr(GA, *Aliasee);
882 visitGlobalValue(GA);
885void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
886 visitGlobalValue(GI);
890 for (
const auto &
I : MDs) {
891 CheckDI(
I.first != LLVMContext::MD_dbg,
892 "an ifunc may not have a !dbg attachment", &GI);
893 Check(
I.first != LLVMContext::MD_prof,
894 "an ifunc may not have a !prof attachment", &GI);
895 visitMDNode(*
I.second, AreDebugLocsAllowed::No);
899 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
900 "weak_odr, or external linkage!",
905 Check(Resolver,
"IFunc must have a Function resolver", &GI);
907 "IFunc resolver must be a definition", &GI);
914 "IFunc resolver must return a pointer", &GI);
917 "IFunc resolver has incorrect type", &GI);
920void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
925 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
926 for (
const MDNode *MD : NMD.
operands()) {
927 if (NMD.
getName() ==
"llvm.dbg.cu")
933 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
937void Verifier::visitMDNode(
const MDNode &BaseMD,
938 AreDebugLocsAllowed AllowLocs) {
941 if (!MDNodes.
insert(&BaseMD).second)
944 std::queue<const MDNode *> Worklist;
945 Worklist.push(&BaseMD);
947 while (!Worklist.empty()) {
948 const MDNode *CurrentMD = Worklist.front();
951 "MDNode context does not match Module context!", CurrentMD);
956 case Metadata::MDTupleKind:
958#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
959 case Metadata::CLASS##Kind: \
960 visit##CLASS(cast<CLASS>(*CurrentMD)); \
962#include "llvm/IR/Metadata.def"
971 "DILocation not allowed within this metadata node", CurrentMD,
979 visitValueAsMetadata(*V,
nullptr);
993 "Expected second operand to be an integer constant of type i32 or "
1001 Check(CurrentMD->
isResolved(),
"All nodes should be resolved!", CurrentMD);
1005void Verifier::visitValueAsMetadata(
const ValueAsMetadata &MD, Function *
F) {
1008 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1014 Check(
F,
"function-local metadata used outside a function", L);
1020 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1027 assert(ActualF &&
"Unimplemented function local metadata case!");
1029 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1032void Verifier::visitDIArgList(
const DIArgList &AL, Function *
F) {
1033 for (
const ValueAsMetadata *VAM :
AL.getArgs())
1034 visitValueAsMetadata(*VAM,
F);
1037void Verifier::visitMetadataAsValue(
const MetadataAsValue &MDV, Function *
F) {
1040 visitMDNode(*
N, AreDebugLocsAllowed::No);
1046 if (!MDNodes.
insert(MD).second)
1050 visitValueAsMetadata(*V,
F);
1053 visitDIArgList(*AL,
F);
1061void Verifier::visitDILocation(
const DILocation &
N) {
1063 "location requires a valid scope", &
N,
N.getRawScope());
1064 if (
auto *IA =
N.getRawInlinedAt())
1067 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1070void Verifier::visitGenericDINode(
const GenericDINode &
N) {
1074void Verifier::visitDIScope(
const DIScope &
N) {
1075 if (
auto *
F =
N.getRawFile())
1079void Verifier::visitDIType(
const DIType &
N) {
1082 CheckDI(
N.getRawFile() ||
N.getLine() == 0,
"line specified with no file", &
N,
1086void Verifier::visitDISubrangeType(
const DISubrangeType &
N) {
1089 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1092 auto *LBound =
N.getRawLowerBound();
1096 "LowerBound must be signed constant or DIVariable or DIExpression or "
1099 auto *UBound =
N.getRawUpperBound();
1103 "UpperBound must be signed constant or DIVariable or DIExpression or "
1106 auto *Stride =
N.getRawStride();
1109 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1110 auto *Bias =
N.getRawBias();
1113 "Bias must be signed constant or DIVariable or DIExpression", &
N);
1115 auto *
Size =
N.getRawSizeInBits();
1117 "SizeInBits must be a constant");
1120void Verifier::visitDISubrange(
const DISubrange &
N) {
1121 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1122 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1123 "Subrange can have any one of count or upperBound", &
N);
1124 auto *CBound =
N.getRawCountNode();
1127 "Count must be signed constant or DIVariable or DIExpression", &
N);
1128 auto Count =
N.getCount();
1131 "invalid subrange count", &
N);
1132 auto *LBound =
N.getRawLowerBound();
1135 "LowerBound must be signed constant or DIVariable or DIExpression",
1137 auto *UBound =
N.getRawUpperBound();
1140 "UpperBound must be signed constant or DIVariable or DIExpression",
1142 auto *Stride =
N.getRawStride();
1145 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1148void Verifier::visitDIGenericSubrange(
const DIGenericSubrange &
N) {
1149 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1150 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1151 "GenericSubrange can have any one of count or upperBound", &
N);
1152 auto *CBound =
N.getRawCountNode();
1154 "Count must be signed constant or DIVariable or DIExpression", &
N);
1155 auto *LBound =
N.getRawLowerBound();
1156 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1158 "LowerBound must be signed constant or DIVariable or DIExpression",
1160 auto *UBound =
N.getRawUpperBound();
1162 "UpperBound must be signed constant or DIVariable or DIExpression",
1164 auto *Stride =
N.getRawStride();
1165 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1167 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1170void Verifier::visitDIEnumerator(
const DIEnumerator &
N) {
1171 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1174void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1177 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1178 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1179 N.getTag() == dwarf::DW_TAG_string_type,
1182 auto *
Size =
N.getRawSizeInBits();
1184 "SizeInBits must be a constant");
1187void Verifier::visitDIFixedPointType(
const DIFixedPointType &
N) {
1188 visitDIBasicType(
N);
1190 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type,
"invalid tag", &
N);
1191 CheckDI(
N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1192 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1193 "invalid encoding", &
N);
1197 "invalid kind", &
N);
1199 N.getFactorRaw() == 0,
1200 "factor should be 0 for rationals", &
N);
1202 (
N.getNumeratorRaw() == 0 &&
N.getDenominatorRaw() == 0),
1203 "numerator and denominator should be 0 for non-rationals", &
N);
1206void Verifier::visitDIStringType(
const DIStringType &
N) {
1209 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1210 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1214void Verifier::visitDIDerivedType(
const DIDerivedType &
N) {
1218 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1219 N.getTag() == dwarf::DW_TAG_pointer_type ||
1220 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1221 N.getTag() == dwarf::DW_TAG_reference_type ||
1222 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1223 N.getTag() == dwarf::DW_TAG_const_type ||
1224 N.getTag() == dwarf::DW_TAG_immutable_type ||
1225 N.getTag() == dwarf::DW_TAG_volatile_type ||
1226 N.getTag() == dwarf::DW_TAG_restrict_type ||
1227 N.getTag() == dwarf::DW_TAG_atomic_type ||
1228 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1229 N.getTag() == dwarf::DW_TAG_member ||
1230 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1231 N.getTag() == dwarf::DW_TAG_inheritance ||
1232 N.getTag() == dwarf::DW_TAG_friend ||
1233 N.getTag() == dwarf::DW_TAG_set_type ||
1234 N.getTag() == dwarf::DW_TAG_template_alias,
1236 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1237 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1238 N.getRawExtraData());
1239 }
else if (
N.getTag() == dwarf::DW_TAG_template_alias) {
1241 N.getRawExtraData());
1242 }
else if (
N.getTag() == dwarf::DW_TAG_inheritance ||
1243 N.getTag() == dwarf::DW_TAG_member ||
1244 N.getTag() == dwarf::DW_TAG_variable) {
1245 auto *ExtraData =
N.getRawExtraData();
1246 auto IsValidExtraData = [&]() {
1247 if (ExtraData ==
nullptr)
1253 if (Tuple->getNumOperands() != 1)
1260 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1261 "or MDTuple with single ConstantAsMetadata operand",
1265 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1266 if (
auto *
T =
N.getRawBaseType()) {
1271 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1272 (Subrange &&
Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1273 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1274 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1275 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1276 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1277 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1278 "invalid set base type", &
N,
T);
1283 N.getRawBaseType());
1285 if (
N.getDWARFAddressSpace()) {
1286 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1287 N.getTag() == dwarf::DW_TAG_reference_type ||
1288 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1289 "DWARF address space only applies to pointer or reference types",
1293 auto *
Size =
N.getRawSizeInBits();
1296 "SizeInBits must be a constant or DIVariable or DIExpression");
1301 return ((Flags & DINode::FlagLValueReference) &&
1302 (Flags & DINode::FlagRValueReference)) ||
1303 ((Flags & DINode::FlagTypePassByValue) &&
1304 (Flags & DINode::FlagTypePassByReference));
1307void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1309 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1316void Verifier::visitDICompositeType(
const DICompositeType &
N) {
1320 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1321 N.getTag() == dwarf::DW_TAG_structure_type ||
1322 N.getTag() == dwarf::DW_TAG_union_type ||
1323 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1324 N.getTag() == dwarf::DW_TAG_class_type ||
1325 N.getTag() == dwarf::DW_TAG_variant_part ||
1326 N.getTag() == dwarf::DW_TAG_variant ||
1327 N.getTag() == dwarf::DW_TAG_namelist,
1331 N.getRawBaseType());
1334 "invalid composite elements", &
N,
N.getRawElements());
1336 N.getRawVTableHolder());
1338 "invalid reference flags", &
N);
1339 unsigned DIBlockByRefStruct = 1 << 4;
1340 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1341 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1343 "DISubprogram contains null entry in `elements` field", &
N);
1346 const DINodeArray
Elements =
N.getElements();
1348 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1349 "invalid vector, expected one element of type subrange", &
N);
1352 if (
auto *Params =
N.getRawTemplateParams())
1353 visitTemplateParams(
N, *Params);
1355 if (
auto *
D =
N.getRawDiscriminator()) {
1357 "discriminator can only appear on variant part");
1360 if (
N.getRawDataLocation()) {
1361 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1362 "dataLocation can only appear in array type");
1365 if (
N.getRawAssociated()) {
1366 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1367 "associated can only appear in array type");
1370 if (
N.getRawAllocated()) {
1371 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1372 "allocated can only appear in array type");
1375 if (
N.getRawRank()) {
1376 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1377 "rank can only appear in array type");
1380 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1381 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1384 auto *
Size =
N.getRawSizeInBits();
1387 "SizeInBits must be a constant or DIVariable or DIExpression");
1390void Verifier::visitDISubroutineType(
const DISubroutineType &
N) {
1392 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1393 if (
auto *Types =
N.getRawTypeArray()) {
1395 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1396 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1400 "invalid reference flags", &
N);
1403void Verifier::visitDIFile(
const DIFile &
N) {
1404 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1405 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1407 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1408 "invalid checksum kind", &
N);
1410 switch (Checksum->Kind) {
1421 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1423 "invalid checksum", &
N);
1427void Verifier::visitDICompileUnit(
const DICompileUnit &
N) {
1428 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1429 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1435 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1439 "invalid emission kind", &
N);
1442 "invalid language dialect", &
N);
1444 if (
auto *Array =
N.getRawEnumTypes()) {
1446 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1448 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1449 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1451 "function-local enum in a DICompileUnit's enum list", &
N,
1452 N.getEnumTypes(),
Op);
1455 if (
auto *Array =
N.getRawRetainedTypes()) {
1457 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1461 "invalid retained type", &
N,
Op);
1464 if (
auto *Array =
N.getRawGlobalVariables()) {
1466 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1468 "invalid global variable ref", &
N,
Op);
1471 if (
auto *Array =
N.getRawImportedEntities()) {
1473 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1475 CheckDI(IE,
"invalid imported entity ref", &
N,
Op);
1477 "function-local imports are not allowed in a DICompileUnit's "
1478 "imported entities list",
1482 if (
auto *Array =
N.getRawMacros()) {
1491void Verifier::visitDISubprogram(
const DISubprogram &
N) {
1492 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1494 if (
auto *
F =
N.getRawFile())
1497 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1498 auto *
T =
N.getRawType();
1499 CheckDI(
T,
"DISubprogram requires a non-null type", &
N);
1501 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1502 N.getRawContainingType());
1503 if (
auto *Params =
N.getRawTemplateParams())
1504 visitTemplateParams(
N, *Params);
1505 if (
auto *S =
N.getRawDeclaration())
1507 "invalid subprogram declaration", &
N, S);
1508 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1510 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1512 DenseMap<unsigned, DILocalVariable *>
Args;
1514 CheckDI(
Op,
"nullptr in retained nodes", &
N, Node);
1516 auto True = [](
const Metadata *) {
return true; };
1517 auto False = [](
const Metadata *) {
return false; };
1518 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1519 Op, True, True, True, True, False);
1521 "invalid retained nodes, expected DILocalVariable, DILabel, "
1522 "DIImportedEntity or DIType",
1529 "invalid retained nodes, retained node is not local", &
N, Node,
1532 DISubprogram *RetainedNodeSP = RetainedNodeScope->getSubprogram();
1533 DICompileUnit *RetainedNodeUnit =
1534 RetainedNodeSP ? RetainedNodeSP->getUnit() :
nullptr;
1536 RetainedNodeSP == &
N,
1537 "invalid retained nodes, retained node does not belong to subprogram",
1538 &
N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1544 if (
unsigned ArgNum = DV->getArg()) {
1546 CheckDI(Inserted || DV == ArgI->second,
1547 "invalid retained nodes, more than one local variable with the "
1548 "same argument index",
1549 &
N,
N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1554 "invalid reference flags", &
N);
1556 auto *
Unit =
N.getRawUnit();
1557 if (
N.isDefinition()) {
1559 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1560 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1565 if (CT && CT->getRawIdentifier() &&
1566 M.getContext().isODRUniquingDebugTypes())
1568 "definition subprograms cannot be nested within DICompositeType "
1569 "when enabling ODR",
1573 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1575 "subprogram declaration must not have a declaration field");
1578 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1580 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1586 if (
N.areAllCallsDescribed())
1588 "DIFlagAllCallsDescribed must be attached to a definition");
1591void Verifier::visitDILexicalBlockBase(
const DILexicalBlockBase &
N) {
1592 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1594 "invalid local scope", &
N,
N.getRawScope());
1596 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1599void Verifier::visitDILexicalBlock(
const DILexicalBlock &
N) {
1600 visitDILexicalBlockBase(
N);
1603 "cannot have column info without line info", &
N);
1606void Verifier::visitDILexicalBlockFile(
const DILexicalBlockFile &
N) {
1607 visitDILexicalBlockBase(
N);
1610void Verifier::visitDICommonBlock(
const DICommonBlock &
N) {
1611 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1612 if (
auto *S =
N.getRawScope())
1614 if (
auto *S =
N.getRawDecl())
1618void Verifier::visitDINamespace(
const DINamespace &
N) {
1619 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1620 if (
auto *S =
N.getRawScope())
1624void Verifier::visitDIMacro(
const DIMacro &
N) {
1627 "invalid macinfo type", &
N);
1628 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1629 if (!
N.getValue().empty()) {
1630 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1634void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1636 "invalid macinfo type", &
N);
1637 if (
auto *
F =
N.getRawFile())
1640 if (
auto *Array =
N.getRawElements()) {
1642 for (
Metadata *
Op :
N.getElements()->operands()) {
1648void Verifier::visitDIModule(
const DIModule &
N) {
1649 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1650 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1653void Verifier::visitDITemplateParameter(
const DITemplateParameter &
N) {
1657void Verifier::visitDITemplateTypeParameter(
const DITemplateTypeParameter &
N) {
1658 visitDITemplateParameter(
N);
1660 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1664void Verifier::visitDITemplateValueParameter(
1665 const DITemplateValueParameter &
N) {
1666 visitDITemplateParameter(
N);
1668 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1669 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1670 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1674void Verifier::visitDIVariable(
const DIVariable &
N) {
1675 if (
auto *S =
N.getRawScope())
1677 if (
auto *
F =
N.getRawFile())
1681void Verifier::visitDIGlobalVariable(
const DIGlobalVariable &
N) {
1685 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1688 if (
N.isDefinition())
1689 CheckDI(
N.getType(),
"missing global variable type", &
N);
1690 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1692 "invalid static data member declaration", &
N, Member);
1696void Verifier::visitDILocalVariable(
const DILocalVariable &
N) {
1701 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1703 "local variable requires a valid scope", &
N,
N.getRawScope());
1704 if (
auto Ty =
N.getType())
1708void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1709 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1710 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1713void Verifier::visitDILabel(
const DILabel &
N) {
1714 if (
auto *S =
N.getRawScope())
1716 if (
auto *
F =
N.getRawFile())
1719 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1721 "label requires a valid scope", &
N,
N.getRawScope());
1724void Verifier::visitDIExpression(
const DIExpression &
N) {
1725 CheckDI(
N.isValid(),
"invalid expression", &
N);
1728void Verifier::visitDIGlobalVariableExpression(
1729 const DIGlobalVariableExpression &GVE) {
1732 visitDIGlobalVariable(*Var);
1734 visitDIExpression(*Expr);
1735 if (
auto Fragment = Expr->getFragmentInfo())
1736 verifyFragmentExpression(*GVE.
getVariable(), *Fragment, &GVE);
1740void Verifier::visitDIObjCProperty(
const DIObjCProperty &
N) {
1741 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1742 if (
auto *
T =
N.getRawType())
1744 if (
auto *
F =
N.getRawFile())
1748void Verifier::visitDIImportedEntity(
const DIImportedEntity &
N) {
1749 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1750 N.getTag() == dwarf::DW_TAG_imported_declaration,
1752 if (
auto *S =
N.getRawScope())
1758void Verifier::visitComdat(
const Comdat &
C) {
1761 if (
TT.isOSBinFormatCOFF())
1762 if (
const GlobalValue *GV =
M.getNamedValue(
C.getName()))
1767void Verifier::visitModuleIdents() {
1768 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1774 for (
const MDNode *
N : Idents->
operands()) {
1775 Check(
N->getNumOperands() == 1,
1776 "incorrect number of operands in llvm.ident metadata",
N);
1778 (
"invalid value for llvm.ident metadata entry operand"
1779 "(the operand should be a string)"),
1784void Verifier::visitModuleCommandLines() {
1785 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1792 for (
const MDNode *
N : CommandLines->
operands()) {
1793 Check(
N->getNumOperands() == 1,
1794 "incorrect number of operands in llvm.commandline metadata",
N);
1796 (
"invalid value for llvm.commandline metadata entry operand"
1797 "(the operand should be a string)"),
1802void Verifier::visitModuleErrnoTBAA() {
1803 const NamedMDNode *ErrnoTBAA =
M.getNamedMetadata(
"llvm.errno.tbaa");
1808 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1810 for (
const MDNode *
N : ErrnoTBAA->
operands())
1814void Verifier::visitModuleFlags() {
1815 const NamedMDNode *
Flags =
M.getModuleFlagsMetadata();
1819 DenseMap<const MDString*, const MDNode*> SeenIDs;
1821 uint64_t PAuthABIPlatform = -1;
1822 uint64_t PAuthABIVersion = -1;
1823 for (
const MDNode *MDN :
Flags->operands()) {
1824 visitModuleFlag(MDN, SeenIDs, Requirements);
1825 if (MDN->getNumOperands() != 3)
1828 if (FlagName->getString() ==
"aarch64-elf-pauthabi-platform") {
1829 if (
const auto *PAP =
1831 PAuthABIPlatform = PAP->getZExtValue();
1832 }
else if (FlagName->getString() ==
"aarch64-elf-pauthabi-version") {
1833 if (
const auto *PAV =
1835 PAuthABIVersion = PAV->getZExtValue();
1840 if ((PAuthABIPlatform == uint64_t(-1)) != (PAuthABIVersion == uint64_t(-1)))
1841 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
1842 "'aarch64-elf-pauthabi-version' module flags must be present");
1845 for (
const MDNode *Requirement : Requirements) {
1847 const Metadata *ReqValue = Requirement->getOperand(1);
1849 const MDNode *
Op = SeenIDs.
lookup(Flag);
1851 CheckFailed(
"invalid requirement on flag, flag is not present in module",
1856 if (
Op->getOperand(2) != ReqValue) {
1857 CheckFailed((
"invalid requirement on flag, "
1858 "flag does not have the required value"),
1866Verifier::visitModuleFlag(
const MDNode *
Op,
1867 DenseMap<const MDString *, const MDNode *> &SeenIDs,
1868 SmallVectorImpl<const MDNode *> &Requirements) {
1872 "incorrect number of operands in module flag",
Op);
1873 Module::ModFlagBehavior MFB;
1874 if (!Module::isValidModFlagBehavior(
Op->getOperand(0), MFB)) {
1876 "invalid behavior operand in module flag (expected constant integer)",
1879 "invalid behavior operand in module flag (unexpected constant)",
1883 Check(
ID,
"invalid ID operand in module flag (expected metadata string)",
1889 case Module::Warning:
1890 case Module::Override:
1896 Check(V &&
V->getValue().isNonNegative(),
1897 "invalid value for 'min' module flag (expected constant non-negative "
1905 "invalid value for 'max' module flag (expected constant integer)",
1910 case Module::Require: {
1915 "invalid value for 'require' module flag (expected metadata pair)",
1918 (
"invalid value for 'require' module flag "
1919 "(first value operand should be a string)"),
1920 Value->getOperand(0));
1928 case Module::Append:
1929 case Module::AppendUnique: {
1932 "invalid value for 'append'-type module flag "
1933 "(expected a metadata node)",
1940 if (MFB != Module::Require) {
1943 "module flag identifiers must be unique (or of 'require' type)",
ID);
1946 if (
ID->getString() ==
"wchar_size") {
1949 Check(
Value,
"wchar_size metadata requires constant integer argument");
1952 if (
ID->getString() ==
"Linker Options") {
1956 Check(
M.getNamedMetadata(
"llvm.linker.options"),
1957 "'Linker Options' named metadata no longer supported");
1960 if (
ID->getString() ==
"SemanticInterposition") {
1961 ConstantInt *
Value =
1964 "SemanticInterposition metadata requires constant integer argument");
1967 if (
ID->getString() ==
"CG Profile") {
1968 for (
const MDOperand &MDO :
cast<MDNode>(
Op->getOperand(2))->operands())
1969 visitModuleFlagCGProfileEntry(MDO);
1976void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
1977 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
1982 "expected a Function or null", FuncMDO);
1985 Check(Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
1986 CheckFunction(
Node->getOperand(0));
1987 CheckFunction(
Node->getOperand(1));
1990 "expected an integer constant",
Node->getOperand(2));
1993void Verifier::verifyAttributeTypes(AttributeSet Attrs,
const Value *V) {
1996 if (
A.isStringAttribute()) {
1997#define GET_ATTR_NAMES
1998#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
1999#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2000 if (A.getKindAsString() == #DISPLAY_NAME) { \
2001 auto V = A.getValueAsString(); \
2002 if (!(V.empty() || V == "true" || V == "false")) \
2003 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2007#include "llvm/IR/Attributes.inc"
2011 if (
A.isIntAttribute() != Attribute::isIntAttrKind(
A.getKindAsEnum())) {
2012 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
2021void Verifier::verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
2023 if (!
Attrs.hasAttributes())
2026 verifyAttributeTypes(Attrs, V);
2029 Check(Attr.isStringAttribute() ||
2030 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2031 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
2034 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
2035 unsigned AttrCount =
2036 Attrs.getNumAttributes() -
Attrs.hasAttribute(Attribute::Range);
2037 Check(AttrCount == 1,
2038 "Attribute 'immarg' is incompatible with other attributes except the "
2039 "'range' attribute",
2045 unsigned AttrCount = 0;
2046 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
2047 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
2048 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
2049 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
2050 Attrs.hasAttribute(Attribute::InReg);
2051 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
2052 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
2053 Check(AttrCount <= 1,
2054 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2055 "'byref', and 'sret' are incompatible!",
2058 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
2059 Attrs.hasAttribute(Attribute::ReadOnly)),
2061 "'inalloca and readonly' are incompatible!",
2064 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
2065 Attrs.hasAttribute(Attribute::Returned)),
2067 "'sret and returned' are incompatible!",
2070 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
2071 Attrs.hasAttribute(Attribute::SExt)),
2073 "'zeroext and signext' are incompatible!",
2076 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2077 Attrs.hasAttribute(Attribute::ReadOnly)),
2079 "'readnone and readonly' are incompatible!",
2082 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2083 Attrs.hasAttribute(Attribute::WriteOnly)),
2085 "'readnone and writeonly' are incompatible!",
2088 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
2089 Attrs.hasAttribute(Attribute::WriteOnly)),
2091 "'readonly and writeonly' are incompatible!",
2094 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2095 Attrs.hasAttribute(Attribute::AlwaysInline)),
2097 "'noinline and alwaysinline' are incompatible!",
2100 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2101 Attrs.hasAttribute(Attribute::ReadNone)),
2102 "Attributes writable and readnone are incompatible!", V);
2104 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2105 Attrs.hasAttribute(Attribute::ReadOnly)),
2106 "Attributes writable and readonly are incompatible!", V);
2108 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2110 if (!Attr.isStringAttribute() &&
2111 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2112 CheckFailed(
"Attribute '" + Attr.getAsString() +
2113 "' applied to incompatible type!", V);
2119 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2120 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2121 Check(AttrAlign.
value() <= Value::MaximumAlignment,
2122 "huge alignment values are unsupported", V);
2124 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2126 SmallPtrSet<Type *, 4> Visited;
2128 "Attribute 'byval' does not support unsized types!", V);
2132 "'byval' argument has illegal target extension type", V);
2133 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2134 "huge 'byval' arguments are unsupported", V);
2136 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2137 SmallPtrSet<Type *, 4> Visited;
2138 Check(
Attrs.getByRefType()->isSized(&Visited),
2139 "Attribute 'byref' does not support unsized types!", V);
2140 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2142 "huge 'byref' arguments are unsupported", V);
2144 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2145 SmallPtrSet<Type *, 4> Visited;
2146 Check(
Attrs.getInAllocaType()->isSized(&Visited),
2147 "Attribute 'inalloca' does not support unsized types!", V);
2148 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2150 "huge 'inalloca' arguments are unsupported", V);
2152 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2153 SmallPtrSet<Type *, 4> Visited;
2154 Check(
Attrs.getPreallocatedType()->isSized(&Visited),
2155 "Attribute 'preallocated' does not support unsized types!", V);
2157 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2159 "huge 'preallocated' arguments are unsupported", V);
2163 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2164 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2165 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2168 "Attribute 'initializes' does not support unordered ranges", V);
2171 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2172 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2173 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2176 "Invalid value for 'nofpclass' test mask", V);
2178 if (
Attrs.hasAttribute(Attribute::Range)) {
2179 const ConstantRange &CR =
2180 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2182 "Range bit width must match type bit width!", V);
2186void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2188 if (
Attrs.hasFnAttr(Attr)) {
2189 StringRef S =
Attrs.getFnAttr(Attr).getValueAsString();
2192 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
2198void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2199 const Value *V,
bool IsIntrinsic,
2201 if (
Attrs.isEmpty())
2204 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2206 "Attribute list does not match Module context!", &Attrs, V);
2207 for (
const auto &AttrSet : Attrs) {
2208 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
2209 "Attribute set does not match Module context!", &AttrSet, V);
2210 for (
const auto &
A : AttrSet) {
2212 "Attribute does not match Module context!", &
A, V);
2217 bool SawNest =
false;
2218 bool SawReturned =
false;
2219 bool SawSRet =
false;
2220 bool SawSwiftSelf =
false;
2221 bool SawSwiftAsync =
false;
2222 bool SawSwiftError =
false;
2225 AttributeSet RetAttrs =
Attrs.getRetAttrs();
2228 Attribute::canUseAsRetAttr(
RetAttr.getKindAsEnum()),
2229 "Attribute '" +
RetAttr.getAsString() +
2230 "' does not apply to function return values",
2233 unsigned MaxParameterWidth = 0;
2234 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2237 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2238 if (
Size > MaxParameterWidth)
2239 MaxParameterWidth =
Size;
2243 GetMaxParameterWidth(FT->getReturnType());
2244 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2247 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2248 Type *Ty = FT->getParamType(i);
2249 AttributeSet ArgAttrs =
Attrs.getParamAttrs(i);
2253 "immarg attribute only applies to intrinsics", V);
2256 "Attribute 'elementtype' can only be applied to intrinsics"
2261 verifyParameterAttrs(ArgAttrs, Ty, V);
2262 GetMaxParameterWidth(Ty);
2265 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2270 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2272 "Incompatible argument and return types for 'returned' attribute",
2278 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2279 Check(i == 0 || i == 1,
2280 "Attribute 'sret' is not on first or second parameter!", V);
2285 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2286 SawSwiftSelf =
true;
2290 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2291 SawSwiftAsync =
true;
2295 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2296 SawSwiftError =
true;
2300 Check(i == FT->getNumParams() - 1,
2301 "inalloca isn't on the last parameter!", V);
2305 if (!
Attrs.hasFnAttrs())
2308 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2311 Attribute::canUseAsFnAttr(
FnAttr.getKindAsEnum()),
2312 "Attribute '" +
FnAttr.getAsString() +
2313 "' does not apply to functions!",
2316 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2317 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2318 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2320 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2322 "Attribute 'optnone' requires 'noinline'!", V);
2324 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2325 "Attributes 'optsize and optnone' are incompatible!", V);
2328 "Attributes 'minsize and optnone' are incompatible!", V);
2330 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2331 "Attributes 'optdebug and optnone' are incompatible!", V);
2334 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2335 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2337 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2340 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2341 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2342 "Attributes 'optsize and optdebug' are incompatible!", V);
2345 "Attributes 'minsize and optdebug' are incompatible!", V);
2348 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2349 isModSet(
Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2350 "Attribute writable and memory without argmem: write are incompatible!",
2353 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2354 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2355 "Attributes 'aarch64_pstate_sm_enabled and "
2356 "aarch64_pstate_sm_compatible' are incompatible!",
2360 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2361 Attrs.hasFnAttr(
"aarch64_inout_za") +
2362 Attrs.hasFnAttr(
"aarch64_out_za") +
2363 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2364 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2365 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2366 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2367 "'aarch64_za_state_agnostic' are mutually exclusive",
2371 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2372 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2373 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2374 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2375 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2376 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2377 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2378 "'aarch64_za_state_agnostic' are mutually exclusive",
2381 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2384 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2387 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2388 auto CheckParam = [&](StringRef
Name,
unsigned ParamNo) {
2389 if (ParamNo >= FT->getNumParams()) {
2390 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds", V);
2394 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2395 CheckFailed(
"'allocsize' " + Name +
2396 " argument must refer to an integer parameter",
2404 if (!CheckParam(
"element size",
Args->first))
2407 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2411 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2414 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2416 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2419 "'allockind()' requires exactly one of alloc, realloc, and free");
2420 if ((
Type == AllocFnKind::Free) &&
2421 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2422 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2423 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2424 "or aligned modifiers.");
2425 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2426 if ((K & ZeroedUninit) == ZeroedUninit)
2427 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2431 StringRef S =
A.getValueAsString();
2432 Check(!S.
empty(),
"'alloc-variant-zeroed' must not be empty");
2440 "'alloc-variant-zeroed' must name a function belonging to the "
2441 "same 'alloc-family'");
2444 (
Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2445 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2446 "'alloc-variant-zeroed' must name a function with "
2447 "'allockind(\"zeroed\")'");
2450 "'alloc-variant-zeroed' must name a function with the same "
2455 "'alloc-variant-zeroed' must name a function with the same "
2456 "calling convention");
2460 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2461 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2463 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2465 CheckFailed(
"'vscale_range' minimum must be power-of-two value", V);
2466 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2467 if (VScaleMax && VScaleMin > VScaleMax)
2468 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2470 CheckFailed(
"'vscale_range' maximum must be power-of-two value", V);
2473 if (
Attribute FPAttr =
Attrs.getFnAttr(
"frame-pointer"); FPAttr.isValid()) {
2474 StringRef
FP = FPAttr.getValueAsString();
2475 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved" &&
2476 FP !=
"non-leaf-no-reserve")
2477 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2480 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2481 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2482 if (
Attrs.hasFnAttr(
"patchable-function-entry-section"))
2483 Check(!
Attrs.getFnAttr(
"patchable-function-entry-section")
2486 "\"patchable-function-entry-section\" must not be empty");
2487 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2489 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2490 StringRef S =
A.getValueAsString();
2491 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2492 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S, V);
2495 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2496 StringRef S =
A.getValueAsString();
2497 if (S !=
"a_key" && S !=
"b_key")
2498 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2500 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2502 "'sign-return-address-key' present without `sign-return-address`");
2506 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2507 StringRef S =
A.getValueAsString();
2508 if (S !=
"" && S !=
"true" && S !=
"false")
2510 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2513 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2514 StringRef S =
A.getValueAsString();
2515 if (S !=
"" && S !=
"true" && S !=
"false")
2517 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2520 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2521 StringRef S =
A.getValueAsString();
2522 if (S !=
"" && S !=
"true" && S !=
"false")
2523 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2527 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2528 StringRef S =
A.getValueAsString();
2531 CheckFailed(
"invalid name for a VFABI variant: " + S, V);
2534 if (
auto A =
Attrs.getFnAttr(
"modular-format");
A.isValid()) {
2535 StringRef S =
A.getValueAsString();
2539 "modular-format attribute requires at least 5 arguments", V);
2540 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2542 Check(!Args[1].getAsInteger(10, FormatIdx),
2543 "modular-format attribute format string index is not an integer", V);
2544 Check(FormatIdx > 0,
2545 "modular-format attribute format string index must be greater than 0",
2547 Check(FormatIdx <= UpperBound,
2548 "modular-format attribute format string index is out of bounds", V);
2549 unsigned FirstArgIdx;
2550 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2551 "modular-format attribute first arg index is not an integer", V);
2552 Check(FirstArgIdx <= UpperBound,
2553 "modular-format attribute first arg index is out of bounds", V);
2555 "modular-format attribute modular implementation function name "
2559 "modular-format attribute implementation name cannot be empty", V);
2562 if (
auto A =
Attrs.getFnAttr(
"target-features");
A.isValid()) {
2563 StringRef S =
A.getValueAsString();
2565 for (
auto FeatureFlag :
split(S,
',')) {
2566 if (FeatureFlag.empty())
2568 "target-features attribute should not contain an empty string");
2570 Check(FeatureFlag[0] ==
'+' || FeatureFlag[0] ==
'-',
2571 "target feature '" + FeatureFlag +
2572 "' must start with a '+' or '-'",
2578void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2580 "'unknown' !prof should have a single additional operand", MD);
2583 "'unknown' !prof should have an additional operand of type "
2586 "the 'unknown' !prof operand should not be an empty string");
2589void Verifier::verifyFunctionMetadata(
2590 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2591 for (
const auto &Pair : MDs) {
2592 if (Pair.first == LLVMContext::MD_prof) {
2593 MDNode *MD = Pair.second;
2595 "!prof annotations should have no less than 2 operands", MD);
2600 verifyUnknownProfileMetadata(MD);
2605 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2608 "expected string with name of the !prof annotation", MD);
2613 "first operand should be 'function_entry_count'"
2614 " or 'synthetic_function_entry_count'",
2618 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2621 "expected integer argument to function_entry_count", MD);
2622 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2623 MDNode *MD = Pair.second;
2625 "!kcfi_type must have exactly one operand", MD);
2626 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2629 "expected a constant operand for !kcfi_type", MD);
2632 "expected a constant integer operand for !kcfi_type", MD);
2634 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2635 }
else if (Pair.first ==
Context.getMDKindID(
"reqd_work_group_size")) {
2636 MDNode *MD = Pair.second;
2638 "reqd_work_group_size must have exactly three operands", MD);
2642 uint64_t Product = 1;
2643 for (
unsigned I = 0;
I != 3; ++
I) {
2645 Check(
C,
"reqd_work_group_size operands must be integer constants", MD);
2649 const APInt &
Value =
C->getValue();
2651 "reqd_work_group_size operands must fit in 64 bits", MD);
2652 if (
Value.getActiveBits() > 64)
2655 uint64_t Dim =
Value.getZExtValue();
2656 Check(Dim == 0 || Product <= std::numeric_limits<uint64_t>::max() / Dim,
2657 "reqd_work_group_size product must fit in 64 bits", MD);
2658 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
2666void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2670 if (!ConstantExprVisited.
insert(EntryC).second)
2674 Stack.push_back(EntryC);
2676 while (!
Stack.empty()) {
2681 visitConstantExpr(CE);
2684 visitConstantPtrAuth(CPA);
2689 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2695 for (
const Use &U :
C->operands()) {
2699 if (!ConstantExprVisited.
insert(OpC).second)
2701 Stack.push_back(OpC);
2706void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2707 if (
CE->getOpcode() == Instruction::BitCast)
2710 "Invalid bitcast", CE);
2711 else if (
CE->getOpcode() == Instruction::PtrToAddr)
2712 checkPtrToAddr(
CE->getOperand(0)->getType(),
CE->getType(), *CE);
2715void Verifier::visitConstantPtrAuth(
const ConstantPtrAuth *CPA) {
2717 "signed ptrauth constant base pointer must have pointer type");
2720 "signed ptrauth constant must have same type as its base pointer");
2723 "signed ptrauth constant key must be i32 constant integer");
2726 "signed ptrauth constant address discriminator must be a pointer");
2729 "signed ptrauth constant discriminator must be i64 constant integer");
2732 "signed ptrauth constant deactivation symbol must be a pointer");
2736 "signed ptrauth constant deactivation symbol must be a global value "
2740bool Verifier::verifyAttributeCount(AttributeList Attrs,
unsigned Params) {
2743 return Attrs.getNumAttrSets() <= Params + 2;
2746void Verifier::verifyInlineAsmCall(
const CallBase &
Call) {
2749 unsigned LabelNo = 0;
2750 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
2760 if (CI.isIndirect) {
2763 "Operand for indirect constraint must have pointer type", &
Call);
2766 "Operand for indirect constraint must have elementtype attribute",
2770 "Elementtype attribute can only be applied for indirect "
2779 Check(LabelNo == CallBr->getNumIndirectDests(),
2780 "Number of label constraints does not match number of callbr dests",
2783 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
2789void Verifier::verifyStatepoint(
const CallBase &
Call) {
2794 "gc.statepoint must read and write all memory to preserve "
2795 "reordering restrictions required by safepoint semantics",
2798 const int64_t NumPatchBytes =
2801 Check(NumPatchBytes >= 0,
2802 "gc.statepoint number of patchable bytes must be "
2807 Check(TargetElemType,
2808 "gc.statepoint callee argument must have elementtype attribute",
Call);
2810 Check(TargetFuncType,
2811 "gc.statepoint callee elementtype must be function type",
Call);
2814 Check(NumCallArgs >= 0,
2815 "gc.statepoint number of arguments to underlying call "
2818 const int NumParams = (int)TargetFuncType->getNumParams();
2819 if (TargetFuncType->isVarArg()) {
2820 Check(NumCallArgs >= NumParams,
2821 "gc.statepoint mismatch in number of vararg call args",
Call);
2824 Check(TargetFuncType->getReturnType()->isVoidTy(),
2825 "gc.statepoint doesn't support wrapping non-void "
2826 "vararg functions yet",
2829 Check(NumCallArgs == NumParams,
2830 "gc.statepoint mismatch in number of call args",
Call);
2832 const uint64_t
Flags
2834 Check((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0,
2835 "unknown flag used in gc.statepoint flags argument",
Call);
2840 for (
int i = 0; i < NumParams; i++) {
2841 Type *ParamType = TargetFuncType->getParamType(i);
2843 Check(ArgType == ParamType,
2844 "gc.statepoint call argument does not match wrapped "
2848 if (TargetFuncType->isVarArg()) {
2849 AttributeSet ArgAttrs =
Attrs.getParamAttrs(5 + i);
2851 "Attribute 'sret' cannot be used for vararg call arguments!",
Call);
2855 const int EndCallArgsInx = 4 + NumCallArgs;
2859 "gc.statepoint number of transition arguments "
2860 "must be constant integer",
2862 const int NumTransitionArgs =
2864 Check(NumTransitionArgs == 0,
2865 "gc.statepoint w/inline transition bundle is deprecated",
Call);
2866 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
2870 "gc.statepoint number of deoptimization arguments "
2871 "must be constant integer",
2874 Check(NumDeoptArgs == 0,
2875 "gc.statepoint w/inline deopt operands is deprecated",
Call);
2877 const int ExpectedNumArgs = 7 + NumCallArgs;
2879 "gc.statepoint too many arguments",
Call);
2886 Check(UserCall,
"illegal use of statepoint token",
Call, U);
2890 "gc.result or gc.relocate are the only value uses "
2891 "of a gc.statepoint",
2894 Check(UserCall->getArgOperand(0) == &
Call,
2895 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
2897 Check(UserCall->getArgOperand(0) == &
Call,
2898 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
2912void Verifier::verifyFrameRecoverIndices() {
2913 for (
auto &Counts : FrameEscapeInfo) {
2915 unsigned EscapedObjectCount = Counts.second.first;
2916 unsigned MaxRecoveredIndex = Counts.second.second;
2917 Check(MaxRecoveredIndex <= EscapedObjectCount,
2918 "all indices passed to llvm.localrecover must be less than the "
2919 "number of arguments passed to llvm.localescape in the parent "
2928 UnwindDest =
II->getUnwindDest();
2930 UnwindDest = CSI->getUnwindDest();
2936void Verifier::verifySiblingFuncletUnwinds() {
2937 llvm::TimeTraceScope timeScope(
"Verifier verify sibling funclet unwinds");
2938 SmallPtrSet<Instruction *, 8> Visited;
2939 SmallPtrSet<Instruction *, 8>
Active;
2940 for (
const auto &Pair : SiblingFuncletInfo) {
2942 if (Visited.
count(PredPad))
2948 if (
Active.count(SuccPad)) {
2951 SmallVector<Instruction *, 8> CycleNodes;
2954 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
2955 if (CycleTerminator != CyclePad)
2958 }
while (CyclePad != SuccPad);
2959 Check(
false,
"EH pads can't handle each other's exceptions",
2963 if (!Visited.
insert(SuccPad).second)
2967 auto TermI = SiblingFuncletInfo.find(PredPad);
2968 if (TermI == SiblingFuncletInfo.end())
2981void Verifier::visitFunction(
const Function &
F) {
2982 visitGlobalValue(
F);
2985 FunctionType *FT =
F.getFunctionType();
2986 unsigned NumArgs =
F.arg_size();
2989 "Function context does not match Module context!", &
F);
2991 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
2992 Check(FT->getNumParams() == NumArgs,
2993 "# formal arguments must match # of arguments for function type!", &
F,
2995 Check(
F.getReturnType()->isFirstClassType() ||
2996 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
2997 "Functions cannot return aggregate values!", &
F);
2999 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
3000 "Invalid struct return type!", &
F);
3002 if (MaybeAlign
A =
F.getAlign()) {
3003 Check(
A->value() <= Value::MaximumAlignment,
3004 "huge alignment values are unsupported", &
F);
3007 AttributeList
Attrs =
F.getAttributes();
3009 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3010 "Attribute after last parameter!", &
F);
3012 bool IsIntrinsic =
F.isIntrinsic();
3015 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
3021 "Attribute 'builtin' can only be applied to a callsite.", &
F);
3023 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
3024 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
3026 if (
Attrs.hasFnAttr(Attribute::Naked))
3027 for (
const Argument &Arg :
F.args())
3028 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
3033 switch (
F.getCallingConv()) {
3035 case CallingConv::C:
3037 case CallingConv::X86_INTR: {
3038 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
3039 "Calling convention parameter requires byval", &
F);
3042 case CallingConv::AMDGPU_KERNEL:
3043 case CallingConv::SPIR_KERNEL:
3044 case CallingConv::AMDGPU_CS_Chain:
3045 case CallingConv::AMDGPU_CS_ChainPreserve:
3046 Check(
F.getReturnType()->isVoidTy(),
3047 "Calling convention requires void return type", &
F);
3049 case CallingConv::AMDGPU_VS:
3050 case CallingConv::AMDGPU_HS:
3051 case CallingConv::AMDGPU_GS:
3052 case CallingConv::AMDGPU_PS:
3053 case CallingConv::AMDGPU_CS:
3054 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
3055 if (
F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3056 const unsigned StackAS =
DL.getAllocaAddrSpace();
3058 for (
const Argument &Arg :
F.args()) {
3059 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
3060 "Calling convention disallows byval", &
F);
3061 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
3062 "Calling convention disallows preallocated", &
F);
3063 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
3064 "Calling convention disallows inalloca", &
F);
3066 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
3069 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3070 "Calling convention disallows stack byref", &
F);
3078 case CallingConv::Fast:
3079 case CallingConv::Cold:
3080 case CallingConv::Intel_OCL_BI:
3081 case CallingConv::PTX_Kernel:
3082 case CallingConv::PTX_Device:
3084 "Calling convention does not support varargs or "
3085 "perfect forwarding!",
3088 case CallingConv::AMDGPU_Gfx_WholeWave:
3089 Check(!
F.arg_empty() &&
F.arg_begin()->getType()->isIntegerTy(1),
3090 "Calling convention requires first argument to be i1", &
F);
3091 Check(!
F.arg_begin()->hasInRegAttr(),
3092 "Calling convention requires first argument to not be inreg", &
F);
3094 "Calling convention does not support varargs or "
3095 "perfect forwarding!",
3102 for (
const Argument &Arg :
F.args()) {
3103 Check(Arg.getType() == FT->getParamType(i),
3104 "Argument value does not match function argument type!", &Arg,
3105 FT->getParamType(i));
3106 Check(Arg.getType()->isFirstClassType(),
3107 "Function arguments must have first-class types!", &Arg);
3109 Check(!Arg.getType()->isMetadataTy(),
3110 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
3111 Check(!Arg.getType()->isTokenLikeTy(),
3112 "Function takes token but isn't an intrinsic", &Arg, &
F);
3113 Check(!Arg.getType()->isX86_AMXTy(),
3114 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
3118 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3119 verifySwiftErrorValue(&Arg);
3125 Check(!
F.getReturnType()->isTokenLikeTy(),
3126 "Function returns a token but isn't an intrinsic", &
F);
3127 Check(!
F.getReturnType()->isX86_AMXTy(),
3128 "Function returns a x86_amx but isn't an intrinsic", &
F);
3133 F.getAllMetadata(MDs);
3134 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
3135 verifyFunctionMetadata(MDs);
3141 if (
F.hasPersonalityFn()) {
3144 Check(Per->getParent() ==
F.getParent(),
3145 "Referencing personality function in another module!", &
F,
3146 F.getParent(), Per, Per->getParent());
3150 BlockEHFuncletColors.
clear();
3152 if (
F.isMaterializable()) {
3154 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
3156 }
else if (
F.isDeclaration()) {
3157 for (
const auto &
I : MDs) {
3159 CheckDI(
I.first != LLVMContext::MD_dbg ||
3161 "function declaration may only have a unique !dbg attachment",
3163 Check(
I.first != LLVMContext::MD_prof,
3164 "function declaration may not have a !prof attachment", &
F);
3167 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
3169 Check(!
F.hasPersonalityFn(),
3170 "Function declaration shouldn't have a personality routine", &
F);
3174 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
3179 "Entry block to function must not have predecessors!", Entry);
3182 if (
Entry->hasAddressTaken()) {
3184 "blockaddress may not be used with the entry block!", Entry);
3187 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3188 NumKCFIAttachments = 0;
3190 for (
const auto &
I : MDs) {
3192 auto AllowLocs = AreDebugLocsAllowed::No;
3196 case LLVMContext::MD_dbg: {
3197 ++NumDebugAttachments;
3198 CheckDI(NumDebugAttachments == 1,
3199 "function must have a single !dbg attachment", &
F,
I.second);
3201 "function !dbg attachment must be a subprogram", &
F,
I.second);
3203 "function definition may only have a distinct !dbg attachment",
3207 const Function *&AttachedTo = DISubprogramAttachments[
SP];
3208 CheckDI(!AttachedTo || AttachedTo == &
F,
3209 "DISubprogram attached to more than one function", SP, &
F);
3211 AllowLocs = AreDebugLocsAllowed::Yes;
3214 case LLVMContext::MD_prof:
3215 ++NumProfAttachments;
3216 Check(NumProfAttachments == 1,
3217 "function must have a single !prof attachment", &
F,
I.second);
3219 case LLVMContext::MD_kcfi_type:
3220 ++NumKCFIAttachments;
3221 Check(NumKCFIAttachments == 1,
3222 "function must have a single !kcfi_type attachment", &
F,
3228 visitMDNode(*
I.second, AllowLocs);
3236 bool isMaterialized =
F.getParent()->isMaterialized();
3237 if (
F.isIntrinsic() && isMaterialized) {
3239 if (
F.hasAddressTaken(&U,
false,
true,
false,
3241 Check(
false,
"Invalid user of intrinsic instruction!", U);
3248 if (IID && (isMaterialized || !
F.materialized_use_empty())) {
3252 raw_string_ostream ErrOS(ErrMsg);
3255 Printable PrintDecl([&
F](raw_ostream &OS) {
F.print(OS); });
3256 Check(IsValid, ErrMsg, PrintDecl);
3263 IID, OverloadTys,
const_cast<Module *
>(
F.getParent()), FT);
3264 Check(ExpectedName ==
F.getName(),
3265 "Intrinsic name not mangled correctly for type arguments! "
3271 auto *
N =
F.getSubprogram();
3272 HasDebugInfo = (
N !=
nullptr);
3280 SmallPtrSet<const MDNode *, 32> Seen;
3292 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3294 DILocalScope *
Scope =
DL->getInlinedAtScope();
3295 Check(Scope,
"Failed to find DILocalScope",
DL);
3297 if (!Seen.
insert(Scope).second)
3300 DISubprogram *
SP =
Scope->getSubprogram();
3304 if ((Scope != SP) && !Seen.
insert(SP).second)
3308 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3312 for (
auto &
I : BB) {
3313 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3315 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3318 if (BrokenDebugInfo)
3325void Verifier::visitBasicBlock(BasicBlock &BB) {
3326 InstsInThisBlock.
clear();
3327 ConvergenceVerifyHelper.
visit(BB);
3338 for (
const PHINode &PN : BB.
phis()) {
3339 Check(PN.getNumIncomingValues() == Preds.size(),
3340 "PHINode should have one entry for each predecessor of its "
3341 "parent basic block!",
3346 Values.reserve(PN.getNumIncomingValues());
3347 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3349 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3352 for (
unsigned i = 0, e =
Values.size(); i != e; ++i) {
3359 "PHI node has multiple entries for the same basic block with "
3360 "different incoming values!",
3366 "PHI node entries do not match predecessors!", &PN,
3367 Values[i].first, Preds[i]);
3375 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3379 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3383void Verifier::visitTerminator(Instruction &
I) {
3385 Check(&
I ==
I.getParent()->getTerminator(),
3386 "Terminator found in the middle of a basic block!",
I.getParent());
3387 visitInstruction(
I);
3390void Verifier::visitCondBrInst(CondBrInst &BI) {
3392 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3393 visitTerminator(BI);
3396void Verifier::visitReturnInst(ReturnInst &RI) {
3399 if (
F->getReturnType()->isVoidTy())
3401 "Found return instr that returns non-void in Function of void "
3403 &RI,
F->getReturnType());
3406 "Function return type does not match operand "
3407 "type of return inst!",
3408 &RI,
F->getReturnType());
3412 visitTerminator(RI);
3415void Verifier::visitSwitchInst(SwitchInst &SI) {
3416 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3419 Type *SwitchTy =
SI.getCondition()->getType();
3420 SmallPtrSet<ConstantInt*, 32>
Constants;
3421 for (
auto &Case :
SI.cases()) {
3423 "Case value is not a constant integer.", &SI);
3424 Check(Case.getCaseValue()->getType() == SwitchTy,
3425 "Switch constants must all be same type as switch value!", &SI);
3427 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3430 visitTerminator(SI);
3433void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3435 "Indirectbr operand must have pointer type!", &BI);
3438 "Indirectbr destinations must all have pointer type!", &BI);
3440 visitTerminator(BI);
3449void Verifier::visitCallBrInst(CallBrInst &CBI) {
3452 "callbr: indirect function / invalid signature");
3454 "callbr for intrinsics currently doesn't support operand bundles");
3458 "callbr currently only supports asm-goto and selected intrinsics");
3463 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3465 verifyInlineAsmCall(CBI);
3467 visitTerminator(CBI);
3470void Verifier::visitSelectInst(SelectInst &SI) {
3473 "Invalid operands for select instruction!", &SI);
3475 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3476 "Select values must have same type as select instruction!", &SI);
3477 visitInstruction(SI);
3483void Verifier::visitUserOp1(Instruction &
I) {
3484 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3487void Verifier::visitTruncInst(TruncInst &
I) {
3489 Type *SrcTy =
I.getOperand(0)->getType();
3490 Type *DestTy =
I.getType();
3499 "trunc source and destination must both be a vector or neither", &
I);
3500 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3502 visitInstruction(
I);
3505void Verifier::visitZExtInst(ZExtInst &
I) {
3507 Type *SrcTy =
I.getOperand(0)->getType();
3508 Type *DestTy =
I.getType();
3514 "zext source and destination must both be a vector or neither", &
I);
3518 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3520 visitInstruction(
I);
3523void Verifier::visitSExtInst(SExtInst &
I) {
3525 Type *SrcTy =
I.getOperand(0)->getType();
3526 Type *DestTy =
I.getType();
3535 "sext source and destination must both be a vector or neither", &
I);
3536 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3538 visitInstruction(
I);
3541void Verifier::visitFPTruncInst(FPTruncInst &
I) {
3543 Type *SrcTy =
I.getOperand(0)->getType();
3544 Type *DestTy =
I.getType();
3552 "fptrunc source and destination must both be a vector or neither", &
I);
3553 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3555 visitInstruction(
I);
3558void Verifier::visitFPExtInst(FPExtInst &
I) {
3560 Type *SrcTy =
I.getOperand(0)->getType();
3561 Type *DestTy =
I.getType();
3570 "fpext source and destination must both be a vector or neither", &
I);
3571 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3573 visitInstruction(
I);
3576void Verifier::visitUIToFPInst(UIToFPInst &
I) {
3578 Type *SrcTy =
I.getOperand(0)->getType();
3579 Type *DestTy =
I.getType();
3584 Check(SrcVec == DstVec,
3585 "UIToFP source and dest must both be vector or scalar", &
I);
3587 "UIToFP source must be integer or integer vector", &
I);
3591 if (SrcVec && DstVec)
3594 "UIToFP source and dest vector length mismatch", &
I);
3596 visitInstruction(
I);
3599void Verifier::visitSIToFPInst(SIToFPInst &
I) {
3601 Type *SrcTy =
I.getOperand(0)->getType();
3602 Type *DestTy =
I.getType();
3607 Check(SrcVec == DstVec,
3608 "SIToFP source and dest must both be vector or scalar", &
I);
3610 "SIToFP source must be integer or integer vector", &
I);
3614 if (SrcVec && DstVec)
3617 "SIToFP source and dest vector length mismatch", &
I);
3619 visitInstruction(
I);
3622void Verifier::visitFPToUIInst(FPToUIInst &
I) {
3624 Type *SrcTy =
I.getOperand(0)->getType();
3625 Type *DestTy =
I.getType();
3630 Check(SrcVec == DstVec,
3631 "FPToUI source and dest must both be vector or scalar", &
I);
3634 "FPToUI result must be integer or integer vector", &
I);
3636 if (SrcVec && DstVec)
3639 "FPToUI source and dest vector length mismatch", &
I);
3641 visitInstruction(
I);
3644void Verifier::visitFPToSIInst(FPToSIInst &
I) {
3646 Type *SrcTy =
I.getOperand(0)->getType();
3647 Type *DestTy =
I.getType();
3652 Check(SrcVec == DstVec,
3653 "FPToSI source and dest must both be vector or scalar", &
I);
3656 "FPToSI result must be integer or integer vector", &
I);
3658 if (SrcVec && DstVec)
3661 "FPToSI source and dest vector length mismatch", &
I);
3663 visitInstruction(
I);
3666void Verifier::checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V) {
3675 Check(VSrc->getElementCount() == VDest->getElementCount(),
3676 "PtrToAddr vector length mismatch", V);
3679 Type *AddrTy =
DL.getAddressType(SrcTy);
3680 Check(AddrTy == DestTy,
"PtrToAddr result must be address width", V);
3683void Verifier::visitPtrToAddrInst(PtrToAddrInst &
I) {
3684 checkPtrToAddr(
I.getOperand(0)->getType(),
I.getType(),
I);
3685 visitInstruction(
I);
3688void Verifier::visitPtrToIntInst(PtrToIntInst &
I) {
3690 Type *SrcTy =
I.getOperand(0)->getType();
3691 Type *DestTy =
I.getType();
3702 Check(VSrc->getElementCount() == VDest->getElementCount(),
3703 "PtrToInt Vector length mismatch", &
I);
3706 visitInstruction(
I);
3709void Verifier::visitIntToPtrInst(IntToPtrInst &
I) {
3711 Type *SrcTy =
I.getOperand(0)->getType();
3712 Type *DestTy =
I.getType();
3722 Check(VSrc->getElementCount() == VDest->getElementCount(),
3723 "IntToPtr Vector length mismatch", &
I);
3725 visitInstruction(
I);
3728void Verifier::visitBitCastInst(BitCastInst &
I) {
3731 "Invalid bitcast", &
I);
3732 visitInstruction(
I);
3735void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
3736 Type *SrcTy =
I.getOperand(0)->getType();
3737 Type *DestTy =
I.getType();
3744 "AddrSpaceCast must be between different address spaces", &
I);
3746 Check(SrcVTy->getElementCount() ==
3748 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3749 visitInstruction(
I);
3754void Verifier::visitPHINode(PHINode &PN) {
3761 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
3770 "PHI node operands are not the same type as the result!", &PN);
3775 visitInstruction(PN);
3778void Verifier::visitCallBase(CallBase &
Call) {
3780 "Called function must be a pointer!",
Call);
3784 if (FTy->isVarArg())
3786 "Called function requires more parameters than were provided!",
Call);
3789 "Incorrect number of arguments passed to called function!",
Call);
3792 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3794 "Call parameter type does not match function signature!",
3800 "Attribute after last parameter!",
Call);
3807 "Intrinsic called with incompatible signature",
Call);
3811 "calling convention does not permit calls",
Call);
3817 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
3820 Align ABIAlign =
DL.getABITypeAlign(Ty);
3821 Check(ABIAlign.
value() <= Value::MaximumAlignment,
3822 "Incorrect alignment of " + Message +
" to called function!",
Call);
3826 VerifyTypeAlign(FTy->getReturnType(),
"return type");
3827 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3828 Type *Ty = FTy->getParamType(i);
3829 VerifyTypeAlign(Ty,
"argument passed");
3833 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
3837 "speculatable attribute may not apply to call sites",
Call);
3840 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
3842 "preallocated as a call site attribute can only be on "
3843 "llvm.call.preallocated.arg");
3846 Check(!
Attrs.hasFnAttr(Attribute::DenormalFPEnv),
3847 "denormal_fpenv attribute may not apply to call sites",
Call);
3858 Check(AI->isUsedWithInAlloca(),
3859 "inalloca argument for call has mismatched alloca", AI,
Call);
3865 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3869 Check(AI->isSwiftError(),
3870 "swifterror argument for call has mismatched alloca", AI,
Call);
3874 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
3875 SwiftErrorArg,
Call);
3876 Check(ArgI->hasSwiftErrorAttr(),
3877 "swifterror argument for call has mismatched parameter", ArgI,
3881 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
3884 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
3893 "immarg operand has non-immediate parameter", ArgVal,
Call);
3899 const ConstantRange &CR =
3902 formatv(
"immarg value {} for arg {} out of range {}",
3903 CI->getValue(), i, CR),
3914 Check(hasOB != isMustTail,
3915 "preallocated operand either requires a preallocated bundle or "
3916 "the call to be musttail (but not both)",
3921 if (FTy->isVarArg()) {
3923 bool SawNest =
false;
3924 bool SawReturned =
false;
3926 for (
unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
3927 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
3929 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
3934 for (
unsigned Idx = FTy->getNumParams(); Idx <
Call.
arg_size(); ++Idx) {
3936 AttributeSet ArgAttrs =
Attrs.getParamAttrs(Idx);
3937 verifyParameterAttrs(ArgAttrs, Ty, &
Call);
3940 Check(!SawNest,
"More than one parameter has attribute nest!",
Call);
3945 Check(!SawReturned,
"More than one parameter has attribute returned!",
3948 "Incompatible argument and return types for 'returned' "
3958 "Attribute 'sret' cannot be used for vararg call arguments!",
3963 "inalloca isn't on the last argument!",
Call);
3969 for (
Type *ParamTy : FTy->params()) {
3970 Check(!ParamTy->isMetadataTy(),
3971 "Function has metadata parameter but isn't an intrinsic",
Call);
3972 Check(!ParamTy->isTokenLikeTy(),
3973 "Function has token parameter but isn't an intrinsic",
Call);
3979 Check(!FTy->getReturnType()->isTokenLikeTy(),
3980 "Return type cannot be token for indirect call!");
3981 Check(!FTy->getReturnType()->isX86_AMXTy(),
3982 "Return type cannot be x86_amx for indirect call!");
3986 visitIntrinsicCall(
ID,
Call);
3991 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
3992 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
3993 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
3994 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
3995 FoundAttachedCallBundle =
false;
4000 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles",
Call);
4001 FoundDeoptBundle =
true;
4003 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
4005 FoundGCTransitionBundle =
true;
4007 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles",
Call);
4008 FoundFuncletBundle =
true;
4010 "Expected exactly one funclet bundle operand",
Call);
4012 "Funclet bundle operands should correspond to a FuncletPadInst",
4015 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
4017 FoundCFGuardTargetBundle =
true;
4019 "Expected exactly one cfguardtarget bundle operand",
Call);
4021 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles",
Call);
4022 FoundPtrauthBundle =
true;
4024 "Expected exactly two ptrauth bundle operands",
Call);
4026 BU.
Inputs[0]->getType()->isIntegerTy(32),
4027 "Ptrauth bundle key operand must be an i32 constant",
Call);
4029 "Ptrauth bundle discriminator operand must be an i64",
Call);
4031 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles",
Call);
4032 FoundKCFIBundle =
true;
4033 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
4036 BU.
Inputs[0]->getType()->isIntegerTy(32),
4037 "Kcfi bundle operand must be an i32 constant",
Call);
4039 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
4041 FoundPreallocatedBundle =
true;
4043 "Expected exactly one preallocated bundle operand",
Call);
4046 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4047 "\"preallocated\" argument must be a token from "
4048 "llvm.call.preallocated.setup",
4051 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles",
Call);
4052 FoundGCLiveBundle =
true;
4054 Check(!FoundAttachedCallBundle,
4055 "Multiple \"clang.arc.attachedcall\" operand bundles",
Call);
4056 FoundAttachedCallBundle =
true;
4057 verifyAttachedCallBundle(
Call, BU);
4063 "Direct call cannot have a ptrauth bundle",
Call);
4075 "inlinable function call in a function with "
4076 "debug info must have a !dbg location",
4080 verifyInlineAsmCall(
Call);
4084 visitInstruction(
Call);
4087void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
4090 Twine(
"inalloca attribute not allowed in ") +
Context);
4092 Twine(
"inreg attribute not allowed in ") +
Context);
4093 Check(!
Attrs.contains(Attribute::SwiftError),
4094 Twine(
"swifterror attribute not allowed in ") +
Context);
4095 Check(!
Attrs.contains(Attribute::Preallocated),
4096 Twine(
"preallocated attribute not allowed in ") +
Context);
4098 Twine(
"byref attribute not allowed in ") +
Context);
4103 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4104 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4105 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4107 AttrBuilder Copy(
C);
4108 for (
auto AK : ABIAttrs) {
4109 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
4111 Copy.addAttribute(Attr);
4115 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
4116 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
4117 Attrs.hasParamAttr(
I, Attribute::ByRef)))
4118 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
4122void Verifier::verifyMustTailCall(CallInst &CI) {
4126 FunctionType *CallerTy =
F->getFunctionType();
4128 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4129 "cannot guarantee tail call due to mismatched varargs", &CI);
4130 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4131 "cannot guarantee tail call due to mismatched return types", &CI);
4135 "cannot guarantee tail call due to mismatched calling conv", &CI);
4143 Check(Ret,
"musttail call must precede a ret", &CI);
4146 "musttail call result must be returned", Ret);
4148 AttributeList CallerAttrs =
F->getAttributes();
4153 CI.
getCallingConv() == CallingConv::Tail ?
"tailcc" :
"swifttailcc";
4157 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4159 SmallString<32>
Context{CCName, StringRef(
" musttail caller")};
4160 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4162 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
4164 SmallString<32>
Context{CCName, StringRef(
" musttail callee")};
4165 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4168 Check(!CallerTy->isVarArg(), Twine(
"cannot guarantee ") + CCName +
4169 " tail call for varargs function");
4175 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4176 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4177 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4178 Check(CallerTy->getParamType(
I) == CalleeTy->getParamType(
I),
4179 "cannot guarantee tail call due to mismatched parameter types",
4186 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4189 Check(CallerABIAttrs == CalleeABIAttrs,
4190 "cannot guarantee tail call due to mismatched ABI impacting "
4191 "function attributes",
4196void Verifier::visitCallInst(CallInst &CI) {
4200 verifyMustTailCall(CI);
4203void Verifier::visitInvokeInst(InvokeInst &
II) {
4209 II.getUnwindDest()->isEHPad(),
4210 "The unwind destination does not have an exception handling instruction!",
4213 visitTerminator(
II);
4218void Verifier::visitUnaryOperator(UnaryOperator &U) {
4219 Check(
U.getType() ==
U.getOperand(0)->getType(),
4220 "Unary operators must have same type for"
4221 "operands and result!",
4224 switch (
U.getOpcode()) {
4227 case Instruction::FNeg:
4228 Check(
U.getType()->isFPOrFPVectorTy(),
4229 "FNeg operator only works with float types!", &U);
4235 visitInstruction(U);
4241void Verifier::visitBinaryOperator(BinaryOperator &
B) {
4242 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
4243 "Both operands to a binary operator are not of the same type!", &
B);
4245 switch (
B.getOpcode()) {
4248 case Instruction::Add:
4249 case Instruction::Sub:
4250 case Instruction::Mul:
4251 case Instruction::SDiv:
4252 case Instruction::UDiv:
4253 case Instruction::SRem:
4254 case Instruction::URem:
4255 Check(
B.getType()->isIntOrIntVectorTy(),
4256 "Integer arithmetic operators only work with integral types!", &
B);
4257 Check(
B.getType() ==
B.getOperand(0)->getType(),
4258 "Integer arithmetic operators must have same type "
4259 "for operands and result!",
4264 case Instruction::FAdd:
4265 case Instruction::FSub:
4266 case Instruction::FMul:
4267 case Instruction::FDiv:
4268 case Instruction::FRem:
4269 Check(
B.getType()->isFPOrFPVectorTy(),
4270 "Floating-point arithmetic operators only work with "
4271 "floating-point types!",
4273 Check(
B.getType() ==
B.getOperand(0)->getType(),
4274 "Floating-point arithmetic operators must have same type "
4275 "for operands and result!",
4279 case Instruction::And:
4280 case Instruction::Or:
4281 case Instruction::Xor:
4282 Check(
B.getType()->isIntOrIntVectorTy(),
4283 "Logical operators only work with integral types!", &
B);
4284 Check(
B.getType() ==
B.getOperand(0)->getType(),
4285 "Logical operators must have same type for operands and result!", &
B);
4287 case Instruction::Shl:
4288 case Instruction::LShr:
4289 case Instruction::AShr:
4290 Check(
B.getType()->isIntOrIntVectorTy(),
4291 "Shifts only work with integral types!", &
B);
4292 Check(
B.getType() ==
B.getOperand(0)->getType(),
4293 "Shift return type must be same as operands!", &
B);
4299 visitInstruction(
B);
4302void Verifier::visitICmpInst(ICmpInst &IC) {
4306 Check(Op0Ty == Op1Ty,
4307 "Both operands to ICmp instruction are not of the same type!", &IC);
4310 "Invalid operand types for ICmp instruction", &IC);
4314 visitInstruction(IC);
4317void Verifier::visitFCmpInst(FCmpInst &FC) {
4319 Type *Op0Ty =
FC.getOperand(0)->getType();
4320 Type *Op1Ty =
FC.getOperand(1)->getType();
4321 Check(Op0Ty == Op1Ty,
4322 "Both operands to FCmp instruction are not of the same type!", &FC);
4327 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
4329 visitInstruction(FC);
4332void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4334 "Invalid extractelement operands!", &EI);
4335 visitInstruction(EI);
4338void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4341 "Invalid insertelement operands!", &IE);
4342 visitInstruction(IE);
4345void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4348 "Invalid shufflevector operands!", &SV);
4349 visitInstruction(SV);
4352void Verifier::visitGetElementPtrInst(GetElementPtrInst &
GEP) {
4354 GEP.getModule()->getModuleFlag(
"require-logical-pointer")))
4355 Check(!MD->getZExtValue(),
4356 "Non-logical getelementptr disallowed for this module.");
4358 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4361 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4362 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4365 Check(!STy->isScalableTy(),
4366 "getelementptr cannot target structure that contains scalable vector"
4371 SmallVector<Value *, 16> Idxs(
GEP.indices());
4373 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
4374 "GEP indexes must be integers", &
GEP);
4377 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4381 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4382 "GEP is not of right type for indices!", &
GEP, ElTy);
4386 ElementCount GEPWidth = GEPVTy->getElementCount();
4387 if (
GEP.getPointerOperandType()->isVectorTy())
4391 "Vector GEP result width doesn't match operand's", &
GEP);
4392 for (
Value *Idx : Idxs) {
4393 Type *IndexTy = Idx->getType();
4395 ElementCount IndexWidth = IndexVTy->getElementCount();
4396 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4399 "All GEP indices should be of integer type");
4406 GTI != GTE; ++GTI) {
4407 if (GTI.isVector()) {
4408 Type *ElemTy = GTI.getIndexedType();
4409 Check(
DL.typeSizeEqualsStoreSize(ElemTy),
4410 "GEP into vector with non-byte-addressable element type", &
GEP);
4414 Check(
GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4415 "GEP address space doesn't match type", &
GEP);
4417 visitInstruction(
GEP);
4421 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4426void Verifier::verifyRangeLikeMetadata(
const Value &
I,
const MDNode *
Range,
4427 Type *Ty, RangeLikeMetadataKind Kind) {
4428 unsigned NumOperands =
Range->getNumOperands();
4429 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4430 unsigned NumRanges = NumOperands / 2;
4431 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4433 ConstantRange LastRange(1,
true);
4434 for (
unsigned i = 0; i < NumRanges; ++i) {
4437 Check(
Low,
"The lower limit must be an integer!",
Low);
4442 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4445 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4447 "noalias.addrspace type must be i32!", &
I);
4450 "Range types must match instruction type!", &
I);
4453 APInt HighV =
High->getValue();
4454 APInt LowV =
Low->getValue();
4459 "The upper and lower limits cannot be the same value", &
I);
4461 ConstantRange CurRange(LowV, HighV);
4462 Check(!CurRange.isEmptySet() &&
4463 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4464 !CurRange.isFullSet()),
4465 "Range must not be empty!",
Range);
4467 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4468 "Intervals are overlapping",
Range);
4469 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
4474 LastRange = ConstantRange(LowV, HighV);
4476 if (NumRanges > 2) {
4481 ConstantRange FirstRange(FirstLow, FirstHigh);
4482 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4483 "Intervals are overlapping",
Range);
4489void Verifier::visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty) {
4491 "precondition violation");
4492 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
4495void Verifier::visitNoFPClassMetadata(Instruction &
I, MDNode *NoFPClass,
4497 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4498 "nofpclass only applies to floating-point typed loads",
I);
4501 "nofpclass must have exactly one entry", NoFPClass);
4502 ConstantInt *MaskVal =
4505 "nofpclass entry must be a constant i32", NoFPClass);
4507 Check(Val != 0,
"'nofpclass' must have at least one test bit set", NoFPClass,
4511 "Invalid value for 'nofpclass' test mask", NoFPClass,
I);
4514void Verifier::visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
4517 "precondition violation");
4518 verifyRangeLikeMetadata(
I,
Range, Ty,
4519 RangeLikeMetadataKind::NoaliasAddrspace);
4522void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I) {
4523 unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
4524 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
4526 "atomic memory access' operand must have a power-of-two size", Ty,
I);
4529void Verifier::visitLoadInst(LoadInst &LI) {
4531 Check(PTy,
"Load operand must be a pointer.", &LI);
4534 Check(
A->value() <= Value::MaximumAlignment,
4535 "huge alignment values are unsupported", &LI);
4537 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4540 LI.
getOrdering() != AtomicOrdering::AcquireRelease,
4541 "Load cannot have Release ordering", &LI);
4545 "atomic load operand must have integer, byte, pointer, floating "
4546 "point, or vector type!",
4549 checkAtomicMemAccessSize(ElTy, &LI);
4552 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4555 visitInstruction(LI);
4558void Verifier::visitStoreInst(StoreInst &SI) {
4560 Check(PTy,
"Store operand must be a pointer.", &SI);
4561 Type *ElTy =
SI.getOperand(0)->getType();
4562 if (MaybeAlign
A =
SI.getAlign()) {
4563 Check(
A->value() <= Value::MaximumAlignment,
4564 "huge alignment values are unsupported", &SI);
4566 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4567 if (
SI.isAtomic()) {
4568 Check(
SI.getOrdering() != AtomicOrdering::Acquire &&
4569 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4570 "Store cannot have Acquire ordering", &SI);
4574 "atomic store operand must have integer, byte, pointer, floating "
4575 "point, or vector type!",
4577 checkAtomicMemAccessSize(ElTy, &SI);
4580 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4582 visitInstruction(SI);
4586void Verifier::verifySwiftErrorCall(CallBase &
Call,
4587 const Value *SwiftErrorVal) {
4589 if (
I.value() == SwiftErrorVal) {
4591 "swifterror value when used in a callsite should be marked "
4592 "with swifterror attribute",
4593 SwiftErrorVal,
Call);
4598void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4601 for (
const User *U : SwiftErrorVal->
users()) {
4604 "swifterror value can only be loaded and stored from, or "
4605 "as a swifterror argument!",
4609 Check(StoreI->getOperand(1) == SwiftErrorVal,
4610 "swifterror value should be the second operand when used "
4614 verifySwiftErrorCall(*
const_cast<CallBase *
>(
Call), SwiftErrorVal);
4618void Verifier::visitAllocaInst(AllocaInst &AI) {
4621 Check(!MD->getZExtValue(),
4622 "Non-logical alloca disallowed for this module.");
4625 SmallPtrSet<Type*, 4> Visited;
4626 Check(Ty->
isSized(&Visited),
"Cannot allocate unsized type", &AI);
4630 "Alloca has illegal target extension type", &AI);
4632 "Alloca array size must have integer type", &AI);
4634 Check(
A->value() <= Value::MaximumAlignment,
4635 "huge alignment values are unsupported", &AI);
4641 "swifterror alloca must not be array allocation", &AI);
4642 verifySwiftErrorValue(&AI);
4645 visitInstruction(AI);
4651void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4654 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4655 checkAtomicMemAccessSize(ElTy, &CXI);
4656 visitInstruction(CXI);
4659void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4661 "atomicrmw instructions cannot be unordered.", &RMWI);
4664 Type *ScalarTy = ElTy;
4667 Check(VecTy,
"atomicrmw elementwise operand must have fixed vector type!",
4670 ScalarTy = VecTy->getElementType();
4677 " operand must have integer or floating point type!",
4682 " operand must have floating-point or fixed vector of "
4689 " operand must have integer type!",
4692 checkAtomicMemAccessSize(ElTy, &RMWI);
4694 "Invalid binary operation!", &RMWI);
4695 visitInstruction(RMWI);
4698void Verifier::visitFenceInst(FenceInst &FI) {
4700 Check(Ordering == AtomicOrdering::Acquire ||
4701 Ordering == AtomicOrdering::Release ||
4702 Ordering == AtomicOrdering::AcquireRelease ||
4703 Ordering == AtomicOrdering::SequentiallyConsistent,
4704 "fence instructions may only have acquire, release, acq_rel, or "
4705 "seq_cst ordering.",
4707 visitInstruction(FI);
4710void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
4713 "Invalid ExtractValueInst operands!", &EVI);
4715 visitInstruction(EVI);
4718void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
4722 "Invalid InsertValueInst operands!", &IVI);
4724 visitInstruction(IVI);
4729 return FPI->getParentPad();
4734void Verifier::visitEHPadPredecessors(Instruction &
I) {
4740 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
4748 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4749 "Block containing LandingPadInst must be jumped to "
4750 "only by the unwind edge of an invoke.",
4758 "Block containg CatchPadInst must be jumped to "
4759 "only by its catchswitch.",
4761 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
4762 "Catchswitch cannot unwind to one of its catchpads",
4763 CPI->getCatchSwitch(), CPI);
4775 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
4776 "EH pad must be jumped to via an unwind edge", ToPad,
II);
4779 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
4783 FromPad = Bundle->Inputs[0];
4787 FromPad = CRI->getOperand(0);
4788 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
4792 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
4796 SmallPtrSet<Value *, 8> Seen;
4798 Check(FromPad != ToPad,
4799 "EH pad cannot handle exceptions raised within it", FromPad, TI);
4800 if (FromPad == ToPadParent) {
4805 "A single unwind edge may only enter one EH pad", TI);
4806 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
4812 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
4817void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
4821 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
4823 visitEHPadPredecessors(LPI);
4825 if (!LandingPadResultTy)
4826 LandingPadResultTy = LPI.
getType();
4829 "The landingpad instruction should have a consistent result type "
4830 "inside a function.",
4834 Check(
F->hasPersonalityFn(),
4835 "LandingPadInst needs to be in a function with a personality.", &LPI);
4840 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
4846 "Catch operand does not have pointer type!", &LPI);
4848 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
4850 "Filter operand is not an array of constants!", &LPI);
4854 visitInstruction(LPI);
4857void Verifier::visitResumeInst(ResumeInst &RI) {
4859 "ResumeInst needs to be in a function with a personality.", &RI);
4861 if (!LandingPadResultTy)
4865 "The resume instruction should have a consistent result type "
4866 "inside a function.",
4869 visitTerminator(RI);
4872void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
4876 Check(
F->hasPersonalityFn(),
4877 "CatchPadInst needs to be in a function with a personality.", &CPI);
4880 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
4886 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
4891 return isa<Constant>(V) || isa<AllocaInst>(V);
4893 "Argument operand must be alloca or constant.", &CPI);
4895 visitEHPadPredecessors(CPI);
4896 visitFuncletPadInst(CPI);
4899void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
4901 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
4904 visitTerminator(CatchReturn);
4907void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
4911 Check(
F->hasPersonalityFn(),
4912 "CleanupPadInst needs to be in a function with a personality.", &CPI);
4917 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
4921 "CleanupPadInst has an invalid parent.", &CPI);
4923 visitEHPadPredecessors(CPI);
4924 visitFuncletPadInst(CPI);
4927void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
4928 User *FirstUser =
nullptr;
4929 Value *FirstUnwindPad =
nullptr;
4931 SmallPtrSet<FuncletPadInst *, 8> Seen;
4933 while (!Worklist.empty()) {
4934 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
4936 "FuncletPadInst must not be nested within itself", CurrentPad);
4937 Value *UnresolvedAncestorPad =
nullptr;
4938 for (User *U : CurrentPad->
users()) {
4941 UnwindDest = CRI->getUnwindDest();
4947 if (CSI->unwindsToCaller())
4949 UnwindDest = CSI->getUnwindDest();
4951 UnwindDest =
II->getUnwindDest();
4961 Worklist.push_back(CPI);
4976 if (UnwindParent == CurrentPad)
4982 Value *ExitedPad = CurrentPad;
4985 if (ExitedPad == &FPI) {
4990 UnresolvedAncestorPad = &FPI;
4994 if (ExitedParent == UnwindParent) {
4998 UnresolvedAncestorPad = ExitedParent;
5001 ExitedPad = ExitedParent;
5007 UnresolvedAncestorPad = &FPI;
5014 Check(UnwindPad == FirstUnwindPad,
5015 "Unwind edges out of a funclet "
5016 "pad must have the same unwind "
5018 &FPI, U, FirstUser);
5021 FirstUnwindPad = UnwindPad;
5030 if (CurrentPad != &FPI)
5033 if (UnresolvedAncestorPad) {
5034 if (CurrentPad == UnresolvedAncestorPad) {
5038 assert(CurrentPad == &FPI);
5046 Value *ResolvedPad = CurrentPad;
5047 while (!Worklist.empty()) {
5048 Value *UnclePad = Worklist.back();
5052 while (ResolvedPad != AncestorPad) {
5054 if (ResolvedParent == UnresolvedAncestorPad) {
5057 ResolvedPad = ResolvedParent;
5061 if (ResolvedPad != AncestorPad)
5064 Worklist.pop_back();
5069 if (FirstUnwindPad) {
5071 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5072 Value *SwitchUnwindPad;
5073 if (SwitchUnwindDest)
5077 Check(SwitchUnwindPad == FirstUnwindPad,
5078 "Unwind edges out of a catch must have the same unwind dest as "
5079 "the parent catchswitch",
5080 &FPI, FirstUser, CatchSwitch);
5084 visitInstruction(FPI);
5087void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5091 Check(
F->hasPersonalityFn(),
5092 "CatchSwitchInst needs to be in a function with a personality.",
5098 "CatchSwitchInst not the first non-PHI instruction in the block.",
5103 "CatchSwitchInst has an invalid parent.", ParentPad);
5108 "CatchSwitchInst must unwind to an EH block which is not a "
5114 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5118 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5120 for (BasicBlock *Handler : CatchSwitch.
handlers()) {
5122 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5125 visitEHPadPredecessors(CatchSwitch);
5126 visitTerminator(CatchSwitch);
5129void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5131 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5137 "CleanupReturnInst must unwind to an EH block which is not a "
5142 visitTerminator(CRI);
5145void Verifier::verifyDominatesUse(Instruction &
I,
unsigned i) {
5151 if (
II->getNormalDest() ==
II->getUnwindDest())
5165 const Use &
U =
I.getOperandUse(i);
5166 Check(DT.dominates(
Op, U),
"Instruction does not dominate all uses!",
Op, &
I);
5169void Verifier::visitDereferenceableMetadata(Instruction&
I, MDNode* MD) {
5170 Check(
I.getType()->isPointerTy(),
5171 "dereferenceable, dereferenceable_or_null "
5172 "apply only to pointer types",
5175 "dereferenceable, dereferenceable_or_null apply only to load"
5176 " and inttoptr instructions, use attributes for calls or invokes",
5179 "dereferenceable, dereferenceable_or_null "
5180 "take one operand!",
5185 "dereferenceable_or_null metadata value must be an i64!",
5189void Verifier::visitNofreeMetadata(Instruction &
I, MDNode *MD) {
5190 Check(
I.getType()->isPointerTy(),
"nofree applies only to pointer types", &
I);
5196void Verifier::visitProfMetadata(Instruction &
I, MDNode *MD) {
5197 auto GetBranchingTerminatorNumOperands = [&]() {
5198 unsigned ExpectedNumOperands = 0;
5202 ExpectedNumOperands =
SI->getNumSuccessors();
5204 ExpectedNumOperands = 1;
5206 ExpectedNumOperands = IBI->getNumDestinations();
5208 ExpectedNumOperands = 2;
5211 return ExpectedNumOperands;
5214 "!prof annotations should have at least 1 operand", MD);
5216 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
5218 "expected string with name of the !prof annotation", MD);
5224 "'unknown' !prof should only appear on instructions on which "
5225 "'branch_weights' would",
5227 verifyUnknownProfileMetadata(MD);
5232 "!prof annotations should have no less than 2 operands", MD);
5238 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5239 "Wrong number of InvokeInst branch_weights operands", MD);
5241 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5242 if (ExpectedNumOperands == 0)
5243 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
5246 Check(NumBranchWeights == ExpectedNumOperands,
"Wrong number of operands",
5252 Check(MDO,
"second operand should not be null", MD);
5254 "!prof brunch_weights operand is not a const int");
5259 Check(KindInt,
"VP !prof missing kind argument", MD);
5262 Check(Kind >= InstrProfValueKind::IPVK_First &&
5263 Kind <= InstrProfValueKind::IPVK_Last,
5264 "Invalid VP !prof kind", MD);
5266 "VP !prof should have an even number "
5267 "of arguments after 'VP'",
5269 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5270 Kind == InstrProfValueKind::IPVK_MemOPSize)
5272 "VP !prof indirect call or memop size expected to be applied to "
5273 "CallBase instructions only",
5276 DenseSet<uint64_t> ProfileValues;
5278 ConstantInt *ProfileValue =
5280 Check(ProfileValue,
"VP !prof value operand is not a const int", MD);
5281 uint64_t ProfileValueInt = ProfileValue->
getZExtValue();
5282 auto [ValueIt,
Inserted] = ProfileValues.
insert(ProfileValueInt);
5283 Check(Inserted,
"VP !prof should not have duplicate profile values", MD);
5286 CheckFailed(
"expected either branch_weights or VP profile name", MD);
5290void Verifier::visitDIAssignIDMetadata(Instruction &
I, MDNode *MD) {
5291 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
5296 bool ExpectedInstTy =
5298 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
5303 for (
auto *User : AsValue->users()) {
5305 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5309 CheckDI(DAI->getFunction() ==
I.getFunction(),
5310 "dbg.assign not in same function as inst", DAI, &
I);
5313 for (DbgVariableRecord *DVR :
5316 "!DIAssignID should only be used by Assign DVRs.", MD, DVR);
5317 CheckDI(DVR->getFunction() ==
I.getFunction(),
5318 "DVRAssign not in same function as inst", DVR, &
I);
5322void Verifier::visitMMRAMetadata(Instruction &
I, MDNode *MD) {
5324 "!mmra metadata attached to unexpected instruction kind",
I, MD);
5335 for (
const MDOperand &MDOp : MD->
operands())
5337 "!mmra metadata tuple operand is not an MMRA tag",
I, MDOp.get());
5340void Verifier::visitCallStackMetadata(MDNode *MD) {
5344 "call stack metadata should have at least 1 operand", MD);
5348 "call stack metadata operand should be constant integer",
Op);
5351void Verifier::visitMemProfMetadata(Instruction &
I, MDNode *MD) {
5354 Check(
I.hasMetadata(LLVMContext::MD_callsite),
5355 "!memprof metadata requires !callsite metadata", &
I, MD);
5357 "!memprof annotations should have at least 1 metadata operand "
5362 for (
auto &MIBOp : MD->
operands()) {
5367 Check(MIB->getNumOperands() >= 2,
5368 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5371 Check(MIB->getOperand(0) !=
nullptr,
5372 "!memprof MemInfoBlock first operand should not be null", MIB);
5374 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5376 visitCallStackMetadata(StackMD);
5380 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5383 for (
unsigned I = 2;
I < MIB->getNumOperands(); ++
I) {
5385 Check(OpNode,
"Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5387 Check(OpNode->getNumOperands() == 2,
5388 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5393 [](
const MDOperand &
Op) {
5394 return mdconst::hasa<ConstantInt>(Op);
5396 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5397 "ConstantInt operands",
5403void Verifier::visitCallsiteMetadata(Instruction &
I, MDNode *MD) {
5407 visitCallStackMetadata(MD);
5410void Verifier::visitCalleeTypeMetadata(Instruction &
I, MDNode *MD) {
5415 "The callee_type metadata must be a list of callgraph metadata nodes",
5418 Check(CallgraphMD->getNumOperands() == 1,
5419 "Well-formed generalized callgraph metadata must contain exactly one "
5423 "The operand of callgraph metadata for functions must be an MDString",
5427 .ends_with(
".generalized"),
5428 "Only generalized callgraph metadata can be part of the callee_type "
5434void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5437 "annotation must have at least one operand");
5439 bool TupleOfStrings =
5445 "operands must be a string or a tuple of strings");
5449void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
5454 "first scope operand must be self-referential or string", MD);
5457 "third scope operand must be string (if used)", MD);
5460 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
5462 unsigned NumDomainOps =
Domain->getNumOperands();
5463 Check(NumDomainOps >= 1 && NumDomainOps <= 2,
5464 "domain must have one or two operands",
Domain);
5467 "first domain operand must be self-referential or string",
Domain);
5468 if (NumDomainOps == 2)
5470 "second domain operand must be string (if used)",
Domain);
5473void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
5476 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
5477 visitAliasScopeMetadata(OpMD);
5481void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
5482 auto IsValidAccessScope = [](
const MDNode *MD) {
5487 if (IsValidAccessScope(MD))
5493 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
5494 Check(IsValidAccessScope(OpMD),
5495 "Access scope list contains invalid access scope", MD);
5499void Verifier::visitCapturesMetadata(Instruction &
I,
const MDNode *Captures) {
5500 static const char *ValidArgs[] = {
"address_is_null",
"address",
5501 "read_provenance",
"provenance"};
5504 Check(SI,
"!captures metadata can only be applied to store instructions", &
I);
5505 Check(
SI->getValueOperand()->getType()->isPointerTy(),
5506 "!captures metadata can only be applied to store with value operand of "
5514 Check(Str,
"!captures metadata must be a list of strings", &
I);
5516 "invalid entry in !captures metadata", &
I, Str);
5520void Verifier::visitAllocTokenMetadata(Instruction &
I, MDNode *MD) {
5525 "expected integer constant", MD);
5528void Verifier::visitInlineHistoryMetadata(Instruction &
I, MDNode *MD) {
5537 ->stripPointerCastsAndAliases()),
5538 "!inline_history operands must be functions or null", MD);
5542void Verifier::visitMemCacheHintMetadata(Instruction &
I, MDNode *MD) {
5543 Check(
I.mayReadOrWriteMemory(),
5544 "!mem.cache_hint is only valid on memory operations", &
I);
5547 "!mem.cache_hint must have even number of operands "
5548 "(operand_no, hint_node pairs)",
5554 "!mem.cache_hint is not supported on non-intrinsic calls", &
I);
5556 unsigned NumOperands = CB ? CB->arg_size() :
I.getNumOperands();
5558 SmallDenseSet<unsigned, 4> SeenOperandNos;
5559 std::optional<uint64_t> LastOperandNo;
5565 "!mem.cache_hint must alternate between i32 operand numbers and "
5566 "metadata hint nodes",
5569 Check(OpNoCI->getValue().isNonNegative(),
5570 "!mem.cache_hint operand number must be non-negative", MD);
5572 uint64_t OperandNo = OpNoCI->getZExtValue();
5573 Check(OperandNo < NumOperands,
5574 "!mem.cache_hint operand number is out of range", &
I);
5577 CB ? CB->getArgOperand(OperandNo) :
I.getOperand(OperandNo);
5579 "!mem.cache_hint operand number must refer to a pointer operand", &
I);
5582 Check(Inserted,
"!mem.cache_hint contains duplicate operand number", MD);
5584 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
5585 "!mem.cache_hint operand numbers must be in increasing order", MD);
5586 LastOperandNo = OperandNo;
5590 "!mem.cache_hint must alternate between i32 operand numbers and "
5591 "metadata hint nodes",
5595 "!mem.cache_hint hint node must have even number of operands "
5596 "(key-value pairs)",
5599 StringSet<> SeenKeys;
5600 for (
unsigned K = 0;
K + 1 <
Node->getNumOperands();
K += 2) {
5602 Check(
Key,
"!mem.cache_hint key must be a string", Node);
5604 StringRef KeyStr =
Key->getString();
5606 "!mem.cache_hint hint node contains duplicate key", Node);
5611 "!mem.cache_hint value must be a string or integer", Node);
5618void Verifier::visitInstruction(Instruction &
I) {
5620 Check(BB,
"Instruction not embedded in basic block!", &
I);
5623 for (User *U :
I.users()) {
5624 Check(U != (User *)&
I || !DT.isReachableFromEntry(BB),
5625 "Only PHI nodes may reference their own value!", &
I);
5630 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
5631 "Instruction has a name, but provides a void value!", &
I);
5635 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
5636 "Instruction returns a non-scalar type!", &
I);
5641 "Invalid use of metadata!", &
I);
5646 for (Use &U :
I.uses()) {
5649 "Instruction referencing"
5650 " instruction not embedded in a basic block!",
5653 CheckFailed(
"Use of instruction is not an instruction!", U);
5662 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i) {
5663 Check(
I.getOperand(i) !=
nullptr,
"Instruction has null operand!", &
I);
5667 if (!
I.getOperand(i)->getType()->isFirstClassType()) {
5668 Check(
false,
"Instruction operands must be first-class values!", &
I);
5674 auto IsAttachedCallOperand = [](
Function *
F,
const CallBase *CBI,
5676 return CBI && CBI->isOperandBundleOfType(
5684 Check((!
F->isIntrinsic() ||
5685 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i)) ||
5686 IsAttachedCallOperand(
F, CBI, i)),
5687 "Cannot take the address of an intrinsic!", &
I);
5689 F->getIntrinsicID() == Intrinsic::donothing ||
5690 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5691 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5692 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5693 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5694 F->getIntrinsicID() == Intrinsic::coro_resume ||
5695 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5696 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5697 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5698 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5699 F->getIntrinsicID() ==
5700 Intrinsic::experimental_patchpoint_void ||
5701 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5702 F->getIntrinsicID() == Intrinsic::fake_use ||
5703 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5704 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5705 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5706 IsAttachedCallOperand(
F, CBI, i),
5707 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5708 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5711 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
5712 &M,
F,
F->getParent());
5715 "Referring to a basic block in another function!", &
I);
5718 "Referring to an argument in another function!", &
I);
5720 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
5724 "Referring to an instruction in another function!", &
I);
5725 verifyDominatesUse(
I, i);
5727 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i),
5728 "Cannot take the address of an inline asm!", &
I);
5730 visitConstantExprsRecursively(
C);
5734 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_fpmath)) {
5736 "fpmath requires a floating point result!", &
I);
5738 if (ConstantFP *CFP0 =
5740 const APFloat &Accuracy = CFP0->getValueAPF();
5742 "fpmath accuracy must have float type", &
I);
5744 "fpmath accuracy not a positive number!", &
I);
5746 Check(
false,
"invalid fpmath accuracy!", &
I);
5750 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_range)) {
5752 "Ranges are only for loads, calls and invokes!", &
I);
5753 visitRangeMetadata(
I,
Range,
I.getType());
5756 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofpclass)) {
5758 visitNoFPClassMetadata(
I, MD,
I.getType());
5761 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
5764 "noalias.addrspace are only for memory operations!", &
I);
5765 visitNoaliasAddrspaceMetadata(
I,
Range,
I.getType());
5768 if (
I.hasMetadata(LLVMContext::MD_invariant_group)) {
5770 "invariant.group metadata is only for loads and stores", &
I);
5773 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nonnull)) {
5774 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
5777 "nonnull applies only to load instructions, use attributes"
5778 " for calls or invokes",
5783 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noundef)) {
5788 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable))
5789 visitDereferenceableMetadata(
I, MD);
5791 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
5792 visitDereferenceableMetadata(
I, MD);
5794 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofree))
5795 visitNofreeMetadata(
I, MD);
5797 if (MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa))
5800 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noalias))
5801 visitAliasScopeListMetadata(MD);
5802 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alias_scope))
5803 visitAliasScopeListMetadata(MD);
5805 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_access_group))
5806 visitAccessGroupMetadata(MD);
5808 if (MDNode *AlignMD =
I.getMetadata(LLVMContext::MD_align)) {
5809 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
5812 "align applies only to load instructions, "
5813 "use attributes for calls or invokes",
5815 Check(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
5818 "align metadata value must be an i64!", &
I);
5822 Check(Align <= Value::MaximumAlignment,
5823 "alignment is larger that implementation defined limit", &
I);
5826 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_prof))
5827 visitProfMetadata(
I, MD);
5829 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_memprof))
5830 visitMemProfMetadata(
I, MD);
5832 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callsite))
5833 visitCallsiteMetadata(
I, MD);
5835 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callee_type))
5836 visitCalleeTypeMetadata(
I, MD);
5838 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_DIAssignID))
5839 visitDIAssignIDMetadata(
I, MD);
5841 if (MDNode *MMRA =
I.getMetadata(LLVMContext::MD_mmra))
5842 visitMMRAMetadata(
I, MMRA);
5844 if (MDNode *Annotation =
I.getMetadata(LLVMContext::MD_annotation))
5845 visitAnnotationMetadata(Annotation);
5847 if (MDNode *Captures =
I.getMetadata(LLVMContext::MD_captures))
5848 visitCapturesMetadata(
I, Captures);
5850 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alloc_token))
5851 visitAllocTokenMetadata(
I, MD);
5853 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_inline_history))
5854 visitInlineHistoryMetadata(
I, MD);
5856 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_mem_cache_hint))
5857 visitMemCacheHintMetadata(
I, MD);
5859 if (MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
5861 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
5864 if (
DL->getAtomGroup()) {
5865 CheckDI(
DL->getScope()->getSubprogram()->getKeyInstructionsEnabled(),
5866 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
5867 "Instructions enabled",
5868 DL,
DL->getScope()->getSubprogram());
5874 I.getAllMetadata(MDs);
5875 for (
auto Attachment : MDs) {
5876 unsigned Kind = Attachment.first;
5878 (
Kind == LLVMContext::MD_dbg ||
Kind == LLVMContext::MD_loop)
5879 ? AreDebugLocsAllowed::Yes
5880 : AreDebugLocsAllowed::
No;
5881 visitMDNode(*Attachment.second, AllowLocs);
5898 "const x86_amx is not allowed in argument!");
5904 case Intrinsic::assume: {
5908 "assume with operand bundles must have i1 true condition",
Call);
5914 auto GetTypeAt = [&](
unsigned Index) {
5915 return OBU.Inputs[
Index]->getType();
5920 CheckFailed(
"tags must be valid attribute names",
Call);
5922 case BundleAttr::Align:
5923 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
5924 "alignment assumptions should have 2 or 3 arguments",
Call);
5927 Check(GetTypeAt(1)->isIntegerTy() &&
5928 GetTypeAt(1)->getIntegerBitWidth() <= 64,
5929 "second argument should be an integer with a maximum width of 64 "
5932 Check(OBU.Inputs.size() < 3 ||
5933 GetTypeAt(2)->isIntegerTy() &&
5934 GetTypeAt(2)->getIntegerBitWidth() <= 64,
5935 "third argument should be an integer with a maximum width of 64 "
5939 case BundleAttr::Cold:
5940 Check(OBU.Inputs.size() == 0,
5941 "cold assumptions should have no arguments",
Call);
5943 case BundleAttr::Dereferenceable:
5944 case BundleAttr::DereferenceableOrNull:
5945 Check(OBU.Inputs.size() == 2,
5946 "dereferenceable assumptions should have 2 arguments",
Call);
5949 Check(GetTypeAt(1)->isIntegerTy() &&
5950 GetTypeAt(1)->getIntegerBitWidth() <= 64,
5951 "second argument should be an integer with a maximum width of 64 "
5955 case BundleAttr::Ignore:
5957 case BundleAttr::NonNull:
5958 Check(OBU.Inputs.size() == 1,
5959 "nonnull assumptions should have 1 argument",
Call);
5963 case BundleAttr::NoUndef:
5964 Check(OBU.Inputs.size() == 1,
5965 "noundef assumptions should have 1 argument",
Call);
5967 case BundleAttr::SeparateStorage:
5968 Check(OBU.Inputs.size() == 2,
5969 "separate_storage assumptions should have 2 arguments",
Call);
5971 "arguments to separate_storage assumptions should be pointers",
5978 case Intrinsic::ucmp:
5979 case Intrinsic::scmp: {
5984 "result type must be at least 2 bits wide",
Call);
5986 bool IsDestTypeVector = DestTy->
isVectorTy();
5988 "ucmp/scmp argument and result types must both be either vector or "
5991 if (IsDestTypeVector) {
5994 Check(SrcVecLen == DestVecLen,
5995 "return type and arguments must have the same number of "
6001 case Intrinsic::coro_begin:
6002 case Intrinsic::coro_begin_custom_abi:
6004 "id argument of llvm.coro.begin must refer to coro.id");
6006 case Intrinsic::coro_id: {
6008 "align argument only accepts constants");
6011 "promise argument must refer to an alloca");
6016 "coro argument must refer to a function");
6020 if (BeforeCoroSplit)
6023 Check(!BeforeCoroEarly,
"cannot run CoroSplit before CoroEarly");
6026 "info argument of llvm.coro.id must refer to an initialized "
6030 "info argument of llvm.coro.id must refer to either a struct or "
6034 case Intrinsic::is_fpclass: {
6037 "unsupported bits for llvm.is.fpclass test mask");
6040 case Intrinsic::fptrunc_round: {
6045 MD = MAV->getMetadata();
6047 Check(MD !=
nullptr,
"missing rounding mode argument",
Call);
6050 (
"invalid value for llvm.fptrunc.round metadata operand"
6051 " (the operand should be a string)"),
6054 std::optional<RoundingMode> RoundMode =
6056 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6057 "unsupported rounding mode argument",
Call);
6060 case Intrinsic::convert_to_arbitrary_fp: {
6068 "if floating-point operand is a vector, integer operand must also "
6071 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6072 "floating-point and integer vector operands must have the same "
6079 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6081 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6082 StringRef Interp = InterpStr->getString();
6084 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6089 "unsupported interpretation metadata string",
Call);
6093 Check(RoundingMAV,
"missing rounding mode metadata operand",
Call);
6095 Check(RoundingStr,
"rounding mode metadata operand must be a string",
Call);
6097 std::optional<RoundingMode>
RM =
6099 Check(RM && *RM != RoundingMode::Dynamic,
6100 "unsupported rounding mode argument",
Call);
6103 case Intrinsic::convert_from_arbitrary_fp: {
6111 "if floating-point operand is a vector, integer operand must also "
6114 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6115 "floating-point and integer vector operands must have the same "
6122 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6124 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6125 StringRef Interp = InterpStr->getString();
6127 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6132 "unsupported interpretation metadata string",
Call);
6135#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6136#include "llvm/IR/VPIntrinsics.def"
6137#undef BEGIN_REGISTER_VP_INTRINSIC
6140#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6141 case Intrinsic::INTRINSIC:
6142#include "llvm/IR/ConstrainedOps.def"
6146 case Intrinsic::dbg_declare:
6147 case Intrinsic::dbg_value:
6148 case Intrinsic::dbg_assign:
6149 case Intrinsic::dbg_label:
6156 case Intrinsic::memcpy:
6157 case Intrinsic::memcpy_inline:
6158 case Intrinsic::memmove:
6159 case Intrinsic::memset:
6160 case Intrinsic::memset_inline:
6162 case Intrinsic::experimental_memset_pattern: {
6164 Check(Memset->getValue()->getType()->isSized(),
6165 "unsized types cannot be used as memset patterns",
Call);
6168 case Intrinsic::memcpy_element_unordered_atomic:
6169 case Intrinsic::memmove_element_unordered_atomic:
6170 case Intrinsic::memset_element_unordered_atomic: {
6173 ConstantInt *ElementSizeCI =
6175 const APInt &ElementSizeVal = ElementSizeCI->
getValue();
6177 "element size of the element-wise atomic memory intrinsic "
6178 "must be a power of 2",
6181 auto IsValidAlignment = [&](MaybeAlign Alignment) {
6182 return Alignment && ElementSizeVal.
ule(Alignment->value());
6184 Check(IsValidAlignment(AMI->getDestAlign()),
6185 "incorrect alignment of the destination argument",
Call);
6187 Check(IsValidAlignment(AMT->getSourceAlign()),
6188 "incorrect alignment of the source argument",
Call);
6192 case Intrinsic::call_preallocated_setup: {
6194 bool FoundCall =
false;
6197 Check(UseCall !=
nullptr,
6198 "Uses of llvm.call.preallocated.setup must be calls");
6200 if (IID == Intrinsic::call_preallocated_arg) {
6202 Check(AllocArgIndex !=
nullptr,
6203 "llvm.call.preallocated.alloc arg index must be a constant");
6204 auto AllocArgIndexInt = AllocArgIndex->getValue();
6205 Check(AllocArgIndexInt.sge(0) &&
6206 AllocArgIndexInt.slt(NumArgs->getValue()),
6207 "llvm.call.preallocated.alloc arg index must be between 0 and "
6209 "llvm.call.preallocated.setup's argument count");
6210 }
else if (IID == Intrinsic::call_preallocated_teardown) {
6213 Check(!FoundCall,
"Can have at most one call corresponding to a "
6214 "llvm.call.preallocated.setup");
6216 size_t NumPreallocatedArgs = 0;
6217 for (
unsigned i = 0; i < UseCall->arg_size(); i++) {
6218 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6219 ++NumPreallocatedArgs;
6222 Check(NumPreallocatedArgs != 0,
6223 "cannot use preallocated intrinsics on a call without "
6224 "preallocated arguments");
6225 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6226 "llvm.call.preallocated.setup arg size must be equal to number "
6227 "of preallocated arguments "
6237 auto PreallocatedBundle =
6239 Check(PreallocatedBundle,
6240 "Use of llvm.call.preallocated.setup outside intrinsics "
6241 "must be in \"preallocated\" operand bundle");
6242 Check(PreallocatedBundle->Inputs.front().get() == &
Call,
6243 "preallocated bundle must have token from corresponding "
6244 "llvm.call.preallocated.setup");
6249 case Intrinsic::call_preallocated_arg: {
6252 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6253 "llvm.call.preallocated.arg token argument must be a "
6254 "llvm.call.preallocated.setup");
6256 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6257 "call site attribute");
6260 case Intrinsic::call_preallocated_teardown: {
6263 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6264 "llvm.call.preallocated.teardown token argument must be a "
6265 "llvm.call.preallocated.setup");
6268 case Intrinsic::gcroot:
6269 case Intrinsic::gcwrite:
6270 case Intrinsic::gcread:
6271 if (
ID == Intrinsic::gcroot) {
6274 Check(AI,
"llvm.gcroot parameter #1 must be an alloca.",
Call);
6276 "llvm.gcroot parameter #2 must be a constant.",
Call);
6279 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6280 "or argument #2 must be a non-null constant.",
6286 "Enclosing function does not use GC.",
Call);
6288 case Intrinsic::init_trampoline:
6290 "llvm.init_trampoline parameter #2 must resolve to a function.",
6293 case Intrinsic::reloc_none: {
6296 "llvm.reloc.none argument must be a metadata string", &
Call);
6299 case Intrinsic::stackprotector:
6301 "llvm.stackprotector parameter #2 must resolve to an alloca.",
Call);
6303 case Intrinsic::localescape: {
6307 Check(!SawFrameEscape,
"multiple calls to llvm.localescape in one function",
6314 "llvm.localescape only accepts static allocas",
Call);
6317 SawFrameEscape =
true;
6320 case Intrinsic::localrecover: {
6323 Check(Fn && !Fn->isDeclaration(),
6324 "llvm.localrecover first "
6325 "argument must be function defined in this module",
6328 auto &
Entry = FrameEscapeInfo[Fn];
6329 Entry.second = unsigned(
6330 std::max(uint64_t(
Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6334 case Intrinsic::experimental_gc_statepoint:
6336 Check(!CI->isInlineAsm(),
6337 "gc.statepoint support for inline assembly unimplemented", CI);
6339 "Enclosing function does not use GC.",
Call);
6341 verifyStatepoint(
Call);
6343 case Intrinsic::experimental_gc_result: {
6345 "Enclosing function does not use GC.",
Call);
6353 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6354 Intrinsic::experimental_gc_statepoint,
6355 "gc.result operand #1 must be from a statepoint",
Call,
6359 auto *TargetFuncType =
6362 "gc.result result type does not match wrapped callee",
Call);
6365 case Intrinsic::experimental_gc_relocate: {
6369 "gc.relocate must return a pointer or a vector of pointers",
Call);
6377 LandingPad->getParent()->getUniquePredecessor();
6381 Check(InvokeBB,
"safepoints should have unique landingpads",
6382 LandingPad->getParent());
6386 "gc relocate should be linked to a statepoint", InvokeBB);
6393 "gc relocate is incorrectly tied to the statepoint",
Call, Token);
6402 "gc.relocate operand #2 must be integer offset",
Call);
6406 "gc.relocate operand #3 must be integer offset",
Call);
6416 Check(BaseIndex < Opt->Inputs.size(),
6417 "gc.relocate: statepoint base index out of bounds",
Call);
6418 Check(DerivedIndex < Opt->Inputs.size(),
6419 "gc.relocate: statepoint derived index out of bounds",
Call);
6432 "gc.relocate: relocated value must be a pointer",
Call);
6433 Check(DerivedType->isPtrOrPtrVectorTy(),
6434 "gc.relocate: relocated value must be a pointer",
Call);
6436 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6437 "gc.relocate: vector relocates to vector and pointer to pointer",
6440 ResultType->getPointerAddressSpace() ==
6441 DerivedType->getPointerAddressSpace(),
6442 "gc.relocate: relocating a pointer shouldn't change its address space",
6446 Check(GC,
"gc.relocate: calling function must have GCStrategy",
6449 auto isGCPtr = [&
GC](
Type *PTy) {
6450 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(
true);
6452 Check(isGCPtr(ResultType),
"gc.relocate: must return gc pointer",
Call);
6454 "gc.relocate: relocated value must be a gc pointer",
Call);
6455 Check(isGCPtr(DerivedType),
6456 "gc.relocate: relocated value must be a gc pointer",
Call);
6460 case Intrinsic::experimental_patchpoint: {
6463 "patchpoint: invalid return type used with anyregcc",
Call);
6467 case Intrinsic::eh_exceptioncode:
6468 case Intrinsic::eh_exceptionpointer: {
6470 "eh.exceptionpointer argument must be a catchpad",
Call);
6473 case Intrinsic::get_active_lane_mask: {
6476 "get_active_lane_mask: element type is not i1",
Call);
6479 case Intrinsic::experimental_get_vector_length: {
6481 Check(!VF->isNegative() && !VF->isZero(),
6482 "get_vector_length: VF must be positive",
Call);
6485 case Intrinsic::experimental_guard: {
6488 "experimental_guard must have exactly one "
6489 "\"deopt\" operand bundle");
6493 case Intrinsic::experimental_deoptimize: {
6497 "experimental_deoptimize must have exactly one "
6498 "\"deopt\" operand bundle");
6500 "experimental_deoptimize return type must match caller return type");
6505 "calls to experimental_deoptimize must be followed by a return");
6509 "calls to experimental_deoptimize must be followed by a return "
6510 "of the value computed by experimental_deoptimize");
6515 case Intrinsic::vastart: {
6517 "va_start called in a non-varargs function");
6520 case Intrinsic::get_dynamic_area_offset: {
6522 Check(IntTy &&
DL.getPointerSizeInBits(
DL.getAllocaAddrSpace()) ==
6523 IntTy->getBitWidth(),
6524 "get_dynamic_area_offset result type must be scalar integer matching "
6525 "alloca address space width",
6529 case Intrinsic::smul_fix:
6530 case Intrinsic::smul_fix_sat:
6531 case Intrinsic::umul_fix:
6532 case Intrinsic::umul_fix_sat:
6533 case Intrinsic::sdiv_fix:
6534 case Intrinsic::sdiv_fix_sat:
6535 case Intrinsic::udiv_fix:
6536 case Intrinsic::udiv_fix_sat: {
6540 if (
ID == Intrinsic::smul_fix ||
ID == Intrinsic::smul_fix_sat ||
6541 ID == Intrinsic::sdiv_fix ||
ID == Intrinsic::sdiv_fix_sat) {
6543 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6547 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6548 "to the width of the operands");
6552 case Intrinsic::lrint:
6553 case Intrinsic::llrint:
6554 case Intrinsic::lround:
6555 case Intrinsic::llround: {
6559 IF->
getName() +
": argument and result disagree on vector use",
6563 Check(VTy->getElementCount() == RTy->getElementCount(),
6564 IF->
getName() +
": argument must be same length as result", &
Call);
6568 case Intrinsic::bswap: {
6571 Check(
Size % 16 == 0,
"bswap must be an even number of bytes", &
Call);
6574 case Intrinsic::invariant_start: {
6576 Check(InvariantSize &&
6577 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
6578 "invariant_start parameter must be -1, 0 or a positive number",
6582 case Intrinsic::matrix_multiply:
6583 case Intrinsic::matrix_transpose:
6584 case Intrinsic::matrix_column_major_load:
6585 case Intrinsic::matrix_column_major_store: {
6587 ConstantInt *Stride =
nullptr;
6588 ConstantInt *NumRows;
6589 ConstantInt *NumColumns;
6591 Type *Op0ElemTy =
nullptr;
6592 Type *Op1ElemTy =
nullptr;
6594 case Intrinsic::matrix_multiply: {
6599 ->getNumElements() ==
6601 "First argument of a matrix operation does not match specified "
6604 ->getNumElements() ==
6606 "Second argument of a matrix operation does not match specified "
6616 case Intrinsic::matrix_transpose:
6623 case Intrinsic::matrix_column_major_load: {
6630 case Intrinsic::matrix_column_major_store: {
6643 Check(ResultTy->getElementType()->isIntegerTy() ||
6644 ResultTy->getElementType()->isFloatingPointTy(),
6645 "Result type must be an integer or floating-point type!", IF);
6648 Check(ResultTy->getElementType() == Op0ElemTy,
6649 "Vector element type mismatch of the result and first operand "
6654 Check(ResultTy->getElementType() == Op1ElemTy,
6655 "Vector element type mismatch of the result and second operand "
6661 "Result of a matrix operation does not fit in the returned vector!");
6667 "Stride must be greater or equal than the number of rows!", IF);
6672 case Intrinsic::stepvector: {
6674 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6675 VecTy->getScalarSizeInBits() >= 8,
6676 "stepvector only supported for vectors of integers "
6677 "with a bitwidth of at least 8.",
6681 case Intrinsic::experimental_vector_match: {
6690 Check(Op1Ty && Op2Ty && MaskTy,
"Operands must be vectors.", &
Call);
6692 "Second operand must be a fixed length vector.", &
Call);
6694 "First operand must be a vector of integers.", &
Call);
6695 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
6696 "First two operands must have the same element type.", &
Call);
6697 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
6698 "First operand and mask must have the same number of elements.",
6700 Check(MaskTy->getElementType()->isIntegerTy(1),
6701 "Mask must be a vector of i1's.", &
Call);
6706 case Intrinsic::vector_insert: {
6715 ElementCount VecEC = VecTy->getElementCount();
6716 ElementCount SubVecEC = SubVecTy->getElementCount();
6717 Check(VecTy->getElementType() == SubVecTy->getElementType(),
6718 "vector_insert parameters must have the same element "
6722 "vector_insert index must be a constant multiple of "
6723 "the subvector's known minimum vector length.");
6731 "subvector operand of vector_insert would overrun the "
6732 "vector being inserted into.");
6736 case Intrinsic::vector_extract: {
6744 ElementCount VecEC = VecTy->getElementCount();
6745 ElementCount ResultEC = ResultTy->getElementCount();
6747 Check(ResultTy->getElementType() == VecTy->getElementType(),
6748 "vector_extract result must have the same element "
6749 "type as the input vector.",
6752 "vector_extract index must be a constant multiple of "
6753 "the result type's known minimum vector length.");
6761 "vector_extract would overrun.");
6765 case Intrinsic::vector_partial_reduce_fadd:
6766 case Intrinsic::vector_partial_reduce_add: {
6770 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
6771 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
6773 Check((VecWidth % AccWidth) == 0,
6774 "Invalid vector widths for partial "
6775 "reduction. The width of the input vector "
6776 "must be a positive integer multiple of "
6777 "the width of the accumulator vector.");
6780 case Intrinsic::experimental_noalias_scope_decl: {
6784 case Intrinsic::preserve_array_access_index:
6785 case Intrinsic::preserve_struct_access_index:
6786 case Intrinsic::aarch64_ldaxr:
6787 case Intrinsic::aarch64_ldxr:
6788 case Intrinsic::arm_ldaex:
6789 case Intrinsic::arm_ldrex: {
6791 Check(ElemTy,
"Intrinsic requires elementtype attribute on first argument.",
6795 case Intrinsic::aarch64_stlxr:
6796 case Intrinsic::aarch64_stxr:
6797 case Intrinsic::arm_stlex:
6798 case Intrinsic::arm_strex: {
6801 "Intrinsic requires elementtype attribute on second argument.",
6805 case Intrinsic::aarch64_prefetch: {
6807 "write argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6809 "target argument to llvm.aarch64.prefetch must be 0-3",
Call);
6811 "stream argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6813 "isdata argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
6816 case Intrinsic::aarch64_range_prefetch: {
6818 "write argument to llvm.aarch64.range.prefetch must be 0 or 1",
Call);
6820 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
6824 case Intrinsic::callbr_landingpad: {
6826 Check(CBR,
"intrinstic requires callbr operand", &
Call);
6833 CheckFailed(
"Intrinsic in block must have 1 unique predecessor", &
Call);
6837 CheckFailed(
"Intrinsic must have corresponding callbr in predecessor",
6842 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
6843 "block in indirect destination list",
6846 Check(&
First == &
Call,
"No other instructions may proceed intrinsic",
6850 case Intrinsic::structured_gep: {
6856 "Intrinsic first parameter is missing an ElementType attribute",
6864 "Index operand type must be an integer", &
Call);
6867 T = AT->getElementType();
6869 Check(CI,
"Indexing into a struct requires a constant int", &
Call);
6871 "Indexing in a struct should be inbounds", &
Call);
6874 T = VT->getElementType();
6876 CheckFailed(
"Reached a non-composite type with more indices to process",
6882 case Intrinsic::structured_alloca:
6884 "@llvm.structured.alloca calls require elementtype attribute.",
6887 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
6888 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
6891 Check(RegCount % 8 == 0,
6892 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
6895 case Intrinsic::experimental_convergence_entry:
6896 case Intrinsic::experimental_convergence_anchor:
6898 case Intrinsic::experimental_convergence_loop:
6900 case Intrinsic::ptrmask: {
6904 "llvm.ptrmask intrinsic first argument must be pointer or vector "
6909 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
6914 "llvm.ptrmask intrinsic arguments must have the same number of "
6918 "llvm.ptrmask intrinsic second argument bitwidth must match "
6919 "pointer index type size of first argument",
6923 case Intrinsic::thread_pointer: {
6925 DL.getDefaultGlobalsAddressSpace(),
6926 "llvm.thread.pointer intrinsic return type must be for the globals "
6931 case Intrinsic::threadlocal_address: {
6934 "llvm.threadlocal.address first argument must be a GlobalValue");
6936 "llvm.threadlocal.address operand isThreadLocal() must be true");
6939 case Intrinsic::lifetime_start:
6940 case Intrinsic::lifetime_end: {
6944 (
II &&
II->getIntrinsicID() == Intrinsic::structured_alloca),
6945 "llvm.lifetime.start/end can only be used on alloca or poison",
6949 case Intrinsic::sponentry: {
6950 const unsigned StackAS =
DL.getAllocaAddrSpace();
6953 "llvm.sponentry must return a pointer to the stack", &
Call);
6956 case Intrinsic::write_volatile_register: {
6960 "llvm.write_volatile_register metadata must be a single MDString",
6969 if (
F->hasPersonalityFn() &&
6973 if (BlockEHFuncletColors.
empty())
6977 bool InEHFunclet =
false;
6981 for (BasicBlock *ColorFirstBB : CV)
6982 if (
auto It = ColorFirstBB->getFirstNonPHIIt();
6983 It != ColorFirstBB->end())
6988 bool HasToken =
false;
6995 Check(HasToken,
"Missing funclet token on intrinsic call", &
Call);
7022void Verifier::visit(DbgLabelRecord &DLR) {
7024 "invalid #dbg_label intrinsic variable", &DLR, DLR.
getRawLabel());
7037 CheckDI(Loc,
"#dbg_label record requires a !dbg attachment", &DLR, BB,
F);
7041 if (!LabelSP || !LocSP)
7045 "mismatched subprogram between #dbg_label label and !dbg attachment",
7046 &DLR, BB,
F, Label,
Label->getScope()->getSubprogram(), Loc,
7047 Loc->getScope()->getSubprogram());
7050void Verifier::visit(DbgVariableRecord &DVR) {
7054 CheckDI(DVR.
getType() == DbgVariableRecord::LocationType::Value ||
7055 DVR.
getType() == DbgVariableRecord::LocationType::Declare ||
7056 DVR.
getType() == DbgVariableRecord::LocationType::DeclareValue ||
7057 DVR.
getType() == DbgVariableRecord::LocationType::Assign,
7058 "invalid #dbg record type", &DVR, DVR.
getType(), BB,
F);
7066 "invalid #dbg record address/value", &DVR, MD, BB,
F);
7068 visitValueAsMetadata(*VAM,
F);
7071 Type *Ty = VAM->getValue()->getType();
7073 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7077 visitDIArgList(*AL,
F);
7091 "invalid #dbg_assign DIAssignID", &DVR, DVR.
getRawAssignID(), BB,
7094 AreDebugLocsAllowed::No);
7103 "invalid #dbg_assign address", &DVR, DVR.
getRawAddress(), BB,
F);
7105 visitValueAsMetadata(*VAM,
F);
7108 "invalid #dbg_assign address expression", &DVR,
7115 "inst not in same function as #dbg_assign",
I, &DVR, BB,
F);
7125 &DVR, DLNode, BB,
F);
7131 if (!VarSP || !LocSP)
7135 "mismatched subprogram between #dbg record variable and DILocation",
7137 Loc->getScope()->getSubprogram(), BB,
F);
7142void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7146 Check(RetTy->getElementCount() == ValTy->getElementCount(),
7147 "VP cast intrinsic first argument and result vector lengths must be "
7151 switch (VPCast->getIntrinsicID()) {
7152 case Intrinsic::vp_trunc:
7154 "llvm.vp.trunc intrinsic the bit size of first argument must be "
7155 "larger than the bit size of the return type",
7158 case Intrinsic::vp_zext:
7159 case Intrinsic::vp_sext:
7161 "llvm.vp.zext or llvm.vp.sext intrinsic the bit size of first "
7162 "argument must be smaller than the bit size of the return type",
7165 case Intrinsic::vp_fptrunc:
7167 "llvm.vp.fptrunc intrinsic the bit size of first argument must be "
7168 "larger than the bit size of the return type",
7171 case Intrinsic::vp_fpext:
7173 "llvm.vp.fpext intrinsic the bit size of first argument must be "
7174 "smaller than the bit size of the return type",
7183 case Intrinsic::vp_fcmp: {
7186 "invalid predicate for VP FP comparison intrinsic", &VPI);
7189 case Intrinsic::vp_icmp: {
7192 "invalid predicate for VP integer comparison intrinsic", &VPI);
7195 case Intrinsic::vp_is_fpclass: {
7198 "unsupported bits for llvm.vp.is.fpclass test mask");
7201 case Intrinsic::experimental_vp_splice: {
7204 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7206 AttributeList
Attrs = VPI.
getParent()->getParent()->getAttributes();
7207 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
7208 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
7210 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7211 (Idx >= 0 && Idx < KnownMinNumElements),
7212 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7213 "known minimum number of elements in the vector. For scalable "
7214 "vectors the minimum number of elements is determined from "
7222void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7224 bool HasRoundingMD =
7228 NumOperands += (1 + HasRoundingMD);
7234 "invalid arguments for constrained FP intrinsic", &FPI);
7237 case Intrinsic::experimental_constrained_fcmp:
7238 case Intrinsic::experimental_constrained_fcmps: {
7241 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7245 case Intrinsic::experimental_constrained_fptosi:
7246 case Intrinsic::experimental_constrained_fptoui: {
7250 "Intrinsic first argument must be floating point", &FPI);
7257 "Intrinsic first argument and result disagree on vector use", &FPI);
7259 "Intrinsic result must be an integer", &FPI);
7262 "Intrinsic first argument and result vector lengths must be equal",
7268 case Intrinsic::experimental_constrained_sitofp:
7269 case Intrinsic::experimental_constrained_uitofp: {
7273 "Intrinsic first argument must be integer", &FPI);
7280 "Intrinsic first argument and result disagree on vector use", &FPI);
7282 "Intrinsic result must be a floating point", &FPI);
7285 "Intrinsic first argument and result vector lengths must be equal",
7291 case Intrinsic::experimental_constrained_fptrunc:
7292 case Intrinsic::experimental_constrained_fpext: {
7298 "Intrinsic first argument must be FP or FP vector", &FPI);
7300 "Intrinsic result must be FP or FP vector", &FPI);
7302 "Intrinsic first argument and result disagree on vector use", &FPI);
7306 "Intrinsic first argument and result vector lengths must be equal",
7309 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7311 "Intrinsic first argument's type must be larger than result type",
7315 "Intrinsic first argument's type must be smaller than result type",
7331 "invalid exception behavior argument", &FPI);
7332 if (HasRoundingMD) {
7338void Verifier::verifyFragmentExpression(
const DbgVariableRecord &DVR) {
7343 if (!V || !
E || !
E->isValid())
7347 auto Fragment =
E->getFragmentInfo();
7357 if (
V->isArtificial())
7360 verifyFragmentExpression(*V, *Fragment, &DVR);
7363template <
typename ValueOrMetadata>
7364void Verifier::verifyFragmentExpression(
const DIVariable &V,
7366 ValueOrMetadata *
Desc) {
7369 auto VarSize =
V.getSizeInBits();
7375 CheckDI(FragSize + FragOffset <= *VarSize,
7376 "fragment is larger than or outside of variable",
Desc, &V);
7377 CheckDI(FragSize != *VarSize,
"fragment covers entire variable",
Desc, &V);
7380void Verifier::verifyFnArgs(
const DbgVariableRecord &DVR) {
7392 CheckDI(Var,
"#dbg record without variable");
7394 unsigned ArgNo = Var->
getArg();
7400 if (DebugFnArgs.
size() < ArgNo)
7401 DebugFnArgs.
resize(ArgNo,
nullptr);
7403 auto *Prev = DebugFnArgs[ArgNo - 1];
7404 DebugFnArgs[ArgNo - 1] = Var;
7405 CheckDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &DVR,
7409void Verifier::verifyNotEntryValue(
const DbgVariableRecord &DVR) {
7413 if (!
E || !
E->isValid())
7423 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7428 "Entry values are only allowed in MIR unless they target a "
7429 "swiftasync Argument",
7433void Verifier::verifyCompileUnits() {
7437 if (
M.getContext().isODRUniquingDebugTypes())
7439 auto *CUs =
M.getNamedMetadata(
"llvm.dbg.cu");
7440 SmallPtrSet<const Metadata *, 2> Listed;
7443 for (
const auto *CU : CUVisited)
7444 CheckDI(Listed.
count(CU),
"DICompileUnit not listed in llvm.dbg.cu", CU);
7448void Verifier::verifyDeoptimizeCallingConvs() {
7449 if (DeoptimizeDeclarations.
empty())
7453 for (
const auto *
F :
ArrayRef(DeoptimizeDeclarations).slice(1)) {
7454 Check(
First->getCallingConv() ==
F->getCallingConv(),
7455 "All llvm.experimental.deoptimize declarations must have the same "
7456 "calling convention",
7461void Verifier::verifyAttachedCallBundle(
const CallBase &
Call,
7462 const OperandBundleUse &BU) {
7465 Check((FTy->getReturnType()->isPointerTy() ||
7467 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7468 "function returning a pointer or a non-returning function that has a "
7473 "operand bundle \"clang.arc.attachedcall\" requires one function as "
7481 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7482 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
7483 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7484 "invalid function argument",
Call);
7486 StringRef FnName = Fn->getName();
7487 Check((FnName ==
"objc_retainAutoreleasedReturnValue" ||
7488 FnName ==
"objc_claimAutoreleasedReturnValue" ||
7489 FnName ==
"objc_unsafeClaimAutoreleasedReturnValue"),
7490 "invalid function argument",
Call);
7494void Verifier::verifyNoAliasScopeDecl() {
7495 if (NoAliasScopeDecls.
empty())
7499 for (
auto *
II : NoAliasScopeDecls) {
7500 assert(
II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7501 "Not a llvm.experimental.noalias.scope.decl ?");
7504 Check(ScopeListMV !=
nullptr,
7505 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7510 Check(ScopeListMD !=
nullptr,
"!id.scope.list must point to an MDNode",
II);
7511 Check(ScopeListMD->getNumOperands() == 1,
7512 "!id.scope.list must point to a list with a single scope",
II);
7513 visitAliasScopeListMetadata(ScopeListMD);
7523 auto GetScope = [](IntrinsicInst *
II) {
7526 return &
cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7531 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7532 return GetScope(Lhs) < GetScope(Rhs);
7539 auto ItCurrent = NoAliasScopeDecls.begin();
7540 while (ItCurrent != NoAliasScopeDecls.end()) {
7541 auto CurScope = GetScope(*ItCurrent);
7542 auto ItNext = ItCurrent;
7545 }
while (ItNext != NoAliasScopeDecls.end() &&
7546 GetScope(*ItNext) == CurScope);
7551 if (ItNext - ItCurrent < 32)
7555 Check(!DT.dominates(
I, J),
7556 "llvm.experimental.noalias.scope.decl dominates another one "
7557 "with the same scope",
7571 Verifier V(OS,
true, *f.getParent());
7575 return !V.verify(
F);
7579 bool *BrokenDebugInfo) {
7581 Verifier V(OS, !BrokenDebugInfo, M);
7583 bool Broken =
false;
7585 Broken |= !V.verify(
F);
7587 Broken |= !V.verify();
7588 if (BrokenDebugInfo)
7589 *BrokenDebugInfo = V.hasBrokenDebugInfo();
7600 std::unique_ptr<Verifier> V;
7601 bool FatalErrors =
true;
7604 explicit VerifierLegacyPass(
bool FatalErrors)
7605 : FunctionPass(
ID), FatalErrors(FatalErrors) {}
7607 bool doInitialization(
Module &M)
override {
7608 V = std::make_unique<Verifier>(
7614 if (!
V->verify(
F) && FatalErrors) {
7615 errs() <<
"in function " <<
F.getName() <<
'\n';
7621 bool doFinalization(
Module &M)
override {
7622 bool HasErrors =
false;
7623 for (Function &
F : M)
7624 if (
F.isDeclaration())
7625 HasErrors |= !
V->verify(
F);
7627 HasErrors |= !
V->verify();
7628 if (FatalErrors && (HasErrors ||
V->hasBrokenDebugInfo()))
7633 void getAnalysisUsage(AnalysisUsage &AU)
const override {
7641template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&... Args) {
7643 return Diagnostic->CheckFailed(
Args...);
7646#define CheckTBAA(C, ...) \
7649 CheckFailed(__VA_ARGS__); \
7657TBAAVerifier::TBAABaseNodeSummary
7661 CheckFailed(
"Base nodes must have at least two operands",
I, BaseNode);
7665 auto Itr = TBAABaseNodes.find(BaseNode);
7666 if (Itr != TBAABaseNodes.end())
7669 auto Result = verifyTBAABaseNodeImpl(
I, BaseNode, IsNewFormat);
7670 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
7672 assert(InsertResult.second &&
"We just checked!");
7676TBAAVerifier::TBAABaseNodeSummary
7677TBAAVerifier::verifyTBAABaseNodeImpl(
const Instruction *
I,
7678 const MDNode *BaseNode,
bool IsNewFormat) {
7679 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0
u};
7683 return isValidScalarTBAANode(BaseNode)
7684 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
7690 CheckFailed(
"Access tag nodes must have the number of operands that is a "
7691 "multiple of 3!", BaseNode);
7696 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
7706 if (!TypeSizeNode) {
7707 CheckFailed(
"Type size nodes must be constants!",
I, BaseNode);
7714 CheckFailed(
"Struct tag nodes have a string as their first operand",
7721 std::optional<APInt> PrevOffset;
7726 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7727 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7728 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
7729 Idx += NumOpsPerField) {
7730 const MDOperand &FieldTy = BaseNode->
getOperand(Idx);
7731 const MDOperand &FieldOffset = BaseNode->
getOperand(Idx + 1);
7733 CheckFailed(
"Incorrect field entry in struct type node!",
I, BaseNode);
7738 auto *OffsetEntryCI =
7740 if (!OffsetEntryCI) {
7741 CheckFailed(
"Offset entries must be constants!",
I, BaseNode);
7747 BitWidth = OffsetEntryCI->getBitWidth();
7749 if (OffsetEntryCI->getBitWidth() !=
BitWidth) {
7751 "Bitwidth between the offsets and struct type entries must match",
I,
7763 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
7766 CheckFailed(
"Offsets must be increasing!",
I, BaseNode);
7770 PrevOffset = OffsetEntryCI->getValue();
7775 if (!MemberSizeNode) {
7776 CheckFailed(
"Member size entries must be constants!",
I, BaseNode);
7783 return Failed ? InvalidNode
7784 : TBAAVerifier::TBAABaseNodeSummary(
false,
BitWidth);
7806 return Parent && Visited.
insert(Parent).second &&
7810bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
7811 auto ResultIt = TBAAScalarNodes.find(MD);
7812 if (ResultIt != TBAAScalarNodes.end())
7813 return ResultIt->second;
7815 SmallPtrSet<const MDNode *, 4> Visited;
7817 auto InsertResult = TBAAScalarNodes.insert({MD,
Result});
7819 assert(InsertResult.second &&
"Just checked!");
7828MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(
const Instruction *
I,
7829 const MDNode *BaseNode,
7840 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
7841 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
7842 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
7843 Idx += NumOpsPerField) {
7844 auto *OffsetEntryCI =
7846 if (OffsetEntryCI->getValue().ugt(
Offset)) {
7847 if (Idx == FirstFieldOpNo) {
7848 CheckFailed(
"Could not find TBAA parent in struct type node",
I,
7853 unsigned PrevIdx = Idx - NumOpsPerField;
7854 auto *PrevOffsetEntryCI =
7856 Offset -= PrevOffsetEntryCI->getValue();
7864 Offset -= LastOffsetEntryCI->getValue();
7869 if (!
Type ||
Type->getNumOperands() < 3)
7885 "This instruction shall not have a TBAA access tag!",
I);
7887 bool IsStructPathTBAA =
7891 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
7901 "Access tag metadata must have either 4 or 5 operands",
I, MD);
7904 "Struct tag metadata must have either 3 or 4 operands",
I, MD);
7911 CheckTBAA(AccessSizeNode,
"Access size field must be a constant",
I, MD);
7915 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
7920 "Immutability tag on struct tag metadata must be a constant",
I,
7923 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
7924 "Immutability part of the struct tag metadata must be either 0 or 1",
I,
7929 "Malformed struct tag metadata: base and access-type "
7930 "should be non-null and point to Metadata nodes",
7931 I, MD, BaseNode, AccessType);
7934 CheckTBAA(isValidScalarTBAANode(AccessType),
7935 "Access type node must be a valid scalar type",
I, MD,
7940 CheckTBAA(OffsetCI,
"Offset must be constant integer",
I, MD);
7943 bool SeenAccessTypeInPath =
false;
7949 getFieldNodeFromTBAABaseNode(
I, BaseNode,
Offset, IsNewFormat)) {
7950 if (!StructPath.
insert(BaseNode).second) {
7951 CheckFailed(
"Cycle detected in struct path",
I, MD);
7956 unsigned BaseNodeBitWidth;
7957 std::tie(
Invalid, BaseNodeBitWidth) =
7958 verifyTBAABaseNode(
I, BaseNode, IsNewFormat);
7965 SeenAccessTypeInPath |= BaseNode == AccessType;
7967 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
7972 (BaseNodeBitWidth == 0 &&
Offset == 0) ||
7973 (IsNewFormat && BaseNodeBitWidth == ~0u),
7974 "Access bit-width not the same as description bit-width",
I, MD,
7975 BaseNodeBitWidth,
Offset.getBitWidth());
7977 if (IsNewFormat && SeenAccessTypeInPath)
7981 CheckTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
I,
7986char VerifierLegacyPass::ID = 0;
7987INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
7990 return new VerifierLegacyPass(FatalErrors);
8008 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8016 if (res.IRBroken && FatalErrors)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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")
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.
static constexpr Value * getValue(Ty &ValueOrUse)
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 unsigned getNumElements(Type *Ty)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> 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 isSupportedCallBrIntrinsic(Intrinsic::ID ID)
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 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.
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.
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.
bool isElementwise() const
Return true if this RMW has elementwise vector semantics.
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.
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_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
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; assumes that the block is well-formed.
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.
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.
auto operand_bundles() const
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.
bool hasRetAttr(Attribute::AttrKind Kind) const
Determine whether the return value 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.
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).
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)
Value * getCondition() const
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.
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.
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 LLVM_ABI 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
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.
DebugLoc getDebugLoc() const
LLVM_ABI BasicBlock * getParent()
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
DIExpression * getAddressExpression() const
LLVM_ABI MDNode * getAsMDNode() const
Return this as a bar MDNode.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
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.
static bool isSupportedFloatingPointType(Type *Ty)
Returns true if Ty is a supported floating-point type for phi, select, or call FPMathOperators.
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.
op_range arg_operands()
arg_operands - iteration adapter for range-for loops.
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.
DISubprogram * getSubprogram() const
Get the attached subprogram.
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 metadata of given kind attached to this GlobalObject.
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.
bool hasCommonLinkage() const
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
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.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
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 const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
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.
A Module instance is used to store all the information related to an LLVM module.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI StringRef getName() const
LLVM_ABI unsigned getNumOperands() const
iterator_range< op_iterator > operands()
op_range incoming_values()
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.
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
Check if the string is empty.
std::pair< typename Base::iterator, bool > insert(StringRef key)
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,...
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
bool isByteTy() const
True if this is an instance of ByteType.
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...
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.
std::pair< iterator, bool > insert(const ValueT &V)
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.
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.
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 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 isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
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)
@ DW_LLVM_LANG_DIALECT_max
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 * > extract_or_null(Y &&MD)
Extract a Value from Metadata, 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.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
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)
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.
RelativeUniformCounterPtr Values
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
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 isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
void verifyAMDGPUAlloca(VerifierSupport &VS, const AllocaInst &AI)
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,...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
void verifyAMDGPUFunctionMetadata(VerifierSupport &VS, const Function &F)
auto dyn_cast_or_null(const Y &Val)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
GenericConvergenceVerifier< SSAContext > ConvergenceVerifier
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.
void verifyAMDGPUIntrinsicCall(VerifierSupport &VS, Intrinsic::ID ID, CallBase &Call)
bool isPointerTy(const Type *T)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
generic_gep_type_iterator<> gep_type_iterator
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_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
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)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
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...
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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
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.
void verifyAMDGPUModuleFlag(VerifierSupport &VS, const MDString *ID, Module::ModFlagBehavior MFB, const MDNode *Op)
bool isAMDGPUCallBrIntrinsic(Intrinsic::ID ID)
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.