99#include "llvm/IR/IntrinsicsAArch64.h"
100#include "llvm/IR/IntrinsicsARM.h"
101#include "llvm/IR/IntrinsicsNVPTX.h"
102#include "llvm/IR/IntrinsicsRISCV.h"
103#include "llvm/IR/IntrinsicsWebAssembly.h"
147 cl::desc(
"Ensure that llvm.experimental.noalias.scope.decl for identical "
148 "scopes are not dominating"));
177 Type *LandingPadResultTy;
184 bool HasDebugInfo =
false;
227 SawFrameEscape(
false), TBAAVerifyHelper(this) {
228 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
231 bool hasBrokenDebugInfo()
const {
return BrokenDebugInfo; }
234 llvm::TimeTraceScope timeScope(
"Verifier");
236 "An instance of this class only works with a specific module!");
246 for (
const BasicBlock &BB :
F) {
247 if (!BB.empty() && BB.back().isTerminator())
251 *OS <<
"Basic Block in function '" <<
F.getName()
252 <<
"' does not have terminator!\n";
253 BB.printAsOperand(*OS,
true, MST);
261 DT.recalculate(
const_cast<Function &
>(
F));
263 auto FailureCB = [
this](
const Twine &Message) {
264 this->CheckFailed(Message);
266 ConvergenceVerifyHelper.initialize(OS, FailureCB,
F);
271 verifySiblingFuncletUnwinds();
273 if (ConvergenceVerifyHelper.sawTokens())
274 ConvergenceVerifyHelper.verify(DT);
276 InstsInThisBlock.clear();
278 DIScopeChainReachesCycle.clear();
279 LandingPadResultTy =
nullptr;
280 SawFrameEscape =
false;
281 SiblingFuncletInfo.clear();
282 verifyNoAliasScopeDecl();
283 NoAliasScopeDecls.clear();
294 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
295 DeoptimizeDeclarations.push_back(&
F);
299 verifyFrameRecoverIndices();
300 for (
const GlobalVariable &GV :
M.globals())
301 visitGlobalVariable(GV);
303 for (
const GlobalAlias &GA :
M.aliases())
304 visitGlobalAlias(GA);
306 for (
const GlobalIFunc &GI :
M.ifuncs())
307 visitGlobalIFunc(GI);
309 for (
const NamedMDNode &NMD :
M.named_metadata())
310 visitNamedMDNode(NMD);
312 for (
const StringMapEntry<Comdat> &SMEC :
M.getComdatSymbolTable())
313 visitComdat(SMEC.getValue());
317 visitModuleCommandLines();
318 visitModuleErrnoTBAA();
320 verifyCompileUnits();
322 verifyDeoptimizeCallingConvs();
323 DISubprogramAttachments.clear();
324 DIScopeChainReachesCycle.clear();
330 enum class AreDebugLocsAllowed {
No,
Yes };
334 enum class RangeLikeMetadataKind {
341 void visitGlobalValue(
const GlobalValue &GV);
342 void visitGlobalVariable(
const GlobalVariable &GV);
343 void visitGlobalAlias(
const GlobalAlias &GA);
344 void visitGlobalIFunc(
const GlobalIFunc &GI);
345 void visitAliaseeSubExpr(
const GlobalAlias &
A,
const Constant &
C);
346 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
347 const GlobalAlias &
A,
const Constant &
C);
348 void visitNamedMDNode(
const NamedMDNode &NMD);
349 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
350 void visitMetadataAsValue(
const MetadataAsValue &MD,
Function *
F);
351 void visitValueAsMetadata(
const ValueAsMetadata &MD,
Function *
F);
352 void visitDIArgList(
const DIArgList &AL,
Function *
F);
353 void visitComdat(
const Comdat &
C);
354 void visitModuleIdents();
355 void visitModuleCommandLines();
356 void visitModuleErrnoTBAA();
357 void visitModuleFlags();
358 void visitModuleFlag(
const MDNode *
Op,
359 DenseMap<const MDString *, const MDNode *> &SeenIDs,
360 SmallVectorImpl<const MDNode *> &Requirements);
361 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
363 void visitBasicBlock(BasicBlock &BB);
364 void verifyRangeLikeMetadata(
const Value &V,
const MDNode *
Range,
Type *Ty,
365 RangeLikeMetadataKind Kind);
366 void visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
367 void visitNoFPClassMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
368 void visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
369 void visitDereferenceableMetadata(Instruction &
I, MDNode *MD);
370 void visitNoFreeObjMetadata(Instruction &
I, MDNode *MD);
371 void visitProfMetadata(Instruction &
I, MDNode *MD);
372 void visitCallStackMetadata(MDNode *MD);
373 void visitMemProfMetadata(Instruction &
I, MDNode *MD);
374 void visitCallsiteMetadata(Instruction &
I, MDNode *MD);
375 void visitCalleeTypeMetadata(Instruction &
I, MDNode *MD);
376 void visitDIAssignIDMetadata(Instruction &
I, MDNode *MD);
377 void visitMMRAMetadata(Instruction &
I, MDNode *MD);
378 void visitAnnotationMetadata(MDNode *Annotation);
379 void visitAliasScopeMetadata(
const MDNode *MD);
380 void visitAliasScopeListMetadata(
const MDNode *MD);
381 void visitAccessGroupMetadata(
const MDNode *MD);
382 void visitCapturesMetadata(Instruction &
I,
const MDNode *Captures);
383 void visitAllocTokenMetadata(Instruction &
I, MDNode *MD);
384 void visitInlineHistoryMetadata(Instruction &
I, MDNode *MD);
385 void visitMemCacheHintMetadata(Instruction &
I, MDNode *MD);
387#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
388#include "llvm/IR/Metadata.def"
389 void visitDIType(
const DIType &
N);
390 void visitDIScope(
const DIScope &
N);
391 void visitDIScopeChain(
const DIScope &
N);
392 bool hasDIScopeCycle(
const Metadata *S);
417 void checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V);
422 void visitPHINode(
PHINode &PN);
433 void visitVAArgInst(
VAArgInst &VAA) { visitInstruction(VAA); }
434 void visitCallInst(CallInst &CI);
435 void visitInvokeInst(InvokeInst &
II);
436 void visitGetElementPtrInst(GetElementPtrInst &
GEP);
437 void visitLoadInst(LoadInst &LI);
438 void visitStoreInst(StoreInst &SI);
439 void verifyDominatesUse(Instruction &
I,
unsigned i);
440 void visitInstruction(Instruction &
I);
441 void visitTerminator(Instruction &
I);
442 void visitCondBrInst(CondBrInst &BI);
443 void visitReturnInst(ReturnInst &RI);
444 void visitSwitchInst(SwitchInst &SI);
445 void visitIndirectBrInst(IndirectBrInst &BI);
446 void visitCallBrInst(CallBrInst &CBI);
447 void visitSelectInst(SelectInst &SI);
448 void visitUserOp1(Instruction &
I);
449 void visitUserOp2(Instruction &
I) { visitUserOp1(
I); }
451 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
452 void visitVPIntrinsic(VPIntrinsic &VPI);
453 void visitDbgLabelIntrinsic(StringRef Kind, DbgLabelInst &DLI);
454 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
455 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
456 void visitFenceInst(FenceInst &FI);
457 void visitAllocaInst(AllocaInst &AI);
458 void visitExtractValueInst(ExtractValueInst &EVI);
459 void visitInsertValueInst(InsertValueInst &IVI);
460 void visitEHPadPredecessors(Instruction &
I);
461 void visitLandingPadInst(LandingPadInst &LPI);
462 void visitResumeInst(ResumeInst &RI);
463 void visitCatchPadInst(CatchPadInst &CPI);
464 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
465 void visitCleanupPadInst(CleanupPadInst &CPI);
466 void visitFuncletPadInst(FuncletPadInst &FPI);
467 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
468 void visitCleanupReturnInst(CleanupReturnInst &CRI);
470 void verifySwiftErrorCall(CallBase &
Call,
const Value *SwiftErrorVal);
471 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
472 void verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs, StringRef
Context);
473 void verifyMustTailCall(CallInst &CI);
474 bool verifyAttributeCount(AttributeList Attrs,
unsigned Params);
475 void verifyAttributeTypes(AttributeSet Attrs,
const Value *V);
476 void verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
const Value *V);
477 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
479 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
480 const Value *V,
bool IsIntrinsic,
bool IsInlineAsm);
481 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
482 void verifyUnknownProfileMetadata(MDNode *MD);
483 void visitConstantExprsRecursively(
const Constant *EntryC);
484 void visitConstantExpr(
const ConstantExpr *CE);
485 void visitConstantPtrAuth(
const ConstantPtrAuth *CPA);
486 void verifyInlineAsmCall(
const CallBase &
Call);
487 void verifyStatepoint(
const CallBase &
Call);
488 void verifyFrameRecoverIndices();
489 void verifySiblingFuncletUnwinds();
491 void verifyFragmentExpression(
const DbgVariableRecord &
I);
492 template <
typename ValueOrMetadata>
493 void verifyFragmentExpression(
const DIVariable &V,
495 ValueOrMetadata *
Desc);
496 void verifyFnArgs(
const DbgVariableRecord &DVR);
497 void verifyNotEntryValue(
const DbgVariableRecord &
I);
500 void verifyCompileUnits();
504 void verifyDeoptimizeCallingConvs();
506 void verifyAttachedCallBundle(
const CallBase &
Call,
507 const OperandBundleUse &BU);
510 void verifyNoAliasScopeDecl();
516#define Check(C, ...) \
519 CheckFailed(__VA_ARGS__); \
526#define CheckDI(C, ...) \
529 DebugInfoCheckFailed(__VA_ARGS__); \
535 if (!
I.getDbgMarker())
537 CheckDI(
I.getDbgMarker()->MarkedInstr == &
I,
538 "Instruction has invalid DebugMarker", &
I);
540 "PHI Node must not have any attached DbgRecords", &
I);
542 CheckDI(DR.getMarker() ==
I.getDbgMarker(),
543 "DbgRecord had invalid DebugMarker", &
I, &DR);
546 visitMDNode(*
Loc, AreDebugLocsAllowed::Yes);
551 verifyFragmentExpression(*DVR);
552 verifyNotEntryValue(*DVR);
559void Verifier::visit(Instruction &
I) {
561 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
562 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
574 while (!WorkList.
empty()) {
576 if (!Visited.
insert(Cur).second)
583void Verifier::visitGlobalValue(
const GlobalValue &GV) {
585 "Global is external, but doesn't have external or weak linkage!", &GV);
588 if (
const MDNode *Associated =
589 GO->getMetadata(LLVMContext::MD_associated)) {
590 Check(Associated->getNumOperands() == 1,
591 "associated metadata must have one operand", &GV, Associated);
592 const Metadata *
Op = Associated->getOperand(0).get();
593 Check(
Op,
"associated metadata must have a global value", GO, Associated);
596 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
599 "associated value must be pointer typed", GV, Associated);
601 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
603 "associated metadata must point to a GlobalObject", GO, Stripped);
604 Check(Stripped != GO,
605 "global values should not associate to themselves", GO,
611 if (
const MDNode *AbsoluteSymbol =
612 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
613 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
614 DL.getIntPtrType(GO->getType()),
615 RangeLikeMetadataKind::AbsoluteSymbol);
618 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
619 Check(!GO->isDeclaration(),
620 "ref metadata must not be placed on a declaration", GO);
623 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
624 for (
const MDNode *MD : MDs) {
625 Check(MD->getNumOperands() == 1,
"ref metadata must have one operand",
629 Check(VM,
"ref metadata must be ValueAsMetadata", GO, MD);
632 "ref value must be pointer typed", GV, MD);
636 "ref metadata must point to a GlobalObject", GO, Stripped);
637 Check(Stripped != GO,
"values should not reference themselves", GO,
643 if (
auto *Props = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
644 Check(Props->getNumOperands() == 2,
645 "elf_section_properties metadata must have two operands", GO,
647 if (Props->getNumOperands() == 2) {
649 Check(
Type,
"type field must be ConstantAsMetadata", GO, Props);
651 Check(TypeInt,
"type field must be ConstantInt", GO, Props);
654 Check(Entsize,
"entsize field must be ConstantAsMetadata", GO, Props);
656 Check(EntsizeInt,
"entsize field must be ConstantInt", GO, Props);
662 "Only global variables can have appending linkage!", &GV);
666 Check(GVar && GVar->getValueType()->isArrayTy(),
667 "Only global arrays can have appending linkage!", GVar);
671 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
675 "dllexport GlobalValue must have default or protected visibility",
680 "dllimport GlobalValue must have default visibility", &GV);
681 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
687 "Global is marked as dllimport, but not external", &GV);
692 "GlobalValue with local linkage or non-default "
693 "visibility must be dso_local!",
698 if (!
I->getParent() || !
I->getParent()->getParent())
699 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
701 else if (
I->getParent()->getParent()->getParent() != &M)
702 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
703 I->getParent()->getParent(),
704 I->getParent()->getParent()->getParent());
707 if (
F->getParent() != &M)
708 CheckFailed(
"Global is used by function in a different module", &GV, &M,
716void Verifier::visitGlobalVariable(
const GlobalVariable &GV) {
724 Check(
A->value() <= Value::MaximumAlignment,
725 "huge alignment values are unsupported", &GV);
730 "Global variable initializer type does not match global "
734 "Global variable initializer must be sized", &GV);
740 "'common' global must have a zero initializer!", &GV);
743 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
748 GV.
getName() ==
"llvm.global_dtors")) {
750 "invalid linkage for intrinsic global variable", &GV);
752 "invalid uses of intrinsic global variable", &GV);
759 PointerType::get(
Context,
DL.getProgramAddressSpace());
760 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
761 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
762 STy->getTypeAtIndex(1) == FuncPtrTy,
763 "wrong type for intrinsic global variable", &GV);
764 Check(STy->getNumElements() == 3,
765 "the third field of the element type is mandatory, "
766 "specify ptr null to migrate from the obsoleted 2-field form");
767 Type *ETy = STy->getTypeAtIndex(2);
776 for (
const Use &U : Init->operands()) {
778 if (!Structor || Structor->getNumOperands() != 3)
781 "signing of ctors/dtors should be requested via module flags");
787 GV.
getName() ==
"llvm.compiler.used")) {
789 "invalid linkage for intrinsic global variable", &GV);
791 "invalid uses of intrinsic global variable", &GV);
795 Check(PTy,
"wrong type for intrinsic global variable", &GV);
799 Check(InitArray,
"wrong initializer for intrinsic global variable",
801 for (
Value *
Op : InitArray->operands()) {
805 Twine(
"invalid ") + GV.
getName() +
" member", V);
807 Twine(
"members of ") + GV.
getName() +
" must be named", V);
816 for (MDNode *MD : MDs) {
818 visitDIGlobalVariableExpression(*GVE);
820 CheckDI(
false,
"!dbg attachment of global variable must be a "
821 "DIGlobalVariableExpression");
831 "Global @" + GV.
getName() +
" has illegal target extension type",
840 "Global variable is too large to fit into the address space", &GV,
844 visitGlobalValue(GV);
851 visitGlobalValue(GV);
854void Verifier::visitAliaseeSubExpr(
const GlobalAlias &GA,
const Constant &
C) {
855 SmallPtrSet<const GlobalAlias*, 4> Visited;
857 visitAliaseeSubExpr(Visited, GA,
C);
860void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
861 const GlobalAlias &GA,
const Constant &
C) {
865 "available_externally alias must point to available_externally "
876 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
878 Check(!GA2->isInterposable(),
879 "Alias cannot point to an interposable alias", &GA);
888 visitConstantExprsRecursively(CE);
890 for (
const Use &U :
C.operands()) {
893 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
895 visitAliaseeSubExpr(Visited, GA, *C2);
899void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
901 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
902 "weak_odr, external, or available_externally linkage!",
905 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
907 "Alias and aliasee types should match!", &GA);
910 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
912 visitAliaseeSubExpr(GA, *Aliasee);
914 visitGlobalValue(GA);
917void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
918 visitGlobalValue(GI);
922 for (
const auto &
I : MDs) {
923 CheckDI(
I.first != LLVMContext::MD_dbg,
924 "an ifunc may not have a !dbg attachment", &GI);
925 Check(
I.first != LLVMContext::MD_prof,
926 "an ifunc may not have a !prof attachment", &GI);
927 visitMDNode(*
I.second, AreDebugLocsAllowed::No);
931 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
932 "weak_odr, or external linkage!",
937 Check(Resolver,
"IFunc must have a Function resolver", &GI);
939 "IFunc resolver must be a definition", &GI);
946 "IFunc resolver must return a pointer", &GI);
949 "IFunc resolver has incorrect type", &GI);
952void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
957 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
958 for (
const MDNode *MD : NMD.
operands()) {
959 if (NMD.
getName() ==
"llvm.dbg.cu")
965 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
976 return T->getRawScope();
978 return SP->getRawScope();
980 return LB->getRawScope();
982 return NS->getRawScope();
984 return CB->getRawScope();
986 return M->getRawScope();
991bool Verifier::hasDIScopeCycle(
const Metadata *S) {
992 SmallPtrSet<const Metadata *, 8> Seen;
993 auto CacheSeen = [&](
bool HasCycle) {
995 DIScopeChainReachesCycle[
M] = HasCycle;
1000 auto It = DIScopeChainReachesCycle.
find(Scope);
1001 bool IsInCache = It != DIScopeChainReachesCycle.
end();
1003 return CacheSeen(It->second);
1004 bool AlreadySeen = !Seen.
insert(Scope).second;
1006 return CacheSeen(
true);
1012 return CacheSeen(
false);
1015void Verifier::visitDIScopeChain(
const DIScope &
N) {
1016 CheckDI(!hasDIScopeCycle(&
N),
"DIScope scope chain must not contain a cycle",
1020void Verifier::visitMDNode(
const MDNode &BaseMD,
1021 AreDebugLocsAllowed AllowLocs) {
1024 if (!MDNodes.
insert(&BaseMD).second)
1027 std::queue<const MDNode *> Worklist;
1028 Worklist.push(&BaseMD);
1030 while (!Worklist.empty()) {
1031 const MDNode *CurrentMD = Worklist.front();
1034 "MDNode context does not match Module context!", CurrentMD);
1039 case Metadata::MDTupleKind:
1041#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
1042 case Metadata::CLASS##Kind: \
1043 visit##CLASS(cast<CLASS>(*CurrentMD)); \
1045#include "llvm/IR/Metadata.def"
1050 visitDIScopeChain(*S);
1058 "DILocation not allowed within this metadata node", CurrentMD,
1066 visitValueAsMetadata(*V,
nullptr);
1087 "Expected second operand to be an integer constant of type i32 or "
1099 Check(AlignMD && AlignMD->getType()->isIntegerTy(32),
1100 "Expected the alignment to be an integer constant of type i32",
1105 "Expected the alignment to be a power of two", CurrentMD);
1106 Check(Align <= Value::MaximumAlignment,
1107 "Alignment is larger than the implementation defined limit",
1119 "Expecting only the metadata name", CurrentMD);
1124 Check(CurrentMD->
isResolved(),
"All nodes should be resolved!", CurrentMD);
1128void Verifier::visitValueAsMetadata(
const ValueAsMetadata &MD,
Function *
F) {
1131 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1137 Check(
F,
"function-local metadata used outside a function", L);
1143 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1150 assert(ActualF &&
"Unimplemented function local metadata case!");
1152 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1155void Verifier::visitDIArgList(
const DIArgList &AL,
Function *
F) {
1156 for (
const ValueAsMetadata *VAM :
AL.getArgs())
1157 visitValueAsMetadata(*VAM,
F);
1160void Verifier::visitMetadataAsValue(
const MetadataAsValue &MDV,
Function *
F) {
1163 visitMDNode(*
N, AreDebugLocsAllowed::No);
1169 if (!MDNodes.
insert(MD).second)
1173 visitValueAsMetadata(*V,
F);
1176 visitDIArgList(*AL,
F);
1184void Verifier::visitDILocation(
const DILocation &
N) {
1186 "location requires a valid scope", &
N,
N.getRawScope());
1187 if (
auto *IA =
N.getRawInlinedAt())
1190 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1193void Verifier::visitGenericDINode(
const GenericDINode &
N) {
1197void Verifier::visitDIScope(
const DIScope &
N) {
1198 if (
auto *
F =
N.getRawFile())
1202void Verifier::visitDIType(
const DIType &
N) {
1205 CheckDI(
N.getRawFile() ||
N.getLine() == 0,
"line specified with no file", &
N,
1209void Verifier::visitDISubrangeType(
const DISubrangeType &
N) {
1212 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1215 auto *LBound =
N.getRawLowerBound();
1219 "LowerBound must be signed constant or DIVariable or DIExpression or "
1222 auto *UBound =
N.getRawUpperBound();
1226 "UpperBound must be signed constant or DIVariable or DIExpression or "
1229 auto *Stride =
N.getRawStride();
1232 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1233 auto *Bias =
N.getRawBias();
1236 "Bias must be signed constant or DIVariable or DIExpression", &
N);
1238 auto *
Size =
N.getRawSizeInBits();
1240 "SizeInBits must be a constant");
1243void Verifier::visitDISubrange(
const DISubrange &
N) {
1244 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1245 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1246 "Subrange can have any one of count or upperBound", &
N);
1247 auto *CBound =
N.getRawCountNode();
1250 "Count must be signed constant or DIVariable or DIExpression", &
N);
1251 auto Count =
N.getCount();
1254 "invalid subrange count", &
N);
1255 auto *LBound =
N.getRawLowerBound();
1258 "LowerBound must be signed constant or DIVariable or DIExpression",
1260 auto *UBound =
N.getRawUpperBound();
1263 "UpperBound must be signed constant or DIVariable or DIExpression",
1265 auto *Stride =
N.getRawStride();
1268 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1271void Verifier::visitDIGenericSubrange(
const DIGenericSubrange &
N) {
1272 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1273 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1274 "GenericSubrange can have any one of count or upperBound", &
N);
1275 auto *CBound =
N.getRawCountNode();
1277 "Count must be signed constant or DIVariable or DIExpression", &
N);
1278 auto *LBound =
N.getRawLowerBound();
1279 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1281 "LowerBound must be signed constant or DIVariable or DIExpression",
1283 auto *UBound =
N.getRawUpperBound();
1285 "UpperBound must be signed constant or DIVariable or DIExpression",
1287 auto *Stride =
N.getRawStride();
1288 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1290 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1293void Verifier::visitDIEnumerator(
const DIEnumerator &
N) {
1294 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1297void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1300 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1301 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1302 N.getTag() == dwarf::DW_TAG_string_type,
1305 auto *
Size =
N.getRawSizeInBits();
1307 "SizeInBits must be a constant");
1310void Verifier::visitDIFixedPointType(
const DIFixedPointType &
N) {
1311 visitDIBasicType(
N);
1313 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type,
"invalid tag", &
N);
1314 CheckDI(
N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1315 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1316 "invalid encoding", &
N);
1320 "invalid kind", &
N);
1322 N.getFactorRaw() == 0,
1323 "factor should be 0 for rationals", &
N);
1325 (
N.getNumeratorRaw() == 0 &&
N.getDenominatorRaw() == 0),
1326 "numerator and denominator should be 0 for non-rationals", &
N);
1329void Verifier::visitDIStringType(
const DIStringType &
N) {
1332 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1333 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1337void Verifier::visitDIDerivedType(
const DIDerivedType &
N) {
1341 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1342 N.getTag() == dwarf::DW_TAG_pointer_type ||
1343 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1344 N.getTag() == dwarf::DW_TAG_reference_type ||
1345 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1346 N.getTag() == dwarf::DW_TAG_const_type ||
1347 N.getTag() == dwarf::DW_TAG_immutable_type ||
1348 N.getTag() == dwarf::DW_TAG_volatile_type ||
1349 N.getTag() == dwarf::DW_TAG_restrict_type ||
1350 N.getTag() == dwarf::DW_TAG_atomic_type ||
1351 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1352 N.getTag() == dwarf::DW_TAG_member ||
1353 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1354 N.getTag() == dwarf::DW_TAG_inheritance ||
1355 N.getTag() == dwarf::DW_TAG_friend ||
1356 N.getTag() == dwarf::DW_TAG_set_type ||
1357 N.getTag() == dwarf::DW_TAG_template_alias,
1359 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1360 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1361 N.getRawExtraData());
1362 }
else if (
N.getTag() == dwarf::DW_TAG_template_alias) {
1364 N.getRawExtraData());
1365 }
else if (
N.getTag() == dwarf::DW_TAG_inheritance ||
1366 N.getTag() == dwarf::DW_TAG_member ||
1367 N.getTag() == dwarf::DW_TAG_variable) {
1368 auto *ExtraData =
N.getRawExtraData();
1369 auto IsValidExtraData = [&]() {
1370 if (ExtraData ==
nullptr)
1376 if (
Tuple->getNumOperands() != 1)
1383 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1384 "or MDTuple with single ConstantAsMetadata operand",
1388 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1389 if (
auto *
T =
N.getRawBaseType()) {
1394 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1395 (Subrange &&
Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1396 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1397 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1398 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1399 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1400 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1401 "invalid set base type", &
N,
T);
1406 N.getRawBaseType());
1408 if (
N.getDWARFAddressSpace()) {
1409 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1410 N.getTag() == dwarf::DW_TAG_reference_type ||
1411 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1412 "DWARF address space only applies to pointer or reference types",
1416 auto *
Size =
N.getRawSizeInBits();
1419 "SizeInBits must be a constant or DIVariable or DIExpression");
1424 return ((Flags & DINode::FlagLValueReference) &&
1425 (Flags & DINode::FlagRValueReference)) ||
1426 ((Flags & DINode::FlagTypePassByValue) &&
1427 (Flags & DINode::FlagTypePassByReference));
1430void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1432 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1439void Verifier::visitDICompositeType(
const DICompositeType &
N) {
1443 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1444 N.getTag() == dwarf::DW_TAG_structure_type ||
1445 N.getTag() == dwarf::DW_TAG_union_type ||
1446 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1447 N.getTag() == dwarf::DW_TAG_class_type ||
1448 N.getTag() == dwarf::DW_TAG_variant_part ||
1449 N.getTag() == dwarf::DW_TAG_variant ||
1450 N.getTag() == dwarf::DW_TAG_namelist,
1454 N.getRawBaseType());
1457 "invalid composite elements", &
N,
N.getRawElements());
1459 N.getRawVTableHolder());
1461 "invalid reference flags", &
N);
1462 unsigned DIBlockByRefStruct = 1 << 4;
1463 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1464 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1466 "DISubprogram contains null entry in `elements` field", &
N);
1469 const DINodeArray
Elements =
N.getElements();
1471 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1472 "invalid vector, expected one element of type subrange", &
N);
1475 if (
auto *Params =
N.getRawTemplateParams())
1476 visitTemplateParams(
N, *Params);
1478 if (
auto *
D =
N.getRawDiscriminator()) {
1480 "discriminator can only appear on variant part");
1483 if (
N.getRawDataLocation()) {
1484 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1485 "dataLocation can only appear in array type");
1488 if (
N.getRawAssociated()) {
1489 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1490 "associated can only appear in array type");
1493 if (
N.getRawAllocated()) {
1494 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1495 "allocated can only appear in array type");
1498 if (
N.getRawRank()) {
1499 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1500 "rank can only appear in array type");
1503 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1504 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1507 auto *
Size =
N.getRawSizeInBits();
1510 "SizeInBits must be a constant or DIVariable or DIExpression");
1513void Verifier::visitDISubroutineType(
const DISubroutineType &
N) {
1515 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1516 if (
auto *Types =
N.getRawTypeArray()) {
1518 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1519 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1523 "invalid reference flags", &
N);
1526void Verifier::visitDIFile(
const DIFile &
N) {
1527 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1528 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1530 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1531 "invalid checksum kind", &
N);
1533 switch (Checksum->Kind) {
1544 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1546 "invalid checksum", &
N);
1550void Verifier::visitDICompileUnit(
const DICompileUnit &
N) {
1551 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1552 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1558 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1562 "invalid emission kind", &
N);
1565 "invalid language dialect", &
N);
1567 if (
auto *Array =
N.getRawEnumTypes()) {
1569 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1571 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1572 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1574 "function-local enum in a DICompileUnit's enum list", &
N,
1575 N.getEnumTypes(),
Op);
1578 if (
auto *Array =
N.getRawRetainedTypes()) {
1580 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1584 "invalid retained type", &
N,
Op);
1587 if (
auto *Array =
N.getRawGlobalVariables()) {
1589 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1591 CheckDI(GVE,
"invalid global variable ref", &
N,
Op);
1593 "function-local variables are not allowed in a DICompileUnit's "
1594 "global variables list",
1598 if (
auto *Array =
N.getRawImportedEntities()) {
1600 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1602 CheckDI(IE,
"invalid imported entity ref", &
N,
Op);
1604 "function-local imports are not allowed in a DICompileUnit's "
1605 "imported entities list",
1609 if (
auto *Array =
N.getRawMacros()) {
1618void Verifier::visitDISubprogram(
const DISubprogram &
N) {
1619 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1621 if (
auto *
F =
N.getRawFile())
1624 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1625 auto *
T =
N.getRawType();
1626 CheckDI(
T,
"DISubprogram requires a non-null type", &
N);
1628 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1629 N.getRawContainingType());
1630 if (
auto *Params =
N.getRawTemplateParams())
1631 visitTemplateParams(
N, *Params);
1632 if (
auto *S =
N.getRawDeclaration())
1634 "invalid subprogram declaration", &
N, S);
1635 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1637 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1639 DenseMap<unsigned, DILocalVariable *>
Args;
1641 CheckDI(
Op,
"nullptr in retained nodes", &
N, Node);
1643 auto True = [](
const Metadata *) {
return true; };
1644 auto False = [](
const Metadata *) {
return false; };
1645 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1646 Op, True, True, True, True, True, False);
1648 "invalid retained nodes, expected DILocalVariable, DILabel, "
1649 "DIImportedEntity, DIType or DIGlobalVariableExpression",
1656 "invalid retained nodes, retained node is not local", &
N, Node,
1659 DISubprogram *RetainedNodeSP =
getSubprogram(RetainedNodeScope);
1660 DICompileUnit *RetainedNodeUnit =
1661 RetainedNodeSP ? RetainedNodeSP->getUnit() :
nullptr;
1663 RetainedNodeSP == &
N,
1664 "invalid retained nodes, retained node does not belong to subprogram",
1665 &
N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1671 if (
unsigned ArgNum = DV->getArg()) {
1673 CheckDI(Inserted || DV == ArgI->second,
1674 "invalid retained nodes, more than one local variable with the "
1675 "same argument index",
1676 &
N,
N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1681 "invalid reference flags", &
N);
1683 auto *
Unit =
N.getRawUnit();
1684 if (
N.isDefinition()) {
1686 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1687 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1692 if (CT && CT->getRawIdentifier() &&
1693 M.getContext().isODRUniquingDebugTypes())
1695 "definition subprograms cannot be nested within DICompositeType "
1696 "when enabling ODR",
1700 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1702 "subprogram declaration must not have a declaration field");
1705 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1707 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1713 if (
N.areAllCallsDescribed())
1715 "DIFlagAllCallsDescribed must be attached to a definition");
1718void Verifier::visitDILexicalBlockBase(
const DILexicalBlockBase &
N) {
1719 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1721 "invalid local scope", &
N,
N.getRawScope());
1723 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1726void Verifier::visitDILexicalBlock(
const DILexicalBlock &
N) {
1727 visitDILexicalBlockBase(
N);
1730 "cannot have column info without line info", &
N);
1733void Verifier::visitDILexicalBlockFile(
const DILexicalBlockFile &
N) {
1734 visitDILexicalBlockBase(
N);
1737void Verifier::visitDICommonBlock(
const DICommonBlock &
N) {
1738 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1739 if (
auto *S =
N.getRawScope())
1741 if (
auto *S =
N.getRawDecl())
1745void Verifier::visitDINamespace(
const DINamespace &
N) {
1746 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1747 if (
auto *S =
N.getRawScope())
1751void Verifier::visitDIMacro(
const DIMacro &
N) {
1754 "invalid macinfo type", &
N);
1755 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1756 if (!
N.getValue().empty()) {
1757 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1761void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1763 "invalid macinfo type", &
N);
1764 if (
auto *
F =
N.getRawFile())
1767 if (
auto *Array =
N.getRawElements()) {
1769 for (
Metadata *
Op :
N.getElements()->operands()) {
1775void Verifier::visitDIModule(
const DIModule &
N) {
1776 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1777 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1780void Verifier::visitDITemplateParameter(
const DITemplateParameter &
N) {
1784void Verifier::visitDITemplateTypeParameter(
const DITemplateTypeParameter &
N) {
1785 visitDITemplateParameter(
N);
1787 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1791void Verifier::visitDITemplateValueParameter(
1792 const DITemplateValueParameter &
N) {
1793 visitDITemplateParameter(
N);
1795 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1796 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1797 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1801void Verifier::visitDIVariable(
const DIVariable &
N) {
1802 if (
auto *S =
N.getRawScope())
1804 if (
auto *
F =
N.getRawFile())
1808void Verifier::visitDIGlobalVariable(
const DIGlobalVariable &
N) {
1812 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1815 if (
N.isDefinition())
1816 CheckDI(
N.getType(),
"missing global variable type", &
N);
1817 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1819 "invalid static data member declaration", &
N, Member);
1823void Verifier::visitDILocalVariable(
const DILocalVariable &
N) {
1828 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1830 "local variable requires a valid scope", &
N,
N.getRawScope());
1831 if (
auto Ty =
N.getType())
1835void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1836 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1837 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1840void Verifier::visitDILabel(
const DILabel &
N) {
1841 if (
auto *S =
N.getRawScope())
1843 if (
auto *
F =
N.getRawFile())
1846 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1848 "label requires a valid scope", &
N,
N.getRawScope());
1851void Verifier::visitDIExpression(
const DIExpression &
N) {
1852 CheckDI(
N.isValid(),
"invalid expression", &
N);
1855void Verifier::visitDIGlobalVariableExpression(
1856 const DIGlobalVariableExpression &GVE) {
1859 visitDIGlobalVariable(*Var);
1861 visitDIExpression(*Expr);
1862 if (
auto Fragment = Expr->getFragmentInfo())
1867void Verifier::visitDIObjCProperty(
const DIObjCProperty &
N) {
1868 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1869 if (
auto *
T =
N.getRawType())
1871 if (
auto *
F =
N.getRawFile())
1875void Verifier::visitDIProperty(
const DIProperty &
N) {
1876 CheckDI(
N.getTag() == dwarf::DW_TAG_property,
"invalid tag", &
N);
1877 if (
auto *
T =
N.getRawType())
1879 if (
auto *
F =
N.getRawFile())
1883 if (DINode *BackingStorage =
N.getBackingStorage()) {
1885 CheckDI(DT && DT->getTag() == dwarf::DW_TAG_member,
1886 "property backing storage must be a member", &
N, BackingStorage);
1890void Verifier::visitDIImportedEntity(
const DIImportedEntity &
N) {
1891 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
1892 N.getTag() == dwarf::DW_TAG_imported_declaration,
1894 if (
auto *S =
N.getRawScope())
1900void Verifier::visitComdat(
const Comdat &
C) {
1903 if (
TT.isOSBinFormatCOFF())
1904 if (
const GlobalValue *GV =
M.getNamedValue(
C.getName()))
1909void Verifier::visitModuleIdents() {
1910 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
1916 for (
const MDNode *
N : Idents->
operands()) {
1917 Check(
N->getNumOperands() == 1,
1918 "incorrect number of operands in llvm.ident metadata",
N);
1920 (
"invalid value for llvm.ident metadata entry operand"
1921 "(the operand should be a string)"),
1926void Verifier::visitModuleCommandLines() {
1927 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
1934 for (
const MDNode *
N : CommandLines->
operands()) {
1935 Check(
N->getNumOperands() == 1,
1936 "incorrect number of operands in llvm.commandline metadata",
N);
1938 (
"invalid value for llvm.commandline metadata entry operand"
1939 "(the operand should be a string)"),
1944void Verifier::visitModuleErrnoTBAA() {
1945 const NamedMDNode *ErrnoTBAA =
M.getNamedMetadata(
"llvm.errno.tbaa");
1950 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
1952 for (
const MDNode *
N : ErrnoTBAA->
operands())
1956void Verifier::visitModuleFlags() {
1957 const NamedMDNode *
Flags =
M.getModuleFlagsMetadata();
1961 DenseMap<const MDString*, const MDNode*> SeenIDs;
1965 std::optional<uint64_t> PAuthABIPlatform;
1966 std::optional<uint64_t> PAuthABIVersion;
1969 uint64_t HasPtrauthInitFiniAddr = 0;
1971 for (
const MDNode *MDN :
Flags->operands()) {
1972 visitModuleFlag(MDN, SeenIDs, Requirements);
1973 if (MDN->getNumOperands() != 3)
1977 auto GetFlagNamed = [&](StringRef
Name) -> std::optional<uint64_t> {
1978 if (FlagName->getString() != Name)
1979 return std::nullopt;
1980 if (
const auto *FlagValue =
1982 return FlagValue->getZExtValue();
1984 CheckFailed(Name +
": module flag expects integer value");
1985 return std::nullopt;
1988 if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-platform"))
1989 PAuthABIPlatform = *
Value;
1990 else if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-version"))
1991 PAuthABIVersion = *
Value;
1992 else if (
auto Value = GetFlagNamed(
"ptrauth-init-fini"))
1993 HasPtrauthInitFini = *
Value;
1994 else if (
auto Value =
1995 GetFlagNamed(
"ptrauth-init-fini-address-discrimination"))
1996 HasPtrauthInitFiniAddr = *
Value;
2001 "ptrauth-init-fini must be 0 or 1");
2003 "ptrauth-init-fini-address-discrimination must be 0 or 1, if set");
2004 if (HasPtrauthInitFiniAddr)
2005 Check(HasPtrauthInitFini,
"ptrauth-init-fini-address-discrimination module "
2006 "flag requires ptrauth-init-fini");
2008 if (PAuthABIPlatform.has_value() != PAuthABIVersion.has_value())
2009 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
2010 "'aarch64-elf-pauthabi-version' module flags must be present");
2013 for (
const MDNode *Requirement : Requirements) {
2015 const Metadata *ReqValue = Requirement->getOperand(1);
2017 const MDNode *
Op = SeenIDs.
lookup(Flag);
2019 CheckFailed(
"invalid requirement on flag, flag is not present in module",
2024 if (
Op->getOperand(2) != ReqValue) {
2025 CheckFailed((
"invalid requirement on flag, "
2026 "flag does not have the required value"),
2034Verifier::visitModuleFlag(
const MDNode *
Op,
2035 DenseMap<const MDString *, const MDNode *> &SeenIDs,
2036 SmallVectorImpl<const MDNode *> &Requirements) {
2040 "incorrect number of operands in module flag",
Op);
2041 Module::ModFlagBehavior MFB;
2042 if (!Module::isValidModFlagBehavior(
Op->getOperand(0), MFB)) {
2044 "invalid behavior operand in module flag (expected constant integer)",
2047 "invalid behavior operand in module flag (unexpected constant)",
2051 Check(ID,
"invalid ID operand in module flag (expected metadata string)",
2057 case Module::Warning:
2058 case Module::Override:
2064 Check(V &&
V->getValue().isNonNegative(),
2065 "invalid value for 'min' module flag (expected constant non-negative "
2073 "invalid value for 'max' module flag (expected constant integer)",
2078 case Module::Require: {
2083 "invalid value for 'require' module flag (expected metadata pair)",
2086 (
"invalid value for 'require' module flag "
2087 "(first value operand should be a string)"),
2088 Value->getOperand(0));
2096 case Module::Append:
2097 case Module::AppendUnique: {
2100 "invalid value for 'append'-type module flag "
2101 "(expected a metadata node)",
2108 if (MFB != Module::Require) {
2111 "module flag identifiers must be unique (or of 'require' type)", ID);
2114 StringRef
Name =
ID->getString();
2115 if (Name ==
"wchar_size") {
2118 Check(
Value,
"wchar_size metadata requires constant integer argument");
2122 if (Name ==
"long-double-type") {
2123 Check(MFB == Module::Error,
2124 "long-double-type module flag must use 'error' merge behavior",
Op);
2126 Check(
Value,
"long-double-type metadata requires a string argument");
2129 "invalid long-double-type metadata value",
Op);
2133 if (Name ==
"float-abi") {
2134 Check(MFB == Module::Error,
2135 "float-abi module flag must use 'error' merge behavior",
Op);
2137 Check(
Value,
"float-abi metadata requires a string argument");
2140 "invalid float-abi metadata value",
Op);
2144 if (Name ==
"thread-model") {
2145 Check(MFB == Module::Error,
2146 "thread-model module flag must use 'error' merge behavior",
Op);
2148 Check(
Value,
"thread-model metadata requires a string argument");
2151 "invalid thread-model metadata value",
Op);
2155 if (Name ==
"target-abi") {
2158 "target-abi metadata requires a non-empty string argument",
Op);
2162 if (
ID->getString() ==
"exception-model") {
2163 Check(MFB == Module::Error,
2164 "exception-model module flag must use 'error' merge behavior",
Op);
2166 Check(
Value,
"exception-model metadata requires a string argument");
2169 "invalid exception-model metadata value",
Op);
2173 if (Name ==
"Linker Options") {
2177 Check(
M.getNamedMetadata(
"llvm.linker.options"),
2178 "'Linker Options' named metadata no longer supported");
2182 if (Name ==
"SemanticInterposition") {
2183 ConstantInt *
Value =
2186 "SemanticInterposition metadata requires constant integer argument");
2190 if (Name ==
"CG Profile") {
2191 for (
const MDOperand &MDO :
cast<MDNode>(
Op->getOperand(2))->operands())
2192 visitModuleFlagCGProfileEntry(MDO);
2200void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
2201 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
2206 "expected a Function or null", FuncMDO);
2209 Check(Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
2210 CheckFunction(
Node->getOperand(0));
2211 CheckFunction(
Node->getOperand(1));
2214 "expected an integer constant",
Node->getOperand(2));
2217void Verifier::verifyAttributeTypes(AttributeSet Attrs,
const Value *V) {
2220 if (
A.isStringAttribute()) {
2221#define GET_ATTR_NAMES
2222#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2223#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2224 if (A.getKindAsString() == #DISPLAY_NAME) { \
2225 auto V = A.getValueAsString(); \
2226 if (!(V.empty() || V == "true" || V == "false")) \
2227 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2231#include "llvm/IR/Attributes.inc"
2235 if (
A.isIntAttribute() != Attribute::isIntAttrKind(
A.getKindAsEnum())) {
2236 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
2245void Verifier::verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
2247 if (!
Attrs.hasAttributes())
2250 verifyAttributeTypes(Attrs, V);
2253 Check(Attr.isStringAttribute() ||
2254 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2255 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
2258 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
2259 unsigned AttrCount =
2260 Attrs.getNumAttributes() -
Attrs.hasAttribute(Attribute::Range);
2261 Check(AttrCount == 1,
2262 "Attribute 'immarg' is incompatible with other attributes except the "
2263 "'range' attribute",
2269 unsigned AttrCount = 0;
2270 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
2271 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
2272 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
2273 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
2274 Attrs.hasAttribute(Attribute::InReg);
2275 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
2276 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
2277 Check(AttrCount <= 1,
2278 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2279 "'byref', and 'sret' are incompatible!",
2282 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
2283 Attrs.hasAttribute(Attribute::ReadOnly)),
2285 "'inalloca and readonly' are incompatible!",
2288 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
2289 Attrs.hasAttribute(Attribute::Returned)),
2291 "'sret and returned' are incompatible!",
2294 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
2295 Attrs.hasAttribute(Attribute::SExt)),
2297 "'zeroext and signext' are incompatible!",
2300 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2301 Attrs.hasAttribute(Attribute::ReadOnly)),
2303 "'readnone and readonly' are incompatible!",
2306 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2307 Attrs.hasAttribute(Attribute::WriteOnly)),
2309 "'readnone and writeonly' are incompatible!",
2312 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
2313 Attrs.hasAttribute(Attribute::WriteOnly)),
2315 "'readonly and writeonly' are incompatible!",
2318 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2319 Attrs.hasAttribute(Attribute::AlwaysInline)),
2321 "'noinline and alwaysinline' are incompatible!",
2324 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2325 Attrs.hasAttribute(Attribute::ReadNone)),
2326 "Attributes writable and readnone are incompatible!", V);
2328 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2329 Attrs.hasAttribute(Attribute::ReadOnly)),
2330 "Attributes writable and readonly are incompatible!", V);
2332 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2334 if (!Attr.isStringAttribute() &&
2335 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2336 CheckFailed(
"Attribute '" + Attr.getAsString() +
2337 "' applied to incompatible type!", V);
2343 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2344 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2345 Check(AttrAlign.
value() <= Value::MaximumAlignment,
2346 "huge alignment values are unsupported", V);
2348 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2351 "Attribute 'byval' does not support unsized types!", V);
2355 "'byval' argument has illegal target extension type", V);
2359 "scalable 'byval' arguments are unsupported", V);
2360 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2361 "huge 'byval' arguments are unsupported", V);
2363 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2365 "Attribute 'byref' does not support unsized types!", V);
2366 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2368 "huge 'byref' arguments are unsupported", V);
2370 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2372 "Attribute 'inalloca' does not support unsized types!", V);
2373 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2375 "huge 'inalloca' arguments are unsupported", V);
2377 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2378 Check(
Attrs.getPreallocatedType()->isSized(),
2379 "Attribute 'preallocated' does not support unsized types!", V);
2381 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2383 "huge 'preallocated' arguments are unsupported", V);
2387 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2388 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2389 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2392 "Attribute 'initializes' does not support unordered ranges", V);
2395 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2396 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2397 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2400 "Invalid value for 'nofpclass' test mask", V);
2402 if (
Attrs.hasAttribute(Attribute::Range)) {
2403 const ConstantRange &CR =
2404 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2406 "Range bit width must match type bit width!", V);
2410void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2412 if (
Attrs.hasFnAttr(Attr)) {
2413 StringRef S =
Attrs.getFnAttr(Attr).getValueAsString();
2416 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S, V);
2422void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2423 const Value *V,
bool IsIntrinsic,
2425 if (
Attrs.isEmpty())
2428 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2430 "Attribute list does not match Module context!", &Attrs, V);
2431 for (
const auto &AttrSet : Attrs) {
2432 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
2433 "Attribute set does not match Module context!", &AttrSet, V);
2434 for (
const auto &
A : AttrSet) {
2436 "Attribute does not match Module context!", &
A, V);
2441 bool SawNest =
false;
2442 bool SawReturned =
false;
2443 bool SawSRet =
false;
2444 bool SawSwiftSelf =
false;
2445 bool SawSwiftAsync =
false;
2446 bool SawSwiftError =
false;
2449 AttributeSet RetAttrs =
Attrs.getRetAttrs();
2452 Attribute::canUseAsRetAttr(
RetAttr.getKindAsEnum()),
2453 "Attribute '" +
RetAttr.getAsString() +
2454 "' does not apply to function return values",
2457 unsigned MaxParameterWidth = 0;
2458 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2461 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2462 if (
Size > MaxParameterWidth)
2463 MaxParameterWidth =
Size;
2467 GetMaxParameterWidth(FT->getReturnType());
2468 verifyParameterAttrs(RetAttrs, FT->getReturnType(), V);
2471 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2472 Type *Ty = FT->getParamType(i);
2473 AttributeSet ArgAttrs =
Attrs.getParamAttrs(i);
2477 "immarg attribute only applies to intrinsics", V);
2480 "Attribute 'elementtype' can only be applied to intrinsics"
2485 verifyParameterAttrs(ArgAttrs, Ty, V);
2486 GetMaxParameterWidth(Ty);
2489 Check(!SawNest,
"More than one parameter has attribute nest!", V);
2494 Check(!SawReturned,
"More than one parameter has attribute returned!", V);
2496 "Incompatible argument and return types for 'returned' attribute",
2502 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!", V);
2503 Check(i == 0 || i == 1,
2504 "Attribute 'sret' is not on first or second parameter!", V);
2509 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!", V);
2510 SawSwiftSelf =
true;
2514 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!", V);
2515 SawSwiftAsync =
true;
2519 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!", V);
2520 SawSwiftError =
true;
2524 Check(i == FT->getNumParams() - 1,
2525 "inalloca isn't on the last parameter!", V);
2529 if (!
Attrs.hasFnAttrs())
2532 verifyAttributeTypes(
Attrs.getFnAttrs(), V);
2535 Attribute::canUseAsFnAttr(
FnAttr.getKindAsEnum()),
2536 "Attribute '" +
FnAttr.getAsString() +
2537 "' does not apply to functions!",
2540 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2541 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2542 "Attributes 'noinline and alwaysinline' are incompatible!", V);
2544 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2546 "Attribute 'optnone' requires 'noinline'!", V);
2548 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2549 "Attributes 'optsize and optnone' are incompatible!", V);
2552 "Attributes 'minsize and optnone' are incompatible!", V);
2554 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2555 "Attributes 'optdebug and optnone' are incompatible!", V);
2558 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2559 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2561 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2564 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2565 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2566 "Attributes 'optsize and optdebug' are incompatible!", V);
2569 "Attributes 'minsize and optdebug' are incompatible!", V);
2572 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2573 isModSet(
Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2574 "Attribute writable and memory without argmem: write are incompatible!",
2577 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2578 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2579 "Attributes 'aarch64_pstate_sm_enabled and "
2580 "aarch64_pstate_sm_compatible' are incompatible!",
2584 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2585 Attrs.hasFnAttr(
"aarch64_inout_za") +
2586 Attrs.hasFnAttr(
"aarch64_out_za") +
2587 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2588 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2589 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2590 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2591 "'aarch64_za_state_agnostic' are mutually exclusive",
2595 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2596 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2597 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2598 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2599 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2600 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2601 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2602 "'aarch64_za_state_agnostic' are mutually exclusive",
2605 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2608 "Attribute 'jumptable' requires 'unnamed_addr'", V);
2611 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2612 auto CheckParam = [&](StringRef
Name,
unsigned ParamNo) {
2613 if (ParamNo >= FT->getNumParams()) {
2614 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds", V);
2618 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2619 CheckFailed(
"'allocsize' " + Name +
2620 " argument must refer to an integer parameter",
2628 if (!CheckParam(
"element size",
Args->first))
2631 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2635 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2638 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2640 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2643 "'allockind()' requires exactly one of alloc, realloc, and free");
2644 if ((
Type == AllocFnKind::Free) &&
2645 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2646 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2647 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2648 "or aligned modifiers.");
2649 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2650 if ((K & ZeroedUninit) == ZeroedUninit)
2651 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2655 StringRef S =
A.getValueAsString();
2656 Check(!S.
empty(),
"'alloc-variant-zeroed' must not be empty");
2664 "'alloc-variant-zeroed' must name a function belonging to the "
2665 "same 'alloc-family'");
2668 (
Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2669 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2670 "'alloc-variant-zeroed' must name a function with "
2671 "'allockind(\"zeroed\")'");
2674 "'alloc-variant-zeroed' must name a function with the same "
2679 "'alloc-variant-zeroed' must name a function with the same "
2680 "calling convention");
2684 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2685 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2687 CheckFailed(
"'vscale_range' minimum must be greater than 0", V);
2689 CheckFailed(
"'vscale_range' minimum must be power-of-two value", V);
2690 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2691 if (VScaleMax && VScaleMin > VScaleMax)
2692 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum", V);
2694 CheckFailed(
"'vscale_range' maximum must be power-of-two value", V);
2697 if (
Attribute FPAttr =
Attrs.getFnAttr(
"frame-pointer"); FPAttr.isValid()) {
2698 StringRef
FP = FPAttr.getValueAsString();
2699 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved" &&
2700 FP !=
"non-leaf-no-reserve")
2701 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP, V);
2704 checkUnsignedBaseTenFuncAttr(Attrs,
"tail-pad-to-size", V);
2705 checkUnsignedBaseTenFuncAttr(Attrs,
"tail-pad-value", V);
2706 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix", V);
2707 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry", V);
2708 if (
Attrs.hasFnAttr(
"patchable-function-entry-section"))
2709 Check(!
Attrs.getFnAttr(
"patchable-function-entry-section")
2712 "\"patchable-function-entry-section\" must not be empty");
2713 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size", V);
2715 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2716 StringRef S =
A.getValueAsString();
2717 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2718 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S, V);
2721 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2722 StringRef S =
A.getValueAsString();
2723 if (S !=
"a_key" && S !=
"b_key")
2724 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2726 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2728 "'sign-return-address-key' present without `sign-return-address`");
2732 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2733 StringRef S =
A.getValueAsString();
2734 if (S !=
"" && S !=
"true" && S !=
"false")
2736 "invalid value for 'branch-target-enforcement' attribute: " + S, V);
2739 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2740 StringRef S =
A.getValueAsString();
2741 if (S !=
"" && S !=
"true" && S !=
"false")
2743 "invalid value for 'branch-protection-pauth-lr' attribute: " + S, V);
2746 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2747 StringRef S =
A.getValueAsString();
2748 if (S !=
"" && S !=
"true" && S !=
"false")
2749 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2753 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2754 StringRef S =
A.getValueAsString();
2757 CheckFailed(
"invalid name for a VFABI variant: " + S, V);
2760 if (
auto A =
Attrs.getFnAttr(
"modular-format");
A.isValid()) {
2761 StringRef S =
A.getValueAsString();
2765 "modular-format attribute requires at least 5 arguments", V);
2766 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2768 Check(!Args[1].getAsInteger(10, FormatIdx),
2769 "modular-format attribute format string index is not an integer", V);
2770 Check(FormatIdx > 0,
2771 "modular-format attribute format string index must be greater than 0",
2773 Check(FormatIdx <= UpperBound,
2774 "modular-format attribute format string index is out of bounds", V);
2775 unsigned FirstArgIdx;
2776 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2777 "modular-format attribute first arg index is not an integer", V);
2778 Check(FirstArgIdx <= UpperBound,
2779 "modular-format attribute first arg index is out of bounds", V);
2781 "modular-format attribute modular implementation function name "
2785 "modular-format attribute implementation name cannot be empty", V);
2788 if (
auto A =
Attrs.getFnAttr(
"target-features");
A.isValid()) {
2789 StringRef S =
A.getValueAsString();
2791 for (
auto FeatureFlag :
split(S,
',')) {
2792 if (FeatureFlag.empty())
2794 "target-features attribute should not contain an empty string");
2796 Check(FeatureFlag[0] ==
'+' || FeatureFlag[0] ==
'-',
2797 "target feature '" + FeatureFlag +
2798 "' must start with a '+' or '-'",
2804void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
2806 "'unknown' !prof should have a single additional operand", MD);
2809 "'unknown' !prof should have an additional operand of type "
2812 "the 'unknown' !prof operand should not be an empty string");
2815void Verifier::verifyFunctionMetadata(
2816 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
2817 for (
const auto &Pair : MDs) {
2818 if (Pair.first == LLVMContext::MD_prof) {
2819 MDNode *MD = Pair.second;
2821 "!prof annotations should have no less than 2 operands", MD);
2826 verifyUnknownProfileMetadata(MD);
2831 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
2834 "expected string with name of the !prof annotation", MD);
2839 "first operand should be 'function_entry_count'"
2840 " or 'synthetic_function_entry_count'",
2844 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
2847 "expected integer argument to function_entry_count", MD);
2848 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
2849 MDNode *MD = Pair.second;
2851 "!kcfi_type must have exactly one operand", MD);
2852 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
2855 "expected a constant operand for !kcfi_type", MD);
2858 "expected a constant integer operand for !kcfi_type", MD);
2860 "expected a 32-bit integer constant operand for !kcfi_type", MD);
2861 }
else if (Pair.first ==
Context.getMDKindID(
"reqd_work_group_size")) {
2862 MDNode *MD = Pair.second;
2864 "reqd_work_group_size must have exactly three operands", MD);
2869 for (
unsigned I = 0;
I != 3; ++
I) {
2871 Check(
C,
"reqd_work_group_size operands must be integer constants", MD);
2875 const APInt &
Value =
C->getValue();
2877 "reqd_work_group_size operands must fit in 64 bits", MD);
2878 if (
Value.getActiveBits() > 64)
2882 Check(Dim == 0 || Product <= std::numeric_limits<uint64_t>::max() / Dim,
2883 "reqd_work_group_size product must fit in 64 bits", MD);
2884 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
2892void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
2896 if (!ConstantExprVisited.
insert(EntryC).second)
2900 Stack.push_back(EntryC);
2902 while (!
Stack.empty()) {
2907 visitConstantExpr(CE);
2910 visitConstantPtrAuth(CPA);
2915 Check(GV->
getParent() == &M,
"Referencing global in another module!",
2921 for (
const Use &U :
C->operands()) {
2925 if (!ConstantExprVisited.
insert(OpC).second)
2927 Stack.push_back(OpC);
2932void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
2933 if (
CE->getOpcode() == Instruction::BitCast)
2936 "Invalid bitcast", CE);
2937 else if (
CE->getOpcode() == Instruction::PtrToAddr)
2938 checkPtrToAddr(
CE->getOperand(0)->getType(),
CE->getType(), *CE);
2941void Verifier::visitConstantPtrAuth(
const ConstantPtrAuth *CPA) {
2943 "signed ptrauth constant base pointer must have pointer type");
2946 "signed ptrauth constant must have same type as its base pointer");
2949 "signed ptrauth constant key must be i32 constant integer");
2952 "signed ptrauth constant address discriminator must be a pointer");
2955 "signed ptrauth constant discriminator must be i64 constant integer");
2958 "signed ptrauth constant deactivation symbol must be a pointer");
2962 "signed ptrauth constant deactivation symbol must be a global value "
2966bool Verifier::verifyAttributeCount(AttributeList Attrs,
unsigned Params) {
2969 return Attrs.getNumAttrSets() <= Params + 2;
2972void Verifier::verifyInlineAsmCall(
const CallBase &
Call) {
2975 unsigned LabelNo = 0;
2976 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
2986 if (CI.isIndirect) {
2989 "Operand for indirect constraint must have pointer type", &
Call);
2992 "Operand for indirect constraint must have elementtype attribute",
2996 "Elementtype attribute can only be applied for indirect "
3005 Check(LabelNo == CallBr->getNumIndirectDests(),
3006 "Number of label constraints does not match number of callbr dests",
3009 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
3015void Verifier::verifyStatepoint(
const CallBase &
Call) {
3020 "gc.statepoint must read and write all memory to preserve "
3021 "reordering restrictions required by safepoint semantics",
3024 const int64_t NumPatchBytes =
3027 Check(NumPatchBytes >= 0,
3028 "gc.statepoint number of patchable bytes must be "
3033 Check(TargetElemType,
3034 "gc.statepoint callee argument must have elementtype attribute",
Call);
3036 Check(TargetFuncType,
3037 "gc.statepoint callee elementtype must be function type",
Call);
3040 Check(NumCallArgs >= 0,
3041 "gc.statepoint number of arguments to underlying call "
3044 const int NumParams = (int)TargetFuncType->getNumParams();
3045 if (TargetFuncType->isVarArg()) {
3046 Check(NumCallArgs >= NumParams,
3047 "gc.statepoint mismatch in number of vararg call args",
Call);
3050 Check(TargetFuncType->getReturnType()->isVoidTy(),
3051 "gc.statepoint doesn't support wrapping non-void "
3052 "vararg functions yet",
3055 Check(NumCallArgs == NumParams,
3056 "gc.statepoint mismatch in number of call args",
Call);
3061 "unknown flag used in gc.statepoint flags argument",
Call);
3066 for (
int i = 0; i < NumParams; i++) {
3067 Type *ParamType = TargetFuncType->getParamType(i);
3069 Check(ArgType == ParamType,
3070 "gc.statepoint call argument does not match wrapped "
3074 if (TargetFuncType->isVarArg()) {
3075 AttributeSet ArgAttrs =
Attrs.getParamAttrs(5 + i);
3077 "Attribute 'sret' cannot be used for vararg call arguments!",
Call);
3081 const int EndCallArgsInx = 4 + NumCallArgs;
3085 "gc.statepoint number of transition arguments "
3086 "must be constant integer",
3088 const int NumTransitionArgs =
3090 Check(NumTransitionArgs == 0,
3091 "gc.statepoint w/inline transition bundle is deprecated",
Call);
3092 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
3096 "gc.statepoint number of deoptimization arguments "
3097 "must be constant integer",
3100 Check(NumDeoptArgs == 0,
3101 "gc.statepoint w/inline deopt operands is deprecated",
Call);
3103 const int ExpectedNumArgs = 7 + NumCallArgs;
3105 "gc.statepoint too many arguments",
Call);
3112 Check(UserCall,
"illegal use of statepoint token",
Call, U);
3116 "gc.result or gc.relocate are the only value uses "
3117 "of a gc.statepoint",
3120 Check(UserCall->getArgOperand(0) == &
Call,
3121 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
3123 Check(UserCall->getArgOperand(0) == &
Call,
3124 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
3138void Verifier::verifyFrameRecoverIndices() {
3139 for (
auto &Counts : FrameEscapeInfo) {
3141 unsigned EscapedObjectCount = Counts.second.first;
3142 unsigned MaxRecoveredIndex = Counts.second.second;
3143 Check(MaxRecoveredIndex <= EscapedObjectCount,
3144 "all indices passed to llvm.localrecover must be less than the "
3145 "number of arguments passed to llvm.localescape in the parent "
3154 UnwindDest =
II->getUnwindDest();
3156 UnwindDest = CSI->getUnwindDest();
3162void Verifier::verifySiblingFuncletUnwinds() {
3163 llvm::TimeTraceScope timeScope(
"Verifier verify sibling funclet unwinds");
3164 SmallPtrSet<Instruction *, 8> Visited;
3165 SmallPtrSet<Instruction *, 8>
Active;
3166 for (
const auto &Pair : SiblingFuncletInfo) {
3168 if (Visited.
count(PredPad))
3174 if (
Active.count(SuccPad)) {
3177 SmallVector<Instruction *, 8> CycleNodes;
3180 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3181 if (CycleTerminator != CyclePad)
3184 }
while (CyclePad != SuccPad);
3185 Check(
false,
"EH pads can't handle each other's exceptions",
3186 ArrayRef<Instruction *>(CycleNodes));
3189 if (!Visited.
insert(SuccPad).second)
3193 auto TermI = SiblingFuncletInfo.find(PredPad);
3194 if (TermI == SiblingFuncletInfo.end())
3207void Verifier::visitFunction(
const Function &
F) {
3208 visitGlobalValue(
F);
3211 FunctionType *FT =
F.getFunctionType();
3212 unsigned NumArgs =
F.arg_size();
3215 "Function context does not match Module context!", &
F);
3217 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
3218 Check(FT->getNumParams() == NumArgs,
3219 "# formal arguments must match # of arguments for function type!", &
F,
3221 Check(
F.getReturnType()->isFirstClassType() ||
3222 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
3223 "Functions cannot return aggregate values!", &
F);
3225 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
3226 "Invalid struct return type!", &
F);
3228 if (MaybeAlign
A =
F.getAlign()) {
3229 Check(
A->value() <= Value::MaximumAlignment,
3230 "huge alignment values are unsupported", &
F);
3233 AttributeList
Attrs =
F.getAttributes();
3235 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3236 "Attribute after last parameter!", &
F);
3238 bool IsIntrinsic =
F.isIntrinsic();
3241 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
3247 "Attribute 'builtin' can only be applied to a callsite.", &
F);
3249 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
3250 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
3252 if (
Attrs.hasFnAttr(Attribute::Naked))
3253 for (
const Argument &Arg :
F.args())
3254 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
3259 switch (
F.getCallingConv()) {
3261 case CallingConv::C:
3263 case CallingConv::X86_INTR: {
3264 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
3265 "Calling convention parameter requires byval", &
F);
3268 case CallingConv::AMDGPU_KERNEL:
3269 case CallingConv::SPIR_KERNEL:
3270 case CallingConv::AMDGPU_CS_Chain:
3271 case CallingConv::AMDGPU_CS_ChainPreserve:
3272 Check(
F.getReturnType()->isVoidTy(),
3273 "Calling convention requires void return type", &
F);
3275 case CallingConv::AMDGPU_VS:
3276 case CallingConv::AMDGPU_HS:
3277 case CallingConv::AMDGPU_GS:
3278 case CallingConv::AMDGPU_PS:
3279 case CallingConv::AMDGPU_CS:
3280 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
3281 if (
F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3282 const unsigned StackAS =
DL.getAllocaAddrSpace();
3284 for (
const Argument &Arg :
F.args()) {
3285 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
3286 "Calling convention disallows byval", &
F);
3287 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
3288 "Calling convention disallows preallocated", &
F);
3289 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
3290 "Calling convention disallows inalloca", &
F);
3292 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
3295 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3296 "Calling convention disallows stack byref", &
F);
3304 case CallingConv::Fast:
3305 case CallingConv::Cold:
3306 case CallingConv::Intel_OCL_BI:
3307 case CallingConv::PTX_Kernel:
3308 case CallingConv::PTX_Device:
3310 "Calling convention does not support varargs or "
3311 "perfect forwarding!",
3314 case CallingConv::AMDGPU_Gfx_WholeWave:
3315 Check(!
F.arg_empty() &&
F.arg_begin()->getType()->isIntegerTy(1),
3316 "Calling convention requires first argument to be i1", &
F);
3317 Check(!
F.arg_begin()->hasInRegAttr(),
3318 "Calling convention requires first argument to not be inreg", &
F);
3320 "Calling convention does not support varargs or "
3321 "perfect forwarding!",
3328 for (
const Argument &Arg :
F.args()) {
3329 Check(Arg.getType() == FT->getParamType(i),
3330 "Argument value does not match function argument type!", &Arg,
3331 FT->getParamType(i));
3332 Check(Arg.getType()->isFirstClassType(),
3333 "Function arguments must have first-class types!", &Arg);
3335 Check(!Arg.getType()->isMetadataTy(),
3336 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
3337 Check(!Arg.getType()->isTokenLikeTy(),
3338 "Function takes token but isn't an intrinsic", &Arg, &
F);
3339 Check(!Arg.getType()->isX86_AMXTy(),
3340 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
3344 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3345 verifySwiftErrorValue(&Arg);
3351 Check(!
F.getReturnType()->isTokenLikeTy(),
3352 "Function returns a token but isn't an intrinsic", &
F);
3353 Check(!
F.getReturnType()->isX86_AMXTy(),
3354 "Function returns a x86_amx but isn't an intrinsic", &
F);
3359 F.getAllMetadata(MDs);
3360 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
3361 verifyFunctionMetadata(MDs);
3367 if (
F.hasPersonalityFn()) {
3370 Check(Per->getParent() ==
F.getParent(),
3371 "Referencing personality function in another module!", &
F,
3372 F.getParent(), Per, Per->getParent());
3376 BlockEHFuncletColors.
clear();
3378 if (
F.isMaterializable()) {
3380 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
3382 }
else if (
F.isDeclaration()) {
3383 for (
const auto &
I : MDs) {
3385 CheckDI(
I.first != LLVMContext::MD_dbg ||
3387 "function declaration may only have a unique !dbg attachment",
3389 Check(
I.first != LLVMContext::MD_prof,
3390 "function declaration may not have a !prof attachment", &
F);
3393 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
3395 Check(!
F.hasPersonalityFn(),
3396 "Function declaration shouldn't have a personality routine", &
F);
3400 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
3405 "Entry block to function must not have predecessors!", Entry);
3408 if (
Entry->hasAddressTaken()) {
3410 "blockaddress may not be used with the entry block!", Entry);
3413 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3414 NumKCFIAttachments = 0;
3416 for (
const auto &
I : MDs) {
3418 auto AllowLocs = AreDebugLocsAllowed::No;
3422 case LLVMContext::MD_dbg: {
3423 ++NumDebugAttachments;
3424 CheckDI(NumDebugAttachments == 1,
3425 "function must have a single !dbg attachment", &
F,
I.second);
3427 "function !dbg attachment must be a subprogram", &
F,
I.second);
3429 "function definition may only have a distinct !dbg attachment",
3433 const Function *&AttachedTo = DISubprogramAttachments[
SP];
3434 CheckDI(!AttachedTo || AttachedTo == &
F,
3435 "DISubprogram attached to more than one function", SP, &
F);
3437 AllowLocs = AreDebugLocsAllowed::Yes;
3440 case LLVMContext::MD_prof:
3441 ++NumProfAttachments;
3442 Check(NumProfAttachments == 1,
3443 "function must have a single !prof attachment", &
F,
I.second);
3445 case LLVMContext::MD_kcfi_type:
3446 ++NumKCFIAttachments;
3447 Check(NumKCFIAttachments == 1,
3448 "function must have a single !kcfi_type attachment", &
F,
3454 visitMDNode(*
I.second, AllowLocs);
3462 bool isMaterialized =
F.getParent()->isMaterialized();
3463 if (
F.isIntrinsic() && isMaterialized) {
3465 if (
F.hasAddressTaken(&U,
false,
true,
false,
3467 Check(
false,
"Invalid user of intrinsic instruction!", U);
3474 if (IID && (isMaterialized || !
F.materialized_use_empty())) {
3478 raw_string_ostream ErrOS(ErrMsg);
3481 Printable PrintDecl([&
F](raw_ostream &OS) {
F.print(OS); });
3482 Check(IsValid, ErrMsg, PrintDecl);
3489 IID, OverloadTys,
const_cast<Module *
>(
F.getParent()), FT);
3490 Check(ExpectedName ==
F.getName(),
3491 "Intrinsic name not mangled correctly for type arguments! "
3497 auto *
N =
F.getSubprogram();
3498 HasDebugInfo = (
N !=
nullptr);
3506 SmallPtrSet<const MDNode *, 32> Seen;
3518 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3520 DILocalScope *
Scope =
DL->getInlinedAtScope();
3521 Check(Scope,
"Failed to find DILocalScope",
DL);
3523 if (!Seen.
insert(Scope).second)
3527 if (hasDIScopeCycle(Scope))
3530 DISubprogram *
SP =
Scope->getSubprogram();
3534 if ((Scope != SP) && !Seen.
insert(SP).second)
3538 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3542 for (
auto &
I : BB) {
3543 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3545 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3548 if (BrokenDebugInfo)
3555void Verifier::visitBasicBlock(BasicBlock &BB) {
3556 InstsInThisBlock.
clear();
3557 ConvergenceVerifyHelper.
visit(BB);
3568 for (
const PHINode &PN : BB.
phis()) {
3569 Check(PN.getNumIncomingValues() == Preds.size(),
3570 "PHINode should have one entry for each predecessor of its "
3571 "parent basic block!",
3576 Values.reserve(PN.getNumIncomingValues());
3577 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3579 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3582 for (
unsigned i = 0, e =
Values.size(); i != e; ++i) {
3589 "PHI node has multiple entries for the same basic block with "
3590 "different incoming values!",
3596 "PHI node entries do not match predecessors!", &PN,
3597 Values[i].first, Preds[i]);
3605 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3609 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3613void Verifier::visitTerminator(Instruction &
I) {
3615 Check(&
I ==
I.getParent()->getTerminator(),
3616 "Terminator found in the middle of a basic block!",
I.getParent());
3617 visitInstruction(
I);
3620void Verifier::visitCondBrInst(CondBrInst &BI) {
3622 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3623 visitTerminator(BI);
3626void Verifier::visitReturnInst(ReturnInst &RI) {
3629 if (
F->getReturnType()->isVoidTy())
3631 "Found return instr that returns non-void in Function of void "
3633 &RI,
F->getReturnType());
3636 "Function return type does not match operand "
3637 "type of return inst!",
3638 &RI,
F->getReturnType());
3642 visitTerminator(RI);
3645void Verifier::visitSwitchInst(SwitchInst &SI) {
3646 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3649 Type *SwitchTy =
SI.getCondition()->getType();
3650 SmallPtrSet<ConstantInt*, 32>
Constants;
3651 for (
auto &Case :
SI.cases()) {
3653 "Case value is not a constant integer.", &SI);
3654 Check(Case.getCaseValue()->getType() == SwitchTy,
3655 "Switch constants must all be same type as switch value!", &SI);
3657 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3660 visitTerminator(SI);
3663void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3665 "Indirectbr operand must have pointer type!", &BI);
3668 "Indirectbr destinations must all have pointer type!", &BI);
3670 visitTerminator(BI);
3679void Verifier::visitCallBrInst(CallBrInst &CBI) {
3682 "callbr: indirect function / invalid signature");
3684 "callbr for intrinsics currently doesn't support operand bundles");
3688 "callbr currently only supports asm-goto and selected intrinsics");
3693 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3695 verifyInlineAsmCall(CBI);
3697 visitTerminator(CBI);
3700void Verifier::visitSelectInst(SelectInst &SI) {
3703 "Invalid operands for select instruction!", &SI);
3705 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3706 "Select values must have same type as select instruction!", &SI);
3707 visitInstruction(SI);
3713void Verifier::visitUserOp1(Instruction &
I) {
3714 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3717void Verifier::visitTruncInst(TruncInst &
I) {
3719 Type *SrcTy =
I.getOperand(0)->getType();
3720 Type *DestTy =
I.getType();
3729 "trunc source and destination must both be a vector or neither", &
I);
3730 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
3732 visitInstruction(
I);
3735void Verifier::visitZExtInst(ZExtInst &
I) {
3737 Type *SrcTy =
I.getOperand(0)->getType();
3738 Type *DestTy =
I.getType();
3744 "zext source and destination must both be a vector or neither", &
I);
3748 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
3750 visitInstruction(
I);
3753void Verifier::visitSExtInst(SExtInst &
I) {
3755 Type *SrcTy =
I.getOperand(0)->getType();
3756 Type *DestTy =
I.getType();
3765 "sext source and destination must both be a vector or neither", &
I);
3766 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
3768 visitInstruction(
I);
3771void Verifier::visitFPTruncInst(FPTruncInst &
I) {
3773 Type *SrcTy =
I.getOperand(0)->getType();
3774 Type *DestTy =
I.getType();
3782 "fptrunc source and destination must both be a vector or neither", &
I);
3783 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
3785 visitInstruction(
I);
3788void Verifier::visitFPExtInst(FPExtInst &
I) {
3790 Type *SrcTy =
I.getOperand(0)->getType();
3791 Type *DestTy =
I.getType();
3800 "fpext source and destination must both be a vector or neither", &
I);
3801 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
3803 visitInstruction(
I);
3806void Verifier::visitUIToFPInst(UIToFPInst &
I) {
3808 Type *SrcTy =
I.getOperand(0)->getType();
3809 Type *DestTy =
I.getType();
3814 Check(SrcVec == DstVec,
3815 "UIToFP source and dest must both be vector or scalar", &
I);
3817 "UIToFP source must be integer or integer vector", &
I);
3821 if (SrcVec && DstVec)
3824 "UIToFP source and dest vector length mismatch", &
I);
3826 visitInstruction(
I);
3829void Verifier::visitSIToFPInst(SIToFPInst &
I) {
3831 Type *SrcTy =
I.getOperand(0)->getType();
3832 Type *DestTy =
I.getType();
3837 Check(SrcVec == DstVec,
3838 "SIToFP source and dest must both be vector or scalar", &
I);
3840 "SIToFP source must be integer or integer vector", &
I);
3844 if (SrcVec && DstVec)
3847 "SIToFP source and dest vector length mismatch", &
I);
3849 visitInstruction(
I);
3852void Verifier::visitFPToUIInst(FPToUIInst &
I) {
3854 Type *SrcTy =
I.getOperand(0)->getType();
3855 Type *DestTy =
I.getType();
3860 Check(SrcVec == DstVec,
3861 "FPToUI source and dest must both be vector or scalar", &
I);
3864 "FPToUI result must be integer or integer vector", &
I);
3866 if (SrcVec && DstVec)
3869 "FPToUI source and dest vector length mismatch", &
I);
3871 visitInstruction(
I);
3874void Verifier::visitFPToSIInst(FPToSIInst &
I) {
3876 Type *SrcTy =
I.getOperand(0)->getType();
3877 Type *DestTy =
I.getType();
3882 Check(SrcVec == DstVec,
3883 "FPToSI source and dest must both be vector or scalar", &
I);
3886 "FPToSI result must be integer or integer vector", &
I);
3888 if (SrcVec && DstVec)
3891 "FPToSI source and dest vector length mismatch", &
I);
3893 visitInstruction(
I);
3896void Verifier::checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &V) {
3905 Check(VSrc->getElementCount() == VDest->getElementCount(),
3906 "PtrToAddr vector length mismatch", V);
3909 Type *AddrTy =
DL.getAddressType(SrcTy);
3910 Check(AddrTy == DestTy,
"PtrToAddr result must be address width", V);
3913void Verifier::visitPtrToAddrInst(PtrToAddrInst &
I) {
3914 checkPtrToAddr(
I.getOperand(0)->getType(),
I.getType(),
I);
3915 visitInstruction(
I);
3918void Verifier::visitPtrToIntInst(PtrToIntInst &
I) {
3920 Type *SrcTy =
I.getOperand(0)->getType();
3921 Type *DestTy =
I.getType();
3932 Check(VSrc->getElementCount() == VDest->getElementCount(),
3933 "PtrToInt Vector length mismatch", &
I);
3936 visitInstruction(
I);
3939void Verifier::visitIntToPtrInst(IntToPtrInst &
I) {
3941 Type *SrcTy =
I.getOperand(0)->getType();
3942 Type *DestTy =
I.getType();
3952 Check(VSrc->getElementCount() == VDest->getElementCount(),
3953 "IntToPtr Vector length mismatch", &
I);
3955 visitInstruction(
I);
3958void Verifier::visitBitCastInst(BitCastInst &
I) {
3961 "Invalid bitcast", &
I);
3962 visitInstruction(
I);
3965void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
3966 Type *SrcTy =
I.getOperand(0)->getType();
3967 Type *DestTy =
I.getType();
3974 "AddrSpaceCast must be between different address spaces", &
I);
3976 Check(SrcVTy->getElementCount() ==
3978 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
3979 visitInstruction(
I);
3984void Verifier::visitPHINode(PHINode &PN) {
3991 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
4000 "PHI node operands are not the same type as the result!", &PN);
4005 visitInstruction(PN);
4008void Verifier::visitCallBase(CallBase &
Call) {
4010 "Called function must be a pointer!",
Call);
4014 if (FTy->isVarArg())
4016 "Called function requires more parameters than were provided!",
Call);
4019 "Incorrect number of arguments passed to called function!",
Call);
4022 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
4024 "Call parameter type does not match function signature!",
4030 "Attribute after last parameter!",
Call);
4037 "Intrinsic called with incompatible signature",
Call);
4041 "calling convention does not permit calls",
Call);
4047 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
4050 Align ABIAlign =
DL.getABITypeAlign(Ty);
4051 Check(ABIAlign.
value() <= Value::MaximumAlignment,
4052 "Incorrect alignment of " + Message +
" to called function!",
Call);
4056 VerifyTypeAlign(FTy->getReturnType(),
"return type");
4057 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4058 Type *Ty = FTy->getParamType(i);
4059 VerifyTypeAlign(Ty,
"argument passed");
4063 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
4067 "speculatable attribute may not apply to call sites",
Call);
4070 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
4072 "preallocated as a call site attribute can only be on "
4073 "llvm.call.preallocated.arg");
4076 Check(!
Attrs.hasFnAttr(Attribute::DenormalFPEnv),
4077 "denormal_fpenv attribute may not apply to call sites",
Call);
4088 Check(AI->isUsedWithInAlloca(),
4089 "inalloca argument for call has mismatched alloca", AI,
Call);
4095 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4099 Check(AI->isSwiftError(),
4100 "swifterror argument for call has mismatched alloca", AI,
Call);
4104 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
4105 SwiftErrorArg,
Call);
4106 Check(ArgI->hasSwiftErrorAttr(),
4107 "swifterror argument for call has mismatched parameter", ArgI,
4111 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
4114 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
4123 "immarg operand has non-immediate parameter", ArgVal,
Call);
4129 const ConstantRange &CR =
4132 formatv(
"immarg value {} for arg {} out of range {}",
4133 CI->getValue(), i, CR),
4140 formatv(
"immarg value {} for arg {} out of range set",
4150 Check(hasOB != isMustTail,
4151 "preallocated operand either requires a preallocated bundle or "
4152 "the call to be musttail (but not both)",
4157 if (FTy->isVarArg()) {
4159 bool SawNest =
false;
4160 bool SawReturned =
false;
4162 for (
unsigned Idx = 0; Idx < FTy->getNumParams(); ++Idx) {
4163 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
4165 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
4170 for (
unsigned Idx = FTy->getNumParams(); Idx <
Call.
arg_size(); ++Idx) {
4172 AttributeSet ArgAttrs =
Attrs.getParamAttrs(Idx);
4173 verifyParameterAttrs(ArgAttrs, Ty, &
Call);
4176 Check(!SawNest,
"More than one parameter has attribute nest!",
Call);
4181 Check(!SawReturned,
"More than one parameter has attribute returned!",
4184 "Incompatible argument and return types for 'returned' "
4194 "Attribute 'sret' cannot be used for vararg call arguments!",
4199 "inalloca isn't on the last argument!",
Call);
4205 for (
Type *ParamTy : FTy->params()) {
4206 Check(!ParamTy->isMetadataTy(),
4207 "Function has metadata parameter but isn't an intrinsic",
Call);
4208 Check(!ParamTy->isTokenLikeTy(),
4209 "Function has token parameter but isn't an intrinsic",
Call);
4215 Check(!FTy->getReturnType()->isTokenLikeTy(),
4216 "Return type cannot be token for indirect call!");
4217 Check(!FTy->getReturnType()->isX86_AMXTy(),
4218 "Return type cannot be x86_amx for indirect call!");
4222 visitIntrinsicCall(ID,
Call);
4227 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
4228 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
4229 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
4230 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
4231 FoundAttachedCallBundle =
false;
4236 "Operand bundle operands cannot be labels",
Call);
4239 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles",
Call);
4240 FoundDeoptBundle =
true;
4242 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
4244 FoundGCTransitionBundle =
true;
4246 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles",
Call);
4247 FoundFuncletBundle =
true;
4249 "Expected exactly one funclet bundle operand",
Call);
4251 "Funclet bundle operands should correspond to a FuncletPadInst",
4254 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
4256 FoundCFGuardTargetBundle =
true;
4258 "Expected exactly one cfguardtarget bundle operand",
Call);
4260 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles",
Call);
4261 FoundPtrauthBundle =
true;
4263 "Expected exactly two ptrauth bundle operands",
Call);
4265 BU.
Inputs[0]->getType()->isIntegerTy(32),
4266 "Ptrauth bundle key operand must be an i32 constant",
Call);
4268 "Ptrauth bundle discriminator operand must be an i64",
Call);
4270 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles",
Call);
4271 FoundKCFIBundle =
true;
4272 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
4275 BU.
Inputs[0]->getType()->isIntegerTy(32),
4276 "Kcfi bundle operand must be an i32 constant",
Call);
4278 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
4280 FoundPreallocatedBundle =
true;
4282 "Expected exactly one preallocated bundle operand",
Call);
4285 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4286 "\"preallocated\" argument must be a token from "
4287 "llvm.call.preallocated.setup",
4290 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles",
Call);
4291 FoundGCLiveBundle =
true;
4293 Check(!FoundAttachedCallBundle,
4294 "Multiple \"clang.arc.attachedcall\" operand bundles",
Call);
4295 FoundAttachedCallBundle =
true;
4296 verifyAttachedCallBundle(
Call, BU);
4302 "Direct call cannot have a ptrauth bundle",
Call);
4314 "inlinable function call in a function with "
4315 "debug info must have a !dbg location",
4319 verifyInlineAsmCall(
Call);
4323 visitInstruction(
Call);
4326void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
4329 Twine(
"inalloca attribute not allowed in ") +
Context);
4331 Twine(
"inreg attribute not allowed in ") +
Context);
4332 Check(!
Attrs.contains(Attribute::SwiftError),
4333 Twine(
"swifterror attribute not allowed in ") +
Context);
4334 Check(!
Attrs.contains(Attribute::Preallocated),
4335 Twine(
"preallocated attribute not allowed in ") +
Context);
4337 Twine(
"byref attribute not allowed in ") +
Context);
4342 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4343 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4344 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4346 AttrBuilder Copy(
C);
4347 for (
auto AK : ABIAttrs) {
4348 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
4350 Copy.addAttribute(Attr);
4354 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
4355 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
4356 Attrs.hasParamAttr(
I, Attribute::ByRef)))
4357 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
4361void Verifier::verifyMustTailCall(CallInst &CI) {
4365 FunctionType *CallerTy =
F->getFunctionType();
4367 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4368 "cannot guarantee tail call due to mismatched varargs", &CI);
4369 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4370 "cannot guarantee tail call due to mismatched return types", &CI);
4374 "cannot guarantee tail call due to mismatched calling conv", &CI);
4382 Check(Ret,
"musttail call must precede a ret", &CI);
4385 "musttail call result must be returned", Ret);
4387 AttributeList CallerAttrs =
F->getAttributes();
4392 CI.
getCallingConv() == CallingConv::Tail ?
"tailcc" :
"swifttailcc";
4396 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4398 SmallString<32>
Context{CCName, StringRef(
" musttail caller")};
4399 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4401 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
4403 SmallString<32>
Context{CCName, StringRef(
" musttail callee")};
4404 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4407 Check(!CallerTy->isVarArg(), Twine(
"cannot guarantee ") + CCName +
4408 " tail call for varargs function");
4414 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4415 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4416 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4417 Check(CallerTy->getParamType(
I) == CalleeTy->getParamType(
I),
4418 "cannot guarantee tail call due to mismatched parameter types",
4425 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4428 Check(CallerABIAttrs == CalleeABIAttrs,
4429 "cannot guarantee tail call due to mismatched ABI impacting "
4430 "function attributes",
4435void Verifier::visitCallInst(CallInst &CI) {
4439 verifyMustTailCall(CI);
4442void Verifier::visitInvokeInst(InvokeInst &
II) {
4448 II.getUnwindDest()->isEHPad(),
4449 "The unwind destination does not have an exception handling instruction!",
4452 visitTerminator(
II);
4457void Verifier::visitUnaryOperator(UnaryOperator &U) {
4458 Check(
U.getType() ==
U.getOperand(0)->getType(),
4459 "Unary operators must have same type for"
4460 "operands and result!",
4463 switch (
U.getOpcode()) {
4466 case Instruction::FNeg:
4467 Check(
U.getType()->isFPOrFPVectorTy(),
4468 "FNeg operator only works with float types!", &U);
4474 visitInstruction(U);
4480void Verifier::visitBinaryOperator(BinaryOperator &
B) {
4481 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
4482 "Both operands to a binary operator are not of the same type!", &
B);
4484 switch (
B.getOpcode()) {
4487 case Instruction::Add:
4488 case Instruction::Sub:
4489 case Instruction::Mul:
4490 case Instruction::SDiv:
4491 case Instruction::UDiv:
4492 case Instruction::SRem:
4493 case Instruction::URem:
4494 Check(
B.getType()->isIntOrIntVectorTy(),
4495 "Integer arithmetic operators only work with integral types!", &
B);
4496 Check(
B.getType() ==
B.getOperand(0)->getType(),
4497 "Integer arithmetic operators must have same type "
4498 "for operands and result!",
4503 case Instruction::FAdd:
4504 case Instruction::FSub:
4505 case Instruction::FMul:
4506 case Instruction::FDiv:
4507 case Instruction::FRem:
4508 Check(
B.getType()->isFPOrFPVectorTy(),
4509 "Floating-point arithmetic operators only work with "
4510 "floating-point types!",
4512 Check(
B.getType() ==
B.getOperand(0)->getType(),
4513 "Floating-point arithmetic operators must have same type "
4514 "for operands and result!",
4518 case Instruction::And:
4519 case Instruction::Or:
4520 case Instruction::Xor:
4521 Check(
B.getType()->isIntOrIntVectorTy(),
4522 "Logical operators only work with integral types!", &
B);
4523 Check(
B.getType() ==
B.getOperand(0)->getType(),
4524 "Logical operators must have same type for operands and result!", &
B);
4526 case Instruction::Shl:
4527 case Instruction::LShr:
4528 case Instruction::AShr:
4529 Check(
B.getType()->isIntOrIntVectorTy(),
4530 "Shifts only work with integral types!", &
B);
4531 Check(
B.getType() ==
B.getOperand(0)->getType(),
4532 "Shift return type must be same as operands!", &
B);
4538 visitInstruction(
B);
4541void Verifier::visitICmpInst(ICmpInst &IC) {
4545 Check(Op0Ty == Op1Ty,
4546 "Both operands to ICmp instruction are not of the same type!", &IC);
4549 "Invalid operand types for ICmp instruction", &IC);
4553 visitInstruction(IC);
4556void Verifier::visitFCmpInst(FCmpInst &FC) {
4558 Type *Op0Ty =
FC.getOperand(0)->getType();
4559 Type *Op1Ty =
FC.getOperand(1)->getType();
4560 Check(Op0Ty == Op1Ty,
4561 "Both operands to FCmp instruction are not of the same type!", &FC);
4566 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
4568 visitInstruction(FC);
4571void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4573 "Invalid extractelement operands!", &EI);
4574 visitInstruction(EI);
4577void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4580 "Invalid insertelement operands!", &IE);
4581 visitInstruction(IE);
4584void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4586 SV.getShuffleMask()),
4587 "Invalid shufflevector operands!", &SV);
4588 visitInstruction(SV);
4591void Verifier::visitBitInsertInst(BitInsertInst &BII) {
4594 Check(
false, Reason, &BII);
4597 "bitinsert val type cannot be wider than base type!", &BII);
4598 visitInstruction(BII);
4601void Verifier::visitBitExtractInst(BitExtractInst &BEI) {
4604 Check(
false, Reason, &BEI);
4607 "bitextract result type cannot be wider than source type!", &BEI);
4608 visitInstruction(BEI);
4611void Verifier::visitGetElementPtrInst(GetElementPtrInst &
GEP) {
4613 GEP.getModule()->getModuleFlag(
"require-logical-pointer")))
4614 Check(!MD->getZExtValue(),
4615 "Non-logical getelementptr disallowed for this module.");
4617 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4620 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4621 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4624 Check(!STy->isScalableTy(),
4625 "getelementptr cannot target structure that contains scalable vector"
4630 SmallVector<Value *, 16> Idxs(
GEP.indices());
4632 all_of(Idxs, [](
Value *V) {
return V->getType()->isIntOrIntVectorTy(); }),
4633 "GEP indexes must be integers", &
GEP);
4636 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4640 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4641 "GEP is not of right type for indices!", &
GEP, ElTy);
4645 ElementCount GEPWidth = GEPVTy->getElementCount();
4646 if (
GEP.getPointerOperandType()->isVectorTy())
4650 "Vector GEP result width doesn't match operand's", &
GEP);
4651 for (
Value *Idx : Idxs) {
4652 Type *IndexTy = Idx->getType();
4654 ElementCount IndexWidth = IndexVTy->getElementCount();
4655 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4658 "All GEP indices should be of integer type");
4665 GTI != GTE; ++GTI) {
4666 if (GTI.isVector()) {
4667 Type *ElemTy = GTI.getIndexedType();
4668 Check(
DL.typeSizeEqualsStoreSize(ElemTy),
4669 "GEP into vector with non-byte-addressable element type", &
GEP);
4673 Check(
GEP.getAddressSpace() == PtrTy->getAddressSpace(),
4674 "GEP address space doesn't match type", &
GEP);
4676 visitInstruction(
GEP);
4680 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4685void Verifier::verifyRangeLikeMetadata(
const Value &
I,
const MDNode *
Range,
4686 Type *Ty, RangeLikeMetadataKind Kind) {
4687 unsigned NumOperands =
Range->getNumOperands();
4688 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4689 unsigned NumRanges = NumOperands / 2;
4690 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4692 ConstantRange LastRange(1,
true);
4693 for (
unsigned i = 0; i < NumRanges; ++i) {
4696 Check(
Low,
"The lower limit must be an integer!",
Low);
4701 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4704 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4706 "noalias.addrspace type must be i32!", &
I);
4709 "Range types must match instruction type!", &
I);
4712 APInt HighV =
High->getValue();
4713 APInt LowV =
Low->getValue();
4718 "The upper and lower limits cannot be the same value", &
I);
4720 ConstantRange CurRange(LowV, HighV);
4721 Check(!CurRange.isEmptySet() &&
4722 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
4723 !CurRange.isFullSet()),
4724 "Range must not be empty!",
Range);
4726 Check(CurRange.intersectWith(LastRange).isEmptySet(),
4727 "Intervals are overlapping",
Range);
4728 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
4733 LastRange = ConstantRange(LowV, HighV);
4735 if (NumRanges > 2) {
4740 ConstantRange FirstRange(FirstLow, FirstHigh);
4741 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
4742 "Intervals are overlapping",
Range);
4748void Verifier::visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty) {
4750 "precondition violation");
4751 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
4754void Verifier::visitNoFPClassMetadata(Instruction &
I, MDNode *NoFPClass,
4756 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
4757 "nofpclass only applies to floating-point typed loads",
I);
4760 "nofpclass must have exactly one entry", NoFPClass);
4761 ConstantInt *MaskVal =
4764 "nofpclass entry must be a constant i32", NoFPClass);
4766 Check(Val != 0,
"'nofpclass' must have at least one test bit set", NoFPClass,
4770 "Invalid value for 'nofpclass' test mask", NoFPClass,
I);
4773void Verifier::visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
4776 "precondition violation");
4777 verifyRangeLikeMetadata(
I,
Range, Ty,
4778 RangeLikeMetadataKind::NoaliasAddrspace);
4781void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I) {
4782 unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
4783 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
4785 "atomic memory access' operand must have a power-of-two size", Ty,
I);
4788void Verifier::visitLoadInst(LoadInst &LI) {
4790 Check(PTy,
"Load operand must be a pointer.", &LI);
4793 Check(
A->value() <= Value::MaximumAlignment,
4794 "huge alignment values are unsupported", &LI);
4796 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
4799 LI.
getOrdering() != AtomicOrdering::AcquireRelease,
4800 "Load cannot have Release ordering", &LI);
4804 "atomic elementwise load cannot be sequentially consistent.", &LI);
4807 "atomic elementwise load operand must have fixed vector type!", &LI,
4810 checkAtomicMemAccessSize(VecTy->getElementType(), &LI);
4816 "atomic load operand must have integer, byte, pointer, floating "
4817 "point, or vector type!",
4820 checkAtomicMemAccessSize(ElTy, &LI);
4824 "Non-atomic load cannot have SynchronizationScope specified", &LI);
4827 visitInstruction(LI);
4830void Verifier::visitStoreInst(StoreInst &SI) {
4832 Check(PTy,
"Store operand must be a pointer.", &SI);
4833 Type *ElTy =
SI.getOperand(0)->getType();
4834 if (MaybeAlign
A =
SI.getAlign()) {
4835 Check(
A->value() <= Value::MaximumAlignment,
4836 "huge alignment values are unsupported", &SI);
4838 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
4839 if (
SI.isAtomic()) {
4840 Check(
SI.getOrdering() != AtomicOrdering::Acquire &&
4841 SI.getOrdering() != AtomicOrdering::AcquireRelease,
4842 "Store cannot have Acquire ordering", &SI);
4844 if (
SI.isElementwise()) {
4845 Check(
SI.getOrdering() != AtomicOrdering::SequentiallyConsistent,
4846 "atomic elementwise store cannot be sequentially consistent.", &SI);
4850 "atomic elementwise store operand must have fixed vector type!",
4853 checkAtomicMemAccessSize(VecTy->getElementType(), &SI);
4859 "atomic store operand must have integer, byte, pointer, floating "
4860 "point, or vector type!",
4862 checkAtomicMemAccessSize(ElTy, &SI);
4864 Check(!
SI.isElementwise(),
"non-atomic store cannot be elementwise", &SI);
4866 "Non-atomic store cannot have SynchronizationScope specified", &SI);
4868 visitInstruction(SI);
4872void Verifier::verifySwiftErrorCall(CallBase &
Call,
4873 const Value *SwiftErrorVal) {
4875 if (
I.value() == SwiftErrorVal) {
4877 "swifterror value when used in a callsite should be marked "
4878 "with swifterror attribute",
4879 SwiftErrorVal,
Call);
4884void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
4887 for (
const User *U : SwiftErrorVal->
users()) {
4890 "swifterror value can only be loaded and stored from, or "
4891 "as a swifterror argument!",
4895 Check(StoreI->getOperand(1) == SwiftErrorVal,
4896 "swifterror value should be the second operand when used "
4900 verifySwiftErrorCall(*
const_cast<CallBase *
>(
Call), SwiftErrorVal);
4904void Verifier::visitAllocaInst(AllocaInst &AI) {
4907 Check(!MD->getZExtValue(),
4908 "Non-logical alloca disallowed for this module.");
4911 Check(Ty->
isSized(),
"Cannot allocate unsized type", &AI);
4915 "Alloca has illegal target extension type", &AI);
4917 "Alloca array size must have integer type", &AI);
4919 Check(
A->value() <= Value::MaximumAlignment,
4920 "huge alignment values are unsupported", &AI);
4926 "swifterror alloca must not be array allocation", &AI);
4927 verifySwiftErrorValue(&AI);
4930 visitInstruction(AI);
4936void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
4939 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
4940 checkAtomicMemAccessSize(ElTy, &CXI);
4941 visitInstruction(CXI);
4944void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
4946 "atomicrmw instructions cannot be unordered.", &RMWI);
4952 "atomicrmw elementwise cannot be sequentially consistent.", &RMWI);
4954 Check(VecTy,
"atomicrmw elementwise operand must have fixed vector type!",
4957 checkAtomicMemAccessSize(VecTy->getElementType(), &RMWI);
4964 " operand must be an integer type, a floating-point type, a "
4965 "pointer type, or a fixed vector of any of these types!",
4970 " operand must have floating-point or fixed vector of "
4977 " operand must have integer or fixed vector of integer type!",
4980 checkAtomicMemAccessSize(ElTy, &RMWI);
4982 "Invalid binary operation!", &RMWI);
4983 visitInstruction(RMWI);
4986void Verifier::visitFenceInst(FenceInst &FI) {
4988 Check(Ordering == AtomicOrdering::Acquire ||
4989 Ordering == AtomicOrdering::Release ||
4990 Ordering == AtomicOrdering::AcquireRelease ||
4991 Ordering == AtomicOrdering::SequentiallyConsistent,
4992 "fence instructions may only have acquire, release, acq_rel, or "
4993 "seq_cst ordering.",
4995 visitInstruction(FI);
4998void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
5001 "Invalid ExtractValueInst operands!", &EVI);
5003 visitInstruction(EVI);
5006void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
5010 "Invalid InsertValueInst operands!", &IVI);
5012 visitInstruction(IVI);
5017 return FPI->getParentPad();
5022void Verifier::visitEHPadPredecessors(Instruction &
I) {
5028 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
5036 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
5037 "Block containing LandingPadInst must be jumped to "
5038 "only by the unwind edge of an invoke.",
5046 "Block containg CatchPadInst must be jumped to "
5047 "only by its catchswitch.",
5049 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
5050 "Catchswitch cannot unwind to one of its catchpads",
5051 CPI->getCatchSwitch(), CPI);
5063 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
5064 "EH pad must be jumped to via an unwind edge", ToPad,
II);
5067 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
5071 FromPad = Bundle->Inputs[0];
5075 FromPad = CRI->getOperand(0);
5076 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
5080 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
5084 SmallPtrSet<Value *, 8> Seen;
5086 Check(FromPad != ToPad,
5087 "EH pad cannot handle exceptions raised within it", FromPad, TI);
5088 if (FromPad == ToPadParent) {
5093 "A single unwind edge may only enter one EH pad", TI);
5094 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
5100 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
5105void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
5109 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
5111 visitEHPadPredecessors(LPI);
5113 if (!LandingPadResultTy)
5114 LandingPadResultTy = LPI.
getType();
5117 "The landingpad instruction should have a consistent result type "
5118 "inside a function.",
5122 Check(
F->hasPersonalityFn(),
5123 "LandingPadInst needs to be in a function with a personality.", &LPI);
5128 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
5134 "Catch operand does not have pointer type!", &LPI);
5136 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
5138 "Filter operand is not an array of constants!", &LPI);
5142 visitInstruction(LPI);
5145void Verifier::visitResumeInst(ResumeInst &RI) {
5147 "ResumeInst needs to be in a function with a personality.", &RI);
5149 if (!LandingPadResultTy)
5153 "The resume instruction should have a consistent result type "
5154 "inside a function.",
5157 visitTerminator(RI);
5160void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
5164 Check(
F->hasPersonalityFn(),
5165 "CatchPadInst needs to be in a function with a personality.", &CPI);
5168 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
5174 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
5179 return isa<Constant>(V) || isa<AllocaInst>(V);
5181 "Argument operand must be alloca or constant.", &CPI);
5183 visitEHPadPredecessors(CPI);
5184 visitFuncletPadInst(CPI);
5187void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
5189 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
5192 visitTerminator(CatchReturn);
5195void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
5199 Check(
F->hasPersonalityFn(),
5200 "CleanupPadInst needs to be in a function with a personality.", &CPI);
5205 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
5209 "CleanupPadInst has an invalid parent.", &CPI);
5211 visitEHPadPredecessors(CPI);
5212 visitFuncletPadInst(CPI);
5215void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
5216 User *FirstUser =
nullptr;
5217 Value *FirstUnwindPad =
nullptr;
5219 SmallPtrSet<FuncletPadInst *, 8> Seen;
5221 while (!Worklist.empty()) {
5222 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
5224 "FuncletPadInst must not be nested within itself", CurrentPad);
5225 Value *UnresolvedAncestorPad =
nullptr;
5226 for (User *U : CurrentPad->
users()) {
5229 UnwindDest = CRI->getUnwindDest();
5235 if (CSI->unwindsToCaller())
5237 UnwindDest = CSI->getUnwindDest();
5239 UnwindDest =
II->getUnwindDest();
5249 Worklist.push_back(CPI);
5264 if (UnwindParent == CurrentPad)
5270 Value *ExitedPad = CurrentPad;
5273 if (ExitedPad == &FPI) {
5278 UnresolvedAncestorPad = &FPI;
5282 if (ExitedParent == UnwindParent) {
5286 UnresolvedAncestorPad = ExitedParent;
5289 ExitedPad = ExitedParent;
5295 UnresolvedAncestorPad = &FPI;
5302 Check(UnwindPad == FirstUnwindPad,
5303 "Unwind edges out of a funclet "
5304 "pad must have the same unwind "
5306 &FPI, U, FirstUser);
5309 FirstUnwindPad = UnwindPad;
5318 if (CurrentPad != &FPI)
5321 if (UnresolvedAncestorPad) {
5322 if (CurrentPad == UnresolvedAncestorPad) {
5326 assert(CurrentPad == &FPI);
5334 Value *ResolvedPad = CurrentPad;
5335 while (!Worklist.empty()) {
5336 Value *UnclePad = Worklist.back();
5340 while (ResolvedPad != AncestorPad) {
5342 if (ResolvedParent == UnresolvedAncestorPad) {
5345 ResolvedPad = ResolvedParent;
5349 if (ResolvedPad != AncestorPad)
5352 Worklist.pop_back();
5357 if (FirstUnwindPad) {
5359 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5360 Value *SwitchUnwindPad;
5361 if (SwitchUnwindDest)
5365 Check(SwitchUnwindPad == FirstUnwindPad,
5366 "Unwind edges out of a catch must have the same unwind dest as "
5367 "the parent catchswitch",
5368 &FPI, FirstUser, CatchSwitch);
5372 visitInstruction(FPI);
5375void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5379 Check(
F->hasPersonalityFn(),
5380 "CatchSwitchInst needs to be in a function with a personality.",
5386 "CatchSwitchInst not the first non-PHI instruction in the block.",
5391 "CatchSwitchInst has an invalid parent.", ParentPad);
5396 "CatchSwitchInst must unwind to an EH block which is not a "
5402 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5406 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5408 for (BasicBlock *Handler : CatchSwitch.
handlers()) {
5410 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5413 visitEHPadPredecessors(CatchSwitch);
5414 visitTerminator(CatchSwitch);
5417void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5419 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5425 "CleanupReturnInst must unwind to an EH block which is not a "
5430 visitTerminator(CRI);
5433void Verifier::verifyDominatesUse(Instruction &
I,
unsigned i) {
5439 if (
II->getNormalDest() ==
II->getUnwindDest())
5453 const Use &
U =
I.getOperandUse(i);
5454 Check(DT.dominates(
Op, U),
"Instruction does not dominate all uses!",
Op, &
I);
5457void Verifier::visitDereferenceableMetadata(Instruction&
I, MDNode* MD) {
5458 Check(
I.getType()->isPointerTy(),
5459 "dereferenceable, dereferenceable_or_null "
5460 "apply only to pointer types",
5463 "dereferenceable, dereferenceable_or_null apply only to load"
5464 " and inttoptr instructions, use attributes for calls or invokes",
5467 "dereferenceable, dereferenceable_or_null "
5468 "take one operand!",
5473 "dereferenceable_or_null metadata value must be an i64!",
5477void Verifier::visitNoFreeObjMetadata(Instruction &
I, MDNode *MD) {
5478 Check(
I.getType()->isPointerTy(),
"nofreeobj applies only to pointer types",
5481 "nofreeobj applies only to inttoptr instruction", &
I);
5485void Verifier::visitProfMetadata(Instruction &
I, MDNode *MD) {
5486 auto GetBranchingTerminatorNumOperands = [&]() {
5487 unsigned ExpectedNumOperands = 0;
5491 ExpectedNumOperands =
SI->getNumSuccessors();
5493 ExpectedNumOperands = 1;
5495 ExpectedNumOperands = IBI->getNumDestinations();
5497 ExpectedNumOperands = 2;
5500 return ExpectedNumOperands;
5503 "!prof annotations should have at least 1 operand", MD);
5505 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
5507 "expected string with name of the !prof annotation", MD);
5513 "'unknown' !prof should only appear on instructions on which "
5514 "'branch_weights' would",
5516 verifyUnknownProfileMetadata(MD);
5521 "!prof annotations should have no less than 2 operands", MD);
5527 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5528 "Wrong number of InvokeInst branch_weights operands", MD);
5530 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5531 if (ExpectedNumOperands == 0)
5532 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
5535 Check(NumBranchWeights == ExpectedNumOperands,
"Wrong number of operands",
5541 Check(MDO,
"second operand should not be null", MD);
5543 "!prof brunch_weights operand is not a const int");
5548 Check(KindInt,
"VP !prof missing kind argument", MD);
5551 Check(Kind >= InstrProfValueKind::IPVK_First &&
5552 Kind <= InstrProfValueKind::IPVK_Last,
5553 "Invalid VP !prof kind", MD);
5555 "VP !prof should have an even number "
5556 "of arguments after 'VP'",
5558 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5559 Kind == InstrProfValueKind::IPVK_MemOPSize)
5561 "VP !prof indirect call or memop size expected to be applied to "
5562 "CallBase instructions only",
5565 DenseSet<uint64_t> ProfileValues;
5567 ConstantInt *ProfileValue =
5569 Check(ProfileValue,
"VP !prof value operand is not a const int", MD);
5571 auto [ValueIt,
Inserted] = ProfileValues.
insert(ProfileValueInt);
5572 Check(Inserted,
"VP !prof should not have duplicate profile values", MD);
5575 CheckFailed(
"expected either branch_weights or VP profile name", MD);
5579void Verifier::visitDIAssignIDMetadata(Instruction &
I, MDNode *MD) {
5580 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
5585 bool ExpectedInstTy =
5587 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
5592 for (
auto *User : AsValue->users()) {
5594 "!DIAssignID should only be used by llvm.dbg.assign intrinsics",
5598 CheckDI(DAI->getFunction() ==
I.getFunction(),
5599 "dbg.assign not in same function as inst", DAI, &
I);
5603 CheckDI(DVR->getFunction() ==
I.getFunction(),
5604 "DVRAssign not in same function as inst", DVR, &
I);
5607void Verifier::visitMMRAMetadata(Instruction &
I, MDNode *MD) {
5609 "!mmra metadata attached to unexpected instruction kind",
I, MD);
5620 for (
const MDOperand &MDOp : MD->
operands())
5622 "!mmra metadata tuple operand is not an MMRA tag",
I, MDOp.get());
5625void Verifier::visitCallStackMetadata(MDNode *MD) {
5629 "call stack metadata should have at least 1 operand", MD);
5633 "call stack metadata operand should be constant integer",
Op);
5636void Verifier::visitMemProfMetadata(Instruction &
I, MDNode *MD) {
5639 Check(
I.hasMetadata(LLVMContext::MD_callsite),
5640 "!memprof metadata requires !callsite metadata", &
I, MD);
5642 "!memprof annotations should have at least 1 metadata operand "
5647 for (
auto &MIBOp : MD->
operands()) {
5652 Check(MIB->getNumOperands() >= 2,
5653 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5656 Check(MIB->getOperand(0) !=
nullptr,
5657 "!memprof MemInfoBlock first operand should not be null", MIB);
5659 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5661 visitCallStackMetadata(StackMD);
5665 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5668 for (
unsigned I = 2;
I < MIB->getNumOperands(); ++
I) {
5670 Check(OpNode,
"Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5672 Check(OpNode->getNumOperands() == 2,
5673 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5678 [](
const MDOperand &
Op) {
5679 return mdconst::hasa<ConstantInt>(Op);
5681 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5682 "ConstantInt operands",
5688void Verifier::visitCallsiteMetadata(Instruction &
I, MDNode *MD) {
5692 visitCallStackMetadata(MD);
5695void Verifier::visitCalleeTypeMetadata(Instruction &
I, MDNode *MD) {
5700 "The callee_type metadata must be a list of callgraph metadata nodes",
5703 Check(CallgraphMD->getNumOperands() == 1,
5704 "Well-formed callgraph metadata must contain exactly one "
5708 "The operand of callgraph metadata for functions must be an MDString",
5713void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5716 "annotation must have at least one operand");
5718 bool TupleOfStrings =
5724 "operands must be a string or a tuple of strings");
5728void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
5733 "first scope operand must be self-referential or string", MD);
5736 "third scope operand must be string (if used)", MD);
5739 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
5741 unsigned NumDomainOps =
Domain->getNumOperands();
5742 Check(NumDomainOps >= 2 && NumDomainOps <= 3,
5743 "domain must have two or three operands",
Domain);
5746 "first domain operand must be self-referential or string",
Domain);
5747 const auto *Disjoint =
5749 Check(Disjoint && Disjoint->getBitWidth() == 1,
5750 "second domain operand must be an i1 constant",
Domain);
5751 if (NumDomainOps == 3)
5753 "third domain operand must be string (if used)",
Domain);
5756void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
5759 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
5760 visitAliasScopeMetadata(OpMD);
5764void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
5765 auto IsValidAccessScope = [](
const MDNode *MD) {
5780 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
5781 Check(IsValidAccessScope(OpMD),
5782 "Access scope list contains invalid access scope", MD);
5786void Verifier::visitCapturesMetadata(Instruction &
I,
const MDNode *Captures) {
5787 static const char *ValidArgs[] = {
"address_is_null",
"address",
5788 "read_provenance",
"provenance"};
5791 Check(SI,
"!captures metadata can only be applied to store instructions", &
I);
5792 Check(
SI->getValueOperand()->getType()->isPointerTy(),
5793 "!captures metadata can only be applied to store with value operand of "
5801 Check(Str,
"!captures metadata must be a list of strings", &
I);
5803 "invalid entry in !captures metadata", &
I, Str);
5807void Verifier::visitAllocTokenMetadata(Instruction &
I, MDNode *MD) {
5812 "expected integer constant", MD);
5815void Verifier::visitInlineHistoryMetadata(Instruction &
I, MDNode *MD) {
5824 ->stripPointerCastsAndAliases()),
5825 "!inline_history operands must be functions or null", MD);
5829void Verifier::visitMemCacheHintMetadata(Instruction &
I, MDNode *MD) {
5830 Check(
I.mayReadOrWriteMemory(),
5831 "!mem.cache_hint is only valid on memory operations", &
I);
5834 "!mem.cache_hint must have even number of operands "
5835 "(operand_no, hint_node pairs)",
5841 "!mem.cache_hint is not supported on non-intrinsic calls", &
I);
5843 unsigned NumOperands = CB ? CB->arg_size() :
I.getNumOperands();
5845 SmallDenseSet<unsigned, 4> SeenOperandNos;
5846 std::optional<uint64_t> LastOperandNo;
5852 "!mem.cache_hint must alternate between i32 operand numbers and "
5853 "metadata hint nodes",
5856 Check(OpNoCI->getValue().isNonNegative(),
5857 "!mem.cache_hint operand number must be non-negative", MD);
5859 uint64_t OperandNo = OpNoCI->getZExtValue();
5860 Check(OperandNo < NumOperands,
5861 "!mem.cache_hint operand number is out of range", &
I);
5864 CB ? CB->getArgOperand(OperandNo) :
I.getOperand(OperandNo);
5866 "!mem.cache_hint operand number must refer to a pointer operand", &
I);
5869 Check(Inserted,
"!mem.cache_hint contains duplicate operand number", MD);
5871 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
5872 "!mem.cache_hint operand numbers must be in increasing order", MD);
5873 LastOperandNo = OperandNo;
5877 "!mem.cache_hint must alternate between i32 operand numbers and "
5878 "metadata hint nodes",
5882 "!mem.cache_hint hint node must have even number of operands "
5883 "(key-value pairs)",
5886 StringSet<> SeenKeys;
5887 for (
unsigned K = 0;
K + 1 <
Node->getNumOperands();
K += 2) {
5889 Check(
Key,
"!mem.cache_hint key must be a string", Node);
5891 StringRef KeyStr =
Key->getString();
5893 "!mem.cache_hint hint node contains duplicate key", Node);
5898 "!mem.cache_hint value must be a string or integer", Node);
5905void Verifier::visitInstruction(Instruction &
I) {
5907 Check(BB,
"Instruction not embedded in basic block!", &
I);
5910 for (User *U :
I.users()) {
5911 Check(U != (User *)&
I || !DT.isReachableFromEntry(BB),
5912 "Only PHI nodes may reference their own value!", &
I);
5917 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
5918 "Instruction has a name, but provides a void value!", &
I);
5922 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
5923 "Instruction returns a non-scalar type!", &
I);
5928 "Invalid use of metadata!", &
I);
5933 for (Use &U :
I.uses()) {
5936 "Instruction referencing"
5937 " instruction not embedded in a basic block!",
5940 CheckFailed(
"Use of instruction is not an instruction!", U);
5949 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i) {
5950 Check(
I.getOperand(i) !=
nullptr,
"Instruction has null operand!", &
I);
5954 if (!
I.getOperand(i)->getType()->isFirstClassType()) {
5955 Check(
false,
"Instruction operands must be first-class values!", &
I);
5961 auto IsAttachedCallOperand = [](
Function *
F,
const CallBase *CBI,
5963 return CBI && CBI->isOperandBundleOfType(
5971 Check((!
F->isIntrinsic() ||
5972 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i)) ||
5973 IsAttachedCallOperand(
F, CBI, i)),
5974 "Cannot take the address of an intrinsic!", &
I);
5976 F->getIntrinsicID() == Intrinsic::donothing ||
5977 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
5978 F->getIntrinsicID() == Intrinsic::seh_try_end ||
5979 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
5980 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
5981 F->getIntrinsicID() == Intrinsic::coro_resume ||
5982 F->getIntrinsicID() == Intrinsic::coro_destroy ||
5983 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
5984 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
5985 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
5986 F->getIntrinsicID() ==
5987 Intrinsic::experimental_patchpoint_void ||
5988 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
5989 F->getIntrinsicID() == Intrinsic::fake_use ||
5990 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
5991 F->getIntrinsicID() == Intrinsic::wasm_throw ||
5992 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
5993 IsAttachedCallOperand(
F, CBI, i),
5994 "Cannot invoke an intrinsic other than donothing, patchpoint, "
5995 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall or "
5998 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
5999 &M,
F,
F->getParent());
6002 "Referring to a basic block in another function!", &
I);
6005 "Referring to an argument in another function!", &
I);
6007 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
6011 "Referring to an instruction in another function!", &
I);
6012 verifyDominatesUse(
I, i);
6014 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i),
6015 "Cannot take the address of an inline asm!", &
I);
6017 visitConstantExprsRecursively(
C);
6021 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_fpmath)) {
6023 "fpmath requires a floating point result!", &
I);
6025 if (ConstantFP *CFP0 =
6027 const APFloat &Accuracy = CFP0->getValueAPF();
6029 "fpmath accuracy must have float type", &
I);
6031 "fpmath accuracy not a positive number!", &
I);
6033 Check(
false,
"invalid fpmath accuracy!", &
I);
6037 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_range)) {
6039 "Ranges are only for loads, calls and invokes!", &
I);
6040 visitRangeMetadata(
I,
Range,
I.getType());
6043 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofpclass)) {
6045 visitNoFPClassMetadata(
I, MD,
I.getType());
6048 if (MDNode *
Range =
I.getMetadata(LLVMContext::MD_noalias_addrspace)) {
6051 "noalias.addrspace are only for memory operations!", &
I);
6052 visitNoaliasAddrspaceMetadata(
I,
Range,
I.getType());
6055 if (
I.hasMetadata(LLVMContext::MD_invariant_group)) {
6057 "invariant.group metadata is only for loads and stores", &
I);
6060 if (
I.hasMetadata(LLVMContext::MD_invariant_load)) {
6063 "invariant.load metadata is only for loads and readonly "
6068 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nonnull)) {
6069 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
6072 "nonnull applies only to load instructions, use attributes"
6073 " for calls or invokes",
6078 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noundef)) {
6083 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable))
6084 visitDereferenceableMetadata(
I, MD);
6086 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_dereferenceable_or_null))
6087 visitDereferenceableMetadata(
I, MD);
6089 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_nofreeobj))
6090 visitNoFreeObjMetadata(
I, MD);
6092 if (MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa))
6095 if (MDNode *TBAAStruct =
I.getMetadata(LLVMContext::MD_tbaa_struct))
6098 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_noalias))
6099 visitAliasScopeListMetadata(MD);
6100 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alias_scope))
6101 visitAliasScopeListMetadata(MD);
6103 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_access_group))
6104 visitAccessGroupMetadata(MD);
6106 if (MDNode *AlignMD =
I.getMetadata(LLVMContext::MD_align)) {
6107 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
6110 "align applies only to load instructions, "
6111 "use attributes for calls or invokes",
6113 Check(AlignMD->getNumOperands() == 1,
"align takes one operand!", &
I);
6116 "align metadata value must be an i64!", &
I);
6120 Check(Align <= Value::MaximumAlignment,
6121 "alignment is larger that implementation defined limit", &
I);
6124 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_prof))
6125 visitProfMetadata(
I, MD);
6127 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_memprof))
6128 visitMemProfMetadata(
I, MD);
6130 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callsite))
6131 visitCallsiteMetadata(
I, MD);
6133 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_callee_type))
6134 visitCalleeTypeMetadata(
I, MD);
6136 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_DIAssignID))
6137 visitDIAssignIDMetadata(
I, MD);
6139 if (MDNode *MMRA =
I.getMetadata(LLVMContext::MD_mmra))
6140 visitMMRAMetadata(
I, MMRA);
6142 if (MDNode *Annotation =
I.getMetadata(LLVMContext::MD_annotation))
6143 visitAnnotationMetadata(Annotation);
6145 if (MDNode *Captures =
I.getMetadata(LLVMContext::MD_captures))
6146 visitCapturesMetadata(
I, Captures);
6148 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_alloc_token))
6149 visitAllocTokenMetadata(
I, MD);
6151 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_inline_history))
6152 visitInlineHistoryMetadata(
I, MD);
6154 if (MDNode *MD =
I.getMetadata(LLVMContext::MD_mem_cache_hint))
6155 visitMemCacheHintMetadata(
I, MD);
6157 if (MDNode *MD =
I.getMetadata(
"amdgpu.expected.active.lanes")) {
6159 "!amdgpu.expected.active.lanes must have exactly one operand", &
I,
6164 "!amdgpu.expected.active.lanes operand must be an i32 constant", &
I,
6168 if (MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
6170 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
6173 if (
DL->getAtomGroup()) {
6175 CheckDI(SP &&
SP->getKeyInstructionsEnabled(),
6176 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
6177 "Instructions enabled",
6184 I.getAllMetadata(MDs);
6185 for (
auto Attachment : MDs) {
6186 unsigned Kind = Attachment.first;
6188 (
Kind == LLVMContext::MD_dbg ||
Kind == LLVMContext::MD_loop)
6189 ? AreDebugLocsAllowed::Yes
6190 : AreDebugLocsAllowed::
No;
6191 visitMDNode(*Attachment.second, AllowLocs);
6208 "const x86_amx is not allowed in argument!");
6214 case Intrinsic::assume: {
6218 "assume with operand bundles must have i1 true condition",
Call);
6224 auto GetTypeAt = [&](
unsigned Index) {
6225 return OBU.Inputs[
Index]->getType();
6230 CheckFailed(
"tags must be valid attribute names",
Call);
6232 case BundleAttr::Align:
6233 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
6234 "alignment assumptions should have 2 or 3 arguments",
Call);
6237 Check(GetTypeAt(1)->isIntegerTy() &&
6238 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6239 "second argument should be an integer with a maximum width of 64 "
6242 Check(OBU.Inputs.size() < 3 ||
6243 (GetTypeAt(2)->isIntegerTy() &&
6244 GetTypeAt(2)->getIntegerBitWidth() <= 64),
6245 "third argument should be an integer with a maximum width of 64 "
6249 case BundleAttr::Cold:
6250 Check(OBU.Inputs.size() == 0,
6251 "cold assumptions should have no arguments",
Call);
6253 case BundleAttr::Dereferenceable:
6254 case BundleAttr::DereferenceableOrNull:
6255 Check(OBU.Inputs.size() == 2,
6256 "dereferenceable assumptions should have 2 arguments",
Call);
6259 Check(GetTypeAt(1)->isIntegerTy() &&
6260 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6261 "second argument should be an integer with a maximum width of 64 "
6265 case BundleAttr::Ignore:
6267 case BundleAttr::NonNull:
6268 Check(OBU.Inputs.size() == 1,
6269 "nonnull assumptions should have 1 argument",
Call);
6273 case BundleAttr::NoUndef:
6274 Check(OBU.Inputs.size() == 1,
6275 "noundef assumptions should have 1 argument",
Call);
6277 case BundleAttr::SeparateStorage:
6278 Check(OBU.Inputs.size() == 2,
6279 "separate_storage assumptions should have 2 arguments",
Call);
6281 "arguments to separate_storage assumptions should be pointers",
6288 case Intrinsic::ucmp:
6289 case Intrinsic::scmp: {
6294 "result type must be at least 2 bits wide",
Call);
6296 bool IsDestTypeVector = DestTy->
isVectorTy();
6298 "ucmp/scmp argument and result types must both be either vector or "
6301 if (IsDestTypeVector) {
6304 Check(SrcVecLen == DestVecLen,
6305 "return type and arguments must have the same number of "
6311 case Intrinsic::coro_begin:
6312 case Intrinsic::coro_begin_custom_abi:
6314 "id argument of llvm.coro.begin must refer to coro.id");
6316 case Intrinsic::coro_id: {
6318 "align argument only accepts constants");
6321 "promise argument must refer to an alloca");
6326 "coro argument must refer to a function");
6330 if (BeforeCoroSplit)
6333 Check(!BeforeCoroEarly,
"cannot run CoroSplit before CoroEarly");
6336 "info argument of llvm.coro.id must refer to an initialized "
6340 "info argument of llvm.coro.id must refer to either a struct or "
6344 case Intrinsic::is_fpclass: {
6347 "unsupported bits for llvm.is.fpclass test mask");
6350 case Intrinsic::fptrunc_round: {
6355 MD = MAV->getMetadata();
6357 Check(MD !=
nullptr,
"missing rounding mode argument",
Call);
6360 (
"invalid value for llvm.fptrunc.round metadata operand"
6361 " (the operand should be a string)"),
6364 std::optional<RoundingMode> RoundMode =
6366 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6367 "unsupported rounding mode argument",
Call);
6370 case Intrinsic::convert_to_arbitrary_fp: {
6378 "if floating-point operand is a vector, integer operand must also "
6381 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6382 "floating-point and integer vector operands must have the same "
6389 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6391 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6392 StringRef Interp = InterpStr->getString();
6394 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6399 "unsupported interpretation metadata string",
Call);
6402 if (
unsigned FormatBits =
6405 "integer type bit width must equal the arbitrary FP format width",
6410 Check(RoundingMAV,
"missing rounding mode metadata operand",
Call);
6412 Check(RoundingStr,
"rounding mode metadata operand must be a string",
Call);
6414 std::optional<RoundingMode>
RM =
6416 Check(RM && *RM != RoundingMode::Dynamic,
6417 "unsupported rounding mode argument",
Call);
6420 case Intrinsic::convert_from_arbitrary_fp: {
6428 "if floating-point operand is a vector, integer operand must also "
6431 Check(ValueVecTy->getElementCount() == IntVecTy->getElementCount(),
6432 "floating-point and integer vector operands must have the same "
6439 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6441 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6442 StringRef Interp = InterpStr->getString();
6444 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6449 "unsupported interpretation metadata string",
Call);
6452 if (
unsigned FormatBits =
6455 "integer type bit width must equal the arbitrary FP format width",
6459#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6460#include "llvm/IR/VPIntrinsics.def"
6461#undef BEGIN_REGISTER_VP_INTRINSIC
6464#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6465 case Intrinsic::INTRINSIC:
6466#include "llvm/IR/ConstrainedOps.def"
6470 case Intrinsic::dbg_declare:
6471 case Intrinsic::dbg_value:
6472 case Intrinsic::dbg_assign:
6473 case Intrinsic::dbg_label:
6480 case Intrinsic::memcpy:
6481 case Intrinsic::memcpy_inline:
6482 case Intrinsic::memmove:
6483 case Intrinsic::memset:
6484 case Intrinsic::memset_inline:
6486 case Intrinsic::experimental_memset_pattern: {
6488 Check(Memset->getValue()->getType()->isSized(),
6489 "unsized types cannot be used as memset patterns",
Call);
6492 case Intrinsic::memcpy_element_unordered_atomic:
6493 case Intrinsic::memmove_element_unordered_atomic:
6494 case Intrinsic::memset_element_unordered_atomic: {
6497 ConstantInt *ElementSizeCI =
6499 const APInt &ElementSizeVal = ElementSizeCI->
getValue();
6501 "element size of the element-wise atomic memory intrinsic "
6502 "must be a power of 2",
6505 auto IsValidAlignment = [&](MaybeAlign
Alignment) {
6508 Check(IsValidAlignment(AMI->getDestAlign()),
6509 "incorrect alignment of the destination argument",
Call);
6511 Check(IsValidAlignment(AMT->getSourceAlign()),
6512 "incorrect alignment of the source argument",
Call);
6516 case Intrinsic::call_preallocated_setup: {
6518 bool FoundCall =
false;
6521 Check(UseCall !=
nullptr,
6522 "Uses of llvm.call.preallocated.setup must be calls");
6524 if (IID == Intrinsic::call_preallocated_arg) {
6526 Check(AllocArgIndex !=
nullptr,
6527 "llvm.call.preallocated.alloc arg index must be a constant");
6528 auto AllocArgIndexInt = AllocArgIndex->getValue();
6529 Check(AllocArgIndexInt.sge(0) &&
6530 AllocArgIndexInt.slt(NumArgs->getValue()),
6531 "llvm.call.preallocated.alloc arg index must be between 0 and "
6533 "llvm.call.preallocated.setup's argument count");
6534 }
else if (IID == Intrinsic::call_preallocated_teardown) {
6537 Check(!FoundCall,
"Can have at most one call corresponding to a "
6538 "llvm.call.preallocated.setup");
6540 size_t NumPreallocatedArgs = 0;
6541 for (
unsigned i = 0; i < UseCall->arg_size(); i++) {
6542 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6543 ++NumPreallocatedArgs;
6546 Check(NumPreallocatedArgs != 0,
6547 "cannot use preallocated intrinsics on a call without "
6548 "preallocated arguments");
6549 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6550 "llvm.call.preallocated.setup arg size must be equal to number "
6551 "of preallocated arguments "
6561 auto PreallocatedBundle =
6563 Check(PreallocatedBundle,
6564 "Use of llvm.call.preallocated.setup outside intrinsics "
6565 "must be in \"preallocated\" operand bundle");
6566 Check(PreallocatedBundle->Inputs.front().get() == &
Call,
6567 "preallocated bundle must have token from corresponding "
6568 "llvm.call.preallocated.setup");
6573 case Intrinsic::call_preallocated_arg: {
6576 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6577 "llvm.call.preallocated.arg token argument must be a "
6578 "llvm.call.preallocated.setup");
6580 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6581 "call site attribute");
6584 case Intrinsic::call_preallocated_teardown: {
6587 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6588 "llvm.call.preallocated.teardown token argument must be a "
6589 "llvm.call.preallocated.setup");
6592 case Intrinsic::gcroot:
6593 case Intrinsic::gcwrite:
6594 case Intrinsic::gcread:
6595 if (ID == Intrinsic::gcroot) {
6598 Check(AI,
"llvm.gcroot parameter #1 must be an alloca.",
Call);
6600 "llvm.gcroot parameter #2 must be a constant.",
Call);
6603 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6604 "or argument #2 must be a non-null constant.",
6610 "Enclosing function does not use GC.",
Call);
6612 case Intrinsic::init_trampoline:
6614 "llvm.init_trampoline parameter #2 must resolve to a function.",
6617 case Intrinsic::reloc_none: {
6620 "llvm.reloc.none argument must be a metadata string", &
Call);
6623 case Intrinsic::stackprotector:
6625 "llvm.stackprotector parameter #2 must resolve to an alloca.",
Call);
6627 case Intrinsic::localescape: {
6631 Check(!SawFrameEscape,
"multiple calls to llvm.localescape in one function",
6638 "llvm.localescape only accepts static allocas",
Call);
6641 SawFrameEscape =
true;
6644 case Intrinsic::localrecover: {
6647 Check(Fn && !Fn->isDeclaration(),
6648 "llvm.localrecover first "
6649 "argument must be function defined in this module",
6652 auto &
Entry = FrameEscapeInfo[Fn];
6653 Entry.second = unsigned(
6654 std::max(
uint64_t(
Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6658 case Intrinsic::experimental_gc_statepoint:
6660 Check(!CI->isInlineAsm(),
6661 "gc.statepoint support for inline assembly unimplemented", CI);
6663 "Enclosing function does not use GC.",
Call);
6665 verifyStatepoint(
Call);
6667 case Intrinsic::experimental_gc_result: {
6669 "Enclosing function does not use GC.",
Call);
6677 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6678 Intrinsic::experimental_gc_statepoint,
6679 "gc.result operand #1 must be from a statepoint",
Call,
6683 auto *TargetFuncType =
6686 "gc.result result type does not match wrapped callee",
Call);
6689 case Intrinsic::experimental_gc_relocate: {
6693 "gc.relocate must return a pointer or a vector of pointers",
Call);
6701 LandingPad->getParent()->getUniquePredecessor();
6705 Check(InvokeBB,
"safepoints should have unique landingpads",
6706 LandingPad->getParent());
6710 "gc relocate should be linked to a statepoint", InvokeBB);
6717 "gc relocate is incorrectly tied to the statepoint",
Call, Token);
6726 "gc.relocate operand #2 must be integer offset",
Call);
6730 "gc.relocate operand #3 must be integer offset",
Call);
6740 Check(BaseIndex < Opt->Inputs.size(),
6741 "gc.relocate: statepoint base index out of bounds",
Call);
6742 Check(DerivedIndex < Opt->Inputs.size(),
6743 "gc.relocate: statepoint derived index out of bounds",
Call);
6756 "gc.relocate: relocated value must be a pointer",
Call);
6757 Check(DerivedType->isPtrOrPtrVectorTy(),
6758 "gc.relocate: relocated value must be a pointer",
Call);
6760 Check(ResultType->isVectorTy() == DerivedType->isVectorTy(),
6761 "gc.relocate: vector relocates to vector and pointer to pointer",
6764 ResultType->getPointerAddressSpace() ==
6765 DerivedType->getPointerAddressSpace(),
6766 "gc.relocate: relocating a pointer shouldn't change its address space",
6770 Check(GC,
"gc.relocate: calling function must have GCStrategy",
6773 auto isGCPtr = [&
GC](
Type *PTy) {
6774 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(
true);
6776 Check(isGCPtr(ResultType),
"gc.relocate: must return gc pointer",
Call);
6778 "gc.relocate: relocated value must be a gc pointer",
Call);
6779 Check(isGCPtr(DerivedType),
6780 "gc.relocate: relocated value must be a gc pointer",
Call);
6784 case Intrinsic::experimental_patchpoint: {
6787 "patchpoint: invalid return type used with anyregcc",
Call);
6791 case Intrinsic::eh_exceptioncode:
6792 case Intrinsic::eh_exceptionpointer: {
6794 "eh.exceptionpointer argument must be a catchpad",
Call);
6797 case Intrinsic::get_active_lane_mask: {
6800 "get_active_lane_mask: element type is not i1",
Call);
6803 case Intrinsic::experimental_get_vector_length: {
6805 Check(!VF->isNegative() && !VF->isZero(),
6806 "get_vector_length: VF must be positive",
Call);
6809 case Intrinsic::experimental_guard: {
6812 "experimental_guard must have exactly one "
6813 "\"deopt\" operand bundle");
6817 case Intrinsic::experimental_deoptimize: {
6821 "experimental_deoptimize must have exactly one "
6822 "\"deopt\" operand bundle");
6824 "experimental_deoptimize return type must match caller return type");
6829 "calls to experimental_deoptimize must be followed by a return");
6833 "calls to experimental_deoptimize must be followed by a return "
6834 "of the value computed by experimental_deoptimize");
6839 case Intrinsic::vastart: {
6841 "va_start called in a non-varargs function");
6844 case Intrinsic::get_dynamic_area_offset: {
6846 Check(IntTy &&
DL.getPointerSizeInBits(
DL.getAllocaAddrSpace()) ==
6847 IntTy->getBitWidth(),
6848 "get_dynamic_area_offset result type must be scalar integer matching "
6849 "alloca address space width",
6853 case Intrinsic::smul_fix:
6854 case Intrinsic::smul_fix_sat:
6855 case Intrinsic::umul_fix:
6856 case Intrinsic::umul_fix_sat:
6857 case Intrinsic::sdiv_fix:
6858 case Intrinsic::sdiv_fix_sat:
6859 case Intrinsic::udiv_fix:
6860 case Intrinsic::udiv_fix_sat: {
6864 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
6865 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
6867 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
6871 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
6872 "to the width of the operands");
6876 case Intrinsic::lrint:
6877 case Intrinsic::llrint:
6878 case Intrinsic::lround:
6879 case Intrinsic::llround: {
6883 IF->
getName() +
": argument and result disagree on vector use",
6887 Check(VTy->getElementCount() == RTy->getElementCount(),
6888 IF->
getName() +
": argument must be same length as result", &
Call);
6892 case Intrinsic::bswap: {
6895 Check(
Size % 16 == 0,
"bswap must be an even number of bytes", &
Call);
6898 case Intrinsic::invariant_start: {
6900 Check(InvariantSize &&
6901 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
6902 "invariant_start parameter must be -1, 0 or a positive number",
6906 case Intrinsic::matrix_multiply:
6907 case Intrinsic::matrix_transpose:
6908 case Intrinsic::matrix_column_major_load:
6909 case Intrinsic::matrix_column_major_store: {
6911 Value *Stride =
nullptr;
6912 ConstantInt *NumRows;
6913 ConstantInt *NumColumns;
6915 Type *Op0ElemTy =
nullptr;
6916 Type *Op1ElemTy =
nullptr;
6918 case Intrinsic::matrix_multiply: {
6923 ->getNumElements() ==
6925 "First argument of a matrix operation does not match specified "
6928 ->getNumElements() ==
6930 "Second argument of a matrix operation does not match specified "
6940 case Intrinsic::matrix_transpose:
6947 case Intrinsic::matrix_column_major_load: {
6954 case Intrinsic::matrix_column_major_store: {
6967 Check(ResultTy->getElementType()->isIntegerTy() ||
6968 ResultTy->getElementType()->isFloatingPointTy(),
6969 "Result type must be an integer or floating-point type!", IF);
6972 Check(ResultTy->getElementType() == Op0ElemTy,
6973 "Vector element type mismatch of the result and first operand "
6978 Check(ResultTy->getElementType() == Op1ElemTy,
6979 "Vector element type mismatch of the result and second operand "
6985 "Result of a matrix operation does not fit in the returned vector!");
6989 "Stride bitwidth cannot exceed 64!", IF);
6993 case Intrinsic::stepvector: {
6995 Check(VecTy && VecTy->getScalarType()->isIntegerTy() &&
6996 VecTy->getScalarSizeInBits() >= 8,
6997 "stepvector only supported for vectors of integers "
6998 "with a bitwidth of at least 8.",
7002 case Intrinsic::experimental_vector_match: {
7011 Check(Op1Ty && Op2Ty && MaskTy,
"Operands must be vectors.", &
Call);
7013 "Second operand must be a fixed length vector.", &
Call);
7015 "First operand must be a vector of integers.", &
Call);
7016 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
7017 "First two operands must have the same element type.", &
Call);
7018 Check(Op1Ty->getElementCount() == MaskTy->getElementCount(),
7019 "First operand and mask must have the same number of elements.",
7021 Check(MaskTy->getElementType()->isIntegerTy(1),
7022 "Mask must be a vector of i1's.", &
Call);
7027 case Intrinsic::speculative_load: {
7030 "llvm.speculative.load return type must be a byte type or a "
7036 "llvm.speculative.load byte type must have a bit width that is "
7041 uint64_t MinSizeInBits =
DL.getTypeSizeInBits(LoadTy).getKnownMinValue();
7043 "llvm.speculative.load return type size in bytes must be a "
7044 "positive power of 2",
7047 constexpr unsigned NumFixedArgs = 3;
7049 Check(NumArgs >= NumFixedArgs,
7050 "llvm.speculative.load requires at least 3 arguments", &
Call);
7055 Check(NumArgs == NumFixedArgs,
7056 "llvm.speculative.load direct form has too many arguments", &
Call);
7061 "llvm.speculative.load third argument must be i64 or a direct "
7062 "reference to an oracle function",
7066 Check(OracleFn->onlyReadsMemory() && OracleFn->onlyAccessesArgMemory() &&
7067 OracleFn->doesNotThrow() && OracleFn->hasNoSync() &&
7068 OracleFn->willReturn(),
7069 "llvm.speculative.load oracle function must be nounwind, nosync "
7070 "and willreturn, must not have side effects and may only read "
7071 "memory through its arguments",
7074 FunctionType *FTy = OracleFn->getFunctionType();
7075 Check(FTy->getReturnType()->isIntegerTy(64),
7076 "llvm.speculative.load oracle function must return i64", &
Call);
7078 Check(!FTy->isVarArg(),
7079 "llvm.speculative.load oracle function must have a fixed argument "
7082 Check(NumArgs - NumFixedArgs == FTy->getNumParams(),
7083 "llvm.speculative.load oracle function argument count mismatch",
7085 for (
auto [ParamTy, Arg] :
7087 Check(ParamTy == Arg->getType(),
7088 "llvm.speculative.load oracle function argument type mismatch",
7093 case Intrinsic::vector_repeat: {
7097 Check(ArgTy,
"vector_repeat argument must be a fixed-length vector.",
7099 Check(ResultTy,
"vector_repeat result must be a scalable vector.", &
Call);
7100 Check(ResultTy->getElementType() == ArgTy->getElementType(),
7101 "vector_repeat argument and result must have the same element "
7104 Check(ArgTy->getNumElements() == ResultTy->getMinNumElements(),
7105 "vector_repeat argument and result must have the same minimum "
7110 case Intrinsic::vector_insert: {
7119 ElementCount VecEC = VecTy->getElementCount();
7120 ElementCount SubVecEC = SubVecTy->getElementCount();
7121 Check(VecTy->getElementType() == SubVecTy->getElementType(),
7122 "vector_insert parameters must have the same element "
7126 "vector_insert index must be a constant multiple of "
7127 "the subvector's known minimum vector length.");
7132 Check(VecEC.
isScalable(),
"cannot vector_insert a scalable vector into "
7142 "subvector operand of vector_insert would overrun the "
7143 "vector being inserted into.");
7147 case Intrinsic::vector_extract: {
7155 ElementCount VecEC = VecTy->getElementCount();
7156 ElementCount ResultEC = ResultTy->getElementCount();
7158 Check(ResultTy->getElementType() == VecTy->getElementType(),
7159 "vector_extract result must have the same element "
7160 "type as the input vector.",
7163 "vector_extract index must be a constant multiple of "
7164 "the result type's known minimum vector length.");
7169 Check(VecEC.
isScalable(),
"cannot vector_extract a scalable vector from "
7179 "vector_extract would overrun.");
7183 case Intrinsic::vector_partial_reduce_fadd:
7184 case Intrinsic::vector_partial_reduce_add: {
7188 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
7189 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
7191 Check((VecWidth % AccWidth) == 0,
7192 "Invalid vector widths for partial "
7193 "reduction. The width of the input vector "
7194 "must be a positive integer multiple of "
7195 "the width of the accumulator vector.");
7198 case Intrinsic::experimental_noalias_scope_decl: {
7202 case Intrinsic::preserve_array_access_index:
7203 case Intrinsic::preserve_struct_access_index:
7204 case Intrinsic::aarch64_ldaxr:
7205 case Intrinsic::aarch64_ldxr:
7206 case Intrinsic::arm_ldaex:
7207 case Intrinsic::arm_ldrex: {
7209 Check(ElemTy,
"Intrinsic requires elementtype attribute on first argument.",
7213 case Intrinsic::aarch64_stlxr:
7214 case Intrinsic::aarch64_stxr:
7215 case Intrinsic::arm_stlex:
7216 case Intrinsic::arm_strex: {
7219 "Intrinsic requires elementtype attribute on second argument.",
7223 case Intrinsic::aarch64_prefetch: {
7225 "write argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7227 "target argument to llvm.aarch64.prefetch must be 0-3",
Call);
7229 "stream argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7231 "isdata argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7234 case Intrinsic::aarch64_range_prefetch: {
7236 "write argument to llvm.aarch64.range.prefetch must be 0 or 1",
Call);
7238 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
7242 case Intrinsic::riscv_vsetvli:
7243 case Intrinsic::riscv_vsetvlimax: {
7248 "llvm.riscv.vsetvli/vsetvlimax result must be i32 or i64", &
Call);
7251 bool HasAVL =
ID == Intrinsic::riscv_vsetvli;
7252 unsigned Offset = HasAVL ? 1 : 0;
7257 Check(VSEW <= 3,
"llvm.riscv.vsetvli/vsetvlimax VSEW must be 0-3", &
Call);
7259 "llvm.riscv.vsetvli/vsetvlimax VLMUL is reserved", &
Call);
7262 case Intrinsic::callbr_landingpad: {
7264 Check(CBR,
"intrinstic requires callbr operand", &
Call);
7271 CheckFailed(
"Intrinsic in block must have 1 unique predecessor", &
Call);
7275 CheckFailed(
"Intrinsic must have corresponding callbr in predecessor",
7280 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
7281 "block in indirect destination list",
7284 Check(&
First == &
Call,
"No other instructions may proceed intrinsic",
7288 case Intrinsic::structured_gep: {
7294 "Intrinsic first parameter is missing an ElementType attribute",
7302 "Index operand type must be an integer", &
Call);
7305 T = AT->getElementType();
7307 Check(CI,
"Indexing into a struct requires a constant int", &
Call);
7309 "Indexing in a struct should be inbounds", &
Call);
7312 T = VT->getElementType();
7314 CheckFailed(
"Reached a non-composite type with more indices to process",
7320 case Intrinsic::structured_alloca:
7322 "@llvm.structured.alloca calls require elementtype attribute.",
7325 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7326 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7329 Check(RegCount % 8 == 0,
7330 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7333 case Intrinsic::nvvm_cp_async_bulk_global_to_shared_cta:
7334 case Intrinsic::nvvm_cp_async_bulk_global_to_shared_cta_relaxed: {
7336 const unsigned FlagValidPatternIndex = ArgSize - 1;
7337 const unsigned IgnoreOOBFlagIndex = 8;
7340 const auto *FlagValidPattern =
7342 Check(!IgnoreOOB || FlagValidPattern->isZero(),
7343 "flag_valid_pattern must be 0 (disabled) when ignore_oob is enabled",
7347 case Intrinsic::experimental_convergence_entry:
7348 case Intrinsic::experimental_convergence_anchor:
7350 case Intrinsic::experimental_convergence_loop:
7352 case Intrinsic::ptrmask: {
7356 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7361 "llvm.ptrmask intrinsic arguments must be both scalars or both vectors",
7366 "llvm.ptrmask intrinsic arguments must have the same number of "
7370 "llvm.ptrmask intrinsic second argument bitwidth must match "
7371 "pointer index type size of first argument",
7375 case Intrinsic::thread_pointer: {
7377 DL.getDefaultGlobalsAddressSpace(),
7378 "llvm.thread.pointer intrinsic return type must be for the globals "
7383 case Intrinsic::threadlocal_address: {
7386 "llvm.threadlocal.address first argument must be a GlobalValue");
7388 "llvm.threadlocal.address operand isThreadLocal() must be true");
7391 case Intrinsic::lifetime_start:
7392 case Intrinsic::lifetime_end: {
7396 (
II &&
II->getIntrinsicID() == Intrinsic::structured_alloca),
7397 "llvm.lifetime.start/end can only be used on alloca or poison",
7401 case Intrinsic::sponentry: {
7402 const unsigned StackAS =
DL.getAllocaAddrSpace();
7405 "llvm.sponentry must return a pointer to the stack", &
Call);
7408 case Intrinsic::write_volatile_register: {
7412 "llvm.write_volatile_register metadata must be a single MDString",
7416 case Intrinsic::ptrauth_auth_with_pc_and_resign: {
7421 "ptrauth.auth.with.pc.and.resign key must be IA (0) or IB (1)",
7430 if (
F->hasPersonalityFn() &&
7434 if (BlockEHFuncletColors.
empty())
7441 auto ColorsIt = BlockEHFuncletColors.
find(CallBB);
7442 if (ColorsIt != BlockEHFuncletColors.
end()) {
7444 bool InEHFunclet =
false;
7447 for (BasicBlock *ColorFirstBB : CV)
7448 if (
auto It = ColorFirstBB->getFirstNonPHIIt();
7449 It != ColorFirstBB->end())
7454 bool HasToken =
false;
7461 Check(HasToken,
"Missing funclet token on intrinsic call", &
Call);
7474DISubprogram *Verifier::getSubprogram(
Metadata *LocalScope) {
7475 if (hasDIScopeCycle(LocalScope))
7492void Verifier::visit(DbgLabelRecord &DLR) {
7494 "invalid #dbg_label intrinsic variable", &DLR, DLR.
getRawLabel());
7507 CheckDI(Loc,
"#dbg_label record requires a !dbg attachment", &DLR, BB,
F);
7511 if (!LabelSP || !LocSP)
7515 "mismatched subprogram between #dbg_label label and !dbg attachment",
7516 &DLR, BB,
F, Label,
Label->getScope()->getSubprogram(), Loc,
7517 Loc->getScope()->getSubprogram());
7520void Verifier::visit(DbgVariableRecord &DVR) {
7524 CheckDI(DVR.
getType() == DbgVariableRecord::LocationType::Value ||
7525 DVR.
getType() == DbgVariableRecord::LocationType::Declare ||
7526 DVR.
getType() == DbgVariableRecord::LocationType::DeclareValue ||
7527 DVR.
getType() == DbgVariableRecord::LocationType::Assign,
7528 "invalid #dbg record type", &DVR, DVR.
getType(), BB,
F);
7536 "invalid #dbg record address/value", &DVR, MD, BB,
F);
7538 "!DIAssignID should only be used by Assign DVRs.", MD, &DVR);
7540 visitValueAsMetadata(*VAM,
F);
7543 Type *Ty = VAM->getValue()->getType();
7545 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7549 visitDIArgList(*AL,
F);
7565 for (DIExpression::ExprOperand
Op : Expr->
expr_ops()) {
7569 "#dbg record expression references nonexistent location operand",
7576 "invalid #dbg_assign DIAssignID", &DVR, DVR.
getRawAssignID(), BB,
7579 AreDebugLocsAllowed::No);
7588 "invalid #dbg_assign address", &DVR, DVR.
getRawAddress(), BB,
F);
7590 visitValueAsMetadata(*VAM,
F);
7593 "invalid #dbg_assign address expression", &DVR,
7600 "inst not in same function as #dbg_assign",
I, &DVR, BB,
F);
7610 &DVR, DLNode, BB,
F);
7616 if (!VarSP || !LocSP)
7620 "mismatched subprogram between #dbg record variable and DILocation",
7622 Loc->getScope()->getSubprogram(), BB,
F);
7627void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7629 case Intrinsic::experimental_vp_splice: {
7632 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7634 AttributeList
Attrs = VPI.
getParent()->getParent()->getAttributes();
7635 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
7636 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
7638 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7639 (Idx >= 0 && Idx < KnownMinNumElements),
7640 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7641 "known minimum number of elements in the vector. For scalable "
7642 "vectors the minimum number of elements is determined from "
7650void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7652 bool HasRoundingMD =
7656 NumOperands += (1 + HasRoundingMD);
7662 "invalid arguments for constrained FP intrinsic", &FPI);
7665 case Intrinsic::experimental_constrained_fcmp:
7666 case Intrinsic::experimental_constrained_fcmps: {
7669 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7673 case Intrinsic::experimental_constrained_fptosi:
7674 case Intrinsic::experimental_constrained_fptoui: {
7678 "Intrinsic first argument must be floating point", &FPI);
7685 "Intrinsic first argument and result disagree on vector use", &FPI);
7687 "Intrinsic result must be an integer", &FPI);
7690 "Intrinsic first argument and result vector lengths must be equal",
7696 case Intrinsic::experimental_constrained_sitofp:
7697 case Intrinsic::experimental_constrained_uitofp: {
7701 "Intrinsic first argument must be integer", &FPI);
7708 "Intrinsic first argument and result disagree on vector use", &FPI);
7710 "Intrinsic result must be a floating point", &FPI);
7713 "Intrinsic first argument and result vector lengths must be equal",
7719 case Intrinsic::experimental_constrained_fptrunc:
7720 case Intrinsic::experimental_constrained_fpext: {
7726 "Intrinsic first argument must be FP or FP vector", &FPI);
7728 "Intrinsic result must be FP or FP vector", &FPI);
7730 "Intrinsic first argument and result disagree on vector use", &FPI);
7734 "Intrinsic first argument and result vector lengths must be equal",
7737 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7739 "Intrinsic first argument's type must be larger than result type",
7743 "Intrinsic first argument's type must be smaller than result type",
7759 "invalid exception behavior argument", &FPI);
7760 if (HasRoundingMD) {
7766void Verifier::verifyFragmentExpression(
const DbgVariableRecord &DVR) {
7771 if (!V || !
E || !
E->isValid())
7785 if (
V->isArtificial())
7788 verifyFragmentExpression(*V, *
Fragment, &DVR);
7791template <
typename ValueOrMetadata>
7792void Verifier::verifyFragmentExpression(
const DIVariable &V,
7794 ValueOrMetadata *
Desc) {
7797 auto VarSize =
V.getSizeInBits();
7801 unsigned FragSize =
Fragment.SizeInBits;
7802 unsigned FragOffset =
Fragment.OffsetInBits;
7803 CheckDI(FragSize + FragOffset <= *VarSize,
7804 "fragment is larger than or outside of variable",
Desc, &V);
7805 CheckDI(FragSize != *VarSize,
"fragment covers entire variable",
Desc, &V);
7808void Verifier::verifyFnArgs(
const DbgVariableRecord &DVR) {
7820 CheckDI(Var,
"#dbg record without variable");
7822 unsigned ArgNo = Var->
getArg();
7828 if (DebugFnArgs.
size() < ArgNo)
7829 DebugFnArgs.
resize(ArgNo,
nullptr);
7831 auto *Prev = DebugFnArgs[ArgNo - 1];
7832 DebugFnArgs[ArgNo - 1] = Var;
7833 CheckDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &DVR,
7837void Verifier::verifyNotEntryValue(
const DbgVariableRecord &DVR) {
7841 if (!
E || !
E->isValid())
7851 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
7856 "Entry values are only allowed in MIR unless they target a "
7857 "swiftasync Argument",
7861void Verifier::verifyCompileUnits() {
7865 if (
M.getContext().isODRUniquingDebugTypes())
7867 auto *CUs =
M.getNamedMetadata(
"llvm.dbg.cu");
7868 SmallPtrSet<const Metadata *, 2> Listed;
7871 for (
const auto *CU : CUVisited)
7872 CheckDI(Listed.
count(CU),
"DICompileUnit not listed in llvm.dbg.cu", CU);
7876void Verifier::verifyDeoptimizeCallingConvs() {
7877 if (DeoptimizeDeclarations.
empty())
7881 for (
const auto *
F :
ArrayRef(DeoptimizeDeclarations).slice(1)) {
7882 Check(
First->getCallingConv() ==
F->getCallingConv(),
7883 "All llvm.experimental.deoptimize declarations must have the same "
7884 "calling convention",
7889void Verifier::verifyAttachedCallBundle(
const CallBase &
Call,
7890 const OperandBundleUse &BU) {
7893 Check((FTy->getReturnType()->isPointerTy() ||
7895 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
7896 "function returning a pointer or a non-returning function that has a "
7901 "operand bundle \"clang.arc.attachedcall\" requires one function as "
7909 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
7910 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
7911 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
7912 "invalid function argument",
Call);
7914 StringRef FnName = Fn->getName();
7915 Check((FnName ==
"objc_retainAutoreleasedReturnValue" ||
7916 FnName ==
"objc_claimAutoreleasedReturnValue" ||
7917 FnName ==
"objc_unsafeClaimAutoreleasedReturnValue"),
7918 "invalid function argument",
Call);
7922void Verifier::verifyNoAliasScopeDecl() {
7923 if (NoAliasScopeDecls.
empty())
7927 for (
auto *
II : NoAliasScopeDecls) {
7928 assert(
II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
7929 "Not a llvm.experimental.noalias.scope.decl ?");
7932 Check(ScopeListMV !=
nullptr,
7933 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
7938 Check(ScopeListMD !=
nullptr,
"!id.scope.list must point to an MDNode",
II);
7939 Check(ScopeListMD->getNumOperands() == 1,
7940 "!id.scope.list must point to a list with a single scope",
II);
7941 visitAliasScopeListMetadata(ScopeListMD);
7951 auto GetScope = [](IntrinsicInst *
II) {
7954 return &
cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
7959 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
7960 return GetScope(Lhs) < GetScope(Rhs);
7967 auto ItCurrent = NoAliasScopeDecls.begin();
7968 while (ItCurrent != NoAliasScopeDecls.end()) {
7969 auto CurScope = GetScope(*ItCurrent);
7970 auto ItNext = ItCurrent;
7973 }
while (ItNext != NoAliasScopeDecls.end() &&
7974 GetScope(*ItNext) == CurScope);
7979 if (ItNext - ItCurrent < 32)
7983 Check(!DT.dominates(
I, J),
7984 "llvm.experimental.noalias.scope.decl dominates another one "
7985 "with the same scope",
7999 Verifier V(OS,
true, *f.getParent());
8003 return !V.verify(
F);
8007 bool *BrokenDebugInfo) {
8009 Verifier V(OS, !BrokenDebugInfo, M);
8011 bool Broken =
false;
8013 Broken |= !V.verify(
F);
8015 Broken |= !V.verify();
8016 if (BrokenDebugInfo)
8017 *BrokenDebugInfo = V.hasBrokenDebugInfo();
8028 std::unique_ptr<Verifier> V;
8029 bool FatalErrors =
true;
8032 explicit VerifierLegacyPass(
bool FatalErrors)
8033 : FunctionPass(
ID), FatalErrors(FatalErrors) {}
8035 bool doInitialization(
Module &M)
override {
8036 V = std::make_unique<Verifier>(
8042 if (!
V->verify(
F) && FatalErrors) {
8043 errs() <<
"in function " <<
F.getName() <<
'\n';
8049 bool doFinalization(
Module &M)
override {
8050 bool HasErrors =
false;
8052 if (
F.isDeclaration())
8053 HasErrors |= !
V->verify(
F);
8055 HasErrors |= !
V->verify();
8056 if (FatalErrors && (HasErrors ||
V->hasBrokenDebugInfo()))
8061 void getAnalysisUsage(AnalysisUsage &AU)
const override {
8069template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&... Args) {
8071 return Diagnostic->CheckFailed(
Args...);
8074#define CheckTBAA(C, ...) \
8077 CheckFailed(__VA_ARGS__); \
8085TBAAVerifier::TBAABaseNodeSummary
8089 CheckFailed(
"Base nodes must have at least two operands",
I, BaseNode);
8093 auto Itr = TBAABaseNodes.find(BaseNode);
8094 if (Itr != TBAABaseNodes.end())
8097 auto Result = verifyTBAABaseNodeImpl(
I, BaseNode, IsNewFormat);
8098 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
8100 assert(InsertResult.second &&
"We just checked!");
8104TBAAVerifier::TBAABaseNodeSummary
8105TBAAVerifier::verifyTBAABaseNodeImpl(
const Instruction *
I,
8106 const MDNode *BaseNode,
bool IsNewFormat) {
8107 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0
u};
8111 return isValidScalarTBAANode(BaseNode)
8112 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
8118 CheckFailed(
"Access tag nodes must have the number of operands that is a "
8119 "multiple of 3!", BaseNode);
8124 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
8134 if (!TypeSizeNode) {
8135 CheckFailed(
"Type size nodes must be constants!",
I, BaseNode);
8142 CheckFailed(
"Struct tag nodes have a string as their first operand",
8149 std::optional<APInt> PrevOffset;
8154 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8155 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8156 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
8157 Idx += NumOpsPerField) {
8158 const MDOperand &FieldTy = BaseNode->
getOperand(Idx);
8159 const MDOperand &FieldOffset = BaseNode->
getOperand(Idx + 1);
8161 CheckFailed(
"Incorrect field entry in struct type node!",
I, BaseNode);
8166 auto *OffsetEntryCI =
8168 if (!OffsetEntryCI) {
8169 CheckFailed(
"Offset entries must be constants!",
I, BaseNode);
8175 BitWidth = OffsetEntryCI->getBitWidth();
8177 if (OffsetEntryCI->getBitWidth() !=
BitWidth) {
8179 "Bitwidth between the offsets and struct type entries must match",
I,
8191 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
8194 CheckFailed(
"Offsets must be increasing!",
I, BaseNode);
8198 PrevOffset = OffsetEntryCI->getValue();
8203 if (!MemberSizeNode) {
8204 CheckFailed(
"Member size entries must be constants!",
I, BaseNode);
8211 return Failed ? InvalidNode
8212 : TBAAVerifier::TBAABaseNodeSummary(
false,
BitWidth);
8234 return Parent && Visited.
insert(Parent).second &&
8238bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
8239 auto ResultIt = TBAAScalarNodes.find(MD);
8240 if (ResultIt != TBAAScalarNodes.end())
8241 return ResultIt->second;
8243 SmallPtrSet<const MDNode *, 4> Visited;
8245 auto InsertResult = TBAAScalarNodes.insert({MD,
Result});
8247 assert(InsertResult.second &&
"Just checked!");
8256MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(
const Instruction *
I,
8257 const MDNode *BaseNode,
8268 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8269 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8270 for (
unsigned Idx = FirstFieldOpNo; Idx < BaseNode->
getNumOperands();
8271 Idx += NumOpsPerField) {
8272 auto *OffsetEntryCI =
8274 if (OffsetEntryCI->getValue().ugt(
Offset)) {
8275 if (Idx == FirstFieldOpNo) {
8276 CheckFailed(
"Could not find TBAA parent in struct type node",
I,
8281 unsigned PrevIdx = Idx - NumOpsPerField;
8282 auto *PrevOffsetEntryCI =
8284 Offset -= PrevOffsetEntryCI->getValue();
8292 Offset -= LastOffsetEntryCI->getValue();
8297 if (!
Type ||
Type->getNumOperands() < 3)
8313 "This instruction shall not have a TBAA access tag!",
I);
8315 bool IsStructPathTBAA =
8319 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8329 "Access tag metadata must have either 4 or 5 operands",
I, MD);
8332 "Struct tag metadata must have either 3 or 4 operands",
I, MD);
8339 CheckTBAA(AccessSizeNode,
"Access size field must be a constant",
I, MD);
8343 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8348 "Immutability tag on struct tag metadata must be a constant",
I,
8351 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8352 "Immutability part of the struct tag metadata must be either 0 or 1",
I,
8357 "Malformed struct tag metadata: base and access-type "
8358 "should be non-null and point to Metadata nodes",
8359 I, MD, BaseNode, AccessType);
8362 CheckTBAA(isValidScalarTBAANode(AccessType),
8363 "Access type node must be a valid scalar type",
I, MD,
8368 CheckTBAA(OffsetCI,
"Offset must be constant integer",
I, MD);
8371 bool SeenAccessTypeInPath =
false;
8377 getFieldNodeFromTBAABaseNode(
I, BaseNode,
Offset, IsNewFormat)) {
8378 if (!StructPath.
insert(BaseNode).second) {
8379 CheckFailed(
"Cycle detected in struct path",
I, MD);
8384 unsigned BaseNodeBitWidth;
8385 std::tie(
Invalid, BaseNodeBitWidth) =
8386 verifyTBAABaseNode(
I, BaseNode, IsNewFormat);
8393 SeenAccessTypeInPath |= BaseNode == AccessType;
8395 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8400 (BaseNodeBitWidth == 0 &&
Offset == 0) ||
8401 (IsNewFormat && BaseNodeBitWidth == ~0u),
8402 "Access bit-width not the same as description bit-width",
I, MD,
8403 BaseNodeBitWidth,
Offset.getBitWidth());
8405 if (IsNewFormat && SeenAccessTypeInPath)
8409 CheckTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
I,
8420 "!tbaa.struct operands must come in groups of three",
I, MD);
8422 std::optional<APInt> PrevOffset;
8423 for (
unsigned Idx = 0, E = MD->
getNumOperands(); Idx != E; Idx += 3) {
8426 CheckTBAA(OffsetCI,
"!tbaa.struct field offset must be a constant integer",
8430 "!tbaa.struct field size must be a constant integer",
I, MD);
8433 CheckTBAA(
Tag,
"!tbaa.struct field tag must be null or an MDNode",
I, MD);
8441 std::max(PrevOffset->getBitWidth(),
Offset.getBitWidth());
8443 "!tbaa.struct field offsets must be non-decreasing",
I, MD);
8450char VerifierLegacyPass::ID = 0;
8451INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
8454 return new VerifierLegacyPass(FatalErrors);
8472 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8480 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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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 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 const Metadata * getRawDIScopeParent(const Metadata *S)
Parent scope operand of S, or null if S has no parent (a DIFile, DICompileUnit, or non-scope).
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....
static LLVM_ABI unsigned getArbitraryFPFormatSizeInBits(StringRef Format)
Returns the size in bits of a valid arbitrary floating-point format string, or 0 if the string is not...
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 const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
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
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
iterator_range< expr_op_iterator > expr_ops() const
DbgVariableFragmentInfo FragmentInfo
LLVM_ABI bool isValid() const
@ 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....
LLVM_ABI bool isKillLocation() const
LocationType getType() const
MDNode * getRawExpression() const
MDNode * getRawAddressExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
LLVM_ABI unsigned getNumVariableLocationOps() 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.
iterator find(const_arg_type_t< KeyT > Val)
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.
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.
iterator_range< user_iterator > users()
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.
bool isElementwise() const
Return true if this is an elementwise atomic load.
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.
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,...
LLVM_ABI bool visitTBAAStructMetadata(const Instruction *I, const MDNode *MD)
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
bool isByteTy() const
True if this is an instance of ByteType.
bool isVectorTy() const
True if this is an instance of VectorType.
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'.
bool isSized() const
Return true if it makes sense to take the size of this type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
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.
LLVM_ABI unsigned getByteBitWidth() const
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
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.
LLVM_ABI bool containsNonLocalTargetExtType() const
Return true if this type is or contains a target extension type that disallows being used as a local.
LLVM_ABI bool containsNonGlobalTargetExtType() const
Return true if this type is or contains a target extension type that disallows being used as a global...
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.
std::optional< ABIType > parseABIType(StringRef S)
Parse the string spelling used by the "float-abi" IR module flag into an ABIType.
@ 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.
LLVM_ABI bool isImmArgValueInRangeSet(ID IID, unsigned ArgIdx, const APInt &Value)
Returns true if Value satisfies the range constraints specified for argument ArgIdx of intrinsic IID.
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)
AssignmentInstRange getAssignmentInsts(DIAssignID *ID)
Return a range of instructions (typically just one) that have ID as an attachment.
SmallVector< DbgVariableRecord * > getAssignmentMarkers(DIAssignID *ID)
initializer< Ty > init(const Ty &Val)
@ DW_LLVM_LANG_DIALECT_max
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
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.
unsigned getNumElements(Type *Ty)
This is an optimization pass for GlobalISel generic memory operations.
std::optional< LongDoubleFormat > parseLongDoubleFormat(StringRef Name)
Parses an IR floating-point type name into a LongDoubleFormat, returning std::nullopt if it does not ...
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool canInstructionHaveMMRAs(const Instruction &I)
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
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)
std::optional< ExceptionHandling > parseExceptionModel(StringRef Name)
Parses the string spelling used by the "exception-model" IR module flag into an ExceptionHandling val...
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
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...
constexpr BooleanLoopTags OldBooleanLoopTags[]
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
std::optional< ThreadModel > parseThreadModel(StringRef S)
Parse the string spelling used by the "thread-model" IR module flag into a ThreadModel.
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)
void verifyAMDGPUGlobalVariable(VerifierSupport &VS, const GlobalVariable &GV)
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.