101#include "llvm/IR/IntrinsicsAArch64.h"
102#include "llvm/IR/IntrinsicsARM.h"
103#include "llvm/IR/IntrinsicsBPF.h"
104#include "llvm/IR/IntrinsicsNVPTX.h"
105#include "llvm/IR/IntrinsicsRISCV.h"
106#include "llvm/IR/IntrinsicsWebAssembly.h"
159 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
162 SmallPtrSet<const Metadata *, 32> MDNodes;
165 DenseMap<const DISubprogram *, const Function *> DISubprogramAttachments;
169 DenseMap<const Metadata *, bool> DIScopeChainReachesCycle;
172 SmallPtrSet<const Metadata *, 2> CUVisited;
175 Type *LandingPadResultTy;
182 bool HasDebugInfo =
false;
186 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
190 MapVector<Instruction *, Instruction *> SiblingFuncletInfo;
194 DenseMap<BasicBlock *, ColorVector> BlockEHFuncletColors;
197 SmallPtrSet<const Constant *, 32> ConstantExprVisited;
203 SmallPtrSet<const void *, 32> AttributeListsVisited;
209 SmallPtrSet<const Value *, 32> GlobalValueVisited;
214 TBAAVerifier TBAAVerifyHelper;
218 unsigned MDAMDGPUExpectedActiveLanes;
219 unsigned MDAMDGPUCFS;
223 void checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I);
226 explicit Verifier(raw_ostream *OS,
bool ShouldTreatBrokenDebugInfoAsError,
228 : VerifierSupport(OS,
M), LandingPadResultTy(nullptr),
229 SawFrameEscape(
false), TBAAVerifyHelper(this),
230 MDAMDGPUExpectedActiveLanes(
231 M.
getContext().getMDKindID(
"amdgpu.expected.active.lanes")),
232 MDAMDGPUCFS(
M.
getContext().getMDKindID(
"amdgpu.cfs")) {
233 TreatBrokenDebugInfoAsError = ShouldTreatBrokenDebugInfoAsError;
236 bool hasBrokenDebugInfo()
const {
return BrokenDebugInfo; }
239 llvm::TimeTraceScope timeScope(
"Verifier");
241 "An instance of this class only works with a specific module!");
251 for (
const BasicBlock &BB :
F) {
252 if (!BB.empty() && BB.back().isTerminator())
256 *OS <<
"Basic Block in function '" <<
F.getName()
257 <<
"' does not have terminator!\n";
258 BB.printAsOperand(*OS,
true, MST);
266 DT.recalculate(
const_cast<Function &
>(
F));
268 auto FailureCB = [
this](
const Twine &Message) {
269 this->CheckFailed(Message);
271 ConvergenceVerifyHelper.initialize(OS, FailureCB,
F);
276 verifySiblingFuncletUnwinds();
278 if (ConvergenceVerifyHelper.sawTokens())
279 ConvergenceVerifyHelper.verify(DT);
281 InstsInThisBlock.clear();
283 DIScopeChainReachesCycle.clear();
284 LandingPadResultTy =
nullptr;
285 SawFrameEscape =
false;
286 SiblingFuncletInfo.clear();
287 verifyNoAliasScopeDecl();
288 NoAliasScopeDecls.clear();
299 if (
F.getIntrinsicID() == Intrinsic::experimental_deoptimize)
300 DeoptimizeDeclarations.push_back(&
F);
304 verifyFrameRecoverIndices();
305 for (
const GlobalVariable &GV :
M.globals())
306 visitGlobalVariable(GV);
308 for (
const GlobalAlias &GA :
M.aliases())
309 visitGlobalAlias(GA);
311 for (
const GlobalIFunc &GI :
M.ifuncs())
312 visitGlobalIFunc(GI);
314 for (
const NamedMDNode &NMD :
M.named_metadata())
315 visitNamedMDNode(NMD);
317 for (
const StringMapEntry<Comdat> &SMEC :
M.getComdatSymbolTable())
318 visitComdat(SMEC.getValue());
322 visitModuleCommandLines();
323 visitModuleErrnoTBAA();
324 visitModuleRawSections();
326 verifyCompileUnits();
328 verifyDeoptimizeCallingConvs();
329 DISubprogramAttachments.clear();
330 DIScopeChainReachesCycle.clear();
336 enum class AreDebugLocsAllowed {
No,
Yes };
340 enum class RangeLikeMetadataKind {
347 void visitGlobalValue(
const GlobalValue &GV);
348 void visitGlobalVariable(
const GlobalVariable &GV);
349 void visitGlobalAlias(
const GlobalAlias &GA);
350 void visitGlobalIFunc(
const GlobalIFunc &GI);
351 void visitAliaseeSubExpr(
const GlobalAlias &
A,
const Constant &
C);
352 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
353 const GlobalAlias &
A,
const Constant &
C);
354 void visitNamedMDNode(
const NamedMDNode &NMD);
355 void visitMDNode(
const MDNode &MD, AreDebugLocsAllowed AllowLocs);
356 void visitMetadataAsValue(
const MetadataAsValue &MD,
Function *
F);
357 void visitValueAsMetadata(
const ValueAsMetadata &MD,
Function *
F);
358 void visitDIArgList(
const DIArgList &AL,
Function *
F);
359 void visitComdat(
const Comdat &
C);
360 void visitModuleIdents();
361 void visitModuleCommandLines();
362 void visitModuleErrnoTBAA();
363 void visitModuleRawSections();
364 void visitModuleFlags();
365 void visitModuleFlag(
const MDNode *
Op,
366 DenseMap<const MDString *, const MDNode *> &SeenIDs,
367 SmallVectorImpl<const MDNode *> &Requirements);
368 void visitModuleFlagCGProfileEntry(
const MDOperand &MDO);
370 void visitBasicBlock(BasicBlock &BB);
371 void verifyRangeLikeMetadata(
const Value &
V,
const MDNode *
Range,
Type *Ty,
372 RangeLikeMetadataKind Kind);
373 void visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
374 void visitNoFPClassMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
375 void visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
Type *Ty);
376 void visitDereferenceableMetadata(Instruction &
I, MDNode *MD);
377 void visitNoFreeObjMetadata(Instruction &
I, MDNode *MD);
378 void visitProfMetadata(Instruction &
I, MDNode *MD);
379 void visitCallStackMetadata(MDNode *MD);
380 void visitMemProfMetadata(Instruction &
I, MDNode *MD);
381 void visitCallsiteMetadata(Instruction &
I, MDNode *MD);
382 void visitCalleeTypeMetadata(Instruction &
I, MDNode *MD);
383 void visitDIAssignIDMetadata(Instruction &
I, MDNode *MD);
384 void visitMMRAMetadata(Instruction &
I, MDNode *MD);
385 void visitAnnotationMetadata(MDNode *Annotation);
386 void visitAliasScopeMetadata(
const MDNode *MD);
387 void visitAliasScopeListMetadata(
const MDNode *MD);
388 void visitAccessGroupMetadata(
const MDNode *MD);
389 void visitCapturesMetadata(Instruction &
I,
const MDNode *Captures);
390 void visitAllocTokenMetadata(Instruction &
I, MDNode *MD);
391 void visitInlineHistoryMetadata(Instruction &
I, MDNode *MD);
392 void visitMemCacheHintMetadata(Instruction &
I, MDNode *MD);
394#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
395#include "llvm/IR/Metadata.def"
396 void visitDIType(
const DIType &
N);
397 void visitDIScope(
const DIScope &
N);
398 void visitDIScopeChain(
const DIScope &
N);
399 bool hasDIScopeCycle(
const Metadata *S);
429 void visitPHINode(
PHINode &PN);
459 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI);
460 void visitVPIntrinsic(VPIntrinsic &VPI);
461 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
462 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
463 void visitFenceInst(FenceInst &FI);
464 void visitAllocaInst(AllocaInst &AI);
465 void visitExtractValueInst(ExtractValueInst &EVI);
466 void visitInsertValueInst(InsertValueInst &IVI);
467 void visitEHPadPredecessors(Instruction &
I);
468 void visitLandingPadInst(LandingPadInst &LPI);
469 void visitResumeInst(ResumeInst &RI);
470 void visitCatchPadInst(CatchPadInst &CPI);
471 void visitCatchReturnInst(CatchReturnInst &CatchReturn);
472 void visitCleanupPadInst(CleanupPadInst &CPI);
473 void visitFuncletPadInst(FuncletPadInst &FPI);
474 void visitCatchSwitchInst(CatchSwitchInst &CatchSwitch);
475 void visitCleanupReturnInst(CleanupReturnInst &CRI);
477 void verifySwiftErrorCall(CallBase &
Call,
const Value *SwiftErrorVal);
478 void verifySwiftErrorValue(
const Value *SwiftErrorVal);
479 void verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs, StringRef
Context);
480 void verifyMustTailCall(CallInst &CI);
481 bool verifyAttributeCount(AttributeList Attrs,
unsigned Params);
482 void verifyAttributeTypes(AttributeSet Attrs,
const Value *
V);
483 void verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
const Value *
V);
484 void checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
486 void verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
487 const Value *
V,
bool IsIntrinsic,
bool IsInlineAsm);
488 void verifyFunctionMetadata(
ArrayRef<std::pair<unsigned, MDNode *>> MDs);
489 void verifyUnknownProfileMetadata(MDNode *MD);
490 void visitConstantExprsRecursively(
const Constant *EntryC);
491 void visitConstantExpr(
const ConstantExpr *CE);
492 void visitConstantPtrAuth(
const ConstantPtrAuth *CPA);
493 void verifyInlineAsmCall(
const CallBase &
Call);
494 void verifyStatepoint(
const CallBase &
Call);
495 void verifyFrameRecoverIndices();
496 void verifySiblingFuncletUnwinds();
498 void verifyFragmentExpression(
const DbgVariableRecord &
I);
499 template <
typename ValueOrMetadata>
500 void verifyFragmentExpression(
const DIVariable &
V,
502 ValueOrMetadata *
Desc);
503 void verifyFnArgs(
const DbgVariableRecord &DVR);
504 void verifyNotEntryValue(
const DbgVariableRecord &
I);
507 void verifyCompileUnits();
511 void verifyDeoptimizeCallingConvs();
513 void verifyAttachedCallBundle(
const CallBase &
Call,
514 const OperandBundleUse &BU);
517 void verifyNoAliasScopeDecl();
523#define Check(C, ...) \
526 CheckFailed(__VA_ARGS__); \
533#define CheckDI(C, ...) \
536 DebugInfoCheckFailed(__VA_ARGS__); \
542 if (!
I.getDbgMarker())
544 CheckDI(
I.getDbgMarker()->MarkedInstr == &
I,
545 "Instruction has invalid DebugMarker", &
I);
547 "PHI Node must not have any attached DbgRecords", &
I);
549 CheckDI(DR.getMarker() ==
I.getDbgMarker(),
550 "DbgRecord had invalid DebugMarker", &
I, &DR);
553 visitMDNode(*
Loc, AreDebugLocsAllowed::Yes);
558 verifyFragmentExpression(*DVR);
559 verifyNotEntryValue(*DVR);
566void Verifier::visit(Instruction &
I) {
568 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i)
569 Check(
I.getOperand(i) !=
nullptr,
"Operand is null", &
I);
581 while (!WorkList.
empty()) {
583 if (!Visited.
insert(Cur).second)
590void Verifier::visitGlobalValue(
const GlobalValue &GV) {
592 "Global is external, but doesn't have external or weak linkage!", &GV);
595 if (
const MDNode *Associated =
596 GO->getMetadata(LLVMContext::MD_associated)) {
597 Check(Associated->getNumOperands() == 1,
598 "associated metadata must have one operand", &GV, Associated);
599 const Metadata *
Op = Associated->getOperand(0).get();
600 Check(
Op,
"associated metadata must have a global value", GO, Associated);
603 Check(VM,
"associated metadata must be ValueAsMetadata", GO, Associated);
606 "associated value must be pointer typed", GV, Associated);
608 const Value *Stripped = VM->getValue()->stripPointerCastsAndAliases();
610 "associated metadata must point to a GlobalObject", GO, Stripped);
611 Check(Stripped != GO,
612 "global values should not associate to themselves", GO,
618 if (
const MDNode *AbsoluteSymbol =
619 GO->getMetadata(LLVMContext::MD_absolute_symbol)) {
620 verifyRangeLikeMetadata(*GO, AbsoluteSymbol,
621 DL.getIntPtrType(GO->getType()),
622 RangeLikeMetadataKind::AbsoluteSymbol);
625 if (GO->hasMetadata(LLVMContext::MD_implicit_ref)) {
626 Check(!GO->isDeclaration(),
627 "ref metadata must not be placed on a declaration", GO);
630 GO->getMetadata(LLVMContext::MD_implicit_ref, MDs);
631 for (
const MDNode *MD : MDs) {
632 Check(MD->getNumOperands() == 1,
"ref metadata must have one operand",
636 Check(VM,
"ref metadata must be ValueAsMetadata", GO, MD);
639 "ref value must be pointer typed", GV, MD);
643 "ref metadata must point to a GlobalObject", GO, Stripped);
644 Check(Stripped != GO,
"values should not reference themselves", GO,
650 if (
auto *Props = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
651 Check(Props->getNumOperands() == 2,
652 "elf_section_properties metadata must have two operands", GO,
654 if (Props->getNumOperands() == 2) {
656 Check(
Type,
"type field must be ConstantAsMetadata", GO, Props);
658 Check(TypeInt,
"type field must be ConstantInt", GO, Props);
661 Check(Entsize,
"entsize field must be ConstantAsMetadata", GO, Props);
663 Check(EntsizeInt,
"entsize field must be ConstantInt", GO, Props);
669 "Only global variables can have appending linkage!", &GV);
673 Check(GVar && GVar->getValueType()->isArrayTy(),
674 "Only global arrays can have appending linkage!", GVar);
678 Check(!GV.
hasComdat(),
"Declaration may not be in a Comdat!", &GV);
682 "dllexport GlobalValue must have default or protected visibility",
687 "dllimport GlobalValue must have default visibility", &GV);
688 Check(!GV.
isDSOLocal(),
"GlobalValue with DLLImport Storage is dso_local!",
694 "Global is marked as dllimport, but not external", &GV);
699 "GlobalValue with local linkage or non-default "
700 "visibility must be dso_local!",
708 "Global is used by a constant but is not marked as possibly having "
714 if (!
I->getParent() || !
I->getParent()->getParent())
715 CheckFailed(
"Global is referenced by parentless instruction!", &GV, &M,
717 else if (
I->getParent()->getParent()->getParent() != &M)
718 CheckFailed(
"Global is referenced in a different module!", &GV, &M,
I,
719 I->getParent()->getParent(),
720 I->getParent()->getParent()->getParent());
723 if (
F->getParent() != &M)
724 CheckFailed(
"Global is used by function in a different module", &GV, &M,
732void Verifier::visitGlobalVariable(
const GlobalVariable &GV) {
740 Check(
A->value() <= Value::MaximumAlignment,
741 "huge alignment values are unsupported", &GV);
746 "Global variable initializer type does not match global "
750 "Global variable initializer must be sized", &GV);
756 "'common' global must have a zero initializer!", &GV);
759 Check(!GV.
hasComdat(),
"'common' global may not be in a Comdat!", &GV);
764 GV.
getName() ==
"llvm.global_dtors")) {
766 "invalid linkage for intrinsic global variable", &GV);
768 "invalid uses of intrinsic global variable", &GV);
775 PointerType::get(
Context,
DL.getProgramAddressSpace());
776 Check(STy && (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
777 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
778 STy->getTypeAtIndex(1) == FuncPtrTy,
779 "wrong type for intrinsic global variable", &GV);
780 Check(STy->getNumElements() == 3,
781 "the third field of the element type is mandatory, "
782 "specify ptr null to migrate from the obsoleted 2-field form");
783 Type *ETy = STy->getTypeAtIndex(2);
792 for (
const Use &U : Init->operands()) {
794 if (!Structor || Structor->getNumOperands() != 3)
797 "signing of ctors/dtors should be requested via module flags");
803 GV.
getName() ==
"llvm.compiler.used")) {
805 "invalid linkage for intrinsic global variable", &GV);
807 "invalid uses of intrinsic global variable", &GV);
811 Check(PTy,
"wrong type for intrinsic global variable", &GV);
815 Check(InitArray,
"wrong initializer for intrinsic global variable",
817 for (
Value *
Op : InitArray->operands()) {
821 Twine(
"invalid ") + GV.
getName() +
" member",
V);
823 Twine(
"members of ") + GV.
getName() +
" must be named",
V);
832 for (MDNode *MD : MDs) {
834 visitDIGlobalVariableExpression(*GVE);
836 CheckDI(
false,
"!dbg attachment of global variable must be a "
837 "DIGlobalVariableExpression");
847 "Global @" + GV.
getName() +
" has illegal target extension type",
856 "Global variable is too large to fit into the address space", &GV,
860 visitGlobalValue(GV);
867 visitGlobalValue(GV);
870void Verifier::visitAliaseeSubExpr(
const GlobalAlias &GA,
const Constant &
C) {
871 SmallPtrSet<const GlobalAlias*, 4> Visited;
873 visitAliaseeSubExpr(Visited, GA,
C);
876void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
877 const GlobalAlias &GA,
const Constant &
C) {
881 "available_externally alias must point to available_externally "
892 Check(Visited.
insert(GA2).second,
"Aliases cannot form a cycle", &GA);
894 Check(!GA2->isInterposable(),
895 "Alias cannot point to an interposable alias", &GA);
904 visitConstantExprsRecursively(CE);
906 for (
const Use &U :
C.operands()) {
909 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
911 visitAliaseeSubExpr(Visited, GA, *C2);
915void Verifier::visitGlobalAlias(
const GlobalAlias &GA) {
917 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
918 "weak_odr, external, or available_externally linkage!",
921 Check(Aliasee,
"Aliasee cannot be NULL!", &GA);
923 "Alias and aliasee types should match!", &GA);
926 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
928 visitAliaseeSubExpr(GA, *Aliasee);
930 visitGlobalValue(GA);
933void Verifier::visitGlobalIFunc(
const GlobalIFunc &GI) {
934 visitGlobalValue(GI);
938 for (
const auto &
I : MDs) {
939 CheckDI(
I.first != LLVMContext::MD_dbg,
940 "an ifunc may not have a !dbg attachment", &GI);
941 Check(
I.first != LLVMContext::MD_prof,
942 "an ifunc may not have a !prof attachment", &GI);
943 visitMDNode(*
I.second, AreDebugLocsAllowed::No);
947 "IFunc should have private, internal, linkonce, weak, linkonce_odr, "
948 "weak_odr, or external linkage!",
953 Check(Resolver,
"IFunc must have a Function resolver", &GI);
955 "IFunc resolver must be a definition", &GI);
962 "IFunc resolver must return a pointer", &GI);
965 "IFunc resolver has incorrect type", &GI);
968void Verifier::visitNamedMDNode(
const NamedMDNode &NMD) {
973 "unrecognized named metadata node in the llvm.dbg namespace", &NMD);
974 for (
const MDNode *MD : NMD.
operands()) {
975 if (NMD.
getName() ==
"llvm.dbg.cu")
981 visitMDNode(*MD, AreDebugLocsAllowed::Yes);
992 return T->getRawScope();
994 return SP->getRawScope();
996 return LB->getRawScope();
998 return NS->getRawScope();
1000 return CB->getRawScope();
1002 return M->getRawScope();
1007bool Verifier::hasDIScopeCycle(
const Metadata *S) {
1008 SmallPtrSet<const Metadata *, 8> Seen;
1009 auto CacheSeen = [&](
bool HasCycle) {
1011 DIScopeChainReachesCycle[
M] = HasCycle;
1016 auto It = DIScopeChainReachesCycle.
find(Scope);
1017 bool IsInCache = It != DIScopeChainReachesCycle.
end();
1019 return CacheSeen(It->second);
1020 bool AlreadySeen = !Seen.
insert(Scope).second;
1022 return CacheSeen(
true);
1028 return CacheSeen(
false);
1031void Verifier::visitDIScopeChain(
const DIScope &
N) {
1032 CheckDI(!hasDIScopeCycle(&
N),
"DIScope scope chain must not contain a cycle",
1036void Verifier::visitMDNode(
const MDNode &BaseMD,
1037 AreDebugLocsAllowed AllowLocs) {
1040 if (!MDNodes.
insert(&BaseMD).second)
1043 std::queue<const MDNode *> Worklist;
1044 Worklist.push(&BaseMD);
1046 while (!Worklist.empty()) {
1047 const MDNode *CurrentMD = Worklist.front();
1050 "MDNode context does not match Module context!", CurrentMD);
1055 case Metadata::MDTupleKind:
1057#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
1058 case Metadata::CLASS##Kind: \
1059 visit##CLASS(cast<CLASS>(*CurrentMD)); \
1061#include "llvm/IR/Metadata.def"
1066 visitDIScopeChain(*S);
1074 "DILocation not allowed within this metadata node", CurrentMD,
1082 visitValueAsMetadata(*
V,
nullptr);
1103 "Expected second operand to be an integer constant of type i32 or "
1115 Check(AlignMD && AlignMD->getType()->isIntegerTy(32),
1116 "Expected the alignment to be an integer constant of type i32",
1121 "Expected the alignment to be a power of two", CurrentMD);
1122 Check(Align <= Value::MaximumAlignment,
1123 "Alignment is larger than the implementation defined limit",
1135 "Expecting only the metadata name", CurrentMD);
1140 Check(CurrentMD->
isResolved(),
"All nodes should be resolved!", CurrentMD);
1144void Verifier::visitValueAsMetadata(
const ValueAsMetadata &MD,
Function *
F) {
1147 "Unexpected metadata round-trip through values", &MD, MD.
getValue());
1153 Check(
F,
"function-local metadata used outside a function", L);
1159 Check(
I->getParent(),
"function-local metadata not in basic block", L,
I);
1166 assert(ActualF &&
"Unimplemented function local metadata case!");
1168 Check(ActualF ==
F,
"function-local metadata used in wrong function", L);
1171void Verifier::visitDIArgList(
const DIArgList &AL,
Function *
F) {
1172 for (
const ValueAsMetadata *VAM :
AL.getArgs())
1173 visitValueAsMetadata(*VAM,
F);
1176void Verifier::visitMetadataAsValue(
const MetadataAsValue &MDV,
Function *
F) {
1179 visitMDNode(*
N, AreDebugLocsAllowed::No);
1185 if (!MDNodes.
insert(MD).second)
1189 visitValueAsMetadata(*
V,
F);
1192 visitDIArgList(*AL,
F);
1200void Verifier::visitMDFunctionLocalContext(
const MDFunctionLocalContext &
N) {
1201 for (
auto [Idx, Scope] :
enumerate(
N.getScopes()))
1202 CheckDI(
Scope.get(),
"MDFunctionLocalContext contains invalid scope", &
N,
1204 for (
auto [Idx, InlinedCall] :
enumerate(
N.getInlinedCalls()))
1205 CheckDI(InlinedCall.getInlinee(),
1206 "MDFunctionLocalContext contains InlinedCall with invalid "
1209 bool IsNonDebugFLContext =
N.isNonDebug();
1210 if (IsNonDebugFLContext) {
1212 "MDFunctionLocalContext that is NonDebug must contain no scopes",
1215 "MDFunctionLocalContext that is NonDebug must contain no srcLocs",
1217 CheckDI(!
N.getInlinedCalls().empty(),
1218 "MDFunctionLocalContext that is NonDebug must contain at least one "
1223 "An MDFunctionLocalContext that is not NonDebug must contain its "
1224 "function's subprogram as the first scope",
1227 "The first scope in an MDFunctionLocalContext with debug info must "
1228 "be the function DISubprogram",
1229 &
N,
N.getScopes()[0].get());
1235 "DISubprogram should only appear as the first scope in a "
1236 "function-local context",
1239 "scope in function-local context points at wrong subprogram for "
1245 for (FLSrcLoc SrcLoc :
N.getSrcLocs())
1246 CheckDI(SrcLoc.ScopeIdx.get() <
N.getScopes().size(),
1247 "FLSrcLoc has invalid ScopeIdx", SrcLoc.ScopeIdx.get(), &
N);
1249 for (
auto [Idx, InlinedCall] :
enumerate(
N.getInlinedCalls())) {
1250 if (!InlinedCall.SrcLocIdx) {
1251 CheckDI(IsNonDebugFLContext && !InlinedCall.isInlined(),
1252 "FLInlinedCall must have a SrcLocIdx unless it is a nodebug "
1257 if (InlinedCall.isInlined()) {
1258 CheckDI(InlinedCall.InlinedAtIdx.get() < Idx,
1259 "FLInlinedCall's InlinedAtIdx cannot point to a later "
1260 "FLInlinedCall entry",
1261 InlinedCall.InlinedAtIdx.get(), &
N);
1262 auto *InlinedFLMD = InlinedCall.getInlinedAt(&
N).InlineeContext;
1263 CheckDI(InlinedCall.SrcLocIdx.get() < InlinedFLMD->getSrcLocs().size(),
1264 "Inlined FLInlinedCall has invalid SrcLocIdx",
1265 InlinedCall.SrcLocIdx.get(), &
N, InlinedFLMD);
1267 CheckDI(InlinedCall.SrcLocIdx.get() <
N.getSrcLocs().size(),
1268 "FLInlinedCall has invalid SrcLocIdx",
1269 InlinedCall.SrcLocIdx.get(), &
N);
1275 N.getUsedMDNodes(NodesToVisit);
1276 for (
auto *Node : NodesToVisit)
1277 visitMDNode(*Node, AreDebugLocsAllowed::No);
1280void Verifier::visitDILocation(
const DILocation &
N) {
1282 "location requires a valid scope", &
N,
N.getRawScope());
1283 if (
auto *IA =
N.getRawInlinedAt())
1286 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1287 if (
auto *L =
N.getRawIRLayers())
1291void Verifier::visitDILayerLoc(
const DILayerLoc &
N) {
1293 "layer kind must be a non-null MDString", &
N,
N.getRawKind());
1295 "layer file must be a non-null DIFile", &
N,
N.getRawFile());
1298void Verifier::visitDILayerLocList(
const DILayerLocList &
N) {
1299 CheckDI(
N.getNumLayers() > 0,
"DILayerLocList must be non-empty", &
N);
1300 for (
const MDOperand &
Op :
N.layers())
1302 "DILayerLocList entry must be a DILayerLoc", &
N,
Op.get());
1305void Verifier::visitGenericDINode(
const GenericDINode &
N) {
1309void Verifier::visitDIScope(
const DIScope &
N) {
1310 if (
auto *
F =
N.getRawFile())
1314void Verifier::visitDIType(
const DIType &
N) {
1317 CheckDI(
N.getRawFile() ||
N.getLine() == 0,
"line specified with no file", &
N,
1321void Verifier::visitDISubrangeType(
const DISubrangeType &
N) {
1324 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1327 auto *LBound =
N.getRawLowerBound();
1331 "LowerBound must be signed constant or DIVariable or DIExpression or "
1334 auto *UBound =
N.getRawUpperBound();
1338 "UpperBound must be signed constant or DIVariable or DIExpression or "
1341 auto *Stride =
N.getRawStride();
1344 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1345 auto *Bias =
N.getRawBias();
1348 "Bias must be signed constant or DIVariable or DIExpression", &
N);
1350 auto *
Size =
N.getRawSizeInBits();
1352 "SizeInBits must be a constant");
1355void Verifier::visitDISubrange(
const DISubrange &
N) {
1356 CheckDI(
N.getTag() == dwarf::DW_TAG_subrange_type,
"invalid tag", &
N);
1357 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1358 "Subrange can have any one of count or upperBound", &
N);
1359 auto *CBound =
N.getRawCountNode();
1362 "Count must be signed constant or DIVariable or DIExpression", &
N);
1363 auto Count =
N.getCount();
1366 "invalid subrange count", &
N);
1367 auto *LBound =
N.getRawLowerBound();
1370 "LowerBound must be signed constant or DIVariable or DIExpression",
1372 auto *UBound =
N.getRawUpperBound();
1375 "UpperBound must be signed constant or DIVariable or DIExpression",
1377 auto *Stride =
N.getRawStride();
1380 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1383void Verifier::visitDIGenericSubrange(
const DIGenericSubrange &
N) {
1384 CheckDI(
N.getTag() == dwarf::DW_TAG_generic_subrange,
"invalid tag", &
N);
1385 CheckDI(!
N.getRawCountNode() || !
N.getRawUpperBound(),
1386 "GenericSubrange can have any one of count or upperBound", &
N);
1387 auto *CBound =
N.getRawCountNode();
1389 "Count must be signed constant or DIVariable or DIExpression", &
N);
1390 auto *LBound =
N.getRawLowerBound();
1391 CheckDI(LBound,
"GenericSubrange must contain lowerBound", &
N);
1393 "LowerBound must be signed constant or DIVariable or DIExpression",
1395 auto *UBound =
N.getRawUpperBound();
1397 "UpperBound must be signed constant or DIVariable or DIExpression",
1399 auto *Stride =
N.getRawStride();
1400 CheckDI(Stride,
"GenericSubrange must contain stride", &
N);
1402 "Stride must be signed constant or DIVariable or DIExpression", &
N);
1405void Verifier::visitDIEnumerator(
const DIEnumerator &
N) {
1406 CheckDI(
N.getTag() == dwarf::DW_TAG_enumerator,
"invalid tag", &
N);
1409void Verifier::visitDIBasicType(
const DIBasicType &
N) {
1412 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type ||
1413 N.getTag() == dwarf::DW_TAG_unspecified_type ||
1414 N.getTag() == dwarf::DW_TAG_string_type,
1417 auto *
Size =
N.getRawSizeInBits();
1419 "SizeInBits must be a constant");
1422void Verifier::visitDIFixedPointType(
const DIFixedPointType &
N) {
1423 visitDIBasicType(
N);
1425 CheckDI(
N.getTag() == dwarf::DW_TAG_base_type,
"invalid tag", &
N);
1426 CheckDI(
N.getEncoding() == dwarf::DW_ATE_signed_fixed ||
1427 N.getEncoding() == dwarf::DW_ATE_unsigned_fixed,
1428 "invalid encoding", &
N);
1432 "invalid kind", &
N);
1434 N.getFactorRaw() == 0,
1435 "factor should be 0 for rationals", &
N);
1437 (
N.getNumeratorRaw() == 0 &&
N.getDenominatorRaw() == 0),
1438 "numerator and denominator should be 0 for non-rationals", &
N);
1441void Verifier::visitDIStringType(
const DIStringType &
N) {
1444 CheckDI(
N.getTag() == dwarf::DW_TAG_string_type,
"invalid tag", &
N);
1445 CheckDI(!(
N.isBigEndian() &&
N.isLittleEndian()),
"has conflicting flags",
1447 if (
N.getRawCharType())
1449 N.getRawCharType());
1452void Verifier::visitDIDerivedType(
const DIDerivedType &
N) {
1456 CheckDI(
N.getTag() == dwarf::DW_TAG_typedef ||
1457 N.getTag() == dwarf::DW_TAG_pointer_type ||
1458 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
1459 N.getTag() == dwarf::DW_TAG_reference_type ||
1460 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
1461 N.getTag() == dwarf::DW_TAG_const_type ||
1462 N.getTag() == dwarf::DW_TAG_immutable_type ||
1463 N.getTag() == dwarf::DW_TAG_volatile_type ||
1464 N.getTag() == dwarf::DW_TAG_restrict_type ||
1465 N.getTag() == dwarf::DW_TAG_atomic_type ||
1466 N.getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ||
1467 N.getTag() == dwarf::DW_TAG_member ||
1468 (
N.getTag() == dwarf::DW_TAG_variable &&
N.isStaticMember()) ||
1469 N.getTag() == dwarf::DW_TAG_inheritance ||
1470 N.getTag() == dwarf::DW_TAG_friend ||
1471 N.getTag() == dwarf::DW_TAG_set_type ||
1472 N.getTag() == dwarf::DW_TAG_template_alias,
1474 if (
N.getTag() == dwarf::DW_TAG_ptr_to_member_type) {
1475 CheckDI(
isType(
N.getRawExtraData()),
"invalid pointer to member type", &
N,
1476 N.getRawExtraData());
1477 }
else if (
N.getTag() == dwarf::DW_TAG_template_alias) {
1479 N.getRawExtraData());
1480 }
else if (
N.getTag() == dwarf::DW_TAG_inheritance ||
1481 N.getTag() == dwarf::DW_TAG_member ||
1482 N.getTag() == dwarf::DW_TAG_variable) {
1483 auto *ExtraData =
N.getRawExtraData();
1484 auto IsValidExtraData = [&]() {
1485 if (ExtraData ==
nullptr)
1491 if (
Tuple->getNumOperands() != 1)
1498 "extraData must be ConstantAsMetadata, MDString, DIObjCProperty, "
1499 "or MDTuple with single ConstantAsMetadata operand",
1503 if (
N.getTag() == dwarf::DW_TAG_set_type) {
1504 if (
auto *
T =
N.getRawBaseType()) {
1509 (Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type) ||
1510 (Subrange &&
Subrange->getTag() == dwarf::DW_TAG_subrange_type) ||
1511 (
Basic && (
Basic->getEncoding() == dwarf::DW_ATE_unsigned ||
1512 Basic->getEncoding() == dwarf::DW_ATE_signed ||
1513 Basic->getEncoding() == dwarf::DW_ATE_unsigned_char ||
1514 Basic->getEncoding() == dwarf::DW_ATE_signed_char ||
1515 Basic->getEncoding() == dwarf::DW_ATE_boolean)),
1516 "invalid set base type", &
N,
T);
1521 N.getRawBaseType());
1523 if (
N.getDWARFAddressSpace()) {
1524 CheckDI(
N.getTag() == dwarf::DW_TAG_pointer_type ||
1525 N.getTag() == dwarf::DW_TAG_reference_type ||
1526 N.getTag() == dwarf::DW_TAG_rvalue_reference_type,
1527 "DWARF address space only applies to pointer or reference types",
1531 auto *
Size =
N.getRawSizeInBits();
1534 "SizeInBits must be a constant or DIVariable or DIExpression");
1539 return ((Flags & DINode::FlagLValueReference) &&
1540 (Flags & DINode::FlagRValueReference)) ||
1541 ((Flags & DINode::FlagTypePassByValue) &&
1542 (Flags & DINode::FlagTypePassByReference));
1545void Verifier::visitTemplateParams(
const MDNode &
N,
const Metadata &RawParams) {
1547 CheckDI(Params,
"invalid template params", &
N, &RawParams);
1554void Verifier::visitDICompositeType(
const DICompositeType &
N) {
1558 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type ||
1559 N.getTag() == dwarf::DW_TAG_structure_type ||
1560 N.getTag() == dwarf::DW_TAG_union_type ||
1561 N.getTag() == dwarf::DW_TAG_enumeration_type ||
1562 N.getTag() == dwarf::DW_TAG_class_type ||
1563 N.getTag() == dwarf::DW_TAG_variant_part ||
1564 N.getTag() == dwarf::DW_TAG_variant ||
1565 N.getTag() == dwarf::DW_TAG_namelist,
1569 N.getRawBaseType());
1572 "invalid composite elements", &
N,
N.getRawElements());
1574 N.getRawVTableHolder());
1576 "invalid reference flags", &
N);
1577 unsigned DIBlockByRefStruct = 1 << 4;
1578 CheckDI((
N.getFlags() & DIBlockByRefStruct) == 0,
1579 "DIBlockByRefStruct on DICompositeType is no longer supported", &
N);
1581 "DISubprogram contains null entry in `elements` field", &
N);
1584 const DINodeArray
Elements =
N.getElements();
1586 Elements[0]->getTag() == dwarf::DW_TAG_subrange_type,
1587 "invalid vector, expected one element of type subrange", &
N);
1590 if (
auto *Params =
N.getRawTemplateParams())
1591 visitTemplateParams(
N, *Params);
1593 if (
auto *
D =
N.getRawDiscriminator()) {
1595 "discriminator can only appear on variant part");
1598 if (
N.getRawDataLocation()) {
1599 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1600 "dataLocation can only appear in array type");
1603 if (
N.getRawAssociated()) {
1604 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1605 "associated can only appear in array type");
1608 if (
N.getRawAllocated()) {
1609 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1610 "allocated can only appear in array type");
1613 if (
N.getRawRank()) {
1614 CheckDI(
N.getTag() == dwarf::DW_TAG_array_type,
1615 "rank can only appear in array type");
1618 if (
N.getTag() == dwarf::DW_TAG_array_type) {
1619 CheckDI(
N.getRawBaseType(),
"array types must have a base type", &
N);
1622 auto *
Size =
N.getRawSizeInBits();
1625 "SizeInBits must be a constant or DIVariable or DIExpression");
1628void Verifier::visitDISubroutineType(
const DISubroutineType &
N) {
1630 CheckDI(
N.getTag() == dwarf::DW_TAG_subroutine_type,
"invalid tag", &
N);
1631 if (
auto *Types =
N.getRawTypeArray()) {
1633 for (
Metadata *Ty :
N.getTypeArray()->operands()) {
1634 CheckDI(
isType(Ty),
"invalid subroutine type ref", &
N, Types, Ty);
1638 "invalid reference flags", &
N);
1641void Verifier::visitDIFile(
const DIFile &
N) {
1642 CheckDI(
N.getTag() == dwarf::DW_TAG_file_type,
"invalid tag", &
N);
1643 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum =
N.getChecksum();
1645 CheckDI(Checksum->Kind <= DIFile::ChecksumKind::CSK_Last,
1646 "invalid checksum kind", &
N);
1648 switch (Checksum->Kind) {
1659 CheckDI(Checksum->Value.size() ==
Size,
"invalid checksum length", &
N);
1661 "invalid checksum", &
N);
1665void Verifier::visitDICompileUnit(
const DICompileUnit &
N) {
1666 CheckDI(
N.isDistinct(),
"compile units must be distinct", &
N);
1667 CheckDI(
N.getTag() == dwarf::DW_TAG_compile_unit,
"invalid tag", &
N);
1673 CheckDI(!
N.getFile()->getFilename().empty(),
"invalid filename", &
N,
1677 "invalid emission kind", &
N);
1680 "invalid language dialect", &
N);
1682 if (
auto *Array =
N.getRawEnumTypes()) {
1684 for (
Metadata *
Op :
N.getEnumTypes()->operands()) {
1686 CheckDI(Enum &&
Enum->getTag() == dwarf::DW_TAG_enumeration_type,
1687 "invalid enum type", &
N,
N.getEnumTypes(),
Op);
1689 "function-local enum in a DICompileUnit's enum list", &
N,
1690 N.getEnumTypes(),
Op);
1693 if (
auto *Array =
N.getRawRetainedTypes()) {
1695 for (
Metadata *
Op :
N.getRetainedTypes()->operands()) {
1699 "invalid retained type", &
N,
Op);
1702 if (
auto *Array =
N.getRawGlobalVariables()) {
1704 for (
Metadata *
Op :
N.getGlobalVariables()->operands()) {
1706 CheckDI(GVE,
"invalid global variable ref", &
N,
Op);
1708 "function-local variables are not allowed in a DICompileUnit's "
1709 "global variables list",
1713 if (
auto *Array =
N.getRawImportedEntities()) {
1715 for (
Metadata *
Op :
N.getImportedEntities()->operands()) {
1717 CheckDI(IE,
"invalid imported entity ref", &
N,
Op);
1719 "function-local imports are not allowed in a DICompileUnit's "
1720 "imported entities list",
1724 if (
auto *Array =
N.getRawMacros()) {
1733void Verifier::visitDISubprogram(
const DISubprogram &
N) {
1734 CheckDI(
N.getTag() == dwarf::DW_TAG_subprogram,
"invalid tag", &
N);
1736 if (
auto *
F =
N.getRawFile())
1739 CheckDI(
N.getLine() == 0,
"line specified with no file", &
N,
N.getLine());
1740 auto *
T =
N.getRawType();
1741 CheckDI(
T,
"DISubprogram requires a non-null type", &
N);
1743 CheckDI(
isType(
N.getRawContainingType()),
"invalid containing type", &
N,
1744 N.getRawContainingType());
1745 if (
auto *Params =
N.getRawTemplateParams())
1746 visitTemplateParams(
N, *Params);
1747 if (
auto *S =
N.getRawDeclaration())
1749 "invalid subprogram declaration", &
N, S);
1750 if (
auto *RawNode =
N.getRawRetainedNodes()) {
1752 CheckDI(Node,
"invalid retained nodes list", &
N, RawNode);
1754 DenseMap<unsigned, DILocalVariable *>
Args;
1756 CheckDI(
Op,
"nullptr in retained nodes", &
N, Node);
1760 bool IsTypeCorrect = DISubprogram::visitRetainedNode<bool>(
1763 "invalid retained nodes, expected DILocalVariable, DILabel, "
1764 "DIImportedEntity, DIType or DIGlobalVariableExpression",
1771 "invalid retained nodes, retained node is not local", &
N, Node,
1774 DISubprogram *RetainedNodeSP =
getSubprogram(RetainedNodeScope);
1775 DICompileUnit *RetainedNodeUnit =
1776 RetainedNodeSP ? RetainedNodeSP->getUnit() :
nullptr;
1778 RetainedNodeSP == &
N,
1779 "invalid retained nodes, retained node does not belong to subprogram",
1780 &
N, Node, RetainedNode, RetainedNodeScope, RetainedNodeSP,
1786 if (
unsigned ArgNum = DV->getArg()) {
1788 CheckDI(Inserted || DV == ArgI->second,
1789 "invalid retained nodes, more than one local variable with the "
1790 "same argument index",
1791 &
N,
N.getUnit(), Node, RetainedNode, Args[ArgNum]);
1796 "invalid reference flags", &
N);
1798 auto *
Unit =
N.getRawUnit();
1799 if (
N.isDefinition()) {
1801 CheckDI(
N.isDistinct(),
"subprogram definitions must be distinct", &
N);
1802 CheckDI(Unit,
"subprogram definitions must have a compile unit", &
N);
1807 if (CT && CT->getRawIdentifier() &&
1808 M.getContext().isODRUniquingDebugTypes())
1810 "definition subprograms cannot be nested within DICompositeType "
1811 "when enabling ODR",
1815 CheckDI(!Unit,
"subprogram declarations must not have a compile unit", &
N);
1817 "subprogram declaration must not have a declaration field");
1820 if (
auto *RawThrownTypes =
N.getRawThrownTypes()) {
1822 CheckDI(ThrownTypes,
"invalid thrown types list", &
N, RawThrownTypes);
1828 if (
N.areAllCallsDescribed())
1830 "DIFlagAllCallsDescribed must be attached to a definition");
1833void Verifier::visitDILexicalBlockBase(
const DILexicalBlockBase &
N) {
1834 CheckDI(
N.getTag() == dwarf::DW_TAG_lexical_block,
"invalid tag", &
N);
1836 "invalid local scope", &
N,
N.getRawScope());
1838 CheckDI(
SP->isDefinition(),
"scope points into the type hierarchy", &
N);
1841void Verifier::visitDILexicalBlock(
const DILexicalBlock &
N) {
1842 visitDILexicalBlockBase(
N);
1845 "cannot have column info without line info", &
N);
1848void Verifier::visitDILexicalBlockFile(
const DILexicalBlockFile &
N) {
1849 visitDILexicalBlockBase(
N);
1852void Verifier::visitDICommonBlock(
const DICommonBlock &
N) {
1853 CheckDI(
N.getTag() == dwarf::DW_TAG_common_block,
"invalid tag", &
N);
1854 if (
auto *S =
N.getRawScope())
1856 if (
auto *S =
N.getRawDecl())
1860void Verifier::visitDINamespace(
const DINamespace &
N) {
1861 CheckDI(
N.getTag() == dwarf::DW_TAG_namespace,
"invalid tag", &
N);
1862 if (
auto *S =
N.getRawScope())
1866void Verifier::visitDIMacro(
const DIMacro &
N) {
1869 "invalid macinfo type", &
N);
1870 CheckDI(!
N.getName().empty(),
"anonymous macro", &
N);
1871 if (!
N.getValue().empty()) {
1872 assert(
N.getValue().data()[0] !=
' ' &&
"Macro value has a space prefix");
1876void Verifier::visitDIMacroFile(
const DIMacroFile &
N) {
1878 "invalid macinfo type", &
N);
1879 if (
auto *
F =
N.getRawFile())
1882 if (
auto *Array =
N.getRawElements()) {
1884 for (
Metadata *
Op :
N.getElements()->operands()) {
1890void Verifier::visitDIModule(
const DIModule &
N) {
1891 CheckDI(
N.getTag() == dwarf::DW_TAG_module,
"invalid tag", &
N);
1892 CheckDI(!
N.getName().empty(),
"anonymous module", &
N);
1895void Verifier::visitDITemplateParameter(
const DITemplateParameter &
N) {
1899void Verifier::visitDITemplateTypeParameter(
const DITemplateTypeParameter &
N) {
1900 visitDITemplateParameter(
N);
1902 CheckDI(
N.getTag() == dwarf::DW_TAG_template_type_parameter,
"invalid tag",
1906void Verifier::visitDITemplateValueParameter(
1907 const DITemplateValueParameter &
N) {
1908 visitDITemplateParameter(
N);
1910 CheckDI(
N.getTag() == dwarf::DW_TAG_template_value_parameter ||
1911 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
1912 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
1916void Verifier::visitDIVariable(
const DIVariable &
N) {
1917 if (
auto *S =
N.getRawScope())
1919 if (
auto *
F =
N.getRawFile())
1923void Verifier::visitDIGlobalVariable(
const DIGlobalVariable &
N) {
1927 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1930 if (
N.isDefinition())
1931 CheckDI(
N.getType(),
"missing global variable type", &
N);
1932 if (
auto *Member =
N.getRawStaticDataMemberDeclaration()) {
1934 "invalid static data member declaration", &
N, Member);
1938void Verifier::visitDILocalVariable(
const DILocalVariable &
N) {
1943 CheckDI(
N.getTag() == dwarf::DW_TAG_variable,
"invalid tag", &
N);
1945 "local variable requires a valid scope", &
N,
N.getRawScope());
1946 if (
auto Ty =
N.getType())
1950void Verifier::visitDIAssignID(
const DIAssignID &
N) {
1951 CheckDI(!
N.getNumOperands(),
"DIAssignID has no arguments", &
N);
1952 CheckDI(
N.isDistinct(),
"DIAssignID must be distinct", &
N);
1955void Verifier::visitDILabel(
const DILabel &
N) {
1956 if (
auto *S =
N.getRawScope())
1958 if (
auto *
F =
N.getRawFile())
1961 CheckDI(
N.getTag() == dwarf::DW_TAG_label,
"invalid tag", &
N);
1963 "label requires a valid scope", &
N,
N.getRawScope());
1966void Verifier::visitDIExpression(
const DIExpression &
N) {
1967 CheckDI(
N.isValid(),
"invalid expression", &
N);
1970void Verifier::visitDIGlobalVariableExpression(
1971 const DIGlobalVariableExpression &GVE) {
1974 visitDIGlobalVariable(*Var);
1976 visitDIExpression(*Expr);
1977 if (
auto Fragment = Expr->getFragmentInfo())
1982void Verifier::visitDIObjCProperty(
const DIObjCProperty &
N) {
1983 CheckDI(
N.getTag() == dwarf::DW_TAG_APPLE_property,
"invalid tag", &
N);
1984 if (
auto *
T =
N.getRawType())
1986 if (
auto *
F =
N.getRawFile())
1990void Verifier::visitDIProperty(
const DIProperty &
N) {
1991 CheckDI(
N.getTag() == dwarf::DW_TAG_property,
"invalid tag", &
N);
1992 if (
auto *
T =
N.getRawType())
1994 if (
auto *
F =
N.getRawFile())
1998 if (DINode *BackingStorage =
N.getBackingStorage()) {
2000 CheckDI(DT && DT->getTag() == dwarf::DW_TAG_member,
2001 "property backing storage must be a member", &
N, BackingStorage);
2005void Verifier::visitDIImportedEntity(
const DIImportedEntity &
N) {
2006 CheckDI(
N.getTag() == dwarf::DW_TAG_imported_module ||
2007 N.getTag() == dwarf::DW_TAG_imported_declaration,
2009 if (
auto *S =
N.getRawScope())
2015void Verifier::visitComdat(
const Comdat &
C) {
2020 if (
TT.isOSBinFormatCOFF()) {
2021 const GlobalValue *GV =
M.getNamedValue(
C.getName());
2027 Check(
C.getUsers().empty(),
2028 "COFF comdats must have a defined global value with the same name",
2033void Verifier::visitModuleIdents() {
2034 const NamedMDNode *Idents =
M.getNamedMetadata(
"llvm.ident");
2040 for (
const MDNode *
N : Idents->
operands()) {
2041 Check(
N->getNumOperands() == 1,
2042 "incorrect number of operands in llvm.ident metadata",
N);
2044 (
"invalid value for llvm.ident metadata entry operand"
2045 "(the operand should be a string)"),
2050void Verifier::visitModuleCommandLines() {
2051 const NamedMDNode *CommandLines =
M.getNamedMetadata(
"llvm.commandline");
2058 for (
const MDNode *
N : CommandLines->
operands()) {
2059 Check(
N->getNumOperands() == 1,
2060 "incorrect number of operands in llvm.commandline metadata",
N);
2062 (
"invalid value for llvm.commandline metadata entry operand"
2063 "(the operand should be a string)"),
2068void Verifier::visitModuleErrnoTBAA() {
2069 const NamedMDNode *ErrnoTBAA =
M.getNamedMetadata(
"llvm.errno.tbaa");
2074 "llvm.errno.tbaa must have at least one operand", ErrnoTBAA);
2076 for (
const MDNode *
N : ErrnoTBAA->
operands())
2080void Verifier::visitModuleRawSections() {
2081 const NamedMDNode *RawSections =
M.getNamedMetadata(
"llvm.raw.sections");
2085 for (
const MDNode *
N : RawSections->
operands()) {
2086 if (
N->getNumOperands() != 4) {
2087 CheckFailed(
"llvm.raw.sections entry must have four operands",
N);
2091 "llvm.raw.sections entry operand 0 must be a string "
2096 "llvm.raw.sections entry operand 1 must be an integer "
2100 CheckFailed(
"llvm.raw.sections entry operand 1 must be a power of two "
2107 "llvm.raw.sections entry operand 2 must be an integer "
2110 if (FlagsCI->getZExtValue() != 0) {
2111 CheckFailed(
"llvm.raw.sections entry operand 2 must be zero (flags are "
2112 "reserved for future use)",
2117 "llvm.raw.sections entry operand 3 must be a string "
2123void Verifier::visitModuleFlags() {
2124 const NamedMDNode *
Flags =
M.getModuleFlagsMetadata();
2128 DenseMap<const MDString*, const MDNode*> SeenIDs;
2132 std::optional<uint64_t> PAuthABIPlatform;
2133 std::optional<uint64_t> PAuthABIVersion;
2136 uint64_t HasPtrauthInitFiniAddr = 0;
2138 for (
const MDNode *MDN :
Flags->operands()) {
2139 visitModuleFlag(MDN, SeenIDs, Requirements);
2140 if (MDN->getNumOperands() != 3)
2144 auto GetFlagNamed = [&](StringRef
Name) -> std::optional<uint64_t> {
2145 if (FlagName->getString() != Name)
2146 return std::nullopt;
2147 if (
const auto *FlagValue =
2149 return FlagValue->getZExtValue();
2151 CheckFailed(Name +
": module flag expects integer value");
2152 return std::nullopt;
2155 if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-platform"))
2156 PAuthABIPlatform = *
Value;
2157 else if (
auto Value = GetFlagNamed(
"aarch64-elf-pauthabi-version"))
2158 PAuthABIVersion = *
Value;
2159 else if (
auto Value = GetFlagNamed(
"ptrauth-init-fini"))
2160 HasPtrauthInitFini = *
Value;
2161 else if (
auto Value =
2162 GetFlagNamed(
"ptrauth-init-fini-address-discrimination"))
2163 HasPtrauthInitFiniAddr = *
Value;
2168 "ptrauth-init-fini must be 0 or 1");
2170 "ptrauth-init-fini-address-discrimination must be 0 or 1, if set");
2171 if (HasPtrauthInitFiniAddr)
2172 Check(HasPtrauthInitFini,
"ptrauth-init-fini-address-discrimination module "
2173 "flag requires ptrauth-init-fini");
2175 if (PAuthABIPlatform.has_value() != PAuthABIVersion.has_value())
2176 CheckFailed(
"either both or no 'aarch64-elf-pauthabi-platform' and "
2177 "'aarch64-elf-pauthabi-version' module flags must be present");
2180 for (
const MDNode *Requirement : Requirements) {
2184 const MDNode *
Op = SeenIDs.
lookup(Flag);
2186 CheckFailed(
"invalid requirement on flag, flag is not present in module",
2191 if (
Op->getOperand(2) != ReqValue) {
2192 CheckFailed((
"invalid requirement on flag, "
2193 "flag does not have the required value"),
2201Verifier::visitModuleFlag(
const MDNode *
Op,
2202 DenseMap<const MDString *, const MDNode *> &SeenIDs,
2203 SmallVectorImpl<const MDNode *> &Requirements) {
2207 "incorrect number of operands in module flag",
Op);
2208 Module::ModFlagBehavior MFB;
2209 if (!Module::isValidModFlagBehavior(
Op->getOperand(0), MFB)) {
2211 "invalid behavior operand in module flag (expected constant integer)",
2214 "invalid behavior operand in module flag (unexpected constant)",
2218 Check(ID,
"invalid ID operand in module flag (expected metadata string)",
2224 case Module::Warning:
2225 case Module::Override:
2231 Check(
V &&
V->getValue().isNonNegative(),
2232 "invalid value for 'min' module flag (expected constant non-negative "
2240 "invalid value for 'max' module flag (expected constant integer)",
2245 case Module::Require: {
2250 "invalid value for 'require' module flag (expected metadata pair)",
2253 (
"invalid value for 'require' module flag "
2254 "(first value operand should be a string)"),
2255 Value->getOperand(0));
2263 case Module::Append:
2264 case Module::AppendUnique: {
2267 "invalid value for 'append'-type module flag "
2268 "(expected a metadata node)",
2275 if (MFB != Module::Require) {
2278 "module flag identifiers must be unique (or of 'require' type)", ID);
2281 StringRef
Name =
ID->getString();
2282 if (Name ==
"wchar_size") {
2286 "wchar_size metadata requires constant positive integer argument");
2290 if (Name ==
"long-double-type") {
2291 Check(MFB == Module::Error,
2292 "long-double-type module flag must use 'error' merge behavior",
Op);
2294 Check(
Value,
"long-double-type metadata requires a string argument");
2297 "invalid long-double-type metadata value",
Op);
2301 if (Name ==
"float-abi") {
2302 Check(MFB == Module::Error,
2303 "float-abi module flag must use 'error' merge behavior",
Op);
2305 Check(
Value,
"float-abi metadata requires a string argument");
2308 "invalid float-abi metadata value",
Op);
2312 if (Name ==
"thread-model") {
2313 Check(MFB == Module::Error,
2314 "thread-model module flag must use 'error' merge behavior",
Op);
2316 Check(
Value,
"thread-model metadata requires a string argument");
2319 "invalid thread-model metadata value",
Op);
2323 if (Name ==
"target-abi") {
2326 "target-abi metadata requires a non-empty string argument",
Op);
2330 if (
ID->getString() ==
"exception-model") {
2331 Check(MFB == Module::Error,
2332 "exception-model module flag must use 'error' merge behavior",
Op);
2334 Check(
Value,
"exception-model metadata requires a string argument");
2337 "invalid exception-model metadata value",
Op);
2341 if (Name ==
"debugger-tuning") {
2344 "debugger-tuning metadata requires a non-empty string argument",
Op);
2348 if (Name ==
"Linker Options") {
2352 Check(
M.getNamedMetadata(
"llvm.linker.options"),
2353 "'Linker Options' named metadata no longer supported");
2357 if (Name ==
"SemanticInterposition") {
2358 ConstantInt *
Value =
2361 "SemanticInterposition metadata requires constant integer argument");
2365 if (Name ==
"CG Profile") {
2366 for (
const MDOperand &MDO :
cast<MDNode>(
Op->getOperand(2))->operands())
2367 visitModuleFlagCGProfileEntry(MDO);
2375void Verifier::visitModuleFlagCGProfileEntry(
const MDOperand &MDO) {
2376 auto CheckFunction = [&](
const MDOperand &FuncMDO) {
2381 "expected a Function or null", FuncMDO);
2384 Check(Node &&
Node->getNumOperands() == 3,
"expected a MDNode triple", MDO);
2385 CheckFunction(
Node->getOperand(0));
2386 CheckFunction(
Node->getOperand(1));
2389 "expected an integer constant",
Node->getOperand(2));
2392void Verifier::verifyAttributeTypes(AttributeSet Attrs,
const Value *
V) {
2395 if (
A.isStringAttribute()) {
2396#define GET_ATTR_NAMES
2397#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME)
2398#define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \
2399 if (A.getKindAsString() == #DISPLAY_NAME) { \
2400 auto V = A.getValueAsString(); \
2401 if (!(V.empty() || V == "true" || V == "false")) \
2402 CheckFailed("invalid value for '" #DISPLAY_NAME "' attribute: " + V + \
2406#include "llvm/IR/Attributes.inc"
2410 if (
A.isIntAttribute() != Attribute::isIntAttrKind(
A.getKindAsEnum())) {
2411 CheckFailed(
"Attribute '" +
A.getAsString() +
"' should have an Argument",
2420void Verifier::verifyParameterAttrs(AttributeSet Attrs,
Type *Ty,
2422 if (!
Attrs.hasAttributes())
2425 verifyAttributeTypes(Attrs,
V);
2428 Check(Attr.isStringAttribute() ||
2429 Attribute::canUseAsParamAttr(Attr.getKindAsEnum()),
2430 "Attribute '" + Attr.getAsString() +
"' does not apply to parameters",
2434 if (
Attrs.getNumAttributes() > 1) {
2435 if (
Attrs.hasAttribute(Attribute::ImmArg)) {
2436 unsigned AttrCount =
2437 Attrs.getNumAttributes() -
Attrs.hasAttribute(Attribute::Range);
2440 "Attribute 'immarg' is incompatible with other attributes except the "
2441 "'range' attribute",
2447 unsigned AttrCount = 0;
2448 AttrCount +=
Attrs.hasAttribute(Attribute::ByVal);
2449 AttrCount +=
Attrs.hasAttribute(Attribute::InAlloca);
2450 AttrCount +=
Attrs.hasAttribute(Attribute::Preallocated);
2451 AttrCount +=
Attrs.hasAttribute(Attribute::StructRet) ||
2452 Attrs.hasAttribute(Attribute::InReg);
2453 AttrCount +=
Attrs.hasAttribute(Attribute::Nest);
2454 AttrCount +=
Attrs.hasAttribute(Attribute::ByRef);
2455 Check(AttrCount <= 1,
2456 "Attributes 'byval', 'inalloca', 'preallocated', 'inreg', 'nest', "
2457 "'byref', and 'sret' are incompatible!",
2460 Check(!(
Attrs.hasAttribute(Attribute::InAlloca) &&
2461 Attrs.hasAttribute(Attribute::ReadOnly)),
2463 "'inalloca and readonly' are incompatible!",
2466 Check(!(
Attrs.hasAttribute(Attribute::StructRet) &&
2467 Attrs.hasAttribute(Attribute::Returned)),
2469 "'sret and returned' are incompatible!",
2472 Check(!(
Attrs.hasAttribute(Attribute::ZExt) &&
2473 Attrs.hasAttribute(Attribute::SExt)),
2475 "'zeroext and signext' are incompatible!",
2478 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2479 Attrs.hasAttribute(Attribute::ReadOnly)),
2481 "'readnone and readonly' are incompatible!",
2484 Check(!(
Attrs.hasAttribute(Attribute::ReadNone) &&
2485 Attrs.hasAttribute(Attribute::WriteOnly)),
2487 "'readnone and writeonly' are incompatible!",
2490 Check(!(
Attrs.hasAttribute(Attribute::ReadOnly) &&
2491 Attrs.hasAttribute(Attribute::WriteOnly)),
2493 "'readonly and writeonly' are incompatible!",
2496 Check(!(
Attrs.hasAttribute(Attribute::NoInline) &&
2497 Attrs.hasAttribute(Attribute::AlwaysInline)),
2499 "'noinline and alwaysinline' are incompatible!",
2502 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2503 Attrs.hasAttribute(Attribute::ReadNone)),
2504 "Attributes writable and readnone are incompatible!",
V);
2506 Check(!(
Attrs.hasAttribute(Attribute::Writable) &&
2507 Attrs.hasAttribute(Attribute::ReadOnly)),
2508 "Attributes writable and readonly are incompatible!",
V);
2511 AttributeMask IncompatibleAttrs = AttributeFuncs::typeIncompatible(Ty, Attrs);
2513 if (!Attr.isStringAttribute() &&
2514 IncompatibleAttrs.
contains(Attr.getKindAsEnum())) {
2515 CheckFailed(
"Attribute '" + Attr.getAsString() +
2516 "' applied to incompatible type!",
V);
2522 if (
Attrs.hasAttribute(Attribute::Alignment)) {
2523 Align AttrAlign =
Attrs.getAlignment().valueOrOne();
2524 Check(AttrAlign.
value() <= Value::MaximumAlignment,
2525 "huge alignment values are unsupported",
V);
2527 if (
Attrs.hasAttribute(Attribute::ByVal)) {
2530 "Attribute 'byval' does not support unsized types!",
V);
2534 "'byval' argument has illegal target extension type",
V);
2538 "scalable 'byval' arguments are unsupported",
V);
2539 Check(
DL.getTypeAllocSize(ByValTy).getKnownMinValue() < (1ULL << 32),
2540 "huge 'byval' arguments are unsupported",
V);
2542 if (
Attrs.hasAttribute(Attribute::ByRef)) {
2544 "Attribute 'byref' does not support unsized types!",
V);
2545 Check(
DL.getTypeAllocSize(
Attrs.getByRefType()).getKnownMinValue() <
2547 "huge 'byref' arguments are unsupported",
V);
2549 if (
Attrs.hasAttribute(Attribute::InAlloca)) {
2551 "Attribute 'inalloca' does not support unsized types!",
V);
2552 Check(
DL.getTypeAllocSize(
Attrs.getInAllocaType()).getKnownMinValue() <
2554 "huge 'inalloca' arguments are unsupported",
V);
2556 if (
Attrs.hasAttribute(Attribute::Preallocated)) {
2557 Check(
Attrs.getPreallocatedType()->isSized(),
2558 "Attribute 'preallocated' does not support unsized types!",
V);
2560 DL.getTypeAllocSize(
Attrs.getPreallocatedType()).getKnownMinValue() <
2562 "huge 'preallocated' arguments are unsupported",
V);
2566 if (
Attrs.hasAttribute(Attribute::Initializes)) {
2567 auto Inits =
Attrs.getAttribute(Attribute::Initializes).getInitializes();
2568 Check(!Inits.empty(),
"Attribute 'initializes' does not support empty list",
2571 "Attribute 'initializes' does not support unordered ranges",
V);
2574 if (
Attrs.hasAttribute(Attribute::NoFPClass)) {
2575 uint64_t Val =
Attrs.getAttribute(Attribute::NoFPClass).getValueAsInt();
2576 Check(Val != 0,
"Attribute 'nofpclass' must have at least one test bit set",
2579 "Invalid value for 'nofpclass' test mask",
V);
2581 if (
Attrs.hasAttribute(Attribute::Range)) {
2582 const ConstantRange &CR =
2583 Attrs.getAttribute(Attribute::Range).getValueAsConstantRange();
2585 "Range bit width must match type bit width!",
V);
2589void Verifier::checkUnsignedBaseTenFuncAttr(AttributeList Attrs, StringRef Attr,
2591 if (
Attrs.hasFnAttr(Attr)) {
2592 StringRef S =
Attrs.getFnAttr(Attr).getValueAsString();
2595 CheckFailed(
"\"" + Attr +
"\" takes an unsigned integer: " + S,
V);
2601void Verifier::verifyFunctionAttrs(FunctionType *FT, AttributeList Attrs,
2602 const Value *
V,
bool IsIntrinsic,
2604 if (
Attrs.isEmpty())
2607 if (AttributeListsVisited.
insert(
Attrs.getRawPointer()).second) {
2609 "Attribute list does not match Module context!", &Attrs,
V);
2610 for (
const auto &AttrSet : Attrs) {
2611 Check(!AttrSet.hasAttributes() || AttrSet.hasParentContext(
Context),
2612 "Attribute set does not match Module context!", &AttrSet,
V);
2613 for (
const auto &
A : AttrSet) {
2615 "Attribute does not match Module context!", &
A,
V);
2620 bool SawNest =
false;
2621 bool SawReturned =
false;
2622 bool SawSRet =
false;
2623 bool SawSwiftSelf =
false;
2624 bool SawSwiftAsync =
false;
2625 bool SawSwiftError =
false;
2628 AttributeSet RetAttrs =
Attrs.getRetAttrs();
2631 Attribute::canUseAsRetAttr(
RetAttr.getKindAsEnum()),
2632 "Attribute '" +
RetAttr.getAsString() +
2633 "' does not apply to function return values",
2636 unsigned MaxParameterWidth = 0;
2637 auto GetMaxParameterWidth = [&MaxParameterWidth](
Type *Ty) {
2640 unsigned Size = VT->getPrimitiveSizeInBits().getFixedValue();
2641 if (
Size > MaxParameterWidth)
2642 MaxParameterWidth =
Size;
2646 GetMaxParameterWidth(FT->getReturnType());
2647 verifyParameterAttrs(RetAttrs, FT->getReturnType(),
V);
2650 for (
unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2651 Type *Ty = FT->getParamType(i);
2652 AttributeSet ArgAttrs =
Attrs.getParamAttrs(i);
2656 "immarg attribute only applies to intrinsics",
V);
2659 "Attribute 'elementtype' can only be applied to intrinsics"
2664 verifyParameterAttrs(ArgAttrs, Ty,
V);
2665 GetMaxParameterWidth(Ty);
2668 Check(!SawNest,
"More than one parameter has attribute nest!",
V);
2673 Check(!SawReturned,
"More than one parameter has attribute returned!",
V);
2675 "Incompatible argument and return types for 'returned' attribute",
2681 Check(!SawSRet,
"Cannot have multiple 'sret' parameters!",
V);
2682 Check(i == 0 || i == 1,
2683 "Attribute 'sret' is not on first or second parameter!",
V);
2688 Check(!SawSwiftSelf,
"Cannot have multiple 'swiftself' parameters!",
V);
2689 SawSwiftSelf =
true;
2693 Check(!SawSwiftAsync,
"Cannot have multiple 'swiftasync' parameters!",
V);
2694 SawSwiftAsync =
true;
2698 Check(!SawSwiftError,
"Cannot have multiple 'swifterror' parameters!",
V);
2699 SawSwiftError =
true;
2703 Check(i == FT->getNumParams() - 1,
2704 "inalloca isn't on the last parameter!",
V);
2708 if (!
Attrs.hasFnAttrs())
2711 verifyAttributeTypes(
Attrs.getFnAttrs(),
V);
2714 Attribute::canUseAsFnAttr(
FnAttr.getKindAsEnum()),
2715 "Attribute '" +
FnAttr.getAsString() +
2716 "' does not apply to functions!",
2719 Check(!(
Attrs.hasFnAttr(Attribute::NoInline) &&
2720 Attrs.hasFnAttr(Attribute::AlwaysInline)),
2721 "Attributes 'noinline and alwaysinline' are incompatible!",
V);
2723 if (
Attrs.hasFnAttr(Attribute::OptimizeNone)) {
2724 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2725 "Attributes 'optsize and optnone' are incompatible!",
V);
2728 "Attributes 'minsize and optnone' are incompatible!",
V);
2730 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForDebugging),
2731 "Attributes 'optdebug and optnone' are incompatible!",
V);
2734 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeRealtime) &&
2735 Attrs.hasFnAttr(Attribute::SanitizeRealtimeBlocking)),
2737 "'sanitize_realtime and sanitize_realtime_blocking' are incompatible!",
2740 Check(!(
Attrs.hasFnAttr(Attribute::SanitizeThread) &&
2741 Attrs.hasFnAttr(Attribute::SanitizeConcurrency)),
2742 "Attributes 'sanitize_thread and sanitize_concurrency' are "
2746 if (
Attrs.hasFnAttr(Attribute::OptimizeForDebugging)) {
2747 Check(!
Attrs.hasFnAttr(Attribute::OptimizeForSize),
2748 "Attributes 'optsize and optdebug' are incompatible!",
V);
2751 "Attributes 'minsize and optdebug' are incompatible!",
V);
2754 Check(!
Attrs.hasAttrSomewhere(Attribute::Writable) ||
2755 isModSet(
Attrs.getMemoryEffects().getModRef(IRMemLocation::ArgMem)),
2756 "Attribute writable and memory without argmem: write are incompatible!",
2759 if (
Attrs.hasFnAttr(
"aarch64_pstate_sm_enabled")) {
2760 Check(!
Attrs.hasFnAttr(
"aarch64_pstate_sm_compatible"),
2761 "Attributes 'aarch64_pstate_sm_enabled and "
2762 "aarch64_pstate_sm_compatible' are incompatible!",
2766 Check((
Attrs.hasFnAttr(
"aarch64_new_za") +
Attrs.hasFnAttr(
"aarch64_in_za") +
2767 Attrs.hasFnAttr(
"aarch64_inout_za") +
2768 Attrs.hasFnAttr(
"aarch64_out_za") +
2769 Attrs.hasFnAttr(
"aarch64_preserves_za") +
2770 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2771 "Attributes 'aarch64_new_za', 'aarch64_in_za', 'aarch64_out_za', "
2772 "'aarch64_inout_za', 'aarch64_preserves_za' and "
2773 "'aarch64_za_state_agnostic' are mutually exclusive",
2777 Attrs.hasFnAttr(
"aarch64_in_zt0") +
2778 Attrs.hasFnAttr(
"aarch64_inout_zt0") +
2779 Attrs.hasFnAttr(
"aarch64_out_zt0") +
2780 Attrs.hasFnAttr(
"aarch64_preserves_zt0") +
2781 Attrs.hasFnAttr(
"aarch64_za_state_agnostic")) <= 1,
2782 "Attributes 'aarch64_new_zt0', 'aarch64_in_zt0', 'aarch64_out_zt0', "
2783 "'aarch64_inout_zt0', 'aarch64_preserves_zt0' and "
2784 "'aarch64_za_state_agnostic' are mutually exclusive",
2787 if (
Attrs.hasFnAttr(Attribute::JumpTable)) {
2790 "Attribute 'jumptable' requires 'unnamed_addr'",
V);
2793 if (
auto Args =
Attrs.getFnAttrs().getAllocSizeArgs()) {
2794 auto CheckParam = [&](StringRef
Name,
unsigned ParamNo) {
2795 if (ParamNo >= FT->getNumParams()) {
2796 CheckFailed(
"'allocsize' " + Name +
" argument is out of bounds",
V);
2800 if (!FT->getParamType(ParamNo)->isIntegerTy()) {
2801 CheckFailed(
"'allocsize' " + Name +
2802 " argument must refer to an integer parameter",
2810 if (!CheckParam(
"element size",
Args->first))
2813 if (
Args->second && !CheckParam(
"number of elements", *
Args->second))
2817 if (
Attrs.hasFnAttr(Attribute::AllocKind)) {
2820 K & (AllocFnKind::Alloc | AllocFnKind::Realloc | AllocFnKind::Free);
2822 {AllocFnKind::Alloc, AllocFnKind::Realloc, AllocFnKind::Free},
2825 "'allockind()' requires exactly one of alloc, realloc, and free");
2826 if ((
Type == AllocFnKind::Free) &&
2827 ((K & (AllocFnKind::Uninitialized | AllocFnKind::Zeroed |
2828 AllocFnKind::Aligned)) != AllocFnKind::Unknown))
2829 CheckFailed(
"'allockind(\"free\")' doesn't allow uninitialized, zeroed, "
2830 "or aligned modifiers.");
2831 AllocFnKind ZeroedUninit = AllocFnKind::Uninitialized | AllocFnKind::Zeroed;
2832 if ((K & ZeroedUninit) == ZeroedUninit)
2833 CheckFailed(
"'allockind()' can't be both zeroed and uninitialized");
2837 StringRef S =
A.getValueAsString();
2838 Check(!S.
empty(),
"'alloc-variant-zeroed' must not be empty");
2846 "'alloc-variant-zeroed' must name a function belonging to the "
2847 "same 'alloc-family'");
2850 (
Variant->getFnAttribute(Attribute::AllocKind).getAllocKind() &
2851 AllocFnKind::Zeroed) != AllocFnKind::Unknown,
2852 "'alloc-variant-zeroed' must name a function with "
2853 "'allockind(\"zeroed\")'");
2856 "'alloc-variant-zeroed' must name a function with the same "
2861 "'alloc-variant-zeroed' must name a function with the same "
2862 "calling convention");
2866 if (
Attrs.hasFnAttr(Attribute::VScaleRange)) {
2867 unsigned VScaleMin =
Attrs.getFnAttrs().getVScaleRangeMin();
2869 CheckFailed(
"'vscale_range' minimum must be greater than 0",
V);
2871 CheckFailed(
"'vscale_range' minimum must be power-of-two value",
V);
2872 std::optional<unsigned> VScaleMax =
Attrs.getFnAttrs().getVScaleRangeMax();
2873 if (VScaleMax && VScaleMin > VScaleMax)
2874 CheckFailed(
"'vscale_range' minimum cannot be greater than maximum",
V);
2876 CheckFailed(
"'vscale_range' maximum must be power-of-two value",
V);
2879 if (
Attribute FPAttr =
Attrs.getFnAttr(
"frame-pointer"); FPAttr.isValid()) {
2880 StringRef
FP = FPAttr.getValueAsString();
2881 if (
FP !=
"all" &&
FP !=
"non-leaf" &&
FP !=
"none" &&
FP !=
"reserved" &&
2882 FP !=
"non-leaf-no-reserve")
2883 CheckFailed(
"invalid value for 'frame-pointer' attribute: " +
FP,
V);
2886 checkUnsignedBaseTenFuncAttr(Attrs,
"tail-pad-to-size",
V);
2887 checkUnsignedBaseTenFuncAttr(Attrs,
"tail-pad-value",
V);
2888 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-prefix",
V);
2889 checkUnsignedBaseTenFuncAttr(Attrs,
"patchable-function-entry",
V);
2890 if (
Attrs.hasFnAttr(
"patchable-function-entry-section"))
2891 Check(!
Attrs.getFnAttr(
"patchable-function-entry-section")
2894 "\"patchable-function-entry-section\" must not be empty");
2895 checkUnsignedBaseTenFuncAttr(Attrs,
"warn-stack-size",
V);
2896 checkUnsignedBaseTenFuncAttr(Attrs,
"unsafe-stack-size",
V);
2898 checkUnsignedBaseTenFuncAttr(Attrs, Attr,
V);
2900 if (
auto A =
Attrs.getFnAttr(
"sign-return-address");
A.isValid()) {
2901 StringRef S =
A.getValueAsString();
2902 if (S !=
"none" && S !=
"all" && S !=
"non-leaf")
2903 CheckFailed(
"invalid value for 'sign-return-address' attribute: " + S,
V);
2906 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-key");
A.isValid()) {
2907 StringRef S =
A.getValueAsString();
2908 if (S !=
"a_key" && S !=
"b_key")
2909 CheckFailed(
"invalid value for 'sign-return-address-key' attribute: " + S,
2911 if (
auto AA =
Attrs.getFnAttr(
"sign-return-address"); !AA.isValid()) {
2913 "'sign-return-address-key' present without `sign-return-address`");
2917 if (
auto A =
Attrs.getFnAttr(
"sign-return-address-harden");
A.isValid()) {
2918 StringRef S =
A.getValueAsString();
2919 if (S !=
"load-return-address" && S !=
"none")
2921 "invalid value for 'sign-return-address-harden' attribute: " + S,
V);
2922 auto SignRetA =
Attrs.getFnAttr(
"sign-return-address");
2923 auto PAuthRetA =
Attrs.getFnAttr(
"ptrauth-returns");
2924 if (!SignRetA.isValid() && !PAuthRetA.isValid())
2925 CheckFailed(
"'sign-return-address-harden' present without "
2926 "'sign-return-address' or 'ptrauth-returns'");
2929 if (
auto A =
Attrs.getFnAttr(
"branch-target-enforcement");
A.isValid()) {
2930 StringRef S =
A.getValueAsString();
2931 if (S !=
"" && S !=
"true" && S !=
"false")
2933 "invalid value for 'branch-target-enforcement' attribute: " + S,
V);
2936 if (
auto A =
Attrs.getFnAttr(
"branch-protection-pauth-lr");
A.isValid()) {
2937 StringRef S =
A.getValueAsString();
2938 if (S !=
"" && S !=
"true" && S !=
"false")
2940 "invalid value for 'branch-protection-pauth-lr' attribute: " + S,
V);
2943 if (
auto A =
Attrs.getFnAttr(
"guarded-control-stack");
A.isValid()) {
2944 StringRef S =
A.getValueAsString();
2945 if (S !=
"" && S !=
"true" && S !=
"false")
2946 CheckFailed(
"invalid value for 'guarded-control-stack' attribute: " + S,
2950 if (
auto A =
Attrs.getFnAttr(
"vector-function-abi-variant");
A.isValid()) {
2951 StringRef S =
A.getValueAsString();
2954 CheckFailed(
"invalid name for a VFABI variant: " + S,
V);
2957 if (
auto A =
Attrs.getFnAttr(
"modular-format");
A.isValid()) {
2958 StringRef S =
A.getValueAsString();
2962 "modular-format attribute requires at least 5 arguments",
V);
2963 unsigned UpperBound = FT->getNumParams() + (FT->isVarArg() ? 1 : 0);
2965 Check(!Args[1].getAsInteger(10, FormatIdx),
2966 "modular-format attribute format string index is not an integer",
V);
2967 Check(FormatIdx > 0,
2968 "modular-format attribute format string index must be greater than 0",
2970 Check(FormatIdx <= UpperBound,
2971 "modular-format attribute format string index is out of bounds",
V);
2972 unsigned FirstArgIdx;
2973 Check(!Args[2].getAsInteger(10, FirstArgIdx),
2974 "modular-format attribute first arg index is not an integer",
V);
2975 Check(FirstArgIdx <= UpperBound,
2976 "modular-format attribute first arg index is out of bounds",
V);
2978 "modular-format attribute modular implementation function name "
2982 "modular-format attribute implementation name cannot be empty",
V);
2985 if (
auto A =
Attrs.getFnAttr(
"target-features");
A.isValid()) {
2986 StringRef S =
A.getValueAsString();
2988 for (
auto FeatureFlag :
split(S,
',')) {
2989 if (FeatureFlag.empty())
2991 "target-features attribute should not contain an empty string");
2993 Check(FeatureFlag[0] ==
'+' || FeatureFlag[0] ==
'-',
2994 "target feature '" + FeatureFlag +
2995 "' must start with a '+' or '-'",
3001 Check(!(
Attrs.hasFnAttr(Attribute::Hot) &&
Attrs.hasFnAttr(Attribute::Cold)),
3002 "Attributes 'hot' and 'cold' are incompatible");
3004 if (
Attrs.hasFnAttr(
"mnop-mcount")) {
3005 auto A =
Attrs.getFnAttr(
"fentry-call");
3006 Check(
A.isValid() &&
A.getValueAsString() ==
"true",
3007 "mnop-mcount only supported with fentry-call");
3010 if (
Attrs.hasFnAttr(
"mrecord-mcount")) {
3011 auto A =
Attrs.getFnAttr(
"fentry-call");
3012 Check(
A.isValid() &&
A.getValueAsString() ==
"true",
3013 "mrecord-mcount only supported with fentry-call");
3016 if (
Attrs.hasFnAttr(
"oracle-function")) {
3018 Check(
F,
"\"oracle-function\" attribute only applies to functions",
V);
3019 Check(
F->hasLocalLinkage(),
"oracle function must have local linkage",
V);
3020 Check(
F->onlyReadsMemory() &&
F->onlyAccessesArgMemory() &&
3021 F->doesNotThrow() &&
F->hasNoSync() &&
F->willReturn(),
3022 "oracle function must be nounwind, nosync and willreturn, must not "
3023 "have side effects and may only read memory through its arguments",
3025 Check(FT->getReturnType()->isIntegerTy(64),
3026 "oracle function must return i64",
V);
3027 Check(!FT->isVarArg(),
"oracle function must have a fixed argument list",
3029 if (
M.isMaterialized()) {
3030 for (
const Use &U :
F->uses()) {
3032 Check(
II &&
II->getIntrinsicID() == Intrinsic::speculative_load &&
3033 II->isArgOperand(&U) &&
II->getArgOperandNo(&U) == 2,
3034 "oracle function may only be used as the oracle operand of "
3035 "llvm.speculative.load",
3042void Verifier::verifyUnknownProfileMetadata(MDNode *MD) {
3044 "'unknown' !prof should have a single additional operand", MD);
3047 "'unknown' !prof should have an additional operand of type "
3050 "the 'unknown' !prof operand should not be an empty string");
3053void Verifier::verifyFunctionMetadata(
3054 ArrayRef<std::pair<unsigned, MDNode *>> MDs) {
3055 for (
const auto &Pair : MDs) {
3056 if (Pair.first == LLVMContext::MD_prof) {
3057 MDNode *MD = Pair.second;
3059 "!prof annotations should have no less than 2 operands", MD);
3064 verifyUnknownProfileMetadata(MD);
3069 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null",
3072 "expected string with name of the !prof annotation", MD);
3076 "first operand should be 'function_entry_count'", MD);
3079 Check(MD->
getOperand(1) !=
nullptr,
"second operand should not be null",
3082 "expected integer argument to function_entry_count", MD);
3083 }
else if (Pair.first == LLVMContext::MD_kcfi_type) {
3084 MDNode *MD = Pair.second;
3086 "!kcfi_type must have exactly one operand", MD);
3087 Check(MD->
getOperand(0) !=
nullptr,
"!kcfi_type operand must not be null",
3090 "expected a constant operand for !kcfi_type", MD);
3093 "expected a constant integer operand for !kcfi_type", MD);
3095 "expected a 32-bit integer constant operand for !kcfi_type", MD);
3096 }
else if (Pair.first ==
Context.getMDKindID(
"reqd_work_group_size")) {
3097 MDNode *MD = Pair.second;
3099 "reqd_work_group_size must have exactly three operands", MD);
3104 for (
unsigned I = 0;
I != 3; ++
I) {
3106 Check(
C,
"reqd_work_group_size operands must be integer constants", MD);
3110 const APInt &
Value =
C->getValue();
3112 "reqd_work_group_size operands must fit in 64 bits", MD);
3113 if (
Value.getActiveBits() > 64)
3117 Check(Dim == 0 || Product <= std::numeric_limits<uint64_t>::max() / Dim,
3118 "reqd_work_group_size product must fit in 64 bits", MD);
3119 if (Dim != 0 && Product > std::numeric_limits<uint64_t>::max() / Dim)
3127void Verifier::visitConstantExprsRecursively(
const Constant *EntryC) {
3131 if (!ConstantExprVisited.
insert(EntryC).second)
3135 Stack.push_back(EntryC);
3137 while (!
Stack.empty()) {
3142 visitConstantExpr(CE);
3145 visitConstantPtrAuth(CPA);
3150 Check(GV->
getParent() == &M,
"Referencing global in another module!",
3156 for (
const Use &U :
C->operands()) {
3160 if (!ConstantExprVisited.
insert(OpC).second)
3162 Stack.push_back(OpC);
3167void Verifier::visitConstantExpr(
const ConstantExpr *CE) {
3168 if (
CE->getOpcode() == Instruction::BitCast) {
3171 "Invalid bitcast", CE);
3172 Check(
DL.getTypeSizeInBits(
CE->getOperand(0)->getType()) ==
3173 DL.getTypeSizeInBits(
CE->getType()),
3174 "Invalid bitcast", CE);
3175 }
else if (
CE->getOpcode() == Instruction::PtrToAddr)
3176 checkPtrToAddr(
CE->getOperand(0)->getType(),
CE->getType(), *CE);
3177 else if (
CE->getOpcode() == Instruction::GetElementPtr)
3181void Verifier::visitConstantPtrAuth(
const ConstantPtrAuth *CPA) {
3183 "signed ptrauth constant base pointer must have pointer type");
3186 "signed ptrauth constant must have same type as its base pointer");
3189 "signed ptrauth constant key must be i32 constant integer");
3192 "signed ptrauth constant address discriminator must be a pointer");
3195 "signed ptrauth constant discriminator must be i64 constant integer");
3198 "signed ptrauth constant deactivation symbol must be a pointer");
3202 "signed ptrauth constant deactivation symbol must be a global value "
3206bool Verifier::verifyAttributeCount(AttributeList Attrs,
unsigned Params) {
3209 return Attrs.getNumAttrSets() <= Params + 2;
3212void Verifier::verifyInlineAsmCall(
const CallBase &
Call) {
3215 unsigned LabelNo = 0;
3216 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
3226 if (CI.isIndirect) {
3229 "Operand for indirect constraint must have pointer type", &
Call);
3232 "Operand for indirect constraint must have elementtype attribute",
3236 "Elementtype attribute can only be applied for indirect "
3245 Check(LabelNo == CallBr->getNumIndirectDests(),
3246 "Number of label constraints does not match number of callbr dests",
3249 Check(LabelNo == 0,
"Label constraints can only be used with callbr",
3255void Verifier::verifyStatepoint(
const CallBase &
Call) {
3260 "gc.statepoint must read and write all memory to preserve "
3261 "reordering restrictions required by safepoint semantics",
3264 const int64_t NumPatchBytes =
3267 Check(NumPatchBytes >= 0,
3268 "gc.statepoint number of patchable bytes must be "
3273 Check(TargetElemType,
3274 "gc.statepoint callee argument must have elementtype attribute",
Call);
3276 Check(TargetFuncType,
3277 "gc.statepoint callee elementtype must be function type",
Call);
3280 Check(NumCallArgs >= 0,
3281 "gc.statepoint number of arguments to underlying call "
3284 const int NumParams = (int)TargetFuncType->getNumParams();
3285 if (TargetFuncType->isVarArg()) {
3286 Check(NumCallArgs >= NumParams,
3287 "gc.statepoint mismatch in number of vararg call args",
Call);
3290 Check(TargetFuncType->getReturnType()->isVoidTy(),
3291 "gc.statepoint doesn't support wrapping non-void "
3292 "vararg functions yet",
3295 Check(NumCallArgs == NumParams,
3296 "gc.statepoint mismatch in number of call args",
Call);
3301 "unknown flag used in gc.statepoint flags argument",
Call);
3306 for (
int i = 0; i < NumParams; i++) {
3307 Type *ParamType = TargetFuncType->getParamType(i);
3309 Check(ArgType == ParamType,
3310 "gc.statepoint call argument does not match wrapped "
3314 if (TargetFuncType->isVarArg()) {
3315 AttributeSet ArgAttrs =
Attrs.getParamAttrs(5 + i);
3317 "Attribute 'sret' cannot be used for vararg call arguments!",
Call);
3321 const int EndCallArgsInx = 4 + NumCallArgs;
3325 "gc.statepoint number of transition arguments "
3326 "must be constant integer",
3328 const int NumTransitionArgs =
3330 Check(NumTransitionArgs == 0,
3331 "gc.statepoint w/inline transition bundle is deprecated",
Call);
3332 const int EndTransitionArgsInx = EndCallArgsInx + 1 + NumTransitionArgs;
3336 "gc.statepoint number of deoptimization arguments "
3337 "must be constant integer",
3340 Check(NumDeoptArgs == 0,
3341 "gc.statepoint w/inline deopt operands is deprecated",
Call);
3343 const int ExpectedNumArgs = 7 + NumCallArgs;
3345 "gc.statepoint too many arguments",
Call);
3352 Check(UserCall,
"illegal use of statepoint token",
Call, U);
3356 "gc.result or gc.relocate are the only value uses "
3357 "of a gc.statepoint",
3360 Check(UserCall->getArgOperand(0) == &
Call,
3361 "gc.result connected to wrong gc.statepoint",
Call, UserCall);
3363 Check(UserCall->getArgOperand(0) == &
Call,
3364 "gc.relocate connected to wrong gc.statepoint",
Call, UserCall);
3378void Verifier::verifyFrameRecoverIndices() {
3379 for (
auto &Counts : FrameEscapeInfo) {
3381 unsigned EscapedObjectCount = Counts.second.first;
3382 unsigned MaxRecoveredIndex = Counts.second.second;
3383 Check(MaxRecoveredIndex <= EscapedObjectCount,
3384 "all indices passed to llvm.localrecover must be less than the "
3385 "number of arguments passed to llvm.localescape in the parent "
3394 UnwindDest =
II->getUnwindDest();
3396 UnwindDest = CSI->getUnwindDest();
3402void Verifier::verifySiblingFuncletUnwinds() {
3403 llvm::TimeTraceScope timeScope(
"Verifier verify sibling funclet unwinds");
3404 SmallPtrSet<Instruction *, 8> Visited;
3405 SmallPtrSet<Instruction *, 8>
Active;
3406 for (
const auto &Pair : SiblingFuncletInfo) {
3408 if (Visited.
count(PredPad))
3414 if (
Active.count(SuccPad)) {
3417 SmallVector<Instruction *, 8> CycleNodes;
3420 Instruction *CycleTerminator = SiblingFuncletInfo[CyclePad];
3421 if (CycleTerminator != CyclePad)
3424 }
while (CyclePad != SuccPad);
3425 Check(
false,
"EH pads can't handle each other's exceptions",
3426 ArrayRef<Instruction *>(CycleNodes));
3429 if (!Visited.
insert(SuccPad).second)
3433 auto TermI = SiblingFuncletInfo.find(PredPad);
3434 if (TermI == SiblingFuncletInfo.end())
3447void Verifier::visitFunction(
const Function &
F) {
3448 visitGlobalValue(
F);
3451 FunctionType *FT =
F.getFunctionType();
3452 unsigned NumArgs =
F.arg_size();
3455 "Function context does not match Module context!", &
F);
3457 Check(!
F.hasCommonLinkage(),
"Functions may not have common linkage", &
F);
3458 Check(FT->getNumParams() == NumArgs,
3459 "# formal arguments must match # of arguments for function type!", &
F,
3461 Check(
F.getReturnType()->isFirstClassType() ||
3462 F.getReturnType()->isVoidTy() ||
F.getReturnType()->isStructTy(),
3463 "Functions cannot return aggregate values!", &
F);
3465 Check(!
F.hasStructRetAttr() ||
F.getReturnType()->isVoidTy(),
3466 "Invalid struct return type!", &
F);
3468 if (MaybeAlign
A =
F.getAlign()) {
3469 Check(
A->value() <= Value::MaximumAlignment,
3470 "huge alignment values are unsupported", &
F);
3473 AttributeList
Attrs =
F.getAttributes();
3475 Check(verifyAttributeCount(Attrs, FT->getNumParams()),
3476 "Attribute after last parameter!", &
F);
3478 bool IsIntrinsic =
F.isIntrinsic();
3481 verifyFunctionAttrs(FT, Attrs, &
F, IsIntrinsic,
false);
3487 "Attribute 'builtin' can only be applied to a callsite.", &
F);
3489 Check(!
Attrs.hasAttrSomewhere(Attribute::ElementType),
3490 "Attribute 'elementtype' can only be applied to a callsite.", &
F);
3492 if (
Attrs.hasFnAttr(Attribute::Naked))
3493 for (
const Argument &Arg :
F.args())
3494 Check(Arg.use_empty(),
"cannot use argument of naked function", &Arg);
3499 switch (
F.getCallingConv()) {
3501 case CallingConv::C:
3503 case CallingConv::X86_INTR: {
3504 Check(
F.arg_empty() ||
Attrs.hasParamAttr(0, Attribute::ByVal),
3505 "Calling convention parameter requires byval", &
F);
3508 case CallingConv::AMDGPU_KERNEL:
3509 case CallingConv::SPIR_KERNEL:
3510 case CallingConv::AMDGPU_CS_Chain:
3511 case CallingConv::AMDGPU_CS_ChainPreserve:
3512 Check(
F.getReturnType()->isVoidTy(),
3513 "Calling convention requires void return type", &
F);
3515 case CallingConv::AMDGPU_VS:
3516 case CallingConv::AMDGPU_HS:
3517 case CallingConv::AMDGPU_GS:
3518 case CallingConv::AMDGPU_PS:
3519 case CallingConv::AMDGPU_CS:
3520 Check(!
F.hasStructRetAttr(),
"Calling convention does not allow sret", &
F);
3521 if (
F.getCallingConv() != CallingConv::SPIR_KERNEL) {
3522 const unsigned StackAS =
DL.getAllocaAddrSpace();
3524 for (
const Argument &Arg :
F.args()) {
3525 Check(!
Attrs.hasParamAttr(i, Attribute::ByVal),
3526 "Calling convention disallows byval", &
F);
3527 Check(!
Attrs.hasParamAttr(i, Attribute::Preallocated),
3528 "Calling convention disallows preallocated", &
F);
3529 Check(!
Attrs.hasParamAttr(i, Attribute::InAlloca),
3530 "Calling convention disallows inalloca", &
F);
3532 if (
Attrs.hasParamAttr(i, Attribute::ByRef)) {
3535 Check(Arg.getType()->getPointerAddressSpace() != StackAS,
3536 "Calling convention disallows stack byref", &
F);
3544 case CallingConv::Fast:
3545 case CallingConv::Cold:
3546 case CallingConv::Intel_OCL_BI:
3547 case CallingConv::PTX_Device:
3549 "Calling convention does not support varargs or "
3550 "perfect forwarding!",
3553 case CallingConv::PTX_Kernel:
3557 Check(!
F.hasFnAttribute(Attr),
3558 "'" + Attr +
"' is not allowed on kernel functions", &
F);
3560 "Calling convention does not support varargs or "
3561 "perfect forwarding!",
3564 case CallingConv::AMDGPU_Gfx_WholeWave:
3565 Check(!
F.arg_empty() &&
F.arg_begin()->getType()->isIntegerTy(1),
3566 "Calling convention requires first argument to be i1", &
F);
3567 Check(!
F.arg_begin()->hasInRegAttr(),
3568 "Calling convention requires first argument to not be inreg", &
F);
3570 "Calling convention does not support varargs or "
3571 "perfect forwarding!",
3578 for (
const Argument &Arg :
F.args()) {
3579 Check(Arg.getType() == FT->getParamType(i),
3580 "Argument value does not match function argument type!", &Arg,
3581 FT->getParamType(i));
3582 Check(Arg.getType()->isFirstClassType(),
3583 "Function arguments must have first-class types!", &Arg);
3585 Check(!Arg.getType()->isMetadataTy(),
3586 "Function takes metadata but isn't an intrinsic", &Arg, &
F);
3587 Check(!Arg.getType()->isTokenLikeTy(),
3588 "Function takes token but isn't an intrinsic", &Arg, &
F);
3589 Check(!Arg.getType()->isX86_AMXTy(),
3590 "Function takes x86_amx but isn't an intrinsic", &Arg, &
F);
3594 if (
Attrs.hasParamAttr(i, Attribute::SwiftError)) {
3595 verifySwiftErrorValue(&Arg);
3601 Check(!
F.getReturnType()->isTokenLikeTy(),
3602 "Function returns a token but isn't an intrinsic", &
F);
3603 Check(!
F.getReturnType()->isX86_AMXTy(),
3604 "Function returns a x86_amx but isn't an intrinsic", &
F);
3609 F.getAllMetadata(MDs);
3610 assert(
F.hasMetadata() != MDs.
empty() &&
"Bit out-of-sync");
3611 verifyFunctionMetadata(MDs);
3617 if (
F.hasPersonalityFn()) {
3620 Check(Per->getParent() ==
F.getParent(),
3621 "Referencing personality function in another module!", &
F,
3622 F.getParent(), Per, Per->getParent());
3626 BlockEHFuncletColors.
clear();
3628 if (
F.isMaterializable()) {
3630 Check(MDs.
empty(),
"unmaterialized function cannot have metadata", &
F,
3632 }
else if (
F.isDeclaration()) {
3633 for (
const auto &
I : MDs) {
3635 CheckDI(
I.first != LLVMContext::MD_dbg ||
3637 "function declaration may only have a unique !dbg attachment",
3639 Check(
I.first != LLVMContext::MD_prof,
3640 "function declaration may not have a !prof attachment", &
F);
3643 visitMDNode(*
I.second, AreDebugLocsAllowed::Yes);
3645 Check(!
F.hasPersonalityFn(),
3646 "Function declaration shouldn't have a personality routine", &
F);
3650 Check(!IsIntrinsic,
"llvm intrinsics cannot be defined!", &
F);
3655 "Entry block to function must not have predecessors!", Entry);
3658 if (
Entry->hasAddressTaken()) {
3660 "blockaddress may not be used with the entry block!", Entry);
3663 unsigned NumDebugAttachments = 0, NumProfAttachments = 0,
3664 NumKCFIAttachments = 0, NumFLMDAttachments = 0;
3666 for (
const auto &
I : MDs) {
3668 auto AllowLocs = AreDebugLocsAllowed::No;
3672 case LLVMContext::MD_dbg: {
3673 ++NumDebugAttachments;
3674 CheckDI(NumDebugAttachments == 1,
3675 "function must have a single !dbg attachment", &
F,
I.second);
3677 "function !dbg attachment must be a subprogram", &
F,
I.second);
3679 "function definition may only have a distinct !dbg attachment",
3683 const Function *&AttachedTo = DISubprogramAttachments[
SP];
3684 CheckDI(!AttachedTo || AttachedTo == &
F,
3685 "DISubprogram attached to more than one function", SP, &
F);
3687 AllowLocs = AreDebugLocsAllowed::Yes;
3690 case LLVMContext::MD_prof:
3691 ++NumProfAttachments;
3692 Check(NumProfAttachments == 1,
3693 "function must have a single !prof attachment", &
F,
I.second);
3695 case LLVMContext::MD_kcfi_type:
3696 ++NumKCFIAttachments;
3697 Check(NumKCFIAttachments == 1,
3698 "function must have a single !kcfi_type attachment", &
F,
3701 case LLVMContext::MD_annotation:
3702 visitAnnotationMetadata(
I.second);
3704 case LLVMContext::MD_flmd:
3705 ++NumFLMDAttachments;
3706 Check(NumFLMDAttachments == 1,
3707 "function must have a single !flmd attachment", &
F,
I.second);
3712 visitMDNode(*
I.second, AllowLocs);
3720 bool isMaterialized =
F.getParent()->isMaterialized();
3721 if (
F.isIntrinsic() && isMaterialized) {
3723 if (
F.hasAddressTaken(&U,
false,
true,
false,
3725 Check(
false,
"Invalid user of intrinsic instruction!", U);
3732 if (IID && (isMaterialized || !
F.materialized_use_empty())) {
3736 raw_string_ostream ErrOS(ErrMsg);
3739 Printable PrintDecl([&
F](raw_ostream &OS) {
F.print(OS); });
3740 Check(IsValid, ErrMsg, PrintDecl);
3747 IID, OverloadTys,
const_cast<Module *
>(
F.getParent()), FT);
3748 Check(ExpectedName ==
F.getName(),
3749 "Intrinsic name not mangled correctly for type arguments! "
3755 auto *
N =
F.getSubprogram();
3756 HasDebugInfo = (
N !=
nullptr);
3761 MDNode *RawFLContext =
F.getMetadata(LLVMContext::MD_flmd);
3764 "Unexpected !flmd attachment to function", &
F, RawFLContext);
3768 CheckDI(!FLContext->getScopes().empty(),
3769 "Function-local context should contain a subprogram pointing at "
3772 CheckDI(!FLContext->getScopes().empty() &&
3775 "First scope in function-local context should be subprogram "
3776 "pointing at the function",
3777 FLContext, &
F, FLContext->getScope(0).get());
3784 SmallPtrSet<const MDNode *, 32> Seen;
3796 "DILocation's scope must be a DILocalScope",
N, &
F, &
I,
DL, Parent);
3798 DILocalScope *
Scope =
DL->getInlinedAtScope();
3799 Check(Scope,
"Failed to find DILocalScope",
DL);
3801 if (!Seen.
insert(Scope).second)
3805 if (hasDIScopeCycle(Scope))
3808 DISubprogram *
SP =
Scope->getSubprogram();
3812 if ((Scope != SP) && !Seen.
insert(SP).second)
3816 "!dbg attachment points at wrong subprogram for function",
N, &
F,
3820 for (
auto &
I : BB) {
3821 VisitDebugLoc(
I,
I.getDebugLoc().getAsMDNode());
3823 if (
auto MD =
I.getMetadata(LLVMContext::MD_loop))
3826 if (BrokenDebugInfo)
3833void Verifier::visitBasicBlock(BasicBlock &BB) {
3834 InstsInThisBlock.
clear();
3835 ConvergenceVerifyHelper.
visit(BB);
3843 for (
const PHINode &PN : BB.
phis()) {
3844 Check(PN.getNumIncomingValues() == Preds.size(),
3845 "PHINode should have one entry for each predecessor of its "
3846 "parent basic block!",
3851 Values.reserve(PN.getNumIncomingValues());
3852 for (
unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3854 std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i)));
3857 for (
unsigned i = 0, e =
Values.size(); i != e; ++i) {
3864 "PHI node has multiple entries for the same basic block with "
3865 "different incoming values!",
3871 "PHI node entries do not match predecessors!", &PN,
3872 Values[i].first, Preds[i]);
3880 Check(
I.getParent() == &BB,
"Instruction has bogus parent pointer!");
3884 CheckDI(!BB.getTrailingDbgRecords(),
"Basic Block has trailing DbgRecords!",
3888void Verifier::visitTerminator(Instruction &
I) {
3890 Check(&
I ==
I.getParent()->getTerminator(),
3891 "Terminator found in the middle of a basic block!",
I.getParent());
3892 visitInstruction(
I);
3895void Verifier::visitCondBrInst(CondBrInst &BI) {
3897 "Branch condition is not 'i1' type!", &BI, BI.
getCondition());
3898 visitTerminator(BI);
3901void Verifier::visitReturnInst(ReturnInst &RI) {
3904 if (
F->getReturnType()->isVoidTy())
3906 "Found return instr that returns non-void in Function of void "
3908 &RI,
F->getReturnType());
3911 "Function return type does not match operand "
3912 "type of return inst!",
3913 &RI,
F->getReturnType());
3917 visitTerminator(RI);
3920void Verifier::visitSwitchInst(SwitchInst &SI) {
3921 Check(
SI.getType()->isVoidTy(),
"Switch must have void result type!", &SI);
3924 Type *SwitchTy =
SI.getCondition()->getType();
3925 SmallPtrSet<ConstantInt*, 32>
Constants;
3926 for (
auto &Case :
SI.cases()) {
3928 "Case value is not a constant integer.", &SI);
3929 Check(Case.getCaseValue()->getType() == SwitchTy,
3930 "Switch constants must all be same type as switch value!", &SI);
3932 "Duplicate integer as switch case", &SI, Case.getCaseValue());
3935 visitTerminator(SI);
3938void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
3940 "Indirectbr operand must have pointer type!", &BI);
3943 "Indirectbr destinations must all have pointer type!", &BI);
3945 visitTerminator(BI);
3954void Verifier::visitCallBrInst(CallBrInst &CBI) {
3957 "callbr: indirect function / invalid signature");
3959 "callbr for intrinsics currently doesn't support operand bundles");
3963 "callbr currently only supports asm-goto and selected intrinsics");
3968 Check(!
IA->canThrow(),
"Unwinding from Callbr is not allowed");
3970 verifyInlineAsmCall(CBI);
3972 visitTerminator(CBI);
3975void Verifier::visitSelectInst(SelectInst &SI) {
3978 "Invalid operands for select instruction!", &SI);
3980 Check(
SI.getTrueValue()->getType() ==
SI.getType(),
3981 "Select values must have same type as select instruction!", &SI);
3982 visitInstruction(SI);
3988void Verifier::visitUserOp1(Instruction &
I) {
3989 Check(
false,
"User-defined operators should not live outside of a pass!", &
I);
3992void Verifier::visitTruncInst(TruncInst &
I) {
3994 Type *SrcTy =
I.getOperand(0)->getType();
3995 Type *DestTy =
I.getType();
4004 "trunc source and destination must both be a vector or neither", &
I);
4005 Check(SrcBitSize > DestBitSize,
"DestTy too big for Trunc", &
I);
4007 visitInstruction(
I);
4010void Verifier::visitZExtInst(ZExtInst &
I) {
4012 Type *SrcTy =
I.getOperand(0)->getType();
4013 Type *DestTy =
I.getType();
4019 "zext source and destination must both be a vector or neither", &
I);
4023 Check(SrcBitSize < DestBitSize,
"Type too small for ZExt", &
I);
4025 visitInstruction(
I);
4028void Verifier::visitSExtInst(SExtInst &
I) {
4030 Type *SrcTy =
I.getOperand(0)->getType();
4031 Type *DestTy =
I.getType();
4040 "sext source and destination must both be a vector or neither", &
I);
4041 Check(SrcBitSize < DestBitSize,
"Type too small for SExt", &
I);
4043 visitInstruction(
I);
4046void Verifier::visitFPTruncInst(FPTruncInst &
I) {
4048 Type *SrcTy =
I.getOperand(0)->getType();
4049 Type *DestTy =
I.getType();
4057 "fptrunc source and destination must both be a vector or neither", &
I);
4058 Check(SrcBitSize > DestBitSize,
"DestTy too big for FPTrunc", &
I);
4060 visitInstruction(
I);
4063void Verifier::visitFPExtInst(FPExtInst &
I) {
4065 Type *SrcTy =
I.getOperand(0)->getType();
4066 Type *DestTy =
I.getType();
4075 "fpext source and destination must both be a vector or neither", &
I);
4076 Check(SrcBitSize < DestBitSize,
"DestTy too small for FPExt", &
I);
4078 visitInstruction(
I);
4081void Verifier::visitUIToFPInst(UIToFPInst &
I) {
4083 Type *SrcTy =
I.getOperand(0)->getType();
4084 Type *DestTy =
I.getType();
4089 Check(SrcVec == DstVec,
4090 "UIToFP source and dest must both be vector or scalar", &
I);
4092 "UIToFP source must be integer or integer vector", &
I);
4096 if (SrcVec && DstVec)
4099 "UIToFP source and dest vector length mismatch", &
I);
4101 visitInstruction(
I);
4104void Verifier::visitSIToFPInst(SIToFPInst &
I) {
4106 Type *SrcTy =
I.getOperand(0)->getType();
4107 Type *DestTy =
I.getType();
4112 Check(SrcVec == DstVec,
4113 "SIToFP source and dest must both be vector or scalar", &
I);
4115 "SIToFP source must be integer or integer vector", &
I);
4119 if (SrcVec && DstVec)
4122 "SIToFP source and dest vector length mismatch", &
I);
4124 visitInstruction(
I);
4127void Verifier::visitFPToUIInst(FPToUIInst &
I) {
4129 Type *SrcTy =
I.getOperand(0)->getType();
4130 Type *DestTy =
I.getType();
4135 Check(SrcVec == DstVec,
4136 "FPToUI source and dest must both be vector or scalar", &
I);
4139 "FPToUI result must be integer or integer vector", &
I);
4141 if (SrcVec && DstVec)
4144 "FPToUI source and dest vector length mismatch", &
I);
4146 visitInstruction(
I);
4149void Verifier::visitFPToSIInst(FPToSIInst &
I) {
4151 Type *SrcTy =
I.getOperand(0)->getType();
4152 Type *DestTy =
I.getType();
4157 Check(SrcVec == DstVec,
4158 "FPToSI source and dest must both be vector or scalar", &
I);
4161 "FPToSI result must be integer or integer vector", &
I);
4163 if (SrcVec && DstVec)
4166 "FPToSI source and dest vector length mismatch", &
I);
4168 visitInstruction(
I);
4171void Verifier::checkPtrToAddr(
Type *SrcTy,
Type *DestTy,
const Value &
V) {
4180 Check(VSrc->getElementCount() == VDest->getElementCount(),
4181 "PtrToAddr vector length mismatch",
V);
4184 Type *AddrTy =
DL.getAddressType(SrcTy);
4185 Check(AddrTy == DestTy,
"PtrToAddr result must be address width",
V);
4188void Verifier::visitPtrToAddrInst(PtrToAddrInst &
I) {
4189 checkPtrToAddr(
I.getOperand(0)->getType(),
I.getType(),
I);
4190 visitInstruction(
I);
4193void Verifier::visitPtrToIntInst(PtrToIntInst &
I) {
4195 Type *SrcTy =
I.getOperand(0)->getType();
4196 Type *DestTy =
I.getType();
4207 Check(VSrc->getElementCount() == VDest->getElementCount(),
4208 "PtrToInt Vector length mismatch", &
I);
4211 visitInstruction(
I);
4214void Verifier::visitIntToPtrInst(IntToPtrInst &
I) {
4216 Type *SrcTy =
I.getOperand(0)->getType();
4217 Type *DestTy =
I.getType();
4227 Check(VSrc->getElementCount() == VDest->getElementCount(),
4228 "IntToPtr Vector length mismatch", &
I);
4230 visitInstruction(
I);
4233void Verifier::visitBitCastInst(BitCastInst &
I) {
4236 "Invalid bitcast", &
I);
4237 Check(
DL.getTypeSizeInBits(
I.getSrcTy()) ==
4238 DL.getTypeSizeInBits(
I.getDestTy()),
4239 "Invalid bitcast", &
I);
4240 visitInstruction(
I);
4243void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &
I) {
4244 Type *SrcTy =
I.getOperand(0)->getType();
4245 Type *DestTy =
I.getType();
4252 "AddrSpaceCast must be between different address spaces", &
I);
4254 Check(SrcVTy->getElementCount() ==
4256 "AddrSpaceCast vector pointer number of elements mismatch", &
I);
4257 visitInstruction(
I);
4262void Verifier::visitPHINode(PHINode &PN) {
4269 "PHI nodes not grouped at top of basic block!", &PN, PN.
getParent());
4278 "PHI node operands are not the same type as the result!", &PN);
4283 visitInstruction(PN);
4286void Verifier::visitCallBase(CallBase &
Call) {
4288 "Called function must be a pointer!",
Call);
4292 if (FTy->isVarArg())
4294 "Called function requires more parameters than were provided!",
Call);
4297 "Incorrect number of arguments passed to called function!",
Call);
4300 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
4302 "Call parameter type does not match function signature!",
4308 "Attribute after last parameter!",
Call);
4315 "Intrinsic called with incompatible signature",
Call);
4319 "calling convention does not permit calls",
Call);
4325 auto VerifyTypeAlign = [&](
Type *Ty,
const Twine &Message) {
4328 Align ABIAlign =
DL.getABITypeAlign(Ty);
4329 Check(ABIAlign.
value() <= Value::MaximumAlignment,
4330 "Incorrect alignment of " + Message +
" to called function!",
Call);
4334 VerifyTypeAlign(FTy->getReturnType(),
"return type");
4335 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4336 Type *Ty = FTy->getParamType(i);
4337 VerifyTypeAlign(Ty,
"argument passed");
4341 if (
Attrs.hasFnAttr(Attribute::Speculatable)) {
4345 "speculatable attribute may not apply to call sites",
Call);
4348 if (
Attrs.hasFnAttr(Attribute::Preallocated)) {
4350 "preallocated as a call site attribute can only be on "
4351 "llvm.call.preallocated.arg");
4354 Check(!
Attrs.hasFnAttr(Attribute::DenormalFPEnv),
4355 "denormal_fpenv attribute may not apply to call sites",
Call);
4366 Check(AI->isUsedWithInAlloca(),
4367 "inalloca argument for call has mismatched alloca", AI,
Call);
4373 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
4377 Check(AI->isSwiftError(),
4378 "swifterror argument for call has mismatched alloca", AI,
Call);
4382 Check(ArgI,
"swifterror argument should come from an alloca or parameter",
4383 SwiftErrorArg,
Call);
4384 Check(ArgI->hasSwiftErrorAttr(),
4385 "swifterror argument for call has mismatched parameter", ArgI,
4389 if (
Attrs.hasParamAttr(i, Attribute::ImmArg)) {
4392 Check(Callee &&
Callee->hasParamAttribute(i, Attribute::ImmArg),
4401 "immarg operand has non-immediate parameter", ArgVal,
Call);
4407 const ConstantRange &CR =
4410 formatv(
"immarg value {} for arg {} out of range {}",
4411 CI->getValue(), i, CR),
4418 formatv(
"immarg value {} for arg {} out of range set",
4428 Check(hasOB != isMustTail,
4429 "preallocated operand either requires a preallocated bundle or "
4430 "the call to be musttail (but not both)",
4435 if (FTy->isVarArg()) {
4437 bool SawNest =
false;
4438 bool SawReturned =
false;
4440 for (
unsigned Idx = 0;
Idx < FTy->getNumParams(); ++
Idx) {
4441 if (
Attrs.hasParamAttr(Idx, Attribute::Nest))
4443 if (
Attrs.hasParamAttr(Idx, Attribute::Returned))
4448 for (
unsigned Idx = FTy->getNumParams(); Idx <
Call.
arg_size(); ++Idx) {
4450 AttributeSet ArgAttrs =
Attrs.getParamAttrs(Idx);
4451 verifyParameterAttrs(ArgAttrs, Ty, &
Call);
4454 Check(!SawNest,
"More than one parameter has attribute nest!",
Call);
4459 Check(!SawReturned,
"More than one parameter has attribute returned!",
4462 "Incompatible argument and return types for 'returned' "
4472 "Attribute 'sret' cannot be used for vararg call arguments!",
4477 "inalloca isn't on the last argument!",
Call);
4483 for (
Type *ParamTy : FTy->params()) {
4484 Check(!ParamTy->isMetadataTy(),
4485 "Function has metadata parameter but isn't an intrinsic",
Call);
4486 Check(!ParamTy->isTokenLikeTy(),
4487 "Function has token parameter but isn't an intrinsic",
Call);
4493 Check(!FTy->getReturnType()->isTokenLikeTy(),
4494 "Return type cannot be token for indirect call!");
4495 Check(!FTy->getReturnType()->isX86_AMXTy(),
4496 "Return type cannot be x86_amx for indirect call!");
4500 visitIntrinsicCall(ID,
Call);
4505 bool FoundDeoptBundle =
false, FoundFuncletBundle =
false,
4506 FoundGCTransitionBundle =
false, FoundCFGuardTargetBundle =
false,
4507 FoundPreallocatedBundle =
false, FoundGCLiveBundle =
false,
4508 FoundPtrauthBundle =
false, FoundKCFIBundle =
false,
4509 FoundAttachedCallBundle =
false;
4514 "Operand bundle operands cannot be labels",
Call);
4517 Check(!FoundDeoptBundle,
"Multiple deopt operand bundles",
Call);
4518 FoundDeoptBundle =
true;
4520 Check(!FoundGCTransitionBundle,
"Multiple gc-transition operand bundles",
4522 FoundGCTransitionBundle =
true;
4524 Check(!FoundFuncletBundle,
"Multiple funclet operand bundles",
Call);
4525 FoundFuncletBundle =
true;
4527 "Expected exactly one funclet bundle operand",
Call);
4529 "Funclet bundle operands should correspond to a FuncletPadInst",
4532 Check(!FoundCFGuardTargetBundle,
"Multiple CFGuardTarget operand bundles",
4534 FoundCFGuardTargetBundle =
true;
4536 "Expected exactly one cfguardtarget bundle operand",
Call);
4538 Check(!FoundPtrauthBundle,
"Multiple ptrauth operand bundles",
Call);
4539 FoundPtrauthBundle =
true;
4541 "Expected exactly two ptrauth bundle operands",
Call);
4543 BU.
Inputs[0]->getType()->isIntegerTy(32),
4544 "Ptrauth bundle key operand must be an i32 constant",
Call);
4546 "Ptrauth bundle discriminator operand must be an i64",
Call);
4548 Check(!FoundKCFIBundle,
"Multiple kcfi operand bundles",
Call);
4549 FoundKCFIBundle =
true;
4550 Check(BU.
Inputs.size() == 1,
"Expected exactly one kcfi bundle operand",
4553 BU.
Inputs[0]->getType()->isIntegerTy(32),
4554 "Kcfi bundle operand must be an i32 constant",
Call);
4556 Check(!FoundPreallocatedBundle,
"Multiple preallocated operand bundles",
4558 FoundPreallocatedBundle =
true;
4560 "Expected exactly one preallocated bundle operand",
Call);
4563 Input->getIntrinsicID() == Intrinsic::call_preallocated_setup,
4564 "\"preallocated\" argument must be a token from "
4565 "llvm.call.preallocated.setup",
4568 Check(!FoundGCLiveBundle,
"Multiple gc-live operand bundles",
Call);
4569 FoundGCLiveBundle =
true;
4571 Check(!FoundAttachedCallBundle,
4572 "Multiple \"clang.arc.attachedcall\" operand bundles",
Call);
4573 FoundAttachedCallBundle =
true;
4574 verifyAttachedCallBundle(
Call, BU);
4580 "Direct call cannot have a ptrauth bundle",
Call);
4592 "inlinable function call in a function with "
4593 "debug info must have a !dbg location",
4597 verifyInlineAsmCall(
Call);
4601 visitInstruction(
Call);
4604void Verifier::verifyTailCCMustTailAttrs(
const AttrBuilder &Attrs,
4607 Twine(
"inalloca attribute not allowed in ") +
Context);
4609 Twine(
"inreg attribute not allowed in ") +
Context);
4610 Check(!
Attrs.contains(Attribute::SwiftError),
4611 Twine(
"swifterror attribute not allowed in ") +
Context);
4612 Check(!
Attrs.contains(Attribute::Preallocated),
4613 Twine(
"preallocated attribute not allowed in ") +
Context);
4615 Twine(
"byref attribute not allowed in ") +
Context);
4620 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
4621 Attribute::InReg, Attribute::StackAlignment, Attribute::SwiftSelf,
4622 Attribute::SwiftAsync, Attribute::SwiftError, Attribute::Preallocated,
4624 AttrBuilder Copy(
C);
4625 for (
auto AK : ABIAttrs) {
4626 Attribute Attr = Attrs.getParamAttrs(
I).getAttribute(AK);
4628 Copy.addAttribute(Attr);
4632 if (Attrs.hasParamAttr(
I, Attribute::Alignment) &&
4633 (Attrs.hasParamAttr(
I, Attribute::ByVal) ||
4634 Attrs.hasParamAttr(
I, Attribute::ByRef)))
4635 Copy.addAlignmentAttr(Attrs.getParamAlignment(
I));
4639void Verifier::verifyMustTailCall(CallInst &CI) {
4643 FunctionType *CallerTy =
F->getFunctionType();
4645 Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
4646 "cannot guarantee tail call due to mismatched varargs", &CI);
4647 Check(CallerTy->getReturnType() == CalleeTy->getReturnType(),
4648 "cannot guarantee tail call due to mismatched return types", &CI);
4652 "cannot guarantee tail call due to mismatched calling conv", &CI);
4660 Check(Ret,
"musttail call must precede a ret", &CI);
4663 "musttail call result must be returned", Ret);
4665 AttributeList CallerAttrs =
F->getAttributes();
4670 CI.
getCallingConv() == CallingConv::Tail ?
"tailcc" :
"swifttailcc";
4674 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4676 SmallString<32>
Context{CCName, StringRef(
" musttail caller")};
4677 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4679 for (
unsigned I = 0,
E = CalleeTy->getNumParams();
I !=
E; ++
I) {
4681 SmallString<32>
Context{CCName, StringRef(
" musttail callee")};
4682 verifyTailCCMustTailAttrs(ABIAttrs,
Context);
4685 Check(!CallerTy->isVarArg(), Twine(
"cannot guarantee ") + CCName +
4686 " tail call for varargs function");
4692 Check(CallerTy->getNumParams() == CalleeTy->getNumParams(),
4693 "cannot guarantee tail call due to mismatched parameter counts", &CI);
4694 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4695 Check(CallerTy->getParamType(
I) == CalleeTy->getParamType(
I),
4696 "cannot guarantee tail call due to mismatched parameter types",
4703 for (
unsigned I = 0,
E = CallerTy->getNumParams();
I !=
E; ++
I) {
4706 Check(CallerABIAttrs == CalleeABIAttrs,
4707 "cannot guarantee tail call due to mismatched ABI impacting "
4708 "function attributes",
4713void Verifier::visitCallInst(CallInst &CI) {
4717 verifyMustTailCall(CI);
4720void Verifier::visitInvokeInst(InvokeInst &
II) {
4726 II.getUnwindDest()->isEHPad(),
4727 "The unwind destination does not have an exception handling instruction!",
4730 visitTerminator(
II);
4735void Verifier::visitUnaryOperator(UnaryOperator &U) {
4736 Check(
U.getType() ==
U.getOperand(0)->getType(),
4737 "Unary operators must have same type for"
4738 "operands and result!",
4741 switch (
U.getOpcode()) {
4744 case Instruction::FNeg:
4745 Check(
U.getType()->isFPOrFPVectorTy(),
4746 "FNeg operator only works with float types!", &U);
4752 visitInstruction(U);
4758void Verifier::visitBinaryOperator(BinaryOperator &
B) {
4759 Check(
B.getOperand(0)->getType() ==
B.getOperand(1)->getType(),
4760 "Both operands to a binary operator are not of the same type!", &
B);
4762 switch (
B.getOpcode()) {
4765 case Instruction::Add:
4766 case Instruction::Sub:
4767 case Instruction::Mul:
4768 case Instruction::SDiv:
4769 case Instruction::UDiv:
4770 case Instruction::SRem:
4771 case Instruction::URem:
4772 Check(
B.getType()->isIntOrIntVectorTy(),
4773 "Integer arithmetic operators only work with integral types!", &
B);
4774 Check(
B.getType() ==
B.getOperand(0)->getType(),
4775 "Integer arithmetic operators must have same type "
4776 "for operands and result!",
4781 case Instruction::FAdd:
4782 case Instruction::FSub:
4783 case Instruction::FMul:
4784 case Instruction::FDiv:
4785 case Instruction::FRem:
4786 Check(
B.getType()->isFPOrFPVectorTy(),
4787 "Floating-point arithmetic operators only work with "
4788 "floating-point types!",
4790 Check(
B.getType() ==
B.getOperand(0)->getType(),
4791 "Floating-point arithmetic operators must have same type "
4792 "for operands and result!",
4796 case Instruction::And:
4797 case Instruction::Or:
4798 case Instruction::Xor:
4799 Check(
B.getType()->isIntOrIntVectorTy(),
4800 "Logical operators only work with integral types!", &
B);
4801 Check(
B.getType() ==
B.getOperand(0)->getType(),
4802 "Logical operators must have same type for operands and result!", &
B);
4804 case Instruction::Shl:
4805 case Instruction::LShr:
4806 case Instruction::AShr:
4807 Check(
B.getType()->isIntOrIntVectorTy(),
4808 "Shifts only work with integral types!", &
B);
4809 Check(
B.getType() ==
B.getOperand(0)->getType(),
4810 "Shift return type must be same as operands!", &
B);
4816 visitInstruction(
B);
4819void Verifier::visitICmpInst(ICmpInst &IC) {
4823 Check(Op0Ty == Op1Ty,
4824 "Both operands to ICmp instruction are not of the same type!", &IC);
4827 "Invalid operand types for ICmp instruction", &IC);
4831 visitInstruction(IC);
4834void Verifier::visitFCmpInst(FCmpInst &FC) {
4836 Type *Op0Ty =
FC.getOperand(0)->getType();
4837 Type *Op1Ty =
FC.getOperand(1)->getType();
4838 Check(Op0Ty == Op1Ty,
4839 "Both operands to FCmp instruction are not of the same type!", &FC);
4844 Check(
FC.isFPPredicate(),
"Invalid predicate in FCmp instruction!", &FC);
4846 visitInstruction(FC);
4849void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
4851 "Invalid extractelement operands!", &EI);
4852 visitInstruction(EI);
4855void Verifier::visitInsertElementInst(InsertElementInst &IE) {
4858 "Invalid insertelement operands!", &IE);
4859 visitInstruction(IE);
4862void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
4864 SV.getShuffleMask()),
4865 "Invalid shufflevector operands!", &SV);
4866 visitInstruction(SV);
4869void Verifier::visitBitInsertInst(BitInsertInst &BII) {
4872 Check(
false, Reason, &BII);
4875 "bitinsert val type cannot be wider than base type!", &BII);
4876 visitInstruction(BII);
4879void Verifier::visitVAArgInst(VAArgInst &VAA) {
4882 "va_arg with an aggregate type is not supported", &VAA);
4883 visitInstruction(VAA);
4886void Verifier::visitBitExtractInst(BitExtractInst &BEI) {
4889 Check(
false, Reason, &BEI);
4892 "bitextract result type cannot be wider than source type!", &BEI);
4893 visitInstruction(BEI);
4896void Verifier::checkGEPOperator(
const GEPOperator &
GEP) {
4897 Type *TargetTy =
GEP.getPointerOperandType()->getScalarType();
4900 "GEP base pointer is not a vector or a vector of pointers", &
GEP);
4901 Check(
GEP.getSourceElementType()->isSized(),
"GEP into unsized type!", &
GEP);
4903 Type *SrcTy =
GEP.getSourceElementType();
4905 SrcTy = ATy->getElementType();
4907 "getelementptr cannot target structure that contains scalable vector "
4911 SmallVector<Value *, 16> Idxs(
GEP.indices());
4913 all_of(Idxs, [](
Value *
V) {
return V->getType()->isIntOrIntVectorTy(); }),
4914 "GEP indexes must be integers", &
GEP);
4917 Check(ElTy,
"Invalid indices for GEP pointer type!", &
GEP);
4921 Check(PtrTy &&
GEP.getResultElementType() == ElTy,
4922 "GEP is not of right type for indices!", &
GEP, ElTy);
4926 ElementCount GEPWidth = GEPVTy->getElementCount();
4927 if (
GEP.getPointerOperandType()->isVectorTy())
4931 "Vector GEP result width doesn't match operand's", &
GEP);
4932 for (
Value *Idx : Idxs) {
4933 Type *IndexTy =
Idx->getType();
4935 ElementCount IndexWidth = IndexVTy->getElementCount();
4936 Check(IndexWidth == GEPWidth,
"Invalid GEP index vector width", &
GEP);
4939 "All GEP indices should be of integer type");
4946 GTI != GTE; ++GTI) {
4947 if (GTI.isVector()) {
4948 Type *ElemTy = GTI.getIndexedType();
4949 Check(
DL.typeSizeEqualsStoreSize(ElemTy),
4950 "GEP into vector with non-byte-addressable element type", &
GEP);
4954 Check(
GEP.getPointerAddressSpace() == PtrTy->getAddressSpace(),
4955 "GEP address space doesn't match type", &
GEP);
4958void Verifier::visitGetElementPtrInst(GetElementPtrInst &
GEP) {
4960 GEP.getModule()->getModuleFlag(
"require-logical-pointer")))
4961 Check(!MD->getZExtValue(),
4962 "Non-logical getelementptr disallowed for this module.");
4965 visitInstruction(
GEP);
4969 return A.getUpper() ==
B.getLower() ||
A.getLower() ==
B.getUpper();
4974void Verifier::verifyRangeLikeMetadata(
const Value &
I,
const MDNode *
Range,
4975 Type *Ty, RangeLikeMetadataKind Kind) {
4976 unsigned NumOperands =
Range->getNumOperands();
4977 Check(NumOperands % 2 == 0,
"Unfinished range!",
Range);
4978 unsigned NumRanges = NumOperands / 2;
4979 Check(NumRanges >= 1,
"It should have at least one range!",
Range);
4981 ConstantRange LastRange(1,
true);
4982 for (
unsigned i = 0; i < NumRanges; ++i) {
4985 Check(
Low,
"The lower limit must be an integer!",
Low);
4990 Check(
High->getType() ==
Low->getType(),
"Range pair types must match!",
4993 if (Kind == RangeLikeMetadataKind::NoaliasAddrspace) {
4995 "noalias.addrspace type must be i32!", &
I);
4998 "Range types must match instruction type!", &
I);
5001 APInt HighV =
High->getValue();
5002 APInt LowV =
Low->getValue();
5007 "The upper and lower limits cannot be the same value", &
I);
5009 ConstantRange CurRange(LowV, HighV);
5010 Check(!CurRange.isEmptySet() &&
5011 (Kind == RangeLikeMetadataKind::AbsoluteSymbol ||
5012 !CurRange.isFullSet()),
5013 "Range must not be empty!",
Range);
5015 Check(CurRange.intersectWith(LastRange).isEmptySet(),
5016 "Intervals are overlapping",
Range);
5017 Check(LowV.
sgt(LastRange.getLower()),
"Intervals are not in order",
5022 LastRange = ConstantRange(LowV, HighV);
5024 if (NumRanges > 2) {
5029 ConstantRange FirstRange(FirstLow, FirstHigh);
5030 Check(FirstRange.intersectWith(LastRange).isEmptySet(),
5031 "Intervals are overlapping",
Range);
5037void Verifier::visitRangeMetadata(Instruction &
I, MDNode *
Range,
Type *Ty) {
5039 "precondition violation");
5040 verifyRangeLikeMetadata(
I,
Range, Ty, RangeLikeMetadataKind::Range);
5043void Verifier::visitNoFPClassMetadata(Instruction &
I, MDNode *NoFPClass,
5045 Check(AttributeFuncs::isNoFPClassCompatibleType(Ty),
5046 "nofpclass only applies to floating-point typed loads",
I);
5049 "nofpclass must have exactly one entry", NoFPClass);
5050 ConstantInt *MaskVal =
5053 "nofpclass entry must be a constant i32", NoFPClass);
5055 Check(Val != 0,
"'nofpclass' must have at least one test bit set", NoFPClass,
5059 "Invalid value for 'nofpclass' test mask", NoFPClass,
I);
5062void Verifier::visitNoaliasAddrspaceMetadata(Instruction &
I, MDNode *
Range,
5065 "precondition violation");
5066 verifyRangeLikeMetadata(
I,
Range, Ty,
5067 RangeLikeMetadataKind::NoaliasAddrspace);
5070void Verifier::checkAtomicMemAccessSize(
Type *Ty,
const Instruction *
I) {
5071 unsigned Size =
DL.getTypeSizeInBits(Ty).getFixedValue();
5072 Check(
Size >= 8,
"atomic memory access' size must be byte-sized", Ty,
I);
5074 "atomic memory access' operand must have a power-of-two size", Ty,
I);
5077void Verifier::visitLoadInst(LoadInst &LI) {
5079 Check(PTy,
"Load operand must be a pointer.", &LI);
5082 Check(
A->value() <= Value::MaximumAlignment,
5083 "huge alignment values are unsupported", &LI);
5085 Check(ElTy->
isSized(),
"loading unsized types is not allowed", &LI);
5088 LI.
getOrdering() != AtomicOrdering::AcquireRelease,
5089 "Load cannot have Release ordering", &LI);
5093 "atomic elementwise load cannot be sequentially consistent.", &LI);
5096 "atomic elementwise load operand must have fixed vector type!", &LI,
5099 checkAtomicMemAccessSize(VecTy->getElementType(), &LI);
5105 "atomic load operand must have integer, byte, pointer, floating "
5106 "point, or vector type!",
5109 checkAtomicMemAccessSize(ElTy, &LI);
5113 "Non-atomic load cannot have SynchronizationScope specified", &LI);
5116 visitInstruction(LI);
5119void Verifier::visitStoreInst(StoreInst &SI) {
5121 Check(PTy,
"Store operand must be a pointer.", &SI);
5122 Type *ElTy =
SI.getOperand(0)->getType();
5123 if (MaybeAlign
A =
SI.getAlign()) {
5124 Check(
A->value() <= Value::MaximumAlignment,
5125 "huge alignment values are unsupported", &SI);
5127 Check(ElTy->
isSized(),
"storing unsized types is not allowed", &SI);
5128 if (
SI.isAtomic()) {
5129 Check(
SI.getOrdering() != AtomicOrdering::Acquire &&
5130 SI.getOrdering() != AtomicOrdering::AcquireRelease,
5131 "Store cannot have Acquire ordering", &SI);
5133 if (
SI.isElementwise()) {
5134 Check(
SI.getOrdering() != AtomicOrdering::SequentiallyConsistent,
5135 "atomic elementwise store cannot be sequentially consistent.", &SI);
5139 "atomic elementwise store operand must have fixed vector type!",
5142 checkAtomicMemAccessSize(VecTy->getElementType(), &SI);
5148 "atomic store operand must have integer, byte, pointer, floating "
5149 "point, or vector type!",
5151 checkAtomicMemAccessSize(ElTy, &SI);
5153 Check(!
SI.isElementwise(),
"non-atomic store cannot be elementwise", &SI);
5155 "Non-atomic store cannot have SynchronizationScope specified", &SI);
5157 visitInstruction(SI);
5161void Verifier::verifySwiftErrorCall(CallBase &
Call,
5162 const Value *SwiftErrorVal) {
5164 if (
I.value() == SwiftErrorVal) {
5166 "swifterror value when used in a callsite should be marked "
5167 "with swifterror attribute",
5168 SwiftErrorVal,
Call);
5173void Verifier::verifySwiftErrorValue(
const Value *SwiftErrorVal) {
5176 for (
const User *U : SwiftErrorVal->
users()) {
5179 "swifterror value can only be loaded and stored from, or "
5180 "as a swifterror argument!",
5184 Check(StoreI->getOperand(1) == SwiftErrorVal,
5185 "swifterror value should be the second operand when used "
5189 verifySwiftErrorCall(*
const_cast<CallBase *
>(
Call), SwiftErrorVal);
5193void Verifier::visitAllocaInst(AllocaInst &AI) {
5196 Check(!MD->getZExtValue(),
5197 "Non-logical alloca disallowed for this module.");
5200 Check(Ty->
isSized(),
"Cannot allocate unsized type", &AI);
5204 "Alloca has illegal target extension type", &AI);
5206 "Alloca array size must have integer type", &AI);
5208 Check(
A->value() <= Value::MaximumAlignment,
5209 "huge alignment values are unsupported", &AI);
5215 "swifterror alloca must not be array allocation", &AI);
5216 verifySwiftErrorValue(&AI);
5219 visitInstruction(AI);
5225void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
5228 "cmpxchg operand must have integer or pointer type", ElTy, &CXI);
5229 checkAtomicMemAccessSize(ElTy, &CXI);
5230 visitInstruction(CXI);
5233void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
5235 "atomicrmw instructions cannot be unordered.", &RMWI);
5241 "atomicrmw elementwise cannot be sequentially consistent.", &RMWI);
5243 Check(VecTy,
"atomicrmw elementwise operand must have fixed vector type!",
5246 checkAtomicMemAccessSize(VecTy->getElementType(), &RMWI);
5253 " operand must be an integer type, a floating-point type, a "
5254 "pointer type, or a fixed vector of any of these types!",
5259 " operand must have floating-point or fixed vector of "
5266 " operand must have integer or fixed vector of integer type!",
5269 checkAtomicMemAccessSize(ElTy, &RMWI);
5271 "Invalid binary operation!", &RMWI);
5272 visitInstruction(RMWI);
5275void Verifier::visitFenceInst(FenceInst &FI) {
5277 Check(Ordering == AtomicOrdering::Acquire ||
5278 Ordering == AtomicOrdering::Release ||
5279 Ordering == AtomicOrdering::AcquireRelease ||
5280 Ordering == AtomicOrdering::SequentiallyConsistent,
5281 "fence instructions may only have acquire, release, acq_rel, or "
5282 "seq_cst ordering.",
5284 visitInstruction(FI);
5287void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
5290 "Invalid ExtractValueInst operands!", &EVI);
5292 visitInstruction(EVI);
5295void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
5299 "Invalid InsertValueInst operands!", &IVI);
5301 visitInstruction(IVI);
5306 return FPI->getParentPad();
5311void Verifier::visitEHPadPredecessors(Instruction &
I) {
5317 Check(BB != &
F->getEntryBlock(),
"EH pad cannot be in entry block.", &
I);
5325 Check(
II &&
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
5326 "Block containing LandingPadInst must be jumped to "
5327 "only by the unwind edge of an invoke.",
5335 "Block containg CatchPadInst must be jumped to "
5336 "only by its catchswitch.",
5338 Check(BB != CPI->getCatchSwitch()->getUnwindDest(),
5339 "Catchswitch cannot unwind to one of its catchpads",
5340 CPI->getCatchSwitch(), CPI);
5352 Check(
II->getUnwindDest() == BB &&
II->getNormalDest() != BB,
5353 "EH pad must be jumped to via an unwind edge", ToPad,
II);
5356 if (CalledFn && CalledFn->isIntrinsic() &&
II->doesNotThrow() &&
5360 FromPad = Bundle->Inputs[0];
5364 FromPad = CRI->getOperand(0);
5365 Check(FromPad != ToPadParent,
"A cleanupret must exit its cleanup", CRI);
5369 Check(
false,
"EH pad must be jumped to via an unwind edge", ToPad, TI);
5373 SmallPtrSet<Value *, 8> Seen;
5375 Check(FromPad != ToPad,
5376 "EH pad cannot handle exceptions raised within it", FromPad, TI);
5377 if (FromPad == ToPadParent) {
5382 "A single unwind edge may only enter one EH pad", TI);
5383 Check(Seen.
insert(FromPad).second,
"EH pad jumps through a cycle of pads",
5389 "Parent pad must be catchpad/cleanuppad/catchswitch", TI);
5394void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
5398 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
5400 visitEHPadPredecessors(LPI);
5402 if (!LandingPadResultTy)
5403 LandingPadResultTy = LPI.
getType();
5406 "The landingpad instruction should have a consistent result type "
5407 "inside a function.",
5411 Check(
F->hasPersonalityFn(),
5412 "LandingPadInst needs to be in a function with a personality.", &LPI);
5417 "LandingPadInst not the first non-PHI instruction in the block.", &LPI);
5423 "Catch operand does not have pointer type!", &LPI);
5425 Check(LPI.
isFilter(i),
"Clause is neither catch nor filter!", &LPI);
5427 "Filter operand is not an array of constants!", &LPI);
5431 visitInstruction(LPI);
5434void Verifier::visitResumeInst(ResumeInst &RI) {
5436 "ResumeInst needs to be in a function with a personality.", &RI);
5438 if (!LandingPadResultTy)
5442 "The resume instruction should have a consistent result type "
5443 "inside a function.",
5446 visitTerminator(RI);
5449void Verifier::visitCatchPadInst(CatchPadInst &CPI) {
5453 Check(
F->hasPersonalityFn(),
5454 "CatchPadInst needs to be in a function with a personality.", &CPI);
5457 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
5463 "CatchPadInst not the first non-PHI instruction in the block.", &CPI);
5468 return isa<Constant>(V) || isa<AllocaInst>(V);
5470 "Argument operand must be alloca or constant.", &CPI);
5472 visitEHPadPredecessors(CPI);
5473 visitFuncletPadInst(CPI);
5476void Verifier::visitCatchReturnInst(CatchReturnInst &CatchReturn) {
5478 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn,
5481 visitTerminator(CatchReturn);
5484void Verifier::visitCleanupPadInst(CleanupPadInst &CPI) {
5488 Check(
F->hasPersonalityFn(),
5489 "CleanupPadInst needs to be in a function with a personality.", &CPI);
5494 "CleanupPadInst not the first non-PHI instruction in the block.", &CPI);
5498 "CleanupPadInst has an invalid parent.", &CPI);
5500 visitEHPadPredecessors(CPI);
5501 visitFuncletPadInst(CPI);
5504void Verifier::visitFuncletPadInst(FuncletPadInst &FPI) {
5505 User *FirstUser =
nullptr;
5506 Value *FirstUnwindPad =
nullptr;
5508 SmallPtrSet<FuncletPadInst *, 8> Seen;
5510 while (!Worklist.empty()) {
5511 FuncletPadInst *CurrentPad = Worklist.pop_back_val();
5513 "FuncletPadInst must not be nested within itself", CurrentPad);
5514 Value *UnresolvedAncestorPad =
nullptr;
5515 for (User *U : CurrentPad->
users()) {
5518 UnwindDest = CRI->getUnwindDest();
5524 if (CSI->unwindsToCaller())
5526 UnwindDest = CSI->getUnwindDest();
5528 UnwindDest =
II->getUnwindDest();
5538 Worklist.push_back(CPI);
5553 if (UnwindParent == CurrentPad)
5559 Value *ExitedPad = CurrentPad;
5562 if (ExitedPad == &FPI) {
5567 UnresolvedAncestorPad = &FPI;
5571 if (ExitedParent == UnwindParent) {
5575 UnresolvedAncestorPad = ExitedParent;
5578 ExitedPad = ExitedParent;
5584 UnresolvedAncestorPad = &FPI;
5591 Check(UnwindPad == FirstUnwindPad,
5592 "Unwind edges out of a funclet "
5593 "pad must have the same unwind "
5595 &FPI, U, FirstUser);
5598 FirstUnwindPad = UnwindPad;
5607 if (CurrentPad != &FPI)
5610 if (UnresolvedAncestorPad) {
5611 if (CurrentPad == UnresolvedAncestorPad) {
5615 assert(CurrentPad == &FPI);
5623 Value *ResolvedPad = CurrentPad;
5624 while (!Worklist.empty()) {
5625 Value *UnclePad = Worklist.back();
5629 while (ResolvedPad != AncestorPad) {
5631 if (ResolvedParent == UnresolvedAncestorPad) {
5634 ResolvedPad = ResolvedParent;
5638 if (ResolvedPad != AncestorPad)
5641 Worklist.pop_back();
5646 if (FirstUnwindPad) {
5648 BasicBlock *SwitchUnwindDest = CatchSwitch->getUnwindDest();
5649 Value *SwitchUnwindPad;
5650 if (SwitchUnwindDest)
5654 Check(SwitchUnwindPad == FirstUnwindPad,
5655 "Unwind edges out of a catch must have the same unwind dest as "
5656 "the parent catchswitch",
5657 &FPI, FirstUser, CatchSwitch);
5661 visitInstruction(FPI);
5664void Verifier::visitCatchSwitchInst(CatchSwitchInst &CatchSwitch) {
5668 Check(
F->hasPersonalityFn(),
5669 "CatchSwitchInst needs to be in a function with a personality.",
5675 "CatchSwitchInst not the first non-PHI instruction in the block.",
5680 "CatchSwitchInst has an invalid parent.", ParentPad);
5685 "CatchSwitchInst must unwind to an EH block which is not a "
5691 SiblingFuncletInfo[&CatchSwitch] = &CatchSwitch;
5695 "CatchSwitchInst cannot have empty handler list", &CatchSwitch);
5697 for (BasicBlock *Handler : CatchSwitch.
handlers()) {
5699 "CatchSwitchInst handlers must be catchpads", &CatchSwitch, Handler);
5702 visitEHPadPredecessors(CatchSwitch);
5703 visitTerminator(CatchSwitch);
5706void Verifier::visitCleanupReturnInst(CleanupReturnInst &CRI) {
5708 "CleanupReturnInst needs to be provided a CleanupPad", &CRI,
5714 "CleanupReturnInst must unwind to an EH block which is not a "
5719 visitTerminator(CRI);
5722void Verifier::verifyDominatesUse(Instruction &
I,
unsigned i) {
5728 if (
II->getNormalDest() ==
II->getUnwindDest())
5742 const Use &
U =
I.getOperandUse(i);
5743 Check(DT.dominates(
Op, U),
"Instruction does not dominate all uses!",
Op, &
I);
5746void Verifier::visitDereferenceableMetadata(Instruction&
I, MDNode* MD) {
5747 Check(
I.getType()->isPointerTy(),
5748 "dereferenceable, dereferenceable_or_null "
5749 "apply only to pointer types",
5752 "dereferenceable, dereferenceable_or_null apply only to load"
5753 " and inttoptr instructions, use attributes for calls or invokes",
5756 "dereferenceable, dereferenceable_or_null "
5757 "take one operand!",
5762 "dereferenceable_or_null metadata value must be an i64!",
5766void Verifier::visitNoFreeObjMetadata(Instruction &
I, MDNode *MD) {
5767 Check(
I.getType()->isPointerTy(),
"nofreeobj applies only to pointer types",
5770 "nofreeobj applies only to inttoptr instruction", &
I);
5774void Verifier::visitProfMetadata(Instruction &
I, MDNode *MD) {
5775 auto GetBranchingTerminatorNumOperands = [&]() {
5776 unsigned ExpectedNumOperands = 0;
5780 ExpectedNumOperands =
SI->getNumSuccessors();
5782 ExpectedNumOperands = 1;
5784 ExpectedNumOperands = IBI->getNumDestinations();
5786 ExpectedNumOperands = 2;
5789 return ExpectedNumOperands;
5792 "!prof annotations should have at least 1 operand", MD);
5794 Check(MD->
getOperand(0) !=
nullptr,
"first operand should not be null", MD);
5796 "expected string with name of the !prof annotation", MD);
5802 "'unknown' !prof should only appear on instructions on which "
5803 "'branch_weights' would",
5805 verifyUnknownProfileMetadata(MD);
5810 "!prof annotations should have no less than 2 operands", MD);
5816 Check(NumBranchWeights == 1 || NumBranchWeights == 2,
5817 "Wrong number of InvokeInst branch_weights operands", MD);
5819 const unsigned ExpectedNumOperands = GetBranchingTerminatorNumOperands();
5820 if (ExpectedNumOperands == 0)
5821 CheckFailed(
"!prof branch_weights are not allowed for this instruction",
5824 Check(NumBranchWeights == ExpectedNumOperands,
"Wrong number of operands",
5830 Check(MDO,
"second operand should not be null", MD);
5832 "!prof brunch_weights operand is not a const int");
5837 Check(KindInt,
"VP !prof missing kind argument", MD);
5840 Check(Kind >= InstrProfValueKind::IPVK_First &&
5841 Kind <= InstrProfValueKind::IPVK_Last,
5842 "Invalid VP !prof kind", MD);
5844 "VP !prof should have an even number "
5845 "of arguments after 'VP'",
5847 if (Kind == InstrProfValueKind::IPVK_IndirectCallTarget ||
5848 Kind == InstrProfValueKind::IPVK_MemOPSize)
5850 "VP !prof indirect call or memop size expected to be applied to "
5851 "CallBase instructions only",
5854 DenseSet<uint64_t> ProfileValues;
5856 ConstantInt *ProfileValue =
5858 Check(ProfileValue,
"VP !prof value operand is not a const int", MD);
5860 auto [ValueIt,
Inserted] = ProfileValues.
insert(ProfileValueInt);
5861 Check(Inserted,
"VP !prof should not have duplicate profile values", MD);
5864 CheckFailed(
"expected either branch_weights or VP profile name", MD);
5868void Verifier::visitDIAssignIDMetadata(Instruction &
I, MDNode *MD) {
5869 assert(
I.hasMetadata(LLVMContext::MD_DIAssignID));
5874 bool ExpectedInstTy =
5876 CheckDI(ExpectedInstTy,
"!DIAssignID attached to unexpected instruction kind",
5879 CheckDI(DVR->getFunction() ==
I.getFunction(),
5880 "DVRAssign not in same function as inst", DVR, &
I);
5883void Verifier::visitMMRAMetadata(Instruction &
I, MDNode *MD) {
5885 "!mmra metadata attached to unexpected instruction kind",
I, MD);
5896 for (
const MDOperand &MDOp : MD->
operands())
5898 "!mmra metadata tuple operand is not an MMRA tag",
I, MDOp.get());
5901void Verifier::visitCallStackMetadata(MDNode *MD) {
5905 "call stack metadata should have at least 1 operand", MD);
5909 "call stack metadata operand should be constant integer",
Op);
5912void Verifier::visitMemProfMetadata(Instruction &
I, MDNode *MD) {
5915 Check(
I.hasMetadata(LLVMContext::MD_callsite),
5916 "!memprof metadata requires !callsite metadata", &
I, MD);
5918 "!memprof annotations should have at least 1 metadata operand "
5923 for (
auto &MIBOp : MD->
operands()) {
5928 Check(MIB->getNumOperands() >= 2,
5929 "Each !memprof MemInfoBlock should have at least 2 operands", MIB);
5932 Check(MIB->getOperand(0) !=
nullptr,
5933 "!memprof MemInfoBlock first operand should not be null", MIB);
5935 "!memprof MemInfoBlock first operand should be an MDNode", MIB);
5937 visitCallStackMetadata(StackMD);
5941 "!memprof MemInfoBlock second operand should be an MDString", MIB);
5944 for (
unsigned I = 2;
I < MIB->getNumOperands(); ++
I) {
5946 Check(OpNode,
"Not all !memprof MemInfoBlock operands 2 to N are MDNode",
5948 Check(OpNode->getNumOperands() == 2,
5949 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with 2 "
5954 [](
const MDOperand &
Op) {
5955 return mdconst::hasa<ConstantInt>(Op);
5957 "Not all !memprof MemInfoBlock operands 2 to N are MDNode with "
5958 "ConstantInt operands",
5964void Verifier::visitCallsiteMetadata(Instruction &
I, MDNode *MD) {
5968 visitCallStackMetadata(MD);
5971void Verifier::visitCalleeTypeMetadata(Instruction &
I, MDNode *MD) {
5976 "The callee_type metadata must be a list of callgraph metadata nodes",
5979 Check(CallgraphMD->getNumOperands() == 1,
5980 "Well-formed callgraph metadata must contain exactly one "
5984 "The operand of callgraph metadata for functions must be an MDString",
5989void Verifier::visitAnnotationMetadata(MDNode *Annotation) {
5992 "annotation must have at least one operand");
5994 bool TupleOfStrings =
6000 "operands must be a string or a tuple of strings");
6004void Verifier::visitAliasScopeMetadata(
const MDNode *MD) {
6009 "first scope operand must be self-referential or string", MD);
6012 "third scope operand must be string (if used)", MD);
6015 Check(
Domain !=
nullptr,
"second scope operand must be MDNode", MD);
6017 unsigned NumDomainOps =
Domain->getNumOperands();
6018 Check(NumDomainOps >= 2 && NumDomainOps <= 3,
6019 "domain must have two or three operands",
Domain);
6022 "first domain operand must be self-referential or string",
Domain);
6023 const auto *Disjoint =
6025 Check(Disjoint && Disjoint->getBitWidth() == 1,
6026 "second domain operand must be an i1 constant",
Domain);
6027 if (NumDomainOps == 3)
6029 "third domain operand must be string (if used)",
Domain);
6032void Verifier::visitAliasScopeListMetadata(
const MDNode *MD) {
6035 Check(OpMD !=
nullptr,
"scope list must consist of MDNodes", MD);
6036 visitAliasScopeMetadata(OpMD);
6040void Verifier::visitAccessGroupMetadata(
const MDNode *MD) {
6041 auto IsValidAccessScope = [](
const MDNode *MD) {
6056 Check(OpMD !=
nullptr,
"Access scope list must consist of MDNodes", MD);
6057 Check(IsValidAccessScope(OpMD),
6058 "Access scope list contains invalid access scope", MD);
6062void Verifier::visitCapturesMetadata(Instruction &
I,
const MDNode *Captures) {
6063 static const char *ValidArgs[] = {
"address_is_null",
"address",
6064 "read_provenance",
"provenance"};
6067 Check(SI,
"!captures metadata can only be applied to store instructions", &
I);
6068 Check(
SI->getValueOperand()->getType()->isPointerTy(),
6069 "!captures metadata can only be applied to store with value operand of "
6077 Check(Str,
"!captures metadata must be a list of strings", &
I);
6079 "invalid entry in !captures metadata", &
I, Str);
6083void Verifier::visitAllocTokenMetadata(Instruction &
I, MDNode *MD) {
6086 "!alloc_token must have 2 or 3 operands", MD);
6089 "expected integer constant", MD);
6092 "expected function name string", MD);
6095void Verifier::visitInlineHistoryMetadata(Instruction &
I, MDNode *MD) {
6104 ->stripPointerCastsAndAliases()),
6105 "!inline_history operands must be functions or null", MD);
6109void Verifier::visitMemCacheHintMetadata(Instruction &
I, MDNode *MD) {
6110 Check(
I.mayReadOrWriteMemory(),
6111 "!mem.cache_hint is only valid on memory operations", &
I);
6114 "!mem.cache_hint must have even number of operands "
6115 "(operand_no, hint_node pairs)",
6121 "!mem.cache_hint is not supported on non-intrinsic calls", &
I);
6123 unsigned NumOperands = CB ? CB->arg_size() :
I.getNumOperands();
6125 SmallDenseSet<unsigned, 4> SeenOperandNos;
6126 std::optional<uint64_t> LastOperandNo;
6132 "!mem.cache_hint must alternate between i32 operand numbers and "
6133 "metadata hint nodes",
6136 Check(OpNoCI->getValue().isNonNegative(),
6137 "!mem.cache_hint operand number must be non-negative", MD);
6139 uint64_t OperandNo = OpNoCI->getZExtValue();
6140 Check(OperandNo < NumOperands,
6141 "!mem.cache_hint operand number is out of range", &
I);
6144 CB ? CB->getArgOperand(OperandNo) :
I.getOperand(OperandNo);
6146 "!mem.cache_hint operand number must refer to a pointer operand", &
I);
6149 Check(Inserted,
"!mem.cache_hint contains duplicate operand number", MD);
6151 Check(!Inserted || !LastOperandNo || OperandNo > *LastOperandNo,
6152 "!mem.cache_hint operand numbers must be in increasing order", MD);
6153 LastOperandNo = OperandNo;
6157 "!mem.cache_hint must alternate between i32 operand numbers and "
6158 "metadata hint nodes",
6162 "!mem.cache_hint hint node must have even number of operands "
6163 "(key-value pairs)",
6166 StringSet<> SeenKeys;
6167 for (
unsigned K = 0;
K + 1 <
Node->getNumOperands();
K += 2) {
6169 Check(
Key,
"!mem.cache_hint key must be a string", Node);
6171 StringRef KeyStr =
Key->getString();
6173 "!mem.cache_hint hint node contains duplicate key", Node);
6178 "!mem.cache_hint value must be a string or integer", Node);
6185void Verifier::visitInstruction(Instruction &
I) {
6187 Check(BB,
"Instruction not embedded in basic block!", &
I);
6190 for (User *U :
I.users()) {
6191 Check(U != (User *)&
I || !DT.isReachableFromEntry(BB),
6192 "Only PHI nodes may reference their own value!", &
I);
6197 Check(!
I.getType()->isVoidTy() || !
I.hasName(),
6198 "Instruction has a name, but provides a void value!", &
I);
6202 Check(
I.getType()->isVoidTy() ||
I.getType()->isFirstClassType(),
6203 "Instruction returns a non-scalar type!", &
I);
6208 "Invalid use of metadata!", &
I);
6213 for (Use &U :
I.uses()) {
6216 "Instruction referencing"
6217 " instruction not embedded in a basic block!",
6220 CheckFailed(
"Use of instruction is not an instruction!", U);
6229 for (
unsigned i = 0, e =
I.getNumOperands(); i != e; ++i) {
6230 Check(
I.getOperand(i) !=
nullptr,
"Instruction has null operand!", &
I);
6234 if (!
I.getOperand(i)->getType()->isFirstClassType()) {
6235 Check(
false,
"Instruction operands must be first-class values!", &
I);
6241 auto IsAttachedCallOperand = [](
Function *
F,
const CallBase *CBI,
6243 return CBI && CBI->isOperandBundleOfType(
6251 Check((!
F->isIntrinsic() ||
6252 (CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i)) ||
6253 IsAttachedCallOperand(
F, CBI, i)),
6254 "Cannot take the address of an intrinsic!", &
I);
6256 F->getIntrinsicID() == Intrinsic::donothing ||
6257 F->getIntrinsicID() == Intrinsic::seh_try_begin ||
6258 F->getIntrinsicID() == Intrinsic::seh_try_end ||
6259 F->getIntrinsicID() == Intrinsic::seh_scope_begin ||
6260 F->getIntrinsicID() == Intrinsic::seh_scope_end ||
6261 F->getIntrinsicID() == Intrinsic::coro_resume ||
6262 F->getIntrinsicID() == Intrinsic::coro_destroy ||
6263 F->getIntrinsicID() == Intrinsic::coro_await_suspend_void ||
6264 F->getIntrinsicID() == Intrinsic::coro_await_suspend_bool ||
6265 F->getIntrinsicID() == Intrinsic::coro_await_suspend_handle ||
6266 F->getIntrinsicID() ==
6267 Intrinsic::experimental_patchpoint_void ||
6268 F->getIntrinsicID() == Intrinsic::experimental_patchpoint ||
6269 F->getIntrinsicID() == Intrinsic::fake_use ||
6270 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint ||
6271 F->getIntrinsicID() == Intrinsic::wasm_throw ||
6272 F->getIntrinsicID() == Intrinsic::wasm_rethrow ||
6273 F->getIntrinsicID() == Intrinsic::bpf_unwind_exit ||
6274 IsAttachedCallOperand(
F, CBI, i),
6275 "Cannot invoke an intrinsic other than donothing, patchpoint, "
6276 "statepoint, coro_resume, coro_destroy, clang.arc.attachedcall, "
6277 "wasm.(re)throw or bpf.unwind.exit",
6279 Check(
F->getParent() == &M,
"Referencing function in another module!", &
I,
6280 &M,
F,
F->getParent());
6283 "Referring to a basic block in another function!", &
I);
6286 "Referring to an argument in another function!", &
I);
6288 Check(GV->
getParent() == &M,
"Referencing global in another module!", &
I,
6292 "Referring to an instruction in another function!", &
I);
6293 verifyDominatesUse(
I, i);
6295 Check(CBI && &CBI->getCalledOperandUse() == &
I.getOperandUse(i),
6296 "Cannot take the address of an inline asm!", &
I);
6298 visitConstantExprsRecursively(
C);
6303 I.getAllMetadataOtherThanDebugLoc(MDs);
6304 for (
auto [Kind, MD] : MDs) {
6306 case LLVMContext::MD_fpmath:
6308 "fpmath requires a floating point result!", &
I);
6310 if (ConstantFP *CFP0 =
6312 const APFloat &Accuracy = CFP0->getValueAPF();
6314 "fpmath accuracy must have float type", &
I);
6316 "fpmath accuracy not a positive number!", &
I);
6318 Check(
false,
"invalid fpmath accuracy!", &
I);
6321 case LLVMContext::MD_range:
6323 "Ranges are only for loads, calls, invokes and phi nodes!", &
I);
6324 visitRangeMetadata(
I, MD,
I.getType());
6326 case LLVMContext::MD_nofpclass:
6328 "nofpclass is only for loads and phi nodes", &
I);
6329 visitNoFPClassMetadata(
I, MD,
I.getType());
6331 case LLVMContext::MD_noalias_addrspace:
6334 "noalias.addrspace are only for memory operations!", &
I);
6335 visitNoaliasAddrspaceMetadata(
I, MD,
I.getType());
6337 case LLVMContext::MD_invariant_group:
6339 "invariant.group metadata is only for loads and stores", &
I);
6341 case LLVMContext::MD_invariant_load: {
6344 "invariant.load metadata is only for loads and readonly "
6349 case LLVMContext::MD_nonnull:
6350 Check(
I.getType()->isPointerTy(),
"nonnull applies only to pointer types",
6353 "nonnull applies only to load instructions or phi nodes, use "
6354 "attributes for calls or invokes",
6358 case LLVMContext::MD_noundef:
6360 "noundef applies only to load instructions or phi nodes", &
I);
6363 case LLVMContext::MD_dereferenceable:
6364 case LLVMContext::MD_dereferenceable_or_null:
6365 visitDereferenceableMetadata(
I, MD);
6367 case LLVMContext::MD_nofreeobj:
6368 visitNoFreeObjMetadata(
I, MD);
6370 case LLVMContext::MD_tbaa:
6373 case LLVMContext::MD_tbaa_struct:
6376 case LLVMContext::MD_noalias:
6377 case LLVMContext::MD_alias_scope:
6378 visitAliasScopeListMetadata(MD);
6380 case LLVMContext::MD_access_group:
6381 visitAccessGroupMetadata(MD);
6383 case LLVMContext::MD_align: {
6384 Check(
I.getType()->isPointerTy(),
"align applies only to pointer types",
6387 "align applies only to load instructions or phi nodes, "
6388 "use attributes for calls or invokes",
6393 "align metadata value must be an i64!", &
I);
6397 Check(Align <= Value::MaximumAlignment,
6398 "alignment is larger that implementation defined limit", &
I);
6401 case LLVMContext::MD_prof:
6402 visitProfMetadata(
I, MD);
6404 case LLVMContext::MD_memprof:
6405 visitMemProfMetadata(
I, MD);
6407 case LLVMContext::MD_callsite:
6408 visitCallsiteMetadata(
I, MD);
6410 case LLVMContext::MD_callee_type:
6411 visitCalleeTypeMetadata(
I, MD);
6413 case LLVMContext::MD_DIAssignID:
6414 visitDIAssignIDMetadata(
I, MD);
6416 case LLVMContext::MD_mmra:
6417 visitMMRAMetadata(
I, MD);
6419 case LLVMContext::MD_annotation:
6420 visitAnnotationMetadata(MD);
6422 case LLVMContext::MD_captures:
6423 visitCapturesMetadata(
I, MD);
6425 case LLVMContext::MD_alloc_token:
6426 visitAllocTokenMetadata(
I, MD);
6428 case LLVMContext::MD_inline_history:
6429 visitInlineHistoryMetadata(
I, MD);
6431 case LLVMContext::MD_mem_cache_hint:
6432 visitMemCacheHintMetadata(
I, MD);
6435 if (Kind == MDAMDGPUExpectedActiveLanes) {
6437 "!amdgpu.expected.active.lanes must have exactly one operand", &
I,
6442 "!amdgpu.expected.active.lanes operand must be an i32 constant",
6444 }
else if (Kind == MDAMDGPUCFS) {
6446 "!amdgpu.cfs must have exactly one operand", &
I, MD);
6450 "!amdgpu.cfs operand must be an i32 constant", &
I, MD);
6452 "!amdgpu.cfs operand must be in the range [0, 3]", &
I, MD);
6458 if (MDNode *
N =
I.getDebugLoc().getAsMDNode()) {
6460 visitMDNode(*
N, AreDebugLocsAllowed::Yes);
6463 if (
DL->getAtomGroup()) {
6465 CheckDI(SP &&
SP->getKeyInstructionsEnabled(),
6466 "DbgLoc uses atomGroup but DISubprogram doesn't have Key "
6467 "Instructions enabled",
6473 for (
auto [Kind, MD] : MDs) {
6474 auto AllowLocs =
Kind == LLVMContext::MD_loop ? AreDebugLocsAllowed::Yes
6475 : AreDebugLocsAllowed::No;
6476 visitMDNode(*MD, AllowLocs);
6491 "const x86_amx is not allowed in argument!");
6503 case Intrinsic::assume: {
6507 "assume with operand bundles must have i1 true condition",
Call);
6513 auto GetTypeAt = [&](
unsigned Index) {
6514 return OBU.Inputs[
Index]->getType();
6519 CheckFailed(
"tags must be valid attribute names",
Call);
6521 case BundleAttr::Align:
6522 Check(OBU.Inputs.size() >= 2 && OBU.Inputs.size() <= 3,
6523 "alignment assumptions should have 2 or 3 arguments",
Call);
6526 Check(GetTypeAt(1)->isIntegerTy() &&
6527 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6528 "second argument should be an integer with a maximum width of 64 "
6531 Check(OBU.Inputs.size() < 3 ||
6532 (GetTypeAt(2)->isIntegerTy() &&
6533 GetTypeAt(2)->getIntegerBitWidth() <= 64),
6534 "third argument should be an integer with a maximum width of 64 "
6538 case BundleAttr::Cold:
6539 Check(OBU.Inputs.size() == 0,
6540 "cold assumptions should have no arguments",
Call);
6542 case BundleAttr::Dereferenceable:
6543 case BundleAttr::DereferenceableOrNull:
6544 Check(OBU.Inputs.size() == 2,
6545 "dereferenceable assumptions should have 2 arguments",
Call);
6548 Check(GetTypeAt(1)->isIntegerTy() &&
6549 GetTypeAt(1)->getIntegerBitWidth() <= 64,
6550 "second argument should be an integer with a maximum width of 64 "
6554 case BundleAttr::Ignore:
6556 case BundleAttr::NonNull:
6557 Check(OBU.Inputs.size() == 1,
6558 "nonnull assumptions should have 1 argument",
Call);
6562 case BundleAttr::NoUndef:
6563 Check(OBU.Inputs.size() == 1,
6564 "noundef assumptions should have 1 argument",
Call);
6566 case BundleAttr::Range: {
6567 Check(OBU.Inputs.size() == 3,
6568 "range assumptions should have 3 arguments",
Call);
6569 Check(GetTypeAt(0)->isIntegerTy(),
6570 "first argument should be an integer",
Call);
6572 Check(LowerBound,
"second argument should be a constant integer",
Call);
6574 Check(UpperBound,
"third argument should be a constant integer",
Call);
6576 "an empty range has to be represented as `0, 0`");
6577 Check(GetTypeAt(0)->getIntegerBitWidth() ==
6578 GetTypeAt(1)->getIntegerBitWidth() &&
6579 GetTypeAt(1)->getIntegerBitWidth() ==
6580 GetTypeAt(2)->getIntegerBitWidth(),
6581 "all arguments should have the same bit width",
Call);
6583 case BundleAttr::SeparateStorage:
6584 Check(OBU.Inputs.size() == 2,
6585 "separate_storage assumptions should have 2 arguments",
Call);
6587 "arguments to separate_storage assumptions should be pointers",
6594 case Intrinsic::ucmp:
6595 case Intrinsic::scmp: {
6598 "result type must be at least 2 bits wide",
Call);
6601 case Intrinsic::coro_begin:
6602 case Intrinsic::coro_begin_custom_abi:
6604 "id argument of llvm.coro.begin must refer to coro.id");
6606 case Intrinsic::coro_id: {
6608 "align argument only accepts constants");
6611 "promise argument must refer to an alloca");
6616 "coro argument must refer to a function");
6620 if (BeforeCoroSplit)
6623 Check(!BeforeCoroEarly,
"cannot run CoroSplit before CoroEarly");
6625 Check(GV && GV->isConstant() && GV->hasDefinitiveInitializer(),
6626 "info argument of llvm.coro.id must refer to an initialized "
6628 Constant *Init = GV->getInitializer();
6630 "info argument of llvm.coro.id must refer to either a struct or "
6634 case Intrinsic::is_fpclass: {
6637 "unsupported bits for llvm.is.fpclass test mask");
6640 case Intrinsic::fptrunc_round: {
6645 MD = MAV->getMetadata();
6647 Check(MD !=
nullptr,
"missing rounding mode argument",
Call);
6650 (
"invalid value for llvm.fptrunc.round metadata operand"
6651 " (the operand should be a string)"),
6654 std::optional<RoundingMode> RoundMode =
6656 Check(RoundMode && *RoundMode != RoundingMode::Dynamic,
6657 "unsupported rounding mode argument",
Call);
6660 case Intrinsic::convert_to_arbitrary_fp: {
6665 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6667 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6668 StringRef Interp = InterpStr->getString();
6670 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6675 "unsupported interpretation metadata string",
Call);
6678 if (
unsigned FormatBits =
6681 "integer type bit width must equal the arbitrary FP format width",
6686 Check(RoundingMAV,
"missing rounding mode metadata operand",
Call);
6688 Check(RoundingStr,
"rounding mode metadata operand must be a string",
Call);
6690 std::optional<RoundingMode>
RM =
6692 Check(RM && *RM != RoundingMode::Dynamic,
6693 "unsupported rounding mode argument",
Call);
6696 case Intrinsic::convert_from_arbitrary_fp: {
6701 Check(InterpMAV,
"missing interpretation metadata operand",
Call);
6703 Check(InterpStr,
"interpretation metadata operand must be a string",
Call);
6704 StringRef Interp = InterpStr->getString();
6706 Check(!Interp.
empty(),
"interpretation metadata string must not be empty",
6711 "unsupported interpretation metadata string",
Call);
6714 if (
unsigned FormatBits =
6717 "integer type bit width must equal the arbitrary FP format width",
6721#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6722#include "llvm/IR/VPIntrinsics.def"
6723#undef BEGIN_REGISTER_VP_INTRINSIC
6726#define INSTRUCTION(NAME, NARGS, ROUND_MODE, INTRINSIC) \
6727 case Intrinsic::INTRINSIC:
6728#include "llvm/IR/ConstrainedOps.def"
6732 case Intrinsic::dbg_declare:
6733 case Intrinsic::dbg_value:
6734 case Intrinsic::dbg_assign:
6735 case Intrinsic::dbg_label:
6742 case Intrinsic::memcpy:
6743 case Intrinsic::memcpy_inline:
6744 case Intrinsic::memmove:
6745 case Intrinsic::memset:
6746 case Intrinsic::memset_inline:
6748 case Intrinsic::experimental_memset_pattern: {
6750 Check(Memset->getValue()->getType()->isSized(),
6751 "unsized types cannot be used as memset patterns",
Call);
6754 case Intrinsic::memcpy_element_unordered_atomic:
6755 case Intrinsic::memmove_element_unordered_atomic:
6756 case Intrinsic::memset_element_unordered_atomic: {
6759 ConstantInt *ElementSizeCI =
6761 const APInt &ElementSizeVal = ElementSizeCI->
getValue();
6763 "element size of the element-wise atomic memory intrinsic "
6764 "must be a power of 2",
6767 auto IsValidAlignment = [&](MaybeAlign
Alignment) {
6770 Check(IsValidAlignment(AMI->getDestAlign()),
6771 "incorrect alignment of the destination argument",
Call);
6773 Check(IsValidAlignment(AMT->getSourceAlign()),
6774 "incorrect alignment of the source argument",
Call);
6778 case Intrinsic::call_preallocated_setup: {
6780 bool FoundCall =
false;
6783 Check(UseCall !=
nullptr,
6784 "Uses of llvm.call.preallocated.setup must be calls");
6786 if (IID == Intrinsic::call_preallocated_arg) {
6788 Check(AllocArgIndex !=
nullptr,
6789 "llvm.call.preallocated.alloc arg index must be a constant");
6790 auto AllocArgIndexInt = AllocArgIndex->getValue();
6791 Check(AllocArgIndexInt.sge(0) &&
6792 AllocArgIndexInt.slt(NumArgs->getValue()),
6793 "llvm.call.preallocated.alloc arg index must be between 0 and "
6795 "llvm.call.preallocated.setup's argument count");
6796 }
else if (IID == Intrinsic::call_preallocated_teardown) {
6799 Check(!FoundCall,
"Can have at most one call corresponding to a "
6800 "llvm.call.preallocated.setup");
6802 size_t NumPreallocatedArgs = 0;
6803 for (
unsigned i = 0; i < UseCall->arg_size(); i++) {
6804 if (UseCall->paramHasAttr(i, Attribute::Preallocated)) {
6805 ++NumPreallocatedArgs;
6808 Check(NumPreallocatedArgs != 0,
6809 "cannot use preallocated intrinsics on a call without "
6810 "preallocated arguments");
6811 Check(NumArgs->equalsInt(NumPreallocatedArgs),
6812 "llvm.call.preallocated.setup arg size must be equal to number "
6813 "of preallocated arguments "
6823 auto PreallocatedBundle =
6825 Check(PreallocatedBundle,
6826 "Use of llvm.call.preallocated.setup outside intrinsics "
6827 "must be in \"preallocated\" operand bundle");
6828 Check(PreallocatedBundle->Inputs.front().get() == &
Call,
6829 "preallocated bundle must have token from corresponding "
6830 "llvm.call.preallocated.setup");
6835 case Intrinsic::call_preallocated_arg: {
6838 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6839 "llvm.call.preallocated.arg token argument must be a "
6840 "llvm.call.preallocated.setup");
6842 "llvm.call.preallocated.arg must be called with a \"preallocated\" "
6843 "call site attribute");
6846 case Intrinsic::call_preallocated_teardown: {
6849 Token->getIntrinsicID() == Intrinsic::call_preallocated_setup,
6850 "llvm.call.preallocated.teardown token argument must be a "
6851 "llvm.call.preallocated.setup");
6854 case Intrinsic::gcroot:
6855 case Intrinsic::gcwrite:
6856 case Intrinsic::gcread:
6857 if (ID == Intrinsic::gcroot) {
6860 Check(AI,
"llvm.gcroot parameter #1 must be an alloca.",
Call);
6862 "llvm.gcroot parameter #2 must be a constant.",
Call);
6865 "llvm.gcroot parameter #1 must either be a pointer alloca, "
6866 "or argument #2 must be a non-null constant.",
6872 "Enclosing function does not use GC.",
Call);
6874 case Intrinsic::init_trampoline:
6876 "llvm.init_trampoline parameter #2 must resolve to a function.",
6879 case Intrinsic::reloc_none: {
6882 "llvm.reloc.none argument must be a metadata string", &
Call);
6885 case Intrinsic::stackprotector:
6887 "llvm.stackprotector parameter #2 must resolve to an alloca.",
Call);
6889 case Intrinsic::localescape: {
6893 Check(!SawFrameEscape,
"multiple calls to llvm.localescape in one function",
6900 "llvm.localescape only accepts static allocas",
Call);
6903 SawFrameEscape =
true;
6906 case Intrinsic::localrecover: {
6909 Check(Fn && !Fn->isDeclaration(),
6910 "llvm.localrecover first "
6911 "argument must be function defined in this module",
6914 auto &
Entry = FrameEscapeInfo[Fn];
6915 Entry.second = unsigned(
6916 std::max(
uint64_t(
Entry.second), IdxArg->getLimitedValue(~0U) + 1));
6920 case Intrinsic::experimental_gc_statepoint:
6922 Check(!CI->isInlineAsm(),
6923 "gc.statepoint support for inline assembly unimplemented", CI);
6925 "Enclosing function does not use GC.",
Call);
6927 verifyStatepoint(
Call);
6929 case Intrinsic::experimental_gc_result: {
6931 "Enclosing function does not use GC.",
Call);
6939 Check(StatepointCall && StatepointCall->getIntrinsicID() ==
6940 Intrinsic::experimental_gc_statepoint,
6941 "gc.result operand #1 must be from a statepoint",
Call,
6945 auto *TargetFuncType =
6948 "gc.result result type does not match wrapped callee",
Call);
6951 case Intrinsic::experimental_gc_relocate: {
6953 "gc.relocate must return a pointer or a vector of pointers",
Call);
6961 LandingPad->getParent()->getUniquePredecessor();
6965 Check(InvokeBB,
"safepoints should have unique landingpads",
6966 LandingPad->getParent());
6968 "gc relocate should be linked to a statepoint", InvokeBB);
6975 "gc relocate is incorrectly tied to the statepoint",
Call, Token);
6984 "gc.relocate operand #2 must be integer offset",
Call);
6988 "gc.relocate operand #3 must be integer offset",
Call);
6998 Check(BaseIndex < Opt->Inputs.size(),
6999 "gc.relocate: statepoint base index out of bounds",
Call);
7000 Check(DerivedIndex < Opt->Inputs.size(),
7001 "gc.relocate: statepoint derived index out of bounds",
Call);
7009 "gc.relocate: relocated value must be a pointer",
Call);
7010 Check(DerivedType->isPtrOrPtrVectorTy(),
7011 "gc.relocate: relocated value must be a pointer",
Call);
7013 "gc.relocate: must return the type of the relocated value",
Call);
7016 Check(GC,
"gc.relocate: calling function must have GCStrategy",
7019 auto isGCPtr = [&
GC](
Type *PTy) {
7020 return GC->isGCManagedPointer(PTy->getScalarType()).value_or(
true);
7023 "gc.relocate: relocated value must be a gc pointer",
Call);
7024 Check(isGCPtr(DerivedType),
7025 "gc.relocate: relocated value must be a gc pointer",
Call);
7029 case Intrinsic::experimental_patchpoint: {
7032 "patchpoint: invalid return type used with anyregcc",
Call);
7036 case Intrinsic::eh_exceptioncode:
7037 case Intrinsic::eh_exceptionpointer: {
7039 "eh.exceptionpointer argument must be a catchpad",
Call);
7042 case Intrinsic::get_active_lane_mask: {
7045 "get_active_lane_mask: element type is not i1",
Call);
7048 case Intrinsic::mask_beforefirst: {
7050 "mask.beforefirst element type must be i1",
Call);
7053 case Intrinsic::experimental_get_vector_length: {
7055 Check(!VF->isNegative() && !VF->isZero(),
7056 "get_vector_length: VF must be positive",
Call);
7059 case Intrinsic::experimental_guard: {
7062 "experimental_guard must have exactly one "
7063 "\"deopt\" operand bundle");
7067 case Intrinsic::experimental_deoptimize: {
7071 "experimental_deoptimize must have exactly one "
7072 "\"deopt\" operand bundle");
7074 "experimental_deoptimize return type must match caller return type");
7079 "calls to experimental_deoptimize must be followed by a return");
7083 "calls to experimental_deoptimize must be followed by a return "
7084 "of the value computed by experimental_deoptimize");
7089 case Intrinsic::vastart: {
7091 "va_start called in a non-varargs function");
7094 case Intrinsic::get_dynamic_area_offset: {
7095 Check(
DL.getPointerSizeInBits(
DL.getAllocaAddrSpace()) ==
7097 "get_dynamic_area_offset result type must match alloca address "
7102 case Intrinsic::smul_fix:
7103 case Intrinsic::smul_fix_sat:
7104 case Intrinsic::umul_fix:
7105 case Intrinsic::umul_fix_sat:
7106 case Intrinsic::sdiv_fix:
7107 case Intrinsic::sdiv_fix_sat:
7108 case Intrinsic::udiv_fix:
7109 case Intrinsic::udiv_fix_sat: {
7113 if (ID == Intrinsic::smul_fix || ID == Intrinsic::smul_fix_sat ||
7114 ID == Intrinsic::sdiv_fix || ID == Intrinsic::sdiv_fix_sat) {
7116 "the scale of s[mul|div]_fix[_sat] must be less than the width of "
7120 "the scale of u[mul|div]_fix[_sat] must be less than or equal "
7121 "to the width of the operands");
7125 case Intrinsic::bswap: {
7128 Check(
Size % 16 == 0,
"bswap must be an even number of bytes", &
Call);
7131 case Intrinsic::invariant_start: {
7133 Check(InvariantSize &&
7134 (!InvariantSize->isNegative() || InvariantSize->isMinusOne()),
7135 "invariant_start parameter must be -1, 0 or a positive number",
7139 case Intrinsic::matrix_multiply:
7140 case Intrinsic::matrix_transpose:
7141 case Intrinsic::matrix_column_major_load:
7142 case Intrinsic::matrix_column_major_store: {
7144 Value *Stride =
nullptr;
7145 ConstantInt *NumRows;
7146 ConstantInt *NumColumns;
7147 FixedVectorType *ResultTy;
7148 Type *Op0ElemTy =
nullptr;
7149 Type *Op1ElemTy =
nullptr;
7151 case Intrinsic::matrix_multiply: {
7158 Check(Op0Ty && Op1Ty && RetTy,
7159 "Matrix operations require fixed-length vectors!", &
Call);
7160 Check(Op0Ty->getNumElements() ==
7162 "First argument of a matrix operation does not match specified "
7164 Check(Op1Ty->getNumElements() ==
7166 "Second argument of a matrix operation does not match specified "
7170 Op0ElemTy = Op0Ty->getElementType();
7171 Op1ElemTy = Op1Ty->getElementType();
7174 case Intrinsic::matrix_transpose: {
7179 Check(Op0Ty && RetTy,
"Matrix operations require fixed-length vectors!",
7182 Op0ElemTy = Op0Ty->getElementType();
7185 case Intrinsic::matrix_column_major_load: {
7190 Check(RetTy,
"Matrix operations require fixed-length vectors!", &
Call);
7194 case Intrinsic::matrix_column_major_store: {
7199 Check(Op0Ty,
"Matrix operations require fixed-length vectors!", &
Call);
7201 Op0ElemTy = Op0Ty->getElementType();
7210 "Result type must be an integer or floating-point type!", IF);
7214 "Vector element type mismatch of the result and first operand "
7220 "Vector element type mismatch of the result and second operand "
7226 "Result of a matrix operation does not fit in the returned vector!");
7230 "Stride bitwidth cannot exceed 64!", IF);
7234 case Intrinsic::stepvector: {
7236 Check(VecTy->getScalarSizeInBits() >= 8,
7237 "stepvector only supported for vectors of integers "
7238 "with a bitwidth of at least 8.",
7242 case Intrinsic::experimental_vector_match: {
7250 "Second operand must be a fixed length vector.", &
Call);
7251 Check(Op1Ty->getElementType() == Op2Ty->getElementType(),
7252 "First two operands must have the same element type.", &
Call);
7255 case Intrinsic::speculative_load: {
7258 "llvm.speculative.load return type must be a byte type or a "
7264 "llvm.speculative.load byte type must have a bit width that is "
7269 uint64_t MinSizeInBits =
DL.getTypeSizeInBits(LoadTy).getKnownMinValue();
7271 "llvm.speculative.load return type size in bytes must be a "
7272 "positive power of 2",
7275 constexpr unsigned NumFixedArgs = 3;
7277 Check(NumArgs >= NumFixedArgs,
7278 "llvm.speculative.load requires at least 3 arguments", &
Call);
7283 Check(NumArgs == NumFixedArgs,
7284 "llvm.speculative.load direct form has too many arguments", &
Call);
7289 "llvm.speculative.load third argument must be i64 or a direct "
7290 "reference to an oracle function",
7293 Check(OracleFn->hasFnAttribute(
"oracle-function"),
7294 "llvm.speculative.load oracle function must have the "
7295 "\"oracle-function\" attribute",
7298 FunctionType *FTy = OracleFn->getFunctionType();
7299 Check(NumArgs - NumFixedArgs == FTy->getNumParams(),
7300 "llvm.speculative.load oracle function argument count mismatch",
7302 for (
auto [ParamTy, Arg] :
7304 Check(ParamTy == Arg->getType(),
7305 "llvm.speculative.load oracle function argument type mismatch",
7310 case Intrinsic::vector_repeat: {
7314 Check(ArgTy,
"vector_repeat argument must be a fixed-length vector.",
7316 Check(ResultTy,
"vector_repeat result must be a scalable vector.", &
Call);
7318 "vector_repeat argument and result must have the same element "
7321 Check(ArgTy->getNumElements() == ResultTy->getMinNumElements(),
7322 "vector_repeat argument and result must have the same minimum "
7327 case Intrinsic::vector_shuffle: {
7331 Check(MaskTy->getElementCount() == RetTy->getElementCount(),
7332 "vector_shuffle mask must have the same number of elements as the "
7337 case Intrinsic::vector_insert: {
7346 ElementCount VecEC = VecTy->getElementCount();
7347 ElementCount SubVecEC =
SubVecTy->getElementCount();
7348 Check(VecTy->getElementType() ==
SubVecTy->getElementType(),
7349 "vector_insert parameters must have the same element "
7353 "vector_insert index must be a constant multiple of "
7354 "the subvector's known minimum vector length.");
7359 Check(VecEC.
isScalable(),
"cannot vector_insert a scalable vector into "
7369 "subvector operand of vector_insert would overrun the "
7370 "vector being inserted into.");
7374 case Intrinsic::vector_extract: {
7382 ElementCount VecEC = VecTy->getElementCount();
7383 ElementCount ResultEC = ResultTy->getElementCount();
7385 Check(ResultTy->getElementType() == VecTy->getElementType(),
7386 "vector_extract result must have the same element "
7387 "type as the input vector.",
7390 "vector_extract index must be a constant multiple of "
7391 "the result type's known minimum vector length.");
7396 Check(VecEC.
isScalable(),
"cannot vector_extract a scalable vector from "
7406 "vector_extract would overrun.");
7410 case Intrinsic::vector_partial_reduce_fadd:
7411 case Intrinsic::vector_partial_reduce_add: {
7415 unsigned VecWidth = VecTy->getElementCount().getKnownMinValue();
7416 unsigned AccWidth = AccTy->getElementCount().getKnownMinValue();
7418 Check((VecWidth % AccWidth) == 0,
7419 "Invalid vector widths for partial "
7420 "reduction. The width of the input vector "
7421 "must be a positive integer multiple of "
7422 "the width of the accumulator vector.");
7424 Check(AccTy->getElementType() == VecTy->getElementType(),
7425 "The element type of the input vector must match the element type "
7426 "of the accumulator vector.",
7430 case Intrinsic::experimental_noalias_scope_decl: {
7434 case Intrinsic::preserve_array_access_index:
7435 case Intrinsic::preserve_struct_access_index:
7436 case Intrinsic::aarch64_ldaxr:
7437 case Intrinsic::aarch64_ldxr:
7438 case Intrinsic::arm_ldaex:
7439 case Intrinsic::arm_ldrex: {
7441 Check(ElemTy,
"Intrinsic requires elementtype attribute on first argument.",
7445 case Intrinsic::aarch64_stlxr:
7446 case Intrinsic::aarch64_stxr:
7447 case Intrinsic::arm_stlex:
7448 case Intrinsic::arm_strex: {
7451 "Intrinsic requires elementtype attribute on second argument.",
7455 case Intrinsic::aarch64_prefetch: {
7457 "write argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7459 "target argument to llvm.aarch64.prefetch must be 0-3",
Call);
7461 "stream argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7463 "isdata argument to llvm.aarch64.prefetch must be 0 or 1",
Call);
7466 case Intrinsic::aarch64_range_prefetch: {
7468 "write argument to llvm.aarch64.range.prefetch must be 0 or 1",
Call);
7470 "stream argument to llvm.aarch64.range.prefetch must be 0 or 1",
7474 case Intrinsic::riscv_vsetvli:
7475 case Intrinsic::riscv_vsetvlimax: {
7480 "llvm.riscv.vsetvli/vsetvlimax result must be i32 or i64", &
Call);
7483 bool HasAVL =
ID == Intrinsic::riscv_vsetvli;
7484 unsigned Offset = HasAVL ? 1 : 0;
7489 Check(VSEW <= 3,
"llvm.riscv.vsetvli/vsetvlimax VSEW must be 0-3", &
Call);
7491 "llvm.riscv.vsetvli/vsetvlimax VLMUL is reserved", &
Call);
7494 case Intrinsic::riscv_sati: {
7498 "llvm.riscv.sati immediate must be in the range [1, bitwidth]",
7502 case Intrinsic::riscv_usati: {
7506 "llvm.riscv.usati immediate must be in the range [0, bitwidth-1]",
7510 case Intrinsic::callbr_landingpad: {
7512 Check(CBR,
"intrinstic requires callbr operand", &
Call);
7519 CheckFailed(
"Intrinsic in block must have 1 unique predecessor", &
Call);
7523 CheckFailed(
"Intrinsic must have corresponding callbr in predecessor",
7528 "Intrinsic's corresponding callbr must have intrinsic's parent basic "
7529 "block in indirect destination list",
7532 Check(&
First == &
Call,
"No other instructions may proceed intrinsic",
7536 case Intrinsic::structured_gep: {
7542 "Intrinsic first parameter is missing an ElementType attribute",
7550 "Index operand type must be an integer", &
Call);
7553 T = AT->getElementType();
7555 Check(CI,
"Indexing into a struct requires a constant int", &
Call);
7557 "Indexing in a struct should be inbounds", &
Call);
7560 T = VT->getElementType();
7562 CheckFailed(
"Reached a non-composite type with more indices to process",
7568 case Intrinsic::structured_alloca:
7570 "@llvm.structured.alloca calls require elementtype attribute.",
7573 case Intrinsic::nvvm_setmaxnreg_inc_sync_aligned_u32:
7574 case Intrinsic::nvvm_setmaxnreg_dec_sync_aligned_u32: {
7577 Check(RegCount % 8 == 0,
7578 "reg_count argument to nvvm.setmaxnreg must be in multiples of 8");
7581 case Intrinsic::nvvm_cp_async_bulk_global_to_shared_cta:
7582 case Intrinsic::nvvm_cp_async_bulk_global_to_shared_cta_relaxed: {
7584 const unsigned FlagValidPatternIndex = ArgSize - 1;
7585 const unsigned IgnoreOOBFlagIndex = 8;
7588 const auto *FlagValidPattern =
7590 Check(!IgnoreOOB || FlagValidPattern->isZero(),
7591 "flag_valid_pattern must be 0 (disabled) when ignore_oob is enabled",
7595 case Intrinsic::experimental_convergence_entry:
7596 case Intrinsic::experimental_convergence_anchor:
7598 case Intrinsic::experimental_convergence_loop:
7600 case Intrinsic::ptrmask: {
7604 "llvm.ptrmask intrinsic first argument must be pointer or vector "
7608 "llvm.ptrmask intrinsic second argument bitwidth must match "
7609 "pointer index type size of first argument",
7613 case Intrinsic::thread_pointer: {
7615 DL.getDefaultGlobalsAddressSpace(),
7616 "llvm.thread.pointer intrinsic return type must be for the globals "
7621 case Intrinsic::threadlocal_address: {
7624 "llvm.threadlocal.address first argument must be a GlobalValue");
7626 "llvm.threadlocal.address operand isThreadLocal() must be true");
7629 case Intrinsic::lifetime_start:
7630 case Intrinsic::lifetime_end: {
7634 (
II &&
II->getIntrinsicID() == Intrinsic::structured_alloca),
7635 "llvm.lifetime.start/end can only be used on alloca or poison",
7639 case Intrinsic::sponentry: {
7640 const unsigned StackAS =
DL.getAllocaAddrSpace();
7643 "llvm.sponentry must return a pointer to the stack", &
Call);
7646 case Intrinsic::write_volatile_register: {
7650 "llvm.write_volatile_register metadata must be a single MDString",
7654 case Intrinsic::ptrauth_auth_with_pc_and_resign: {
7659 "ptrauth.auth.with.pc.and.resign key must be IA (0) or IB (1)",
7668 if (
F->hasPersonalityFn() &&
7672 if (BlockEHFuncletColors.
empty())
7679 auto ColorsIt = BlockEHFuncletColors.
find(CallBB);
7680 if (ColorsIt != BlockEHFuncletColors.
end()) {
7682 bool InEHFunclet =
false;
7685 for (BasicBlock *ColorFirstBB : CV)
7686 if (
auto It = ColorFirstBB->getFirstNonPHIIt();
7687 It != ColorFirstBB->end())
7692 bool HasToken =
false;
7699 Check(HasToken,
"Missing funclet token on intrinsic call", &
Call);
7713DISubprogram *Verifier::getSubprogram(
Metadata *LocalScope) {
7714 if (hasDIScopeCycle(LocalScope))
7731void Verifier::visit(DbgLabelRecord &DLR) {
7733 "invalid #dbg_label intrinsic variable", &DLR, DLR.
getRawLabel());
7746 CheckDI(Loc,
"#dbg_label record requires a !dbg attachment", &DLR, BB,
F);
7750 if (!LabelSP || !LocSP)
7754 "mismatched subprogram between #dbg_label label and !dbg attachment",
7755 &DLR, BB,
F, Label,
Label->getScope()->getSubprogram(), Loc,
7756 Loc->getScope()->getSubprogram());
7759void Verifier::visit(DbgVariableRecord &DVR) {
7763 CheckDI(DVR.
getType() == DbgVariableRecord::LocationType::Value ||
7764 DVR.
getType() == DbgVariableRecord::LocationType::Declare ||
7765 DVR.
getType() == DbgVariableRecord::LocationType::DeclareValue ||
7766 DVR.
getType() == DbgVariableRecord::LocationType::Assign,
7767 "invalid #dbg record type", &DVR, DVR.
getType(), BB,
F);
7775 "invalid #dbg record address/value", &DVR, MD, BB,
F);
7777 "!DIAssignID should only be used by Assign DVRs.", MD, &DVR);
7779 visitValueAsMetadata(*VAM,
F);
7782 Type *Ty = VAM->getValue()->getType();
7784 "location of #dbg_declare must be a pointer or int", &DVR, MD, BB,
7788 visitDIArgList(*AL,
F);
7804 for (DIExpression::ExprOperand
Op : Expr->
expr_ops()) {
7808 "#dbg record expression references nonexistent location operand",
7815 "invalid #dbg_assign DIAssignID", &DVR, DVR.
getRawAssignID(), BB,
7818 AreDebugLocsAllowed::No);
7827 "invalid #dbg_assign address", &DVR, DVR.
getRawAddress(), BB,
F);
7829 visitValueAsMetadata(*VAM,
F);
7832 "invalid #dbg_assign address expression", &DVR,
7839 "inst not in same function as #dbg_assign",
I, &DVR, BB,
F);
7849 &DVR, DLNode, BB,
F);
7855 if (!VarSP || !LocSP)
7859 "mismatched subprogram between #dbg record variable and DILocation",
7861 Loc->getScope()->getSubprogram(), BB,
F);
7866void Verifier::visitVPIntrinsic(VPIntrinsic &VPI) {
7868 case Intrinsic::experimental_vp_splice: {
7871 int64_t KnownMinNumElements = VecTy->getElementCount().getKnownMinValue();
7873 AttributeList
Attrs = VPI.
getParent()->getParent()->getAttributes();
7874 if (
Attrs.hasFnAttr(Attribute::VScaleRange))
7875 KnownMinNumElements *=
Attrs.getFnAttrs().getVScaleRangeMin();
7877 Check((Idx < 0 && std::abs(Idx) <= KnownMinNumElements) ||
7878 (Idx >= 0 && Idx < KnownMinNumElements),
7879 "The splice index exceeds the range [-VL, VL-1] where VL is the "
7880 "known minimum number of elements in the vector. For scalable "
7881 "vectors the minimum number of elements is determined from "
7889void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic &FPI) {
7891 case Intrinsic::experimental_constrained_fcmp:
7892 case Intrinsic::experimental_constrained_fcmps: {
7895 "invalid predicate for constrained FP comparison intrinsic", &FPI);
7899 case Intrinsic::experimental_constrained_fptrunc:
7900 case Intrinsic::experimental_constrained_fpext: {
7903 if (FPI.
getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc) {
7905 "Intrinsic first argument's type must be larger than result type",
7909 "Intrinsic first argument's type must be smaller than result type",
7925 "invalid exception behavior argument", &FPI);
7932void Verifier::verifyFragmentExpression(
const DbgVariableRecord &DVR) {
7937 if (!
V || !
E || !
E->isValid())
7951 if (
V->isArtificial())
7954 verifyFragmentExpression(*
V, *
Fragment, &DVR);
7957template <
typename ValueOrMetadata>
7958void Verifier::verifyFragmentExpression(
const DIVariable &
V,
7960 ValueOrMetadata *
Desc) {
7963 auto VarSize =
V.getSizeInBits();
7967 unsigned FragSize =
Fragment.SizeInBits;
7968 unsigned FragOffset =
Fragment.OffsetInBits;
7969 CheckDI(FragSize + FragOffset <= *VarSize,
7970 "fragment is larger than or outside of variable",
Desc, &
V);
7971 CheckDI(FragSize != *VarSize,
"fragment covers entire variable",
Desc, &
V);
7974void Verifier::verifyFnArgs(
const DbgVariableRecord &DVR) {
7986 CheckDI(Var,
"#dbg record without variable");
7988 unsigned ArgNo = Var->
getArg();
7994 if (DebugFnArgs.
size() < ArgNo)
7995 DebugFnArgs.
resize(ArgNo,
nullptr);
7997 auto *Prev = DebugFnArgs[ArgNo - 1];
7998 DebugFnArgs[ArgNo - 1] = Var;
7999 CheckDI(!Prev || (Prev == Var),
"conflicting debug info for argument", &DVR,
8003void Verifier::verifyNotEntryValue(
const DbgVariableRecord &DVR) {
8007 if (!
E || !
E->isValid())
8017 ArgLoc && ArgLoc->hasAttribute(Attribute::SwiftAsync))
8022 "Entry values are only allowed in MIR unless they target a "
8023 "swiftasync Argument",
8027void Verifier::verifyCompileUnits() {
8031 if (
M.getContext().isODRUniquingDebugTypes())
8033 auto *CUs =
M.getNamedMetadata(
"llvm.dbg.cu");
8034 SmallPtrSet<const Metadata *, 2> Listed;
8037 for (
const auto *CU : CUVisited)
8038 CheckDI(Listed.
count(CU),
"DICompileUnit not listed in llvm.dbg.cu", CU);
8042void Verifier::verifyDeoptimizeCallingConvs() {
8043 if (DeoptimizeDeclarations.
empty())
8047 for (
const auto *
F :
ArrayRef(DeoptimizeDeclarations).slice(1)) {
8048 Check(
First->getCallingConv() ==
F->getCallingConv(),
8049 "All llvm.experimental.deoptimize declarations must have the same "
8050 "calling convention",
8055void Verifier::verifyAttachedCallBundle(
const CallBase &
Call,
8056 const OperandBundleUse &BU) {
8059 Check((FTy->getReturnType()->isPointerTy() ||
8061 "a call with operand bundle \"clang.arc.attachedcall\" must call a "
8062 "function returning a pointer or a non-returning function that has a "
8067 "operand bundle \"clang.arc.attachedcall\" requires one function as "
8075 Check((IID == Intrinsic::objc_retainAutoreleasedReturnValue ||
8076 IID == Intrinsic::objc_claimAutoreleasedReturnValue ||
8077 IID == Intrinsic::objc_unsafeClaimAutoreleasedReturnValue),
8078 "invalid function argument",
Call);
8080 StringRef FnName = Fn->getName();
8081 Check((FnName ==
"objc_retainAutoreleasedReturnValue" ||
8082 FnName ==
"objc_claimAutoreleasedReturnValue" ||
8083 FnName ==
"objc_unsafeClaimAutoreleasedReturnValue"),
8084 "invalid function argument",
Call);
8088void Verifier::verifyNoAliasScopeDecl() {
8089 if (NoAliasScopeDecls.
empty())
8093 for (
auto *
II : NoAliasScopeDecls) {
8094 assert(
II->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl &&
8095 "Not a llvm.experimental.noalias.scope.decl ?");
8098 Check(ScopeListMV !=
nullptr,
8099 "llvm.experimental.noalias.scope.decl must have a MetadataAsValue "
8104 Check(ScopeListMD !=
nullptr,
"!id.scope.list must point to an MDNode",
II);
8105 Check(ScopeListMD->getNumOperands() == 1,
8106 "!id.scope.list must point to a list with a single scope",
II);
8107 visitAliasScopeListMetadata(ScopeListMD);
8112 if (!
getIROptions(
M.getContext()).verify_noalias_scope_decl_dom)
8117 auto GetScope = [](IntrinsicInst *
II) {
8120 return &
cast<MDNode>(ScopeListMV->getMetadata())->getOperand(0);
8125 auto Compare = [GetScope](IntrinsicInst *Lhs, IntrinsicInst *Rhs) {
8126 return GetScope(Lhs) < GetScope(Rhs);
8133 auto ItCurrent = NoAliasScopeDecls.begin();
8134 while (ItCurrent != NoAliasScopeDecls.end()) {
8135 auto CurScope = GetScope(*ItCurrent);
8136 auto ItNext = ItCurrent;
8139 }
while (ItNext != NoAliasScopeDecls.end() &&
8140 GetScope(*ItNext) == CurScope);
8145 if (ItNext - ItCurrent < 32)
8149 Check(!DT.dominates(
I, J),
8150 "llvm.experimental.noalias.scope.decl dominates another one "
8151 "with the same scope",
8165 Verifier
V(OS,
true, *f.getParent());
8169 return !V.verify(
F);
8173 bool *BrokenDebugInfo) {
8175 Verifier
V(OS, !BrokenDebugInfo, M);
8177 bool Broken =
false;
8179 Broken |= !V.verify(
F);
8181 Broken |= !V.verify();
8182 if (BrokenDebugInfo)
8183 *BrokenDebugInfo = V.hasBrokenDebugInfo();
8194 std::unique_ptr<Verifier>
V;
8195 bool FatalErrors =
true;
8198 explicit VerifierLegacyPass(
bool FatalErrors)
8199 : FunctionPass(
ID), FatalErrors(FatalErrors) {}
8201 bool doInitialization(
Module &M)
override {
8202 V = std::make_unique<Verifier>(
8208 if (!
V->verify(
F) && FatalErrors) {
8209 errs() <<
"in function " <<
F.getName() <<
'\n';
8215 bool doFinalization(
Module &M)
override {
8216 bool HasErrors =
false;
8218 if (
F.isDeclaration())
8219 HasErrors |= !
V->verify(
F);
8221 HasErrors |= !
V->verify();
8222 if (FatalErrors && (HasErrors ||
V->hasBrokenDebugInfo()))
8227 void getAnalysisUsage(AnalysisUsage &AU)
const override {
8235template <
typename... Tys>
void TBAAVerifier::CheckFailed(Tys &&... Args) {
8237 return Diagnostic->CheckFailed(
Args...);
8240#define CheckTBAA(C, ...) \
8243 CheckFailed(__VA_ARGS__); \
8251TBAAVerifier::TBAABaseNodeSummary
8255 CheckFailed(
"Base nodes must have at least two operands",
I, BaseNode);
8259 auto Itr = TBAABaseNodes.find(BaseNode);
8260 if (Itr != TBAABaseNodes.end())
8263 auto Result = verifyTBAABaseNodeImpl(
I, BaseNode, IsNewFormat);
8264 auto InsertResult = TBAABaseNodes.insert({BaseNode, Result});
8266 assert(InsertResult.second &&
"We just checked!");
8270TBAAVerifier::TBAABaseNodeSummary
8271TBAAVerifier::verifyTBAABaseNodeImpl(
const Instruction *
I,
8272 const MDNode *BaseNode,
bool IsNewFormat) {
8273 const TBAAVerifier::TBAABaseNodeSummary InvalidNode = {
true, ~0
u};
8277 return isValidScalarTBAANode(BaseNode)
8278 ? TBAAVerifier::TBAABaseNodeSummary({
false, 0})
8284 CheckFailed(
"Access tag nodes must have the number of operands that is a "
8285 "multiple of 3!", BaseNode);
8290 CheckFailed(
"Struct tag nodes must have an odd number of operands!",
8300 if (!TypeSizeNode) {
8301 CheckFailed(
"Type size nodes must be constants!",
I, BaseNode);
8308 CheckFailed(
"Struct tag nodes have a string as their first operand",
8315 std::optional<APInt> PrevOffset;
8320 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8321 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8323 Idx += NumOpsPerField) {
8324 const MDOperand &FieldTy = BaseNode->
getOperand(Idx);
8325 const MDOperand &FieldOffset = BaseNode->
getOperand(Idx + 1);
8327 CheckFailed(
"Incorrect field entry in struct type node!",
I, BaseNode);
8332 auto *OffsetEntryCI =
8334 if (!OffsetEntryCI) {
8335 CheckFailed(
"Offset entries must be constants!",
I, BaseNode);
8341 BitWidth = OffsetEntryCI->getBitWidth();
8343 if (OffsetEntryCI->getBitWidth() !=
BitWidth) {
8345 "Bitwidth between the offsets and struct type entries must match",
I,
8357 !PrevOffset || PrevOffset->ule(OffsetEntryCI->getValue());
8360 CheckFailed(
"Offsets must be increasing!",
I, BaseNode);
8364 PrevOffset = OffsetEntryCI->getValue();
8369 if (!MemberSizeNode) {
8370 CheckFailed(
"Member size entries must be constants!",
I, BaseNode);
8377 return Failed ? InvalidNode
8378 : TBAAVerifier::TBAABaseNodeSummary(
false,
BitWidth);
8400 return Parent && Visited.
insert(Parent).second &&
8404bool TBAAVerifier::isValidScalarTBAANode(
const MDNode *MD) {
8405 auto ResultIt = TBAAScalarNodes.find(MD);
8406 if (ResultIt != TBAAScalarNodes.end())
8407 return ResultIt->second;
8409 SmallPtrSet<const MDNode *, 4> Visited;
8411 auto InsertResult = TBAAScalarNodes.insert({MD,
Result});
8413 assert(InsertResult.second &&
"Just checked!");
8422MDNode *TBAAVerifier::getFieldNodeFromTBAABaseNode(
const Instruction *
I,
8423 const MDNode *BaseNode,
8434 unsigned FirstFieldOpNo = IsNewFormat ? 3 : 1;
8435 unsigned NumOpsPerField = IsNewFormat ? 3 : 2;
8437 Idx += NumOpsPerField) {
8438 auto *OffsetEntryCI =
8440 if (OffsetEntryCI->getValue().ugt(
Offset)) {
8441 if (Idx == FirstFieldOpNo) {
8442 CheckFailed(
"Could not find TBAA parent in struct type node",
I,
8447 unsigned PrevIdx =
Idx - NumOpsPerField;
8448 auto *PrevOffsetEntryCI =
8450 Offset -= PrevOffsetEntryCI->getValue();
8458 Offset -= LastOffsetEntryCI->getValue();
8463 if (!
Type ||
Type->getNumOperands() < 3)
8475 if (!Visited.
insert(
N).second)
8495 "This instruction shall not have a TBAA access tag!",
I);
8497 bool IsStructPathTBAA =
8501 "Old-style TBAA is no longer allowed, use struct-path TBAA instead",
8511 "Access tag metadata must have either 4 or 5 operands",
I, MD);
8514 "Struct tag metadata must have either 3 or 4 operands",
I, MD);
8521 CheckTBAA(AccessSizeNode,
"Access size field must be a constant",
I, MD);
8525 unsigned ImmutabilityFlagOpNo = IsNewFormat ? 4 : 3;
8530 "Immutability tag on struct tag metadata must be a constant",
I,
8533 IsImmutableCI->isZero() || IsImmutableCI->isOne(),
8534 "Immutability part of the struct tag metadata must be either 0 or 1",
I,
8539 "Malformed struct tag metadata: base and access-type "
8540 "should be non-null and point to Metadata nodes",
8541 I, MD, BaseNode, AccessType);
8544 CheckTBAA(isValidScalarTBAANode(AccessType),
8545 "Access type node must be a valid scalar type",
I, MD,
8549 "Cycle detected in access type parent chain",
I, MD, AccessType);
8553 CheckTBAA(OffsetCI,
"Offset must be constant integer",
I, MD);
8556 bool SeenAccessTypeInPath =
false;
8562 getFieldNodeFromTBAABaseNode(
I, BaseNode,
Offset, IsNewFormat)) {
8563 if (!StructPath.
insert(BaseNode).second) {
8564 CheckFailed(
"Cycle detected in struct path",
I, MD);
8569 unsigned BaseNodeBitWidth;
8570 std::tie(
Invalid, BaseNodeBitWidth) =
8571 verifyTBAABaseNode(
I, BaseNode, IsNewFormat);
8578 SeenAccessTypeInPath |= BaseNode == AccessType;
8580 if (isValidScalarTBAANode(BaseNode) || BaseNode == AccessType)
8585 (BaseNodeBitWidth == 0 &&
Offset == 0) ||
8586 (IsNewFormat && BaseNodeBitWidth == ~0u),
8587 "Access bit-width not the same as description bit-width",
I, MD,
8588 BaseNodeBitWidth,
Offset.getBitWidth());
8590 if (IsNewFormat && SeenAccessTypeInPath)
8594 CheckTBAA(SeenAccessTypeInPath,
"Did not see access type in access path!",
I,
8605 "!tbaa.struct operands must come in groups of three",
I, MD);
8607 std::optional<APInt> PrevOffset;
8608 for (
unsigned Idx = 0, E = MD->
getNumOperands(); Idx != E; Idx += 3) {
8611 CheckTBAA(OffsetCI,
"!tbaa.struct field offset must be a constant integer",
8615 "!tbaa.struct field size must be a constant integer",
I, MD);
8618 CheckTBAA(
Tag,
"!tbaa.struct field tag must be null or an MDNode",
I, MD);
8626 std::max(PrevOffset->getBitWidth(),
Offset.getBitWidth());
8628 "!tbaa.struct field offsets must be non-decreasing",
I, MD);
8635char VerifierLegacyPass::ID = 0;
8636INITIALIZE_PASS(VerifierLegacyPass,
"verify",
"Module Verifier",
false,
false)
8639 return new VerifierLegacyPass(FatalErrors);
8657 if (FatalErrors && (Res.IRBroken || Res.DebugInfoBroken))
8665 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
Function Alias Analysis false
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.
SmallVector< MachineOperand, 4 > Cond
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
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)
#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 bool hasAcyclicTBAAParentChain(const MDNode *MD)
Returns true if the parent chain of the TBAA type node MD is acyclic.
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 bool isNewFormatTBAATypeNode(const MDNode *Type)
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.
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.
bool isValid() const
Return true if the attribute is any kind of attribute.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
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).
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
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)
Conditional Branch instruction.
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
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)
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.
unsigned getNumElements() const
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)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
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 mayHaveConstantUsers() const
Return true if a constant other than a GlobalValue may use this global, that is, if removeDeadConstan...
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...
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
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 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.
An instruction for reading from memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
bool isAtomic() const
Return true if this load has an atomic ordering.
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
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.
Return a value (possibly void), from a function.
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.
This class represents the LLVM 'select' instruction.
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.
An instruction for storing to memory.
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)
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.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element 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.
bool isAggregateType() const
Return true if the type is an aggregate 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.
Type * getElementType() const
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 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.
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.
constexpr StringLiteral AbiPreserveAttrs[]
@ 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)
@ 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.
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 >
const IROptions & getIROptions(const LLVMContext &C)
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.
void verifyNVVMIntrinsicCall(VerifierSupport &VS, Intrinsic::ID ID, CallBase &Call)
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 * 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.