1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the function verifier interface, that can be used for some
10 // sanity checking of input to the system.
12 // Note that this does not provide full `Java style' security and verifications,
13 // instead it just tries to ensure that code is well-formed.
15 // * Both of a binary operator's parameters are of the same type
16 // * Verify that the indices of mem access instructions match other operands
17 // * Verify that arithmetic and other things are only performed on first-class
18 // types. Verify that shifts & logicals only happen on integrals f.e.
19 // * All of the constants in a switch statement are of the correct type
20 // * The code is in valid SSA form
21 // * It should be illegal to put a label into any other type (like a structure)
22 // or to return one. [except constant arrays!]
23 // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
24 // * PHI nodes must have an entry for each predecessor, with no extras.
25 // * PHI nodes must be the first thing in a basic block, all grouped together
26 // * PHI nodes must have at least one entry
27 // * All basic blocks should only end with terminator insts, not contain them
28 // * The entry node to a function must not have predecessors
29 // * All Instructions must be embedded into a basic block
30 // * Functions cannot take a void-typed parameter
31 // * Verify that a function's argument list agrees with it's declared type.
32 // * It is illegal to specify a name for a void value.
33 // * It is illegal to have a internal global value with no initializer
34 // * It is illegal to have a ret instruction that returns a value that does not
35 // agree with the function return value type.
36 // * Function call argument types match the function prototype
37 // * A landing pad is defined by a landingpad instruction, and can be jumped to
38 // only by the unwind edge of an invoke instruction.
39 // * A landingpad instruction must be the first non-PHI instruction in the
41 // * Landingpad instructions must be in a function with a personality function.
42 // * All other things that are tested by asserts spread about the code...
44 //===----------------------------------------------------------------------===//
46 #include "llvm/IR/Verifier.h"
47 #include "llvm/ADT/APFloat.h"
48 #include "llvm/ADT/APInt.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/MapVector.h"
52 #include "llvm/ADT/Optional.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallSet.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/StringExtras.h"
58 #include "llvm/ADT/StringMap.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/Twine.h"
61 #include "llvm/ADT/ilist.h"
62 #include "llvm/BinaryFormat/Dwarf.h"
63 #include "llvm/IR/Argument.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/BasicBlock.h"
66 #include "llvm/IR/CFG.h"
67 #include "llvm/IR/CallingConv.h"
68 #include "llvm/IR/Comdat.h"
69 #include "llvm/IR/Constant.h"
70 #include "llvm/IR/ConstantRange.h"
71 #include "llvm/IR/Constants.h"
72 #include "llvm/IR/DataLayout.h"
73 #include "llvm/IR/DebugInfo.h"
74 #include "llvm/IR/DebugInfoMetadata.h"
75 #include "llvm/IR/DebugLoc.h"
76 #include "llvm/IR/DerivedTypes.h"
77 #include "llvm/IR/Dominators.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/GlobalAlias.h"
80 #include "llvm/IR/GlobalValue.h"
81 #include "llvm/IR/GlobalVariable.h"
82 #include "llvm/IR/InlineAsm.h"
83 #include "llvm/IR/InstVisitor.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/LLVMContext.h"
90 #include "llvm/IR/Metadata.h"
91 #include "llvm/IR/Module.h"
92 #include "llvm/IR/ModuleSlotTracker.h"
93 #include "llvm/IR/PassManager.h"
94 #include "llvm/IR/Statepoint.h"
95 #include "llvm/IR/Type.h"
96 #include "llvm/IR/Use.h"
97 #include "llvm/IR/User.h"
98 #include "llvm/IR/Value.h"
99 #include "llvm/Pass.h"
100 #include "llvm/Support/AtomicOrdering.h"
101 #include "llvm/Support/Casting.h"
102 #include "llvm/Support/CommandLine.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/MathExtras.h"
106 #include "llvm/Support/raw_ostream.h"
114 using namespace llvm
;
118 struct VerifierSupport
{
121 ModuleSlotTracker MST
;
122 const DataLayout
&DL
;
123 LLVMContext
&Context
;
125 /// Track the brokenness of the module while recursively visiting.
127 /// Broken debug info can be "recovered" from by stripping the debug info.
128 bool BrokenDebugInfo
= false;
129 /// Whether to treat broken debug info as an error.
130 bool TreatBrokenDebugInfoAsError
= true;
132 explicit VerifierSupport(raw_ostream
*OS
, const Module
&M
)
133 : OS(OS
), M(M
), MST(&M
), DL(M
.getDataLayout()), Context(M
.getContext()) {}
136 void Write(const Module
*M
) {
137 *OS
<< "; ModuleID = '" << M
->getModuleIdentifier() << "'\n";
140 void Write(const Value
*V
) {
145 void Write(const Value
&V
) {
146 if (isa
<Instruction
>(V
)) {
150 V
.printAsOperand(*OS
, true, MST
);
155 void Write(const Metadata
*MD
) {
158 MD
->print(*OS
, MST
, &M
);
162 template <class T
> void Write(const MDTupleTypedArrayWrapper
<T
> &MD
) {
166 void Write(const NamedMDNode
*NMD
) {
169 NMD
->print(*OS
, MST
);
173 void Write(Type
*T
) {
179 void Write(const Comdat
*C
) {
185 void Write(const APInt
*AI
) {
191 void Write(const unsigned i
) { *OS
<< i
<< '\n'; }
193 template <typename T
> void Write(ArrayRef
<T
> Vs
) {
194 for (const T
&V
: Vs
)
198 template <typename T1
, typename
... Ts
>
199 void WriteTs(const T1
&V1
, const Ts
&... Vs
) {
204 template <typename
... Ts
> void WriteTs() {}
207 /// A check failed, so printout out the condition and the message.
209 /// This provides a nice place to put a breakpoint if you want to see why
210 /// something is not correct.
211 void CheckFailed(const Twine
&Message
) {
213 *OS
<< Message
<< '\n';
217 /// A check failed (with values to print).
219 /// This calls the Message-only version so that the above is easier to set a
221 template <typename T1
, typename
... Ts
>
222 void CheckFailed(const Twine
&Message
, const T1
&V1
, const Ts
&... Vs
) {
223 CheckFailed(Message
);
228 /// A debug info check failed.
229 void DebugInfoCheckFailed(const Twine
&Message
) {
231 *OS
<< Message
<< '\n';
232 Broken
|= TreatBrokenDebugInfoAsError
;
233 BrokenDebugInfo
= true;
236 /// A debug info check failed (with values to print).
237 template <typename T1
, typename
... Ts
>
238 void DebugInfoCheckFailed(const Twine
&Message
, const T1
&V1
,
240 DebugInfoCheckFailed(Message
);
250 class Verifier
: public InstVisitor
<Verifier
>, VerifierSupport
{
251 friend class InstVisitor
<Verifier
>;
255 /// When verifying a basic block, keep track of all of the
256 /// instructions we have seen so far.
258 /// This allows us to do efficient dominance checks for the case when an
259 /// instruction has an operand that is an instruction in the same block.
260 SmallPtrSet
<Instruction
*, 16> InstsInThisBlock
;
262 /// Keep track of the metadata nodes that have been checked already.
263 SmallPtrSet
<const Metadata
*, 32> MDNodes
;
265 /// Keep track which DISubprogram is attached to which function.
266 DenseMap
<const DISubprogram
*, const Function
*> DISubprogramAttachments
;
268 /// Track all DICompileUnits visited.
269 SmallPtrSet
<const Metadata
*, 2> CUVisited
;
271 /// The result type for a landingpad.
272 Type
*LandingPadResultTy
;
274 /// Whether we've seen a call to @llvm.localescape in this function
278 /// Whether the current function has a DISubprogram attached to it.
279 bool HasDebugInfo
= false;
281 /// Whether source was present on the first DIFile encountered in each CU.
282 DenseMap
<const DICompileUnit
*, bool> HasSourceDebugInfo
;
284 /// Stores the count of how many objects were passed to llvm.localescape for a
285 /// given function and the largest index passed to llvm.localrecover.
286 DenseMap
<Function
*, std::pair
<unsigned, unsigned>> FrameEscapeInfo
;
288 // Maps catchswitches and cleanuppads that unwind to siblings to the
289 // terminators that indicate the unwind, used to detect cycles therein.
290 MapVector
<Instruction
*, Instruction
*> SiblingFuncletInfo
;
292 /// Cache of constants visited in search of ConstantExprs.
293 SmallPtrSet
<const Constant
*, 32> ConstantExprVisited
;
295 /// Cache of declarations of the llvm.experimental.deoptimize.<ty> intrinsic.
296 SmallVector
<const Function
*, 4> DeoptimizeDeclarations
;
298 // Verify that this GlobalValue is only used in this module.
299 // This map is used to avoid visiting uses twice. We can arrive at a user
300 // twice, if they have multiple operands. In particular for very large
301 // constant expressions, we can arrive at a particular user many times.
302 SmallPtrSet
<const Value
*, 32> GlobalValueVisited
;
304 // Keeps track of duplicate function argument debug info.
305 SmallVector
<const DILocalVariable
*, 16> DebugFnArgs
;
307 TBAAVerifier TBAAVerifyHelper
;
309 void checkAtomicMemAccessSize(Type
*Ty
, const Instruction
*I
);
312 explicit Verifier(raw_ostream
*OS
, bool ShouldTreatBrokenDebugInfoAsError
,
314 : VerifierSupport(OS
, M
), LandingPadResultTy(nullptr),
315 SawFrameEscape(false), TBAAVerifyHelper(this) {
316 TreatBrokenDebugInfoAsError
= ShouldTreatBrokenDebugInfoAsError
;
319 bool hasBrokenDebugInfo() const { return BrokenDebugInfo
; }
321 bool verify(const Function
&F
) {
322 assert(F
.getParent() == &M
&&
323 "An instance of this class only works with a specific module!");
325 // First ensure the function is well-enough formed to compute dominance
326 // information, and directly compute a dominance tree. We don't rely on the
327 // pass manager to provide this as it isolates us from a potentially
328 // out-of-date dominator tree and makes it significantly more complex to run
329 // this code outside of a pass manager.
330 // FIXME: It's really gross that we have to cast away constness here.
332 DT
.recalculate(const_cast<Function
&>(F
));
334 for (const BasicBlock
&BB
: F
) {
335 if (!BB
.empty() && BB
.back().isTerminator())
339 *OS
<< "Basic Block in function '" << F
.getName()
340 << "' does not have terminator!\n";
341 BB
.printAsOperand(*OS
, true, MST
);
348 // FIXME: We strip const here because the inst visitor strips const.
349 visit(const_cast<Function
&>(F
));
350 verifySiblingFuncletUnwinds();
351 InstsInThisBlock
.clear();
353 LandingPadResultTy
= nullptr;
354 SawFrameEscape
= false;
355 SiblingFuncletInfo
.clear();
360 /// Verify the module that this instance of \c Verifier was initialized with.
364 // Collect all declarations of the llvm.experimental.deoptimize intrinsic.
365 for (const Function
&F
: M
)
366 if (F
.getIntrinsicID() == Intrinsic::experimental_deoptimize
)
367 DeoptimizeDeclarations
.push_back(&F
);
369 // Now that we've visited every function, verify that we never asked to
370 // recover a frame index that wasn't escaped.
371 verifyFrameRecoverIndices();
372 for (const GlobalVariable
&GV
: M
.globals())
373 visitGlobalVariable(GV
);
375 for (const GlobalAlias
&GA
: M
.aliases())
376 visitGlobalAlias(GA
);
378 for (const NamedMDNode
&NMD
: M
.named_metadata())
379 visitNamedMDNode(NMD
);
381 for (const StringMapEntry
<Comdat
> &SMEC
: M
.getComdatSymbolTable())
382 visitComdat(SMEC
.getValue());
385 visitModuleIdents(M
);
386 visitModuleCommandLines(M
);
388 verifyCompileUnits();
390 verifyDeoptimizeCallingConvs();
391 DISubprogramAttachments
.clear();
396 // Verification methods...
397 void visitGlobalValue(const GlobalValue
&GV
);
398 void visitGlobalVariable(const GlobalVariable
&GV
);
399 void visitGlobalAlias(const GlobalAlias
&GA
);
400 void visitAliaseeSubExpr(const GlobalAlias
&A
, const Constant
&C
);
401 void visitAliaseeSubExpr(SmallPtrSetImpl
<const GlobalAlias
*> &Visited
,
402 const GlobalAlias
&A
, const Constant
&C
);
403 void visitNamedMDNode(const NamedMDNode
&NMD
);
404 void visitMDNode(const MDNode
&MD
);
405 void visitMetadataAsValue(const MetadataAsValue
&MD
, Function
*F
);
406 void visitValueAsMetadata(const ValueAsMetadata
&MD
, Function
*F
);
407 void visitComdat(const Comdat
&C
);
408 void visitModuleIdents(const Module
&M
);
409 void visitModuleCommandLines(const Module
&M
);
410 void visitModuleFlags(const Module
&M
);
411 void visitModuleFlag(const MDNode
*Op
,
412 DenseMap
<const MDString
*, const MDNode
*> &SeenIDs
,
413 SmallVectorImpl
<const MDNode
*> &Requirements
);
414 void visitModuleFlagCGProfileEntry(const MDOperand
&MDO
);
415 void visitFunction(const Function
&F
);
416 void visitBasicBlock(BasicBlock
&BB
);
417 void visitRangeMetadata(Instruction
&I
, MDNode
*Range
, Type
*Ty
);
418 void visitDereferenceableMetadata(Instruction
&I
, MDNode
*MD
);
420 template <class Ty
> bool isValidMetadataArray(const MDTuple
&N
);
421 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
422 #include "llvm/IR/Metadata.def"
423 void visitDIScope(const DIScope
&N
);
424 void visitDIVariable(const DIVariable
&N
);
425 void visitDILexicalBlockBase(const DILexicalBlockBase
&N
);
426 void visitDITemplateParameter(const DITemplateParameter
&N
);
428 void visitTemplateParams(const MDNode
&N
, const Metadata
&RawParams
);
430 // InstVisitor overrides...
431 using InstVisitor
<Verifier
>::visit
;
432 void visit(Instruction
&I
);
434 void visitTruncInst(TruncInst
&I
);
435 void visitZExtInst(ZExtInst
&I
);
436 void visitSExtInst(SExtInst
&I
);
437 void visitFPTruncInst(FPTruncInst
&I
);
438 void visitFPExtInst(FPExtInst
&I
);
439 void visitFPToUIInst(FPToUIInst
&I
);
440 void visitFPToSIInst(FPToSIInst
&I
);
441 void visitUIToFPInst(UIToFPInst
&I
);
442 void visitSIToFPInst(SIToFPInst
&I
);
443 void visitIntToPtrInst(IntToPtrInst
&I
);
444 void visitPtrToIntInst(PtrToIntInst
&I
);
445 void visitBitCastInst(BitCastInst
&I
);
446 void visitAddrSpaceCastInst(AddrSpaceCastInst
&I
);
447 void visitPHINode(PHINode
&PN
);
448 void visitCallBase(CallBase
&Call
);
449 void visitUnaryOperator(UnaryOperator
&U
);
450 void visitBinaryOperator(BinaryOperator
&B
);
451 void visitICmpInst(ICmpInst
&IC
);
452 void visitFCmpInst(FCmpInst
&FC
);
453 void visitExtractElementInst(ExtractElementInst
&EI
);
454 void visitInsertElementInst(InsertElementInst
&EI
);
455 void visitShuffleVectorInst(ShuffleVectorInst
&EI
);
456 void visitVAArgInst(VAArgInst
&VAA
) { visitInstruction(VAA
); }
457 void visitCallInst(CallInst
&CI
);
458 void visitInvokeInst(InvokeInst
&II
);
459 void visitGetElementPtrInst(GetElementPtrInst
&GEP
);
460 void visitLoadInst(LoadInst
&LI
);
461 void visitStoreInst(StoreInst
&SI
);
462 void verifyDominatesUse(Instruction
&I
, unsigned i
);
463 void visitInstruction(Instruction
&I
);
464 void visitTerminator(Instruction
&I
);
465 void visitBranchInst(BranchInst
&BI
);
466 void visitReturnInst(ReturnInst
&RI
);
467 void visitSwitchInst(SwitchInst
&SI
);
468 void visitIndirectBrInst(IndirectBrInst
&BI
);
469 void visitCallBrInst(CallBrInst
&CBI
);
470 void visitSelectInst(SelectInst
&SI
);
471 void visitUserOp1(Instruction
&I
);
472 void visitUserOp2(Instruction
&I
) { visitUserOp1(I
); }
473 void visitIntrinsicCall(Intrinsic::ID ID
, CallBase
&Call
);
474 void visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic
&FPI
);
475 void visitDbgIntrinsic(StringRef Kind
, DbgVariableIntrinsic
&DII
);
476 void visitDbgLabelIntrinsic(StringRef Kind
, DbgLabelInst
&DLI
);
477 void visitAtomicCmpXchgInst(AtomicCmpXchgInst
&CXI
);
478 void visitAtomicRMWInst(AtomicRMWInst
&RMWI
);
479 void visitFenceInst(FenceInst
&FI
);
480 void visitAllocaInst(AllocaInst
&AI
);
481 void visitExtractValueInst(ExtractValueInst
&EVI
);
482 void visitInsertValueInst(InsertValueInst
&IVI
);
483 void visitEHPadPredecessors(Instruction
&I
);
484 void visitLandingPadInst(LandingPadInst
&LPI
);
485 void visitResumeInst(ResumeInst
&RI
);
486 void visitCatchPadInst(CatchPadInst
&CPI
);
487 void visitCatchReturnInst(CatchReturnInst
&CatchReturn
);
488 void visitCleanupPadInst(CleanupPadInst
&CPI
);
489 void visitFuncletPadInst(FuncletPadInst
&FPI
);
490 void visitCatchSwitchInst(CatchSwitchInst
&CatchSwitch
);
491 void visitCleanupReturnInst(CleanupReturnInst
&CRI
);
493 void verifySwiftErrorCall(CallBase
&Call
, const Value
*SwiftErrorVal
);
494 void verifySwiftErrorValue(const Value
*SwiftErrorVal
);
495 void verifyMustTailCall(CallInst
&CI
);
496 bool performTypeCheck(Intrinsic::ID ID
, Function
*F
, Type
*Ty
, int VT
,
497 unsigned ArgNo
, std::string
&Suffix
);
498 bool verifyAttributeCount(AttributeList Attrs
, unsigned Params
);
499 void verifyAttributeTypes(AttributeSet Attrs
, bool IsFunction
,
501 void verifyParameterAttrs(AttributeSet Attrs
, Type
*Ty
, const Value
*V
);
502 void verifyFunctionAttrs(FunctionType
*FT
, AttributeList Attrs
,
503 const Value
*V
, bool IsIntrinsic
);
504 void verifyFunctionMetadata(ArrayRef
<std::pair
<unsigned, MDNode
*>> MDs
);
506 void visitConstantExprsRecursively(const Constant
*EntryC
);
507 void visitConstantExpr(const ConstantExpr
*CE
);
508 void verifyStatepoint(const CallBase
&Call
);
509 void verifyFrameRecoverIndices();
510 void verifySiblingFuncletUnwinds();
512 void verifyFragmentExpression(const DbgVariableIntrinsic
&I
);
513 template <typename ValueOrMetadata
>
514 void verifyFragmentExpression(const DIVariable
&V
,
515 DIExpression::FragmentInfo Fragment
,
516 ValueOrMetadata
*Desc
);
517 void verifyFnArgs(const DbgVariableIntrinsic
&I
);
519 /// Module-level debug info verification...
520 void verifyCompileUnits();
522 /// Module-level verification that all @llvm.experimental.deoptimize
523 /// declarations share the same calling convention.
524 void verifyDeoptimizeCallingConvs();
526 /// Verify all-or-nothing property of DIFile source attribute within a CU.
527 void verifySourceDebugInfo(const DICompileUnit
&U
, const DIFile
&F
);
530 } // end anonymous namespace
532 /// We know that cond should be true, if not print an error message.
533 #define Assert(C, ...) \
534 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
536 /// We know that a debug info condition should be true, if not print
537 /// an error message.
538 #define AssertDI(C, ...) \
539 do { if (!(C)) { DebugInfoCheckFailed(__VA_ARGS__); return; } } while (false)
541 void Verifier::visit(Instruction
&I
) {
542 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
)
543 Assert(I
.getOperand(i
) != nullptr, "Operand is null", &I
);
544 InstVisitor
<Verifier
>::visit(I
);
547 // Helper to recursively iterate over indirect users. By
548 // returning false, the callback can ask to stop recursing
550 static void forEachUser(const Value
*User
,
551 SmallPtrSet
<const Value
*, 32> &Visited
,
552 llvm::function_ref
<bool(const Value
*)> Callback
) {
553 if (!Visited
.insert(User
).second
)
555 for (const Value
*TheNextUser
: User
->materialized_users())
556 if (Callback(TheNextUser
))
557 forEachUser(TheNextUser
, Visited
, Callback
);
560 void Verifier::visitGlobalValue(const GlobalValue
&GV
) {
561 Assert(!GV
.isDeclaration() || GV
.hasValidDeclarationLinkage(),
562 "Global is external, but doesn't have external or weak linkage!", &GV
);
564 Assert(GV
.getAlignment() <= Value::MaximumAlignment
,
565 "huge alignment values are unsupported", &GV
);
566 Assert(!GV
.hasAppendingLinkage() || isa
<GlobalVariable
>(GV
),
567 "Only global variables can have appending linkage!", &GV
);
569 if (GV
.hasAppendingLinkage()) {
570 const GlobalVariable
*GVar
= dyn_cast
<GlobalVariable
>(&GV
);
571 Assert(GVar
&& GVar
->getValueType()->isArrayTy(),
572 "Only global arrays can have appending linkage!", GVar
);
575 if (GV
.isDeclarationForLinker())
576 Assert(!GV
.hasComdat(), "Declaration may not be in a Comdat!", &GV
);
578 if (GV
.hasDLLImportStorageClass()) {
579 Assert(!GV
.isDSOLocal(),
580 "GlobalValue with DLLImport Storage is dso_local!", &GV
);
582 Assert((GV
.isDeclaration() && GV
.hasExternalLinkage()) ||
583 GV
.hasAvailableExternallyLinkage(),
584 "Global is marked as dllimport, but not external", &GV
);
587 if (GV
.hasLocalLinkage())
588 Assert(GV
.isDSOLocal(),
589 "GlobalValue with private or internal linkage must be dso_local!",
592 if (!GV
.hasDefaultVisibility() && !GV
.hasExternalWeakLinkage())
593 Assert(GV
.isDSOLocal(),
594 "GlobalValue with non default visibility must be dso_local!", &GV
);
596 forEachUser(&GV
, GlobalValueVisited
, [&](const Value
*V
) -> bool {
597 if (const Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
598 if (!I
->getParent() || !I
->getParent()->getParent())
599 CheckFailed("Global is referenced by parentless instruction!", &GV
, &M
,
601 else if (I
->getParent()->getParent()->getParent() != &M
)
602 CheckFailed("Global is referenced in a different module!", &GV
, &M
, I
,
603 I
->getParent()->getParent(),
604 I
->getParent()->getParent()->getParent());
606 } else if (const Function
*F
= dyn_cast
<Function
>(V
)) {
607 if (F
->getParent() != &M
)
608 CheckFailed("Global is used by function in a different module", &GV
, &M
,
616 void Verifier::visitGlobalVariable(const GlobalVariable
&GV
) {
617 if (GV
.hasInitializer()) {
618 Assert(GV
.getInitializer()->getType() == GV
.getValueType(),
619 "Global variable initializer type does not match global "
622 // If the global has common linkage, it must have a zero initializer and
623 // cannot be constant.
624 if (GV
.hasCommonLinkage()) {
625 Assert(GV
.getInitializer()->isNullValue(),
626 "'common' global must have a zero initializer!", &GV
);
627 Assert(!GV
.isConstant(), "'common' global may not be marked constant!",
629 Assert(!GV
.hasComdat(), "'common' global may not be in a Comdat!", &GV
);
633 if (GV
.hasName() && (GV
.getName() == "llvm.global_ctors" ||
634 GV
.getName() == "llvm.global_dtors")) {
635 Assert(!GV
.hasInitializer() || GV
.hasAppendingLinkage(),
636 "invalid linkage for intrinsic global variable", &GV
);
637 // Don't worry about emitting an error for it not being an array,
638 // visitGlobalValue will complain on appending non-array.
639 if (ArrayType
*ATy
= dyn_cast
<ArrayType
>(GV
.getValueType())) {
640 StructType
*STy
= dyn_cast
<StructType
>(ATy
->getElementType());
641 PointerType
*FuncPtrTy
=
642 FunctionType::get(Type::getVoidTy(Context
), false)->
643 getPointerTo(DL
.getProgramAddressSpace());
645 (STy
->getNumElements() == 2 || STy
->getNumElements() == 3) &&
646 STy
->getTypeAtIndex(0u)->isIntegerTy(32) &&
647 STy
->getTypeAtIndex(1) == FuncPtrTy
,
648 "wrong type for intrinsic global variable", &GV
);
649 Assert(STy
->getNumElements() == 3,
650 "the third field of the element type is mandatory, "
651 "specify i8* null to migrate from the obsoleted 2-field form");
652 Type
*ETy
= STy
->getTypeAtIndex(2);
653 Assert(ETy
->isPointerTy() &&
654 cast
<PointerType
>(ETy
)->getElementType()->isIntegerTy(8),
655 "wrong type for intrinsic global variable", &GV
);
659 if (GV
.hasName() && (GV
.getName() == "llvm.used" ||
660 GV
.getName() == "llvm.compiler.used")) {
661 Assert(!GV
.hasInitializer() || GV
.hasAppendingLinkage(),
662 "invalid linkage for intrinsic global variable", &GV
);
663 Type
*GVType
= GV
.getValueType();
664 if (ArrayType
*ATy
= dyn_cast
<ArrayType
>(GVType
)) {
665 PointerType
*PTy
= dyn_cast
<PointerType
>(ATy
->getElementType());
666 Assert(PTy
, "wrong type for intrinsic global variable", &GV
);
667 if (GV
.hasInitializer()) {
668 const Constant
*Init
= GV
.getInitializer();
669 const ConstantArray
*InitArray
= dyn_cast
<ConstantArray
>(Init
);
670 Assert(InitArray
, "wrong initalizer for intrinsic global variable",
672 for (Value
*Op
: InitArray
->operands()) {
673 Value
*V
= Op
->stripPointerCastsNoFollowAliases();
674 Assert(isa
<GlobalVariable
>(V
) || isa
<Function
>(V
) ||
676 "invalid llvm.used member", V
);
677 Assert(V
->hasName(), "members of llvm.used must be named", V
);
683 // Visit any debug info attachments.
684 SmallVector
<MDNode
*, 1> MDs
;
685 GV
.getMetadata(LLVMContext::MD_dbg
, MDs
);
686 for (auto *MD
: MDs
) {
687 if (auto *GVE
= dyn_cast
<DIGlobalVariableExpression
>(MD
))
688 visitDIGlobalVariableExpression(*GVE
);
690 AssertDI(false, "!dbg attachment of global variable must be a "
691 "DIGlobalVariableExpression");
694 // Scalable vectors cannot be global variables, since we don't know
695 // the runtime size. If the global is a struct or an array containing
696 // scalable vectors, that will be caught by the isValidElementType methods
697 // in StructType or ArrayType instead.
698 if (auto *VTy
= dyn_cast
<VectorType
>(GV
.getValueType()))
699 Assert(!VTy
->isScalable(), "Globals cannot contain scalable vectors", &GV
);
701 if (!GV
.hasInitializer()) {
702 visitGlobalValue(GV
);
706 // Walk any aggregate initializers looking for bitcasts between address spaces
707 visitConstantExprsRecursively(GV
.getInitializer());
709 visitGlobalValue(GV
);
712 void Verifier::visitAliaseeSubExpr(const GlobalAlias
&GA
, const Constant
&C
) {
713 SmallPtrSet
<const GlobalAlias
*, 4> Visited
;
715 visitAliaseeSubExpr(Visited
, GA
, C
);
718 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl
<const GlobalAlias
*> &Visited
,
719 const GlobalAlias
&GA
, const Constant
&C
) {
720 if (const auto *GV
= dyn_cast
<GlobalValue
>(&C
)) {
721 Assert(!GV
->isDeclarationForLinker(), "Alias must point to a definition",
724 if (const auto *GA2
= dyn_cast
<GlobalAlias
>(GV
)) {
725 Assert(Visited
.insert(GA2
).second
, "Aliases cannot form a cycle", &GA
);
727 Assert(!GA2
->isInterposable(), "Alias cannot point to an interposable alias",
730 // Only continue verifying subexpressions of GlobalAliases.
731 // Do not recurse into global initializers.
736 if (const auto *CE
= dyn_cast
<ConstantExpr
>(&C
))
737 visitConstantExprsRecursively(CE
);
739 for (const Use
&U
: C
.operands()) {
741 if (const auto *GA2
= dyn_cast
<GlobalAlias
>(V
))
742 visitAliaseeSubExpr(Visited
, GA
, *GA2
->getAliasee());
743 else if (const auto *C2
= dyn_cast
<Constant
>(V
))
744 visitAliaseeSubExpr(Visited
, GA
, *C2
);
748 void Verifier::visitGlobalAlias(const GlobalAlias
&GA
) {
749 Assert(GlobalAlias::isValidLinkage(GA
.getLinkage()),
750 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
751 "weak_odr, or external linkage!",
753 const Constant
*Aliasee
= GA
.getAliasee();
754 Assert(Aliasee
, "Aliasee cannot be NULL!", &GA
);
755 Assert(GA
.getType() == Aliasee
->getType(),
756 "Alias and aliasee types should match!", &GA
);
758 Assert(isa
<GlobalValue
>(Aliasee
) || isa
<ConstantExpr
>(Aliasee
),
759 "Aliasee should be either GlobalValue or ConstantExpr", &GA
);
761 visitAliaseeSubExpr(GA
, *Aliasee
);
763 visitGlobalValue(GA
);
766 void Verifier::visitNamedMDNode(const NamedMDNode
&NMD
) {
767 // There used to be various other llvm.dbg.* nodes, but we don't support
768 // upgrading them and we want to reserve the namespace for future uses.
769 if (NMD
.getName().startswith("llvm.dbg."))
770 AssertDI(NMD
.getName() == "llvm.dbg.cu",
771 "unrecognized named metadata node in the llvm.dbg namespace",
773 for (const MDNode
*MD
: NMD
.operands()) {
774 if (NMD
.getName() == "llvm.dbg.cu")
775 AssertDI(MD
&& isa
<DICompileUnit
>(MD
), "invalid compile unit", &NMD
, MD
);
784 void Verifier::visitMDNode(const MDNode
&MD
) {
785 // Only visit each node once. Metadata can be mutually recursive, so this
786 // avoids infinite recursion here, as well as being an optimization.
787 if (!MDNodes
.insert(&MD
).second
)
790 switch (MD
.getMetadataID()) {
792 llvm_unreachable("Invalid MDNode subclass");
793 case Metadata::MDTupleKind
:
795 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
796 case Metadata::CLASS##Kind: \
797 visit##CLASS(cast<CLASS>(MD)); \
799 #include "llvm/IR/Metadata.def"
802 for (const Metadata
*Op
: MD
.operands()) {
805 Assert(!isa
<LocalAsMetadata
>(Op
), "Invalid operand for global metadata!",
807 if (auto *N
= dyn_cast
<MDNode
>(Op
)) {
811 if (auto *V
= dyn_cast
<ValueAsMetadata
>(Op
)) {
812 visitValueAsMetadata(*V
, nullptr);
817 // Check these last, so we diagnose problems in operands first.
818 Assert(!MD
.isTemporary(), "Expected no forward declarations!", &MD
);
819 Assert(MD
.isResolved(), "All nodes should be resolved!", &MD
);
822 void Verifier::visitValueAsMetadata(const ValueAsMetadata
&MD
, Function
*F
) {
823 Assert(MD
.getValue(), "Expected valid value", &MD
);
824 Assert(!MD
.getValue()->getType()->isMetadataTy(),
825 "Unexpected metadata round-trip through values", &MD
, MD
.getValue());
827 auto *L
= dyn_cast
<LocalAsMetadata
>(&MD
);
831 Assert(F
, "function-local metadata used outside a function", L
);
833 // If this was an instruction, bb, or argument, verify that it is in the
834 // function that we expect.
835 Function
*ActualF
= nullptr;
836 if (Instruction
*I
= dyn_cast
<Instruction
>(L
->getValue())) {
837 Assert(I
->getParent(), "function-local metadata not in basic block", L
, I
);
838 ActualF
= I
->getParent()->getParent();
839 } else if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(L
->getValue()))
840 ActualF
= BB
->getParent();
841 else if (Argument
*A
= dyn_cast
<Argument
>(L
->getValue()))
842 ActualF
= A
->getParent();
843 assert(ActualF
&& "Unimplemented function local metadata case!");
845 Assert(ActualF
== F
, "function-local metadata used in wrong function", L
);
848 void Verifier::visitMetadataAsValue(const MetadataAsValue
&MDV
, Function
*F
) {
849 Metadata
*MD
= MDV
.getMetadata();
850 if (auto *N
= dyn_cast
<MDNode
>(MD
)) {
855 // Only visit each node once. Metadata can be mutually recursive, so this
856 // avoids infinite recursion here, as well as being an optimization.
857 if (!MDNodes
.insert(MD
).second
)
860 if (auto *V
= dyn_cast
<ValueAsMetadata
>(MD
))
861 visitValueAsMetadata(*V
, F
);
864 static bool isType(const Metadata
*MD
) { return !MD
|| isa
<DIType
>(MD
); }
865 static bool isScope(const Metadata
*MD
) { return !MD
|| isa
<DIScope
>(MD
); }
866 static bool isDINode(const Metadata
*MD
) { return !MD
|| isa
<DINode
>(MD
); }
868 void Verifier::visitDILocation(const DILocation
&N
) {
869 AssertDI(N
.getRawScope() && isa
<DILocalScope
>(N
.getRawScope()),
870 "location requires a valid scope", &N
, N
.getRawScope());
871 if (auto *IA
= N
.getRawInlinedAt())
872 AssertDI(isa
<DILocation
>(IA
), "inlined-at should be a location", &N
, IA
);
873 if (auto *SP
= dyn_cast
<DISubprogram
>(N
.getRawScope()))
874 AssertDI(SP
->isDefinition(), "scope points into the type hierarchy", &N
);
877 void Verifier::visitGenericDINode(const GenericDINode
&N
) {
878 AssertDI(N
.getTag(), "invalid tag", &N
);
881 void Verifier::visitDIScope(const DIScope
&N
) {
882 if (auto *F
= N
.getRawFile())
883 AssertDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
886 void Verifier::visitDISubrange(const DISubrange
&N
) {
887 AssertDI(N
.getTag() == dwarf::DW_TAG_subrange_type
, "invalid tag", &N
);
888 auto Count
= N
.getCount();
889 AssertDI(Count
, "Count must either be a signed constant or a DIVariable",
891 AssertDI(!Count
.is
<ConstantInt
*>() ||
892 Count
.get
<ConstantInt
*>()->getSExtValue() >= -1,
893 "invalid subrange count", &N
);
896 void Verifier::visitDIEnumerator(const DIEnumerator
&N
) {
897 AssertDI(N
.getTag() == dwarf::DW_TAG_enumerator
, "invalid tag", &N
);
900 void Verifier::visitDIBasicType(const DIBasicType
&N
) {
901 AssertDI(N
.getTag() == dwarf::DW_TAG_base_type
||
902 N
.getTag() == dwarf::DW_TAG_unspecified_type
,
904 AssertDI(!(N
.isBigEndian() && N
.isLittleEndian()) ,
905 "has conflicting flags", &N
);
908 void Verifier::visitDIDerivedType(const DIDerivedType
&N
) {
909 // Common scope checks.
912 AssertDI(N
.getTag() == dwarf::DW_TAG_typedef
||
913 N
.getTag() == dwarf::DW_TAG_pointer_type
||
914 N
.getTag() == dwarf::DW_TAG_ptr_to_member_type
||
915 N
.getTag() == dwarf::DW_TAG_reference_type
||
916 N
.getTag() == dwarf::DW_TAG_rvalue_reference_type
||
917 N
.getTag() == dwarf::DW_TAG_const_type
||
918 N
.getTag() == dwarf::DW_TAG_volatile_type
||
919 N
.getTag() == dwarf::DW_TAG_restrict_type
||
920 N
.getTag() == dwarf::DW_TAG_atomic_type
||
921 N
.getTag() == dwarf::DW_TAG_member
||
922 N
.getTag() == dwarf::DW_TAG_inheritance
||
923 N
.getTag() == dwarf::DW_TAG_friend
,
925 if (N
.getTag() == dwarf::DW_TAG_ptr_to_member_type
) {
926 AssertDI(isType(N
.getRawExtraData()), "invalid pointer to member type", &N
,
927 N
.getRawExtraData());
930 AssertDI(isScope(N
.getRawScope()), "invalid scope", &N
, N
.getRawScope());
931 AssertDI(isType(N
.getRawBaseType()), "invalid base type", &N
,
934 if (N
.getDWARFAddressSpace()) {
935 AssertDI(N
.getTag() == dwarf::DW_TAG_pointer_type
||
936 N
.getTag() == dwarf::DW_TAG_reference_type
||
937 N
.getTag() == dwarf::DW_TAG_rvalue_reference_type
,
938 "DWARF address space only applies to pointer or reference types",
943 /// Detect mutually exclusive flags.
944 static bool hasConflictingReferenceFlags(unsigned Flags
) {
945 return ((Flags
& DINode::FlagLValueReference
) &&
946 (Flags
& DINode::FlagRValueReference
)) ||
947 ((Flags
& DINode::FlagTypePassByValue
) &&
948 (Flags
& DINode::FlagTypePassByReference
));
951 void Verifier::visitTemplateParams(const MDNode
&N
, const Metadata
&RawParams
) {
952 auto *Params
= dyn_cast
<MDTuple
>(&RawParams
);
953 AssertDI(Params
, "invalid template params", &N
, &RawParams
);
954 for (Metadata
*Op
: Params
->operands()) {
955 AssertDI(Op
&& isa
<DITemplateParameter
>(Op
), "invalid template parameter",
960 void Verifier::visitDICompositeType(const DICompositeType
&N
) {
961 // Common scope checks.
964 AssertDI(N
.getTag() == dwarf::DW_TAG_array_type
||
965 N
.getTag() == dwarf::DW_TAG_structure_type
||
966 N
.getTag() == dwarf::DW_TAG_union_type
||
967 N
.getTag() == dwarf::DW_TAG_enumeration_type
||
968 N
.getTag() == dwarf::DW_TAG_class_type
||
969 N
.getTag() == dwarf::DW_TAG_variant_part
,
972 AssertDI(isScope(N
.getRawScope()), "invalid scope", &N
, N
.getRawScope());
973 AssertDI(isType(N
.getRawBaseType()), "invalid base type", &N
,
976 AssertDI(!N
.getRawElements() || isa
<MDTuple
>(N
.getRawElements()),
977 "invalid composite elements", &N
, N
.getRawElements());
978 AssertDI(isType(N
.getRawVTableHolder()), "invalid vtable holder", &N
,
979 N
.getRawVTableHolder());
980 AssertDI(!hasConflictingReferenceFlags(N
.getFlags()),
981 "invalid reference flags", &N
);
984 const DINodeArray Elements
= N
.getElements();
985 AssertDI(Elements
.size() == 1 &&
986 Elements
[0]->getTag() == dwarf::DW_TAG_subrange_type
,
987 "invalid vector, expected one element of type subrange", &N
);
990 if (auto *Params
= N
.getRawTemplateParams())
991 visitTemplateParams(N
, *Params
);
993 if (N
.getTag() == dwarf::DW_TAG_class_type
||
994 N
.getTag() == dwarf::DW_TAG_union_type
) {
995 AssertDI(N
.getFile() && !N
.getFile()->getFilename().empty(),
996 "class/union requires a filename", &N
, N
.getFile());
999 if (auto *D
= N
.getRawDiscriminator()) {
1000 AssertDI(isa
<DIDerivedType
>(D
) && N
.getTag() == dwarf::DW_TAG_variant_part
,
1001 "discriminator can only appear on variant part");
1005 void Verifier::visitDISubroutineType(const DISubroutineType
&N
) {
1006 AssertDI(N
.getTag() == dwarf::DW_TAG_subroutine_type
, "invalid tag", &N
);
1007 if (auto *Types
= N
.getRawTypeArray()) {
1008 AssertDI(isa
<MDTuple
>(Types
), "invalid composite elements", &N
, Types
);
1009 for (Metadata
*Ty
: N
.getTypeArray()->operands()) {
1010 AssertDI(isType(Ty
), "invalid subroutine type ref", &N
, Types
, Ty
);
1013 AssertDI(!hasConflictingReferenceFlags(N
.getFlags()),
1014 "invalid reference flags", &N
);
1017 void Verifier::visitDIFile(const DIFile
&N
) {
1018 AssertDI(N
.getTag() == dwarf::DW_TAG_file_type
, "invalid tag", &N
);
1019 Optional
<DIFile::ChecksumInfo
<StringRef
>> Checksum
= N
.getChecksum();
1021 AssertDI(Checksum
->Kind
<= DIFile::ChecksumKind::CSK_Last
,
1022 "invalid checksum kind", &N
);
1024 switch (Checksum
->Kind
) {
1025 case DIFile::CSK_MD5
:
1028 case DIFile::CSK_SHA1
:
1032 AssertDI(Checksum
->Value
.size() == Size
, "invalid checksum length", &N
);
1033 AssertDI(Checksum
->Value
.find_if_not(llvm::isHexDigit
) == StringRef::npos
,
1034 "invalid checksum", &N
);
1038 void Verifier::visitDICompileUnit(const DICompileUnit
&N
) {
1039 AssertDI(N
.isDistinct(), "compile units must be distinct", &N
);
1040 AssertDI(N
.getTag() == dwarf::DW_TAG_compile_unit
, "invalid tag", &N
);
1042 // Don't bother verifying the compilation directory or producer string
1043 // as those could be empty.
1044 AssertDI(N
.getRawFile() && isa
<DIFile
>(N
.getRawFile()), "invalid file", &N
,
1046 AssertDI(!N
.getFile()->getFilename().empty(), "invalid filename", &N
,
1049 verifySourceDebugInfo(N
, *N
.getFile());
1051 AssertDI((N
.getEmissionKind() <= DICompileUnit::LastEmissionKind
),
1052 "invalid emission kind", &N
);
1054 if (auto *Array
= N
.getRawEnumTypes()) {
1055 AssertDI(isa
<MDTuple
>(Array
), "invalid enum list", &N
, Array
);
1056 for (Metadata
*Op
: N
.getEnumTypes()->operands()) {
1057 auto *Enum
= dyn_cast_or_null
<DICompositeType
>(Op
);
1058 AssertDI(Enum
&& Enum
->getTag() == dwarf::DW_TAG_enumeration_type
,
1059 "invalid enum type", &N
, N
.getEnumTypes(), Op
);
1062 if (auto *Array
= N
.getRawRetainedTypes()) {
1063 AssertDI(isa
<MDTuple
>(Array
), "invalid retained type list", &N
, Array
);
1064 for (Metadata
*Op
: N
.getRetainedTypes()->operands()) {
1065 AssertDI(Op
&& (isa
<DIType
>(Op
) ||
1066 (isa
<DISubprogram
>(Op
) &&
1067 !cast
<DISubprogram
>(Op
)->isDefinition())),
1068 "invalid retained type", &N
, Op
);
1071 if (auto *Array
= N
.getRawGlobalVariables()) {
1072 AssertDI(isa
<MDTuple
>(Array
), "invalid global variable list", &N
, Array
);
1073 for (Metadata
*Op
: N
.getGlobalVariables()->operands()) {
1074 AssertDI(Op
&& (isa
<DIGlobalVariableExpression
>(Op
)),
1075 "invalid global variable ref", &N
, Op
);
1078 if (auto *Array
= N
.getRawImportedEntities()) {
1079 AssertDI(isa
<MDTuple
>(Array
), "invalid imported entity list", &N
, Array
);
1080 for (Metadata
*Op
: N
.getImportedEntities()->operands()) {
1081 AssertDI(Op
&& isa
<DIImportedEntity
>(Op
), "invalid imported entity ref",
1085 if (auto *Array
= N
.getRawMacros()) {
1086 AssertDI(isa
<MDTuple
>(Array
), "invalid macro list", &N
, Array
);
1087 for (Metadata
*Op
: N
.getMacros()->operands()) {
1088 AssertDI(Op
&& isa
<DIMacroNode
>(Op
), "invalid macro ref", &N
, Op
);
1091 CUVisited
.insert(&N
);
1094 void Verifier::visitDISubprogram(const DISubprogram
&N
) {
1095 AssertDI(N
.getTag() == dwarf::DW_TAG_subprogram
, "invalid tag", &N
);
1096 AssertDI(isScope(N
.getRawScope()), "invalid scope", &N
, N
.getRawScope());
1097 if (auto *F
= N
.getRawFile())
1098 AssertDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
1100 AssertDI(N
.getLine() == 0, "line specified with no file", &N
, N
.getLine());
1101 if (auto *T
= N
.getRawType())
1102 AssertDI(isa
<DISubroutineType
>(T
), "invalid subroutine type", &N
, T
);
1103 AssertDI(isType(N
.getRawContainingType()), "invalid containing type", &N
,
1104 N
.getRawContainingType());
1105 if (auto *Params
= N
.getRawTemplateParams())
1106 visitTemplateParams(N
, *Params
);
1107 if (auto *S
= N
.getRawDeclaration())
1108 AssertDI(isa
<DISubprogram
>(S
) && !cast
<DISubprogram
>(S
)->isDefinition(),
1109 "invalid subprogram declaration", &N
, S
);
1110 if (auto *RawNode
= N
.getRawRetainedNodes()) {
1111 auto *Node
= dyn_cast
<MDTuple
>(RawNode
);
1112 AssertDI(Node
, "invalid retained nodes list", &N
, RawNode
);
1113 for (Metadata
*Op
: Node
->operands()) {
1114 AssertDI(Op
&& (isa
<DILocalVariable
>(Op
) || isa
<DILabel
>(Op
)),
1115 "invalid retained nodes, expected DILocalVariable or DILabel",
1119 AssertDI(!hasConflictingReferenceFlags(N
.getFlags()),
1120 "invalid reference flags", &N
);
1122 auto *Unit
= N
.getRawUnit();
1123 if (N
.isDefinition()) {
1124 // Subprogram definitions (not part of the type hierarchy).
1125 AssertDI(N
.isDistinct(), "subprogram definitions must be distinct", &N
);
1126 AssertDI(Unit
, "subprogram definitions must have a compile unit", &N
);
1127 AssertDI(isa
<DICompileUnit
>(Unit
), "invalid unit type", &N
, Unit
);
1129 verifySourceDebugInfo(*N
.getUnit(), *N
.getFile());
1131 // Subprogram declarations (part of the type hierarchy).
1132 AssertDI(!Unit
, "subprogram declarations must not have a compile unit", &N
);
1135 if (auto *RawThrownTypes
= N
.getRawThrownTypes()) {
1136 auto *ThrownTypes
= dyn_cast
<MDTuple
>(RawThrownTypes
);
1137 AssertDI(ThrownTypes
, "invalid thrown types list", &N
, RawThrownTypes
);
1138 for (Metadata
*Op
: ThrownTypes
->operands())
1139 AssertDI(Op
&& isa
<DIType
>(Op
), "invalid thrown type", &N
, ThrownTypes
,
1143 if (N
.areAllCallsDescribed())
1144 AssertDI(N
.isDefinition(),
1145 "DIFlagAllCallsDescribed must be attached to a definition");
1148 void Verifier::visitDILexicalBlockBase(const DILexicalBlockBase
&N
) {
1149 AssertDI(N
.getTag() == dwarf::DW_TAG_lexical_block
, "invalid tag", &N
);
1150 AssertDI(N
.getRawScope() && isa
<DILocalScope
>(N
.getRawScope()),
1151 "invalid local scope", &N
, N
.getRawScope());
1152 if (auto *SP
= dyn_cast
<DISubprogram
>(N
.getRawScope()))
1153 AssertDI(SP
->isDefinition(), "scope points into the type hierarchy", &N
);
1156 void Verifier::visitDILexicalBlock(const DILexicalBlock
&N
) {
1157 visitDILexicalBlockBase(N
);
1159 AssertDI(N
.getLine() || !N
.getColumn(),
1160 "cannot have column info without line info", &N
);
1163 void Verifier::visitDILexicalBlockFile(const DILexicalBlockFile
&N
) {
1164 visitDILexicalBlockBase(N
);
1167 void Verifier::visitDICommonBlock(const DICommonBlock
&N
) {
1168 AssertDI(N
.getTag() == dwarf::DW_TAG_common_block
, "invalid tag", &N
);
1169 if (auto *S
= N
.getRawScope())
1170 AssertDI(isa
<DIScope
>(S
), "invalid scope ref", &N
, S
);
1171 if (auto *S
= N
.getRawDecl())
1172 AssertDI(isa
<DIGlobalVariable
>(S
), "invalid declaration", &N
, S
);
1175 void Verifier::visitDINamespace(const DINamespace
&N
) {
1176 AssertDI(N
.getTag() == dwarf::DW_TAG_namespace
, "invalid tag", &N
);
1177 if (auto *S
= N
.getRawScope())
1178 AssertDI(isa
<DIScope
>(S
), "invalid scope ref", &N
, S
);
1181 void Verifier::visitDIMacro(const DIMacro
&N
) {
1182 AssertDI(N
.getMacinfoType() == dwarf::DW_MACINFO_define
||
1183 N
.getMacinfoType() == dwarf::DW_MACINFO_undef
,
1184 "invalid macinfo type", &N
);
1185 AssertDI(!N
.getName().empty(), "anonymous macro", &N
);
1186 if (!N
.getValue().empty()) {
1187 assert(N
.getValue().data()[0] != ' ' && "Macro value has a space prefix");
1191 void Verifier::visitDIMacroFile(const DIMacroFile
&N
) {
1192 AssertDI(N
.getMacinfoType() == dwarf::DW_MACINFO_start_file
,
1193 "invalid macinfo type", &N
);
1194 if (auto *F
= N
.getRawFile())
1195 AssertDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
1197 if (auto *Array
= N
.getRawElements()) {
1198 AssertDI(isa
<MDTuple
>(Array
), "invalid macro list", &N
, Array
);
1199 for (Metadata
*Op
: N
.getElements()->operands()) {
1200 AssertDI(Op
&& isa
<DIMacroNode
>(Op
), "invalid macro ref", &N
, Op
);
1205 void Verifier::visitDIModule(const DIModule
&N
) {
1206 AssertDI(N
.getTag() == dwarf::DW_TAG_module
, "invalid tag", &N
);
1207 AssertDI(!N
.getName().empty(), "anonymous module", &N
);
1210 void Verifier::visitDITemplateParameter(const DITemplateParameter
&N
) {
1211 AssertDI(isType(N
.getRawType()), "invalid type ref", &N
, N
.getRawType());
1214 void Verifier::visitDITemplateTypeParameter(const DITemplateTypeParameter
&N
) {
1215 visitDITemplateParameter(N
);
1217 AssertDI(N
.getTag() == dwarf::DW_TAG_template_type_parameter
, "invalid tag",
1221 void Verifier::visitDITemplateValueParameter(
1222 const DITemplateValueParameter
&N
) {
1223 visitDITemplateParameter(N
);
1225 AssertDI(N
.getTag() == dwarf::DW_TAG_template_value_parameter
||
1226 N
.getTag() == dwarf::DW_TAG_GNU_template_template_param
||
1227 N
.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack
,
1231 void Verifier::visitDIVariable(const DIVariable
&N
) {
1232 if (auto *S
= N
.getRawScope())
1233 AssertDI(isa
<DIScope
>(S
), "invalid scope", &N
, S
);
1234 if (auto *F
= N
.getRawFile())
1235 AssertDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
1238 void Verifier::visitDIGlobalVariable(const DIGlobalVariable
&N
) {
1239 // Checks common to all variables.
1242 AssertDI(N
.getTag() == dwarf::DW_TAG_variable
, "invalid tag", &N
);
1243 AssertDI(isType(N
.getRawType()), "invalid type ref", &N
, N
.getRawType());
1244 AssertDI(N
.getType(), "missing global variable type", &N
);
1245 if (auto *Member
= N
.getRawStaticDataMemberDeclaration()) {
1246 AssertDI(isa
<DIDerivedType
>(Member
),
1247 "invalid static data member declaration", &N
, Member
);
1251 void Verifier::visitDILocalVariable(const DILocalVariable
&N
) {
1252 // Checks common to all variables.
1255 AssertDI(isType(N
.getRawType()), "invalid type ref", &N
, N
.getRawType());
1256 AssertDI(N
.getTag() == dwarf::DW_TAG_variable
, "invalid tag", &N
);
1257 AssertDI(N
.getRawScope() && isa
<DILocalScope
>(N
.getRawScope()),
1258 "local variable requires a valid scope", &N
, N
.getRawScope());
1259 if (auto Ty
= N
.getType())
1260 AssertDI(!isa
<DISubroutineType
>(Ty
), "invalid type", &N
, N
.getType());
1263 void Verifier::visitDILabel(const DILabel
&N
) {
1264 if (auto *S
= N
.getRawScope())
1265 AssertDI(isa
<DIScope
>(S
), "invalid scope", &N
, S
);
1266 if (auto *F
= N
.getRawFile())
1267 AssertDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
1269 AssertDI(N
.getTag() == dwarf::DW_TAG_label
, "invalid tag", &N
);
1270 AssertDI(N
.getRawScope() && isa
<DILocalScope
>(N
.getRawScope()),
1271 "label requires a valid scope", &N
, N
.getRawScope());
1274 void Verifier::visitDIExpression(const DIExpression
&N
) {
1275 AssertDI(N
.isValid(), "invalid expression", &N
);
1278 void Verifier::visitDIGlobalVariableExpression(
1279 const DIGlobalVariableExpression
&GVE
) {
1280 AssertDI(GVE
.getVariable(), "missing variable");
1281 if (auto *Var
= GVE
.getVariable())
1282 visitDIGlobalVariable(*Var
);
1283 if (auto *Expr
= GVE
.getExpression()) {
1284 visitDIExpression(*Expr
);
1285 if (auto Fragment
= Expr
->getFragmentInfo())
1286 verifyFragmentExpression(*GVE
.getVariable(), *Fragment
, &GVE
);
1290 void Verifier::visitDIObjCProperty(const DIObjCProperty
&N
) {
1291 AssertDI(N
.getTag() == dwarf::DW_TAG_APPLE_property
, "invalid tag", &N
);
1292 if (auto *T
= N
.getRawType())
1293 AssertDI(isType(T
), "invalid type ref", &N
, T
);
1294 if (auto *F
= N
.getRawFile())
1295 AssertDI(isa
<DIFile
>(F
), "invalid file", &N
, F
);
1298 void Verifier::visitDIImportedEntity(const DIImportedEntity
&N
) {
1299 AssertDI(N
.getTag() == dwarf::DW_TAG_imported_module
||
1300 N
.getTag() == dwarf::DW_TAG_imported_declaration
,
1302 if (auto *S
= N
.getRawScope())
1303 AssertDI(isa
<DIScope
>(S
), "invalid scope for imported entity", &N
, S
);
1304 AssertDI(isDINode(N
.getRawEntity()), "invalid imported entity", &N
,
1308 void Verifier::visitComdat(const Comdat
&C
) {
1309 // The Module is invalid if the GlobalValue has private linkage. Entities
1310 // with private linkage don't have entries in the symbol table.
1311 if (const GlobalValue
*GV
= M
.getNamedValue(C
.getName()))
1312 Assert(!GV
->hasPrivateLinkage(), "comdat global value has private linkage",
1316 void Verifier::visitModuleIdents(const Module
&M
) {
1317 const NamedMDNode
*Idents
= M
.getNamedMetadata("llvm.ident");
1321 // llvm.ident takes a list of metadata entry. Each entry has only one string.
1322 // Scan each llvm.ident entry and make sure that this requirement is met.
1323 for (const MDNode
*N
: Idents
->operands()) {
1324 Assert(N
->getNumOperands() == 1,
1325 "incorrect number of operands in llvm.ident metadata", N
);
1326 Assert(dyn_cast_or_null
<MDString
>(N
->getOperand(0)),
1327 ("invalid value for llvm.ident metadata entry operand"
1328 "(the operand should be a string)"),
1333 void Verifier::visitModuleCommandLines(const Module
&M
) {
1334 const NamedMDNode
*CommandLines
= M
.getNamedMetadata("llvm.commandline");
1338 // llvm.commandline takes a list of metadata entry. Each entry has only one
1339 // string. Scan each llvm.commandline entry and make sure that this
1340 // requirement is met.
1341 for (const MDNode
*N
: CommandLines
->operands()) {
1342 Assert(N
->getNumOperands() == 1,
1343 "incorrect number of operands in llvm.commandline metadata", N
);
1344 Assert(dyn_cast_or_null
<MDString
>(N
->getOperand(0)),
1345 ("invalid value for llvm.commandline metadata entry operand"
1346 "(the operand should be a string)"),
1351 void Verifier::visitModuleFlags(const Module
&M
) {
1352 const NamedMDNode
*Flags
= M
.getModuleFlagsMetadata();
1355 // Scan each flag, and track the flags and requirements.
1356 DenseMap
<const MDString
*, const MDNode
*> SeenIDs
;
1357 SmallVector
<const MDNode
*, 16> Requirements
;
1358 for (const MDNode
*MDN
: Flags
->operands())
1359 visitModuleFlag(MDN
, SeenIDs
, Requirements
);
1361 // Validate that the requirements in the module are valid.
1362 for (const MDNode
*Requirement
: Requirements
) {
1363 const MDString
*Flag
= cast
<MDString
>(Requirement
->getOperand(0));
1364 const Metadata
*ReqValue
= Requirement
->getOperand(1);
1366 const MDNode
*Op
= SeenIDs
.lookup(Flag
);
1368 CheckFailed("invalid requirement on flag, flag is not present in module",
1373 if (Op
->getOperand(2) != ReqValue
) {
1374 CheckFailed(("invalid requirement on flag, "
1375 "flag does not have the required value"),
1383 Verifier::visitModuleFlag(const MDNode
*Op
,
1384 DenseMap
<const MDString
*, const MDNode
*> &SeenIDs
,
1385 SmallVectorImpl
<const MDNode
*> &Requirements
) {
1386 // Each module flag should have three arguments, the merge behavior (a
1387 // constant int), the flag ID (an MDString), and the value.
1388 Assert(Op
->getNumOperands() == 3,
1389 "incorrect number of operands in module flag", Op
);
1390 Module::ModFlagBehavior MFB
;
1391 if (!Module::isValidModFlagBehavior(Op
->getOperand(0), MFB
)) {
1393 mdconst::dyn_extract_or_null
<ConstantInt
>(Op
->getOperand(0)),
1394 "invalid behavior operand in module flag (expected constant integer)",
1397 "invalid behavior operand in module flag (unexpected constant)",
1400 MDString
*ID
= dyn_cast_or_null
<MDString
>(Op
->getOperand(1));
1401 Assert(ID
, "invalid ID operand in module flag (expected metadata string)",
1404 // Sanity check the values for behaviors with additional requirements.
1407 case Module::Warning
:
1408 case Module::Override
:
1409 // These behavior types accept any value.
1413 Assert(mdconst::dyn_extract_or_null
<ConstantInt
>(Op
->getOperand(2)),
1414 "invalid value for 'max' module flag (expected constant integer)",
1419 case Module::Require
: {
1420 // The value should itself be an MDNode with two operands, a flag ID (an
1421 // MDString), and a value.
1422 MDNode
*Value
= dyn_cast
<MDNode
>(Op
->getOperand(2));
1423 Assert(Value
&& Value
->getNumOperands() == 2,
1424 "invalid value for 'require' module flag (expected metadata pair)",
1426 Assert(isa
<MDString
>(Value
->getOperand(0)),
1427 ("invalid value for 'require' module flag "
1428 "(first value operand should be a string)"),
1429 Value
->getOperand(0));
1431 // Append it to the list of requirements, to check once all module flags are
1433 Requirements
.push_back(Value
);
1437 case Module::Append
:
1438 case Module::AppendUnique
: {
1439 // These behavior types require the operand be an MDNode.
1440 Assert(isa
<MDNode
>(Op
->getOperand(2)),
1441 "invalid value for 'append'-type module flag "
1442 "(expected a metadata node)",
1448 // Unless this is a "requires" flag, check the ID is unique.
1449 if (MFB
!= Module::Require
) {
1450 bool Inserted
= SeenIDs
.insert(std::make_pair(ID
, Op
)).second
;
1452 "module flag identifiers must be unique (or of 'require' type)", ID
);
1455 if (ID
->getString() == "wchar_size") {
1457 = mdconst::dyn_extract_or_null
<ConstantInt
>(Op
->getOperand(2));
1458 Assert(Value
, "wchar_size metadata requires constant integer argument");
1461 if (ID
->getString() == "Linker Options") {
1462 // If the llvm.linker.options named metadata exists, we assume that the
1463 // bitcode reader has upgraded the module flag. Otherwise the flag might
1464 // have been created by a client directly.
1465 Assert(M
.getNamedMetadata("llvm.linker.options"),
1466 "'Linker Options' named metadata no longer supported");
1469 if (ID
->getString() == "CG Profile") {
1470 for (const MDOperand
&MDO
: cast
<MDNode
>(Op
->getOperand(2))->operands())
1471 visitModuleFlagCGProfileEntry(MDO
);
1475 void Verifier::visitModuleFlagCGProfileEntry(const MDOperand
&MDO
) {
1476 auto CheckFunction
= [&](const MDOperand
&FuncMDO
) {
1479 auto F
= dyn_cast
<ValueAsMetadata
>(FuncMDO
);
1480 Assert(F
&& isa
<Function
>(F
->getValue()), "expected a Function or null",
1483 auto Node
= dyn_cast_or_null
<MDNode
>(MDO
);
1484 Assert(Node
&& Node
->getNumOperands() == 3, "expected a MDNode triple", MDO
);
1485 CheckFunction(Node
->getOperand(0));
1486 CheckFunction(Node
->getOperand(1));
1487 auto Count
= dyn_cast_or_null
<ConstantAsMetadata
>(Node
->getOperand(2));
1488 Assert(Count
&& Count
->getType()->isIntegerTy(),
1489 "expected an integer constant", Node
->getOperand(2));
1492 /// Return true if this attribute kind only applies to functions.
1493 static bool isFuncOnlyAttr(Attribute::AttrKind Kind
) {
1495 case Attribute::NoReturn
:
1496 case Attribute::NoSync
:
1497 case Attribute::WillReturn
:
1498 case Attribute::NoCfCheck
:
1499 case Attribute::NoUnwind
:
1500 case Attribute::NoInline
:
1501 case Attribute::NoFree
:
1502 case Attribute::AlwaysInline
:
1503 case Attribute::OptimizeForSize
:
1504 case Attribute::StackProtect
:
1505 case Attribute::StackProtectReq
:
1506 case Attribute::StackProtectStrong
:
1507 case Attribute::SafeStack
:
1508 case Attribute::ShadowCallStack
:
1509 case Attribute::NoRedZone
:
1510 case Attribute::NoImplicitFloat
:
1511 case Attribute::Naked
:
1512 case Attribute::InlineHint
:
1513 case Attribute::StackAlignment
:
1514 case Attribute::UWTable
:
1515 case Attribute::NonLazyBind
:
1516 case Attribute::ReturnsTwice
:
1517 case Attribute::SanitizeAddress
:
1518 case Attribute::SanitizeHWAddress
:
1519 case Attribute::SanitizeThread
:
1520 case Attribute::SanitizeMemory
:
1521 case Attribute::MinSize
:
1522 case Attribute::NoDuplicate
:
1523 case Attribute::Builtin
:
1524 case Attribute::NoBuiltin
:
1525 case Attribute::Cold
:
1526 case Attribute::OptForFuzzing
:
1527 case Attribute::OptimizeNone
:
1528 case Attribute::JumpTable
:
1529 case Attribute::Convergent
:
1530 case Attribute::ArgMemOnly
:
1531 case Attribute::NoRecurse
:
1532 case Attribute::InaccessibleMemOnly
:
1533 case Attribute::InaccessibleMemOrArgMemOnly
:
1534 case Attribute::AllocSize
:
1535 case Attribute::SpeculativeLoadHardening
:
1536 case Attribute::Speculatable
:
1537 case Attribute::StrictFP
:
1545 /// Return true if this is a function attribute that can also appear on
1547 static bool isFuncOrArgAttr(Attribute::AttrKind Kind
) {
1548 return Kind
== Attribute::ReadOnly
|| Kind
== Attribute::WriteOnly
||
1549 Kind
== Attribute::ReadNone
;
1552 void Verifier::verifyAttributeTypes(AttributeSet Attrs
, bool IsFunction
,
1554 for (Attribute A
: Attrs
) {
1555 if (A
.isStringAttribute())
1558 if (isFuncOnlyAttr(A
.getKindAsEnum())) {
1560 CheckFailed("Attribute '" + A
.getAsString() +
1561 "' only applies to functions!",
1565 } else if (IsFunction
&& !isFuncOrArgAttr(A
.getKindAsEnum())) {
1566 CheckFailed("Attribute '" + A
.getAsString() +
1567 "' does not apply to functions!",
1574 // VerifyParameterAttrs - Check the given attributes for an argument or return
1575 // value of the specified type. The value V is printed in error messages.
1576 void Verifier::verifyParameterAttrs(AttributeSet Attrs
, Type
*Ty
,
1578 if (!Attrs
.hasAttributes())
1581 verifyAttributeTypes(Attrs
, /*IsFunction=*/false, V
);
1583 if (Attrs
.hasAttribute(Attribute::ImmArg
)) {
1584 Assert(Attrs
.getNumAttributes() == 1,
1585 "Attribute 'immarg' is incompatible with other attributes", V
);
1588 // Check for mutually incompatible attributes. Only inreg is compatible with
1590 unsigned AttrCount
= 0;
1591 AttrCount
+= Attrs
.hasAttribute(Attribute::ByVal
);
1592 AttrCount
+= Attrs
.hasAttribute(Attribute::InAlloca
);
1593 AttrCount
+= Attrs
.hasAttribute(Attribute::StructRet
) ||
1594 Attrs
.hasAttribute(Attribute::InReg
);
1595 AttrCount
+= Attrs
.hasAttribute(Attribute::Nest
);
1596 Assert(AttrCount
<= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1597 "and 'sret' are incompatible!",
1600 Assert(!(Attrs
.hasAttribute(Attribute::InAlloca
) &&
1601 Attrs
.hasAttribute(Attribute::ReadOnly
)),
1603 "'inalloca and readonly' are incompatible!",
1606 Assert(!(Attrs
.hasAttribute(Attribute::StructRet
) &&
1607 Attrs
.hasAttribute(Attribute::Returned
)),
1609 "'sret and returned' are incompatible!",
1612 Assert(!(Attrs
.hasAttribute(Attribute::ZExt
) &&
1613 Attrs
.hasAttribute(Attribute::SExt
)),
1615 "'zeroext and signext' are incompatible!",
1618 Assert(!(Attrs
.hasAttribute(Attribute::ReadNone
) &&
1619 Attrs
.hasAttribute(Attribute::ReadOnly
)),
1621 "'readnone and readonly' are incompatible!",
1624 Assert(!(Attrs
.hasAttribute(Attribute::ReadNone
) &&
1625 Attrs
.hasAttribute(Attribute::WriteOnly
)),
1627 "'readnone and writeonly' are incompatible!",
1630 Assert(!(Attrs
.hasAttribute(Attribute::ReadOnly
) &&
1631 Attrs
.hasAttribute(Attribute::WriteOnly
)),
1633 "'readonly and writeonly' are incompatible!",
1636 Assert(!(Attrs
.hasAttribute(Attribute::NoInline
) &&
1637 Attrs
.hasAttribute(Attribute::AlwaysInline
)),
1639 "'noinline and alwaysinline' are incompatible!",
1642 if (Attrs
.hasAttribute(Attribute::ByVal
) && Attrs
.getByValType()) {
1643 Assert(Attrs
.getByValType() == cast
<PointerType
>(Ty
)->getElementType(),
1644 "Attribute 'byval' type does not match parameter!", V
);
1647 AttrBuilder IncompatibleAttrs
= AttributeFuncs::typeIncompatible(Ty
);
1648 Assert(!AttrBuilder(Attrs
).overlaps(IncompatibleAttrs
),
1649 "Wrong types for attribute: " +
1650 AttributeSet::get(Context
, IncompatibleAttrs
).getAsString(),
1653 if (PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
)) {
1654 SmallPtrSet
<Type
*, 4> Visited
;
1655 if (!PTy
->getElementType()->isSized(&Visited
)) {
1656 Assert(!Attrs
.hasAttribute(Attribute::ByVal
) &&
1657 !Attrs
.hasAttribute(Attribute::InAlloca
),
1658 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1661 if (!isa
<PointerType
>(PTy
->getElementType()))
1662 Assert(!Attrs
.hasAttribute(Attribute::SwiftError
),
1663 "Attribute 'swifterror' only applies to parameters "
1664 "with pointer to pointer type!",
1667 Assert(!Attrs
.hasAttribute(Attribute::ByVal
),
1668 "Attribute 'byval' only applies to parameters with pointer type!",
1670 Assert(!Attrs
.hasAttribute(Attribute::SwiftError
),
1671 "Attribute 'swifterror' only applies to parameters "
1672 "with pointer type!",
1677 // Check parameter attributes against a function type.
1678 // The value V is printed in error messages.
1679 void Verifier::verifyFunctionAttrs(FunctionType
*FT
, AttributeList Attrs
,
1680 const Value
*V
, bool IsIntrinsic
) {
1681 if (Attrs
.isEmpty())
1684 bool SawNest
= false;
1685 bool SawReturned
= false;
1686 bool SawSRet
= false;
1687 bool SawSwiftSelf
= false;
1688 bool SawSwiftError
= false;
1690 // Verify return value attributes.
1691 AttributeSet RetAttrs
= Attrs
.getRetAttributes();
1692 Assert((!RetAttrs
.hasAttribute(Attribute::ByVal
) &&
1693 !RetAttrs
.hasAttribute(Attribute::Nest
) &&
1694 !RetAttrs
.hasAttribute(Attribute::StructRet
) &&
1695 !RetAttrs
.hasAttribute(Attribute::NoCapture
) &&
1696 !RetAttrs
.hasAttribute(Attribute::Returned
) &&
1697 !RetAttrs
.hasAttribute(Attribute::InAlloca
) &&
1698 !RetAttrs
.hasAttribute(Attribute::SwiftSelf
) &&
1699 !RetAttrs
.hasAttribute(Attribute::SwiftError
)),
1700 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', "
1701 "'returned', 'swiftself', and 'swifterror' do not apply to return "
1704 Assert((!RetAttrs
.hasAttribute(Attribute::ReadOnly
) &&
1705 !RetAttrs
.hasAttribute(Attribute::WriteOnly
) &&
1706 !RetAttrs
.hasAttribute(Attribute::ReadNone
)),
1707 "Attribute '" + RetAttrs
.getAsString() +
1708 "' does not apply to function returns",
1710 verifyParameterAttrs(RetAttrs
, FT
->getReturnType(), V
);
1712 // Verify parameter attributes.
1713 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
) {
1714 Type
*Ty
= FT
->getParamType(i
);
1715 AttributeSet ArgAttrs
= Attrs
.getParamAttributes(i
);
1718 Assert(!ArgAttrs
.hasAttribute(Attribute::ImmArg
),
1719 "immarg attribute only applies to intrinsics",V
);
1722 verifyParameterAttrs(ArgAttrs
, Ty
, V
);
1724 if (ArgAttrs
.hasAttribute(Attribute::Nest
)) {
1725 Assert(!SawNest
, "More than one parameter has attribute nest!", V
);
1729 if (ArgAttrs
.hasAttribute(Attribute::Returned
)) {
1730 Assert(!SawReturned
, "More than one parameter has attribute returned!",
1732 Assert(Ty
->canLosslesslyBitCastTo(FT
->getReturnType()),
1733 "Incompatible argument and return types for 'returned' attribute",
1738 if (ArgAttrs
.hasAttribute(Attribute::StructRet
)) {
1739 Assert(!SawSRet
, "Cannot have multiple 'sret' parameters!", V
);
1740 Assert(i
== 0 || i
== 1,
1741 "Attribute 'sret' is not on first or second parameter!", V
);
1745 if (ArgAttrs
.hasAttribute(Attribute::SwiftSelf
)) {
1746 Assert(!SawSwiftSelf
, "Cannot have multiple 'swiftself' parameters!", V
);
1747 SawSwiftSelf
= true;
1750 if (ArgAttrs
.hasAttribute(Attribute::SwiftError
)) {
1751 Assert(!SawSwiftError
, "Cannot have multiple 'swifterror' parameters!",
1753 SawSwiftError
= true;
1756 if (ArgAttrs
.hasAttribute(Attribute::InAlloca
)) {
1757 Assert(i
== FT
->getNumParams() - 1,
1758 "inalloca isn't on the last parameter!", V
);
1762 if (!Attrs
.hasAttributes(AttributeList::FunctionIndex
))
1765 verifyAttributeTypes(Attrs
.getFnAttributes(), /*IsFunction=*/true, V
);
1767 Assert(!(Attrs
.hasFnAttribute(Attribute::ReadNone
) &&
1768 Attrs
.hasFnAttribute(Attribute::ReadOnly
)),
1769 "Attributes 'readnone and readonly' are incompatible!", V
);
1771 Assert(!(Attrs
.hasFnAttribute(Attribute::ReadNone
) &&
1772 Attrs
.hasFnAttribute(Attribute::WriteOnly
)),
1773 "Attributes 'readnone and writeonly' are incompatible!", V
);
1775 Assert(!(Attrs
.hasFnAttribute(Attribute::ReadOnly
) &&
1776 Attrs
.hasFnAttribute(Attribute::WriteOnly
)),
1777 "Attributes 'readonly and writeonly' are incompatible!", V
);
1779 Assert(!(Attrs
.hasFnAttribute(Attribute::ReadNone
) &&
1780 Attrs
.hasFnAttribute(Attribute::InaccessibleMemOrArgMemOnly
)),
1781 "Attributes 'readnone and inaccessiblemem_or_argmemonly' are "
1785 Assert(!(Attrs
.hasFnAttribute(Attribute::ReadNone
) &&
1786 Attrs
.hasFnAttribute(Attribute::InaccessibleMemOnly
)),
1787 "Attributes 'readnone and inaccessiblememonly' are incompatible!", V
);
1789 Assert(!(Attrs
.hasFnAttribute(Attribute::NoInline
) &&
1790 Attrs
.hasFnAttribute(Attribute::AlwaysInline
)),
1791 "Attributes 'noinline and alwaysinline' are incompatible!", V
);
1793 if (Attrs
.hasFnAttribute(Attribute::OptimizeNone
)) {
1794 Assert(Attrs
.hasFnAttribute(Attribute::NoInline
),
1795 "Attribute 'optnone' requires 'noinline'!", V
);
1797 Assert(!Attrs
.hasFnAttribute(Attribute::OptimizeForSize
),
1798 "Attributes 'optsize and optnone' are incompatible!", V
);
1800 Assert(!Attrs
.hasFnAttribute(Attribute::MinSize
),
1801 "Attributes 'minsize and optnone' are incompatible!", V
);
1804 if (Attrs
.hasFnAttribute(Attribute::JumpTable
)) {
1805 const GlobalValue
*GV
= cast
<GlobalValue
>(V
);
1806 Assert(GV
->hasGlobalUnnamedAddr(),
1807 "Attribute 'jumptable' requires 'unnamed_addr'", V
);
1810 if (Attrs
.hasFnAttribute(Attribute::AllocSize
)) {
1811 std::pair
<unsigned, Optional
<unsigned>> Args
=
1812 Attrs
.getAllocSizeArgs(AttributeList::FunctionIndex
);
1814 auto CheckParam
= [&](StringRef Name
, unsigned ParamNo
) {
1815 if (ParamNo
>= FT
->getNumParams()) {
1816 CheckFailed("'allocsize' " + Name
+ " argument is out of bounds", V
);
1820 if (!FT
->getParamType(ParamNo
)->isIntegerTy()) {
1821 CheckFailed("'allocsize' " + Name
+
1822 " argument must refer to an integer parameter",
1830 if (!CheckParam("element size", Args
.first
))
1833 if (Args
.second
&& !CheckParam("number of elements", *Args
.second
))
1838 void Verifier::verifyFunctionMetadata(
1839 ArrayRef
<std::pair
<unsigned, MDNode
*>> MDs
) {
1840 for (const auto &Pair
: MDs
) {
1841 if (Pair
.first
== LLVMContext::MD_prof
) {
1842 MDNode
*MD
= Pair
.second
;
1843 Assert(MD
->getNumOperands() >= 2,
1844 "!prof annotations should have no less than 2 operands", MD
);
1846 // Check first operand.
1847 Assert(MD
->getOperand(0) != nullptr, "first operand should not be null",
1849 Assert(isa
<MDString
>(MD
->getOperand(0)),
1850 "expected string with name of the !prof annotation", MD
);
1851 MDString
*MDS
= cast
<MDString
>(MD
->getOperand(0));
1852 StringRef ProfName
= MDS
->getString();
1853 Assert(ProfName
.equals("function_entry_count") ||
1854 ProfName
.equals("synthetic_function_entry_count"),
1855 "first operand should be 'function_entry_count'"
1856 " or 'synthetic_function_entry_count'",
1859 // Check second operand.
1860 Assert(MD
->getOperand(1) != nullptr, "second operand should not be null",
1862 Assert(isa
<ConstantAsMetadata
>(MD
->getOperand(1)),
1863 "expected integer argument to function_entry_count", MD
);
1868 void Verifier::visitConstantExprsRecursively(const Constant
*EntryC
) {
1869 if (!ConstantExprVisited
.insert(EntryC
).second
)
1872 SmallVector
<const Constant
*, 16> Stack
;
1873 Stack
.push_back(EntryC
);
1875 while (!Stack
.empty()) {
1876 const Constant
*C
= Stack
.pop_back_val();
1878 // Check this constant expression.
1879 if (const auto *CE
= dyn_cast
<ConstantExpr
>(C
))
1880 visitConstantExpr(CE
);
1882 if (const auto *GV
= dyn_cast
<GlobalValue
>(C
)) {
1883 // Global Values get visited separately, but we do need to make sure
1884 // that the global value is in the correct module
1885 Assert(GV
->getParent() == &M
, "Referencing global in another module!",
1886 EntryC
, &M
, GV
, GV
->getParent());
1890 // Visit all sub-expressions.
1891 for (const Use
&U
: C
->operands()) {
1892 const auto *OpC
= dyn_cast
<Constant
>(U
);
1895 if (!ConstantExprVisited
.insert(OpC
).second
)
1897 Stack
.push_back(OpC
);
1902 void Verifier::visitConstantExpr(const ConstantExpr
*CE
) {
1903 if (CE
->getOpcode() == Instruction::BitCast
)
1904 Assert(CastInst::castIsValid(Instruction::BitCast
, CE
->getOperand(0),
1906 "Invalid bitcast", CE
);
1908 if (CE
->getOpcode() == Instruction::IntToPtr
||
1909 CE
->getOpcode() == Instruction::PtrToInt
) {
1910 auto *PtrTy
= CE
->getOpcode() == Instruction::IntToPtr
1912 : CE
->getOperand(0)->getType();
1913 StringRef Msg
= CE
->getOpcode() == Instruction::IntToPtr
1914 ? "inttoptr not supported for non-integral pointers"
1915 : "ptrtoint not supported for non-integral pointers";
1917 !DL
.isNonIntegralPointerType(cast
<PointerType
>(PtrTy
->getScalarType())),
1922 bool Verifier::verifyAttributeCount(AttributeList Attrs
, unsigned Params
) {
1923 // There shouldn't be more attribute sets than there are parameters plus the
1924 // function and return value.
1925 return Attrs
.getNumAttrSets() <= Params
+ 2;
1928 /// Verify that statepoint intrinsic is well formed.
1929 void Verifier::verifyStatepoint(const CallBase
&Call
) {
1930 assert(Call
.getCalledFunction() &&
1931 Call
.getCalledFunction()->getIntrinsicID() ==
1932 Intrinsic::experimental_gc_statepoint
);
1934 Assert(!Call
.doesNotAccessMemory() && !Call
.onlyReadsMemory() &&
1935 !Call
.onlyAccessesArgMemory(),
1936 "gc.statepoint must read and write all memory to preserve "
1937 "reordering restrictions required by safepoint semantics",
1940 const int64_t NumPatchBytes
=
1941 cast
<ConstantInt
>(Call
.getArgOperand(1))->getSExtValue();
1942 assert(isInt
<32>(NumPatchBytes
) && "NumPatchBytesV is an i32!");
1943 Assert(NumPatchBytes
>= 0,
1944 "gc.statepoint number of patchable bytes must be "
1948 const Value
*Target
= Call
.getArgOperand(2);
1949 auto *PT
= dyn_cast
<PointerType
>(Target
->getType());
1950 Assert(PT
&& PT
->getElementType()->isFunctionTy(),
1951 "gc.statepoint callee must be of function pointer type", Call
, Target
);
1952 FunctionType
*TargetFuncType
= cast
<FunctionType
>(PT
->getElementType());
1954 const int NumCallArgs
= cast
<ConstantInt
>(Call
.getArgOperand(3))->getZExtValue();
1955 Assert(NumCallArgs
>= 0,
1956 "gc.statepoint number of arguments to underlying call "
1959 const int NumParams
= (int)TargetFuncType
->getNumParams();
1960 if (TargetFuncType
->isVarArg()) {
1961 Assert(NumCallArgs
>= NumParams
,
1962 "gc.statepoint mismatch in number of vararg call args", Call
);
1964 // TODO: Remove this limitation
1965 Assert(TargetFuncType
->getReturnType()->isVoidTy(),
1966 "gc.statepoint doesn't support wrapping non-void "
1967 "vararg functions yet",
1970 Assert(NumCallArgs
== NumParams
,
1971 "gc.statepoint mismatch in number of call args", Call
);
1973 const uint64_t Flags
1974 = cast
<ConstantInt
>(Call
.getArgOperand(4))->getZExtValue();
1975 Assert((Flags
& ~(uint64_t)StatepointFlags::MaskAll
) == 0,
1976 "unknown flag used in gc.statepoint flags argument", Call
);
1978 // Verify that the types of the call parameter arguments match
1979 // the type of the wrapped callee.
1980 AttributeList Attrs
= Call
.getAttributes();
1981 for (int i
= 0; i
< NumParams
; i
++) {
1982 Type
*ParamType
= TargetFuncType
->getParamType(i
);
1983 Type
*ArgType
= Call
.getArgOperand(5 + i
)->getType();
1984 Assert(ArgType
== ParamType
,
1985 "gc.statepoint call argument does not match wrapped "
1989 if (TargetFuncType
->isVarArg()) {
1990 AttributeSet ArgAttrs
= Attrs
.getParamAttributes(5 + i
);
1991 Assert(!ArgAttrs
.hasAttribute(Attribute::StructRet
),
1992 "Attribute 'sret' cannot be used for vararg call arguments!",
1997 const int EndCallArgsInx
= 4 + NumCallArgs
;
1999 const Value
*NumTransitionArgsV
= Call
.getArgOperand(EndCallArgsInx
+ 1);
2000 Assert(isa
<ConstantInt
>(NumTransitionArgsV
),
2001 "gc.statepoint number of transition arguments "
2002 "must be constant integer",
2004 const int NumTransitionArgs
=
2005 cast
<ConstantInt
>(NumTransitionArgsV
)->getZExtValue();
2006 Assert(NumTransitionArgs
>= 0,
2007 "gc.statepoint number of transition arguments must be positive", Call
);
2008 const int EndTransitionArgsInx
= EndCallArgsInx
+ 1 + NumTransitionArgs
;
2010 const Value
*NumDeoptArgsV
= Call
.getArgOperand(EndTransitionArgsInx
+ 1);
2011 Assert(isa
<ConstantInt
>(NumDeoptArgsV
),
2012 "gc.statepoint number of deoptimization arguments "
2013 "must be constant integer",
2015 const int NumDeoptArgs
= cast
<ConstantInt
>(NumDeoptArgsV
)->getZExtValue();
2016 Assert(NumDeoptArgs
>= 0,
2017 "gc.statepoint number of deoptimization arguments "
2021 const int ExpectedNumArgs
=
2022 7 + NumCallArgs
+ NumTransitionArgs
+ NumDeoptArgs
;
2023 Assert(ExpectedNumArgs
<= (int)Call
.arg_size(),
2024 "gc.statepoint too few arguments according to length fields", Call
);
2026 // Check that the only uses of this gc.statepoint are gc.result or
2027 // gc.relocate calls which are tied to this statepoint and thus part
2028 // of the same statepoint sequence
2029 for (const User
*U
: Call
.users()) {
2030 const CallInst
*UserCall
= dyn_cast
<const CallInst
>(U
);
2031 Assert(UserCall
, "illegal use of statepoint token", Call
, U
);
2034 Assert(isa
<GCRelocateInst
>(UserCall
) || isa
<GCResultInst
>(UserCall
),
2035 "gc.result or gc.relocate are the only value uses "
2036 "of a gc.statepoint",
2038 if (isa
<GCResultInst
>(UserCall
)) {
2039 Assert(UserCall
->getArgOperand(0) == &Call
,
2040 "gc.result connected to wrong gc.statepoint", Call
, UserCall
);
2041 } else if (isa
<GCRelocateInst
>(Call
)) {
2042 Assert(UserCall
->getArgOperand(0) == &Call
,
2043 "gc.relocate connected to wrong gc.statepoint", Call
, UserCall
);
2047 // Note: It is legal for a single derived pointer to be listed multiple
2048 // times. It's non-optimal, but it is legal. It can also happen after
2049 // insertion if we strip a bitcast away.
2050 // Note: It is really tempting to check that each base is relocated and
2051 // that a derived pointer is never reused as a base pointer. This turns
2052 // out to be problematic since optimizations run after safepoint insertion
2053 // can recognize equality properties that the insertion logic doesn't know
2054 // about. See example statepoint.ll in the verifier subdirectory
2057 void Verifier::verifyFrameRecoverIndices() {
2058 for (auto &Counts
: FrameEscapeInfo
) {
2059 Function
*F
= Counts
.first
;
2060 unsigned EscapedObjectCount
= Counts
.second
.first
;
2061 unsigned MaxRecoveredIndex
= Counts
.second
.second
;
2062 Assert(MaxRecoveredIndex
<= EscapedObjectCount
,
2063 "all indices passed to llvm.localrecover must be less than the "
2064 "number of arguments passed to llvm.localescape in the parent "
2070 static Instruction
*getSuccPad(Instruction
*Terminator
) {
2071 BasicBlock
*UnwindDest
;
2072 if (auto *II
= dyn_cast
<InvokeInst
>(Terminator
))
2073 UnwindDest
= II
->getUnwindDest();
2074 else if (auto *CSI
= dyn_cast
<CatchSwitchInst
>(Terminator
))
2075 UnwindDest
= CSI
->getUnwindDest();
2077 UnwindDest
= cast
<CleanupReturnInst
>(Terminator
)->getUnwindDest();
2078 return UnwindDest
->getFirstNonPHI();
2081 void Verifier::verifySiblingFuncletUnwinds() {
2082 SmallPtrSet
<Instruction
*, 8> Visited
;
2083 SmallPtrSet
<Instruction
*, 8> Active
;
2084 for (const auto &Pair
: SiblingFuncletInfo
) {
2085 Instruction
*PredPad
= Pair
.first
;
2086 if (Visited
.count(PredPad
))
2088 Active
.insert(PredPad
);
2089 Instruction
*Terminator
= Pair
.second
;
2091 Instruction
*SuccPad
= getSuccPad(Terminator
);
2092 if (Active
.count(SuccPad
)) {
2093 // Found a cycle; report error
2094 Instruction
*CyclePad
= SuccPad
;
2095 SmallVector
<Instruction
*, 8> CycleNodes
;
2097 CycleNodes
.push_back(CyclePad
);
2098 Instruction
*CycleTerminator
= SiblingFuncletInfo
[CyclePad
];
2099 if (CycleTerminator
!= CyclePad
)
2100 CycleNodes
.push_back(CycleTerminator
);
2101 CyclePad
= getSuccPad(CycleTerminator
);
2102 } while (CyclePad
!= SuccPad
);
2103 Assert(false, "EH pads can't handle each other's exceptions",
2104 ArrayRef
<Instruction
*>(CycleNodes
));
2106 // Don't re-walk a node we've already checked
2107 if (!Visited
.insert(SuccPad
).second
)
2109 // Walk to this successor if it has a map entry.
2111 auto TermI
= SiblingFuncletInfo
.find(PredPad
);
2112 if (TermI
== SiblingFuncletInfo
.end())
2114 Terminator
= TermI
->second
;
2115 Active
.insert(PredPad
);
2117 // Each node only has one successor, so we've walked all the active
2118 // nodes' successors.
2123 // visitFunction - Verify that a function is ok.
2125 void Verifier::visitFunction(const Function
&F
) {
2126 visitGlobalValue(F
);
2128 // Check function arguments.
2129 FunctionType
*FT
= F
.getFunctionType();
2130 unsigned NumArgs
= F
.arg_size();
2132 Assert(&Context
== &F
.getContext(),
2133 "Function context does not match Module context!", &F
);
2135 Assert(!F
.hasCommonLinkage(), "Functions may not have common linkage", &F
);
2136 Assert(FT
->getNumParams() == NumArgs
,
2137 "# formal arguments must match # of arguments for function type!", &F
,
2139 Assert(F
.getReturnType()->isFirstClassType() ||
2140 F
.getReturnType()->isVoidTy() || F
.getReturnType()->isStructTy(),
2141 "Functions cannot return aggregate values!", &F
);
2143 Assert(!F
.hasStructRetAttr() || F
.getReturnType()->isVoidTy(),
2144 "Invalid struct return type!", &F
);
2146 AttributeList Attrs
= F
.getAttributes();
2148 Assert(verifyAttributeCount(Attrs
, FT
->getNumParams()),
2149 "Attribute after last parameter!", &F
);
2151 bool isLLVMdotName
= F
.getName().size() >= 5 &&
2152 F
.getName().substr(0, 5) == "llvm.";
2154 // Check function attributes.
2155 verifyFunctionAttrs(FT
, Attrs
, &F
, isLLVMdotName
);
2157 // On function declarations/definitions, we do not support the builtin
2158 // attribute. We do not check this in VerifyFunctionAttrs since that is
2159 // checking for Attributes that can/can not ever be on functions.
2160 Assert(!Attrs
.hasFnAttribute(Attribute::Builtin
),
2161 "Attribute 'builtin' can only be applied to a callsite.", &F
);
2163 // Check that this function meets the restrictions on this calling convention.
2164 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
2165 // restrictions can be lifted.
2166 switch (F
.getCallingConv()) {
2168 case CallingConv::C
:
2170 case CallingConv::AMDGPU_KERNEL
:
2171 case CallingConv::SPIR_KERNEL
:
2172 Assert(F
.getReturnType()->isVoidTy(),
2173 "Calling convention requires void return type", &F
);
2175 case CallingConv::AMDGPU_VS
:
2176 case CallingConv::AMDGPU_HS
:
2177 case CallingConv::AMDGPU_GS
:
2178 case CallingConv::AMDGPU_PS
:
2179 case CallingConv::AMDGPU_CS
:
2180 Assert(!F
.hasStructRetAttr(),
2181 "Calling convention does not allow sret", &F
);
2183 case CallingConv::Fast
:
2184 case CallingConv::Cold
:
2185 case CallingConv::Intel_OCL_BI
:
2186 case CallingConv::PTX_Kernel
:
2187 case CallingConv::PTX_Device
:
2188 Assert(!F
.isVarArg(), "Calling convention does not support varargs or "
2189 "perfect forwarding!",
2194 // Check that the argument values match the function type for this function...
2196 for (const Argument
&Arg
: F
.args()) {
2197 Assert(Arg
.getType() == FT
->getParamType(i
),
2198 "Argument value does not match function argument type!", &Arg
,
2199 FT
->getParamType(i
));
2200 Assert(Arg
.getType()->isFirstClassType(),
2201 "Function arguments must have first-class types!", &Arg
);
2202 if (!isLLVMdotName
) {
2203 Assert(!Arg
.getType()->isMetadataTy(),
2204 "Function takes metadata but isn't an intrinsic", &Arg
, &F
);
2205 Assert(!Arg
.getType()->isTokenTy(),
2206 "Function takes token but isn't an intrinsic", &Arg
, &F
);
2209 // Check that swifterror argument is only used by loads and stores.
2210 if (Attrs
.hasParamAttribute(i
, Attribute::SwiftError
)) {
2211 verifySwiftErrorValue(&Arg
);
2217 Assert(!F
.getReturnType()->isTokenTy(),
2218 "Functions returns a token but isn't an intrinsic", &F
);
2220 // Get the function metadata attachments.
2221 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDs
;
2222 F
.getAllMetadata(MDs
);
2223 assert(F
.hasMetadata() != MDs
.empty() && "Bit out-of-sync");
2224 verifyFunctionMetadata(MDs
);
2226 // Check validity of the personality function
2227 if (F
.hasPersonalityFn()) {
2228 auto *Per
= dyn_cast
<Function
>(F
.getPersonalityFn()->stripPointerCasts());
2230 Assert(Per
->getParent() == F
.getParent(),
2231 "Referencing personality function in another module!",
2232 &F
, F
.getParent(), Per
, Per
->getParent());
2235 if (F
.isMaterializable()) {
2236 // Function has a body somewhere we can't see.
2237 Assert(MDs
.empty(), "unmaterialized function cannot have metadata", &F
,
2238 MDs
.empty() ? nullptr : MDs
.front().second
);
2239 } else if (F
.isDeclaration()) {
2240 for (const auto &I
: MDs
) {
2241 // This is used for call site debug information.
2242 AssertDI(I
.first
!= LLVMContext::MD_dbg
||
2243 !cast
<DISubprogram
>(I
.second
)->isDistinct(),
2244 "function declaration may only have a unique !dbg attachment",
2246 Assert(I
.first
!= LLVMContext::MD_prof
,
2247 "function declaration may not have a !prof attachment", &F
);
2249 // Verify the metadata itself.
2250 visitMDNode(*I
.second
);
2252 Assert(!F
.hasPersonalityFn(),
2253 "Function declaration shouldn't have a personality routine", &F
);
2255 // Verify that this function (which has a body) is not named "llvm.*". It
2256 // is not legal to define intrinsics.
2257 Assert(!isLLVMdotName
, "llvm intrinsics cannot be defined!", &F
);
2259 // Check the entry node
2260 const BasicBlock
*Entry
= &F
.getEntryBlock();
2261 Assert(pred_empty(Entry
),
2262 "Entry block to function must not have predecessors!", Entry
);
2264 // The address of the entry block cannot be taken, unless it is dead.
2265 if (Entry
->hasAddressTaken()) {
2266 Assert(!BlockAddress::lookup(Entry
)->isConstantUsed(),
2267 "blockaddress may not be used with the entry block!", Entry
);
2270 unsigned NumDebugAttachments
= 0, NumProfAttachments
= 0;
2271 // Visit metadata attachments.
2272 for (const auto &I
: MDs
) {
2273 // Verify that the attachment is legal.
2277 case LLVMContext::MD_dbg
: {
2278 ++NumDebugAttachments
;
2279 AssertDI(NumDebugAttachments
== 1,
2280 "function must have a single !dbg attachment", &F
, I
.second
);
2281 AssertDI(isa
<DISubprogram
>(I
.second
),
2282 "function !dbg attachment must be a subprogram", &F
, I
.second
);
2283 auto *SP
= cast
<DISubprogram
>(I
.second
);
2284 const Function
*&AttachedTo
= DISubprogramAttachments
[SP
];
2285 AssertDI(!AttachedTo
|| AttachedTo
== &F
,
2286 "DISubprogram attached to more than one function", SP
, &F
);
2290 case LLVMContext::MD_prof
:
2291 ++NumProfAttachments
;
2292 Assert(NumProfAttachments
== 1,
2293 "function must have a single !prof attachment", &F
, I
.second
);
2297 // Verify the metadata itself.
2298 visitMDNode(*I
.second
);
2302 // If this function is actually an intrinsic, verify that it is only used in
2303 // direct call/invokes, never having its "address taken".
2304 // Only do this if the module is materialized, otherwise we don't have all the
2306 if (F
.getIntrinsicID() && F
.getParent()->isMaterialized()) {
2308 if (F
.hasAddressTaken(&U
))
2309 Assert(false, "Invalid user of intrinsic instruction!", U
);
2312 auto *N
= F
.getSubprogram();
2313 HasDebugInfo
= (N
!= nullptr);
2317 // Check that all !dbg attachments lead to back to N (or, at least, another
2318 // subprogram that describes the same function).
2320 // FIXME: Check this incrementally while visiting !dbg attachments.
2321 // FIXME: Only check when N is the canonical subprogram for F.
2322 SmallPtrSet
<const MDNode
*, 32> Seen
;
2323 auto VisitDebugLoc
= [&](const Instruction
&I
, const MDNode
*Node
) {
2324 // Be careful about using DILocation here since we might be dealing with
2325 // broken code (this is the Verifier after all).
2326 const DILocation
*DL
= dyn_cast_or_null
<DILocation
>(Node
);
2329 if (!Seen
.insert(DL
).second
)
2332 Metadata
*Parent
= DL
->getRawScope();
2333 AssertDI(Parent
&& isa
<DILocalScope
>(Parent
),
2334 "DILocation's scope must be a DILocalScope", N
, &F
, &I
, DL
,
2336 DILocalScope
*Scope
= DL
->getInlinedAtScope();
2337 if (Scope
&& !Seen
.insert(Scope
).second
)
2340 DISubprogram
*SP
= Scope
? Scope
->getSubprogram() : nullptr;
2342 // Scope and SP could be the same MDNode and we don't want to skip
2343 // validation in that case
2344 if (SP
&& ((Scope
!= SP
) && !Seen
.insert(SP
).second
))
2347 // FIXME: Once N is canonical, check "SP == &N".
2348 AssertDI(SP
->describes(&F
),
2349 "!dbg attachment points at wrong subprogram for function", N
, &F
,
2353 for (auto &I
: BB
) {
2354 VisitDebugLoc(I
, I
.getDebugLoc().getAsMDNode());
2355 // The llvm.loop annotations also contain two DILocations.
2356 if (auto MD
= I
.getMetadata(LLVMContext::MD_loop
))
2357 for (unsigned i
= 1; i
< MD
->getNumOperands(); ++i
)
2358 VisitDebugLoc(I
, dyn_cast_or_null
<MDNode
>(MD
->getOperand(i
)));
2359 if (BrokenDebugInfo
)
2364 // verifyBasicBlock - Verify that a basic block is well formed...
2366 void Verifier::visitBasicBlock(BasicBlock
&BB
) {
2367 InstsInThisBlock
.clear();
2369 // Ensure that basic blocks have terminators!
2370 Assert(BB
.getTerminator(), "Basic Block does not have terminator!", &BB
);
2372 // Check constraints that this basic block imposes on all of the PHI nodes in
2374 if (isa
<PHINode
>(BB
.front())) {
2375 SmallVector
<BasicBlock
*, 8> Preds(pred_begin(&BB
), pred_end(&BB
));
2376 SmallVector
<std::pair
<BasicBlock
*, Value
*>, 8> Values
;
2378 for (const PHINode
&PN
: BB
.phis()) {
2379 // Ensure that PHI nodes have at least one entry!
2380 Assert(PN
.getNumIncomingValues() != 0,
2381 "PHI nodes must have at least one entry. If the block is dead, "
2382 "the PHI should be removed!",
2384 Assert(PN
.getNumIncomingValues() == Preds
.size(),
2385 "PHINode should have one entry for each predecessor of its "
2386 "parent basic block!",
2389 // Get and sort all incoming values in the PHI node...
2391 Values
.reserve(PN
.getNumIncomingValues());
2392 for (unsigned i
= 0, e
= PN
.getNumIncomingValues(); i
!= e
; ++i
)
2394 std::make_pair(PN
.getIncomingBlock(i
), PN
.getIncomingValue(i
)));
2397 for (unsigned i
= 0, e
= Values
.size(); i
!= e
; ++i
) {
2398 // Check to make sure that if there is more than one entry for a
2399 // particular basic block in this PHI node, that the incoming values are
2402 Assert(i
== 0 || Values
[i
].first
!= Values
[i
- 1].first
||
2403 Values
[i
].second
== Values
[i
- 1].second
,
2404 "PHI node has multiple entries for the same basic block with "
2405 "different incoming values!",
2406 &PN
, Values
[i
].first
, Values
[i
].second
, Values
[i
- 1].second
);
2408 // Check to make sure that the predecessors and PHI node entries are
2410 Assert(Values
[i
].first
== Preds
[i
],
2411 "PHI node entries do not match predecessors!", &PN
,
2412 Values
[i
].first
, Preds
[i
]);
2417 // Check that all instructions have their parent pointers set up correctly.
2420 Assert(I
.getParent() == &BB
, "Instruction has bogus parent pointer!");
2424 void Verifier::visitTerminator(Instruction
&I
) {
2425 // Ensure that terminators only exist at the end of the basic block.
2426 Assert(&I
== I
.getParent()->getTerminator(),
2427 "Terminator found in the middle of a basic block!", I
.getParent());
2428 visitInstruction(I
);
2431 void Verifier::visitBranchInst(BranchInst
&BI
) {
2432 if (BI
.isConditional()) {
2433 Assert(BI
.getCondition()->getType()->isIntegerTy(1),
2434 "Branch condition is not 'i1' type!", &BI
, BI
.getCondition());
2436 visitTerminator(BI
);
2439 void Verifier::visitReturnInst(ReturnInst
&RI
) {
2440 Function
*F
= RI
.getParent()->getParent();
2441 unsigned N
= RI
.getNumOperands();
2442 if (F
->getReturnType()->isVoidTy())
2444 "Found return instr that returns non-void in Function of void "
2446 &RI
, F
->getReturnType());
2448 Assert(N
== 1 && F
->getReturnType() == RI
.getOperand(0)->getType(),
2449 "Function return type does not match operand "
2450 "type of return inst!",
2451 &RI
, F
->getReturnType());
2453 // Check to make sure that the return value has necessary properties for
2455 visitTerminator(RI
);
2458 void Verifier::visitSwitchInst(SwitchInst
&SI
) {
2459 // Check to make sure that all of the constants in the switch instruction
2460 // have the same type as the switched-on value.
2461 Type
*SwitchTy
= SI
.getCondition()->getType();
2462 SmallPtrSet
<ConstantInt
*, 32> Constants
;
2463 for (auto &Case
: SI
.cases()) {
2464 Assert(Case
.getCaseValue()->getType() == SwitchTy
,
2465 "Switch constants must all be same type as switch value!", &SI
);
2466 Assert(Constants
.insert(Case
.getCaseValue()).second
,
2467 "Duplicate integer as switch case", &SI
, Case
.getCaseValue());
2470 visitTerminator(SI
);
2473 void Verifier::visitIndirectBrInst(IndirectBrInst
&BI
) {
2474 Assert(BI
.getAddress()->getType()->isPointerTy(),
2475 "Indirectbr operand must have pointer type!", &BI
);
2476 for (unsigned i
= 0, e
= BI
.getNumDestinations(); i
!= e
; ++i
)
2477 Assert(BI
.getDestination(i
)->getType()->isLabelTy(),
2478 "Indirectbr destinations must all have pointer type!", &BI
);
2480 visitTerminator(BI
);
2483 void Verifier::visitCallBrInst(CallBrInst
&CBI
) {
2484 Assert(CBI
.isInlineAsm(), "Callbr is currently only used for asm-goto!",
2486 Assert(CBI
.getType()->isVoidTy(), "Callbr return value is not supported!",
2488 for (unsigned i
= 0, e
= CBI
.getNumSuccessors(); i
!= e
; ++i
)
2489 Assert(CBI
.getSuccessor(i
)->getType()->isLabelTy(),
2490 "Callbr successors must all have pointer type!", &CBI
);
2491 for (unsigned i
= 0, e
= CBI
.getNumOperands(); i
!= e
; ++i
) {
2492 Assert(i
>= CBI
.getNumArgOperands() || !isa
<BasicBlock
>(CBI
.getOperand(i
)),
2493 "Using an unescaped label as a callbr argument!", &CBI
);
2494 if (isa
<BasicBlock
>(CBI
.getOperand(i
)))
2495 for (unsigned j
= i
+ 1; j
!= e
; ++j
)
2496 Assert(CBI
.getOperand(i
) != CBI
.getOperand(j
),
2497 "Duplicate callbr destination!", &CBI
);
2500 visitTerminator(CBI
);
2503 void Verifier::visitSelectInst(SelectInst
&SI
) {
2504 Assert(!SelectInst::areInvalidOperands(SI
.getOperand(0), SI
.getOperand(1),
2506 "Invalid operands for select instruction!", &SI
);
2508 Assert(SI
.getTrueValue()->getType() == SI
.getType(),
2509 "Select values must have same type as select instruction!", &SI
);
2510 visitInstruction(SI
);
2513 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
2514 /// a pass, if any exist, it's an error.
2516 void Verifier::visitUserOp1(Instruction
&I
) {
2517 Assert(false, "User-defined operators should not live outside of a pass!", &I
);
2520 void Verifier::visitTruncInst(TruncInst
&I
) {
2521 // Get the source and destination types
2522 Type
*SrcTy
= I
.getOperand(0)->getType();
2523 Type
*DestTy
= I
.getType();
2525 // Get the size of the types in bits, we'll need this later
2526 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
2527 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
2529 Assert(SrcTy
->isIntOrIntVectorTy(), "Trunc only operates on integer", &I
);
2530 Assert(DestTy
->isIntOrIntVectorTy(), "Trunc only produces integer", &I
);
2531 Assert(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
2532 "trunc source and destination must both be a vector or neither", &I
);
2533 Assert(SrcBitSize
> DestBitSize
, "DestTy too big for Trunc", &I
);
2535 visitInstruction(I
);
2538 void Verifier::visitZExtInst(ZExtInst
&I
) {
2539 // Get the source and destination types
2540 Type
*SrcTy
= I
.getOperand(0)->getType();
2541 Type
*DestTy
= I
.getType();
2543 // Get the size of the types in bits, we'll need this later
2544 Assert(SrcTy
->isIntOrIntVectorTy(), "ZExt only operates on integer", &I
);
2545 Assert(DestTy
->isIntOrIntVectorTy(), "ZExt only produces an integer", &I
);
2546 Assert(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
2547 "zext source and destination must both be a vector or neither", &I
);
2548 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
2549 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
2551 Assert(SrcBitSize
< DestBitSize
, "Type too small for ZExt", &I
);
2553 visitInstruction(I
);
2556 void Verifier::visitSExtInst(SExtInst
&I
) {
2557 // Get the source and destination types
2558 Type
*SrcTy
= I
.getOperand(0)->getType();
2559 Type
*DestTy
= I
.getType();
2561 // Get the size of the types in bits, we'll need this later
2562 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
2563 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
2565 Assert(SrcTy
->isIntOrIntVectorTy(), "SExt only operates on integer", &I
);
2566 Assert(DestTy
->isIntOrIntVectorTy(), "SExt only produces an integer", &I
);
2567 Assert(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
2568 "sext source and destination must both be a vector or neither", &I
);
2569 Assert(SrcBitSize
< DestBitSize
, "Type too small for SExt", &I
);
2571 visitInstruction(I
);
2574 void Verifier::visitFPTruncInst(FPTruncInst
&I
) {
2575 // Get the source and destination types
2576 Type
*SrcTy
= I
.getOperand(0)->getType();
2577 Type
*DestTy
= I
.getType();
2578 // Get the size of the types in bits, we'll need this later
2579 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
2580 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
2582 Assert(SrcTy
->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I
);
2583 Assert(DestTy
->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I
);
2584 Assert(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
2585 "fptrunc source and destination must both be a vector or neither", &I
);
2586 Assert(SrcBitSize
> DestBitSize
, "DestTy too big for FPTrunc", &I
);
2588 visitInstruction(I
);
2591 void Verifier::visitFPExtInst(FPExtInst
&I
) {
2592 // Get the source and destination types
2593 Type
*SrcTy
= I
.getOperand(0)->getType();
2594 Type
*DestTy
= I
.getType();
2596 // Get the size of the types in bits, we'll need this later
2597 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
2598 unsigned DestBitSize
= DestTy
->getScalarSizeInBits();
2600 Assert(SrcTy
->isFPOrFPVectorTy(), "FPExt only operates on FP", &I
);
2601 Assert(DestTy
->isFPOrFPVectorTy(), "FPExt only produces an FP", &I
);
2602 Assert(SrcTy
->isVectorTy() == DestTy
->isVectorTy(),
2603 "fpext source and destination must both be a vector or neither", &I
);
2604 Assert(SrcBitSize
< DestBitSize
, "DestTy too small for FPExt", &I
);
2606 visitInstruction(I
);
2609 void Verifier::visitUIToFPInst(UIToFPInst
&I
) {
2610 // Get the source and destination types
2611 Type
*SrcTy
= I
.getOperand(0)->getType();
2612 Type
*DestTy
= I
.getType();
2614 bool SrcVec
= SrcTy
->isVectorTy();
2615 bool DstVec
= DestTy
->isVectorTy();
2617 Assert(SrcVec
== DstVec
,
2618 "UIToFP source and dest must both be vector or scalar", &I
);
2619 Assert(SrcTy
->isIntOrIntVectorTy(),
2620 "UIToFP source must be integer or integer vector", &I
);
2621 Assert(DestTy
->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
2624 if (SrcVec
&& DstVec
)
2625 Assert(cast
<VectorType
>(SrcTy
)->getNumElements() ==
2626 cast
<VectorType
>(DestTy
)->getNumElements(),
2627 "UIToFP source and dest vector length mismatch", &I
);
2629 visitInstruction(I
);
2632 void Verifier::visitSIToFPInst(SIToFPInst
&I
) {
2633 // Get the source and destination types
2634 Type
*SrcTy
= I
.getOperand(0)->getType();
2635 Type
*DestTy
= I
.getType();
2637 bool SrcVec
= SrcTy
->isVectorTy();
2638 bool DstVec
= DestTy
->isVectorTy();
2640 Assert(SrcVec
== DstVec
,
2641 "SIToFP source and dest must both be vector or scalar", &I
);
2642 Assert(SrcTy
->isIntOrIntVectorTy(),
2643 "SIToFP source must be integer or integer vector", &I
);
2644 Assert(DestTy
->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
2647 if (SrcVec
&& DstVec
)
2648 Assert(cast
<VectorType
>(SrcTy
)->getNumElements() ==
2649 cast
<VectorType
>(DestTy
)->getNumElements(),
2650 "SIToFP source and dest vector length mismatch", &I
);
2652 visitInstruction(I
);
2655 void Verifier::visitFPToUIInst(FPToUIInst
&I
) {
2656 // Get the source and destination types
2657 Type
*SrcTy
= I
.getOperand(0)->getType();
2658 Type
*DestTy
= I
.getType();
2660 bool SrcVec
= SrcTy
->isVectorTy();
2661 bool DstVec
= DestTy
->isVectorTy();
2663 Assert(SrcVec
== DstVec
,
2664 "FPToUI source and dest must both be vector or scalar", &I
);
2665 Assert(SrcTy
->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
2667 Assert(DestTy
->isIntOrIntVectorTy(),
2668 "FPToUI result must be integer or integer vector", &I
);
2670 if (SrcVec
&& DstVec
)
2671 Assert(cast
<VectorType
>(SrcTy
)->getNumElements() ==
2672 cast
<VectorType
>(DestTy
)->getNumElements(),
2673 "FPToUI source and dest vector length mismatch", &I
);
2675 visitInstruction(I
);
2678 void Verifier::visitFPToSIInst(FPToSIInst
&I
) {
2679 // Get the source and destination types
2680 Type
*SrcTy
= I
.getOperand(0)->getType();
2681 Type
*DestTy
= I
.getType();
2683 bool SrcVec
= SrcTy
->isVectorTy();
2684 bool DstVec
= DestTy
->isVectorTy();
2686 Assert(SrcVec
== DstVec
,
2687 "FPToSI source and dest must both be vector or scalar", &I
);
2688 Assert(SrcTy
->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
2690 Assert(DestTy
->isIntOrIntVectorTy(),
2691 "FPToSI result must be integer or integer vector", &I
);
2693 if (SrcVec
&& DstVec
)
2694 Assert(cast
<VectorType
>(SrcTy
)->getNumElements() ==
2695 cast
<VectorType
>(DestTy
)->getNumElements(),
2696 "FPToSI source and dest vector length mismatch", &I
);
2698 visitInstruction(I
);
2701 void Verifier::visitPtrToIntInst(PtrToIntInst
&I
) {
2702 // Get the source and destination types
2703 Type
*SrcTy
= I
.getOperand(0)->getType();
2704 Type
*DestTy
= I
.getType();
2706 Assert(SrcTy
->isPtrOrPtrVectorTy(), "PtrToInt source must be pointer", &I
);
2708 if (auto *PTy
= dyn_cast
<PointerType
>(SrcTy
->getScalarType()))
2709 Assert(!DL
.isNonIntegralPointerType(PTy
),
2710 "ptrtoint not supported for non-integral pointers");
2712 Assert(DestTy
->isIntOrIntVectorTy(), "PtrToInt result must be integral", &I
);
2713 Assert(SrcTy
->isVectorTy() == DestTy
->isVectorTy(), "PtrToInt type mismatch",
2716 if (SrcTy
->isVectorTy()) {
2717 VectorType
*VSrc
= dyn_cast
<VectorType
>(SrcTy
);
2718 VectorType
*VDest
= dyn_cast
<VectorType
>(DestTy
);
2719 Assert(VSrc
->getNumElements() == VDest
->getNumElements(),
2720 "PtrToInt Vector width mismatch", &I
);
2723 visitInstruction(I
);
2726 void Verifier::visitIntToPtrInst(IntToPtrInst
&I
) {
2727 // Get the source and destination types
2728 Type
*SrcTy
= I
.getOperand(0)->getType();
2729 Type
*DestTy
= I
.getType();
2731 Assert(SrcTy
->isIntOrIntVectorTy(),
2732 "IntToPtr source must be an integral", &I
);
2733 Assert(DestTy
->isPtrOrPtrVectorTy(), "IntToPtr result must be a pointer", &I
);
2735 if (auto *PTy
= dyn_cast
<PointerType
>(DestTy
->getScalarType()))
2736 Assert(!DL
.isNonIntegralPointerType(PTy
),
2737 "inttoptr not supported for non-integral pointers");
2739 Assert(SrcTy
->isVectorTy() == DestTy
->isVectorTy(), "IntToPtr type mismatch",
2741 if (SrcTy
->isVectorTy()) {
2742 VectorType
*VSrc
= dyn_cast
<VectorType
>(SrcTy
);
2743 VectorType
*VDest
= dyn_cast
<VectorType
>(DestTy
);
2744 Assert(VSrc
->getNumElements() == VDest
->getNumElements(),
2745 "IntToPtr Vector width mismatch", &I
);
2747 visitInstruction(I
);
2750 void Verifier::visitBitCastInst(BitCastInst
&I
) {
2752 CastInst::castIsValid(Instruction::BitCast
, I
.getOperand(0), I
.getType()),
2753 "Invalid bitcast", &I
);
2754 visitInstruction(I
);
2757 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst
&I
) {
2758 Type
*SrcTy
= I
.getOperand(0)->getType();
2759 Type
*DestTy
= I
.getType();
2761 Assert(SrcTy
->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
2763 Assert(DestTy
->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
2765 Assert(SrcTy
->getPointerAddressSpace() != DestTy
->getPointerAddressSpace(),
2766 "AddrSpaceCast must be between different address spaces", &I
);
2767 if (SrcTy
->isVectorTy())
2768 Assert(SrcTy
->getVectorNumElements() == DestTy
->getVectorNumElements(),
2769 "AddrSpaceCast vector pointer number of elements mismatch", &I
);
2770 visitInstruction(I
);
2773 /// visitPHINode - Ensure that a PHI node is well formed.
2775 void Verifier::visitPHINode(PHINode
&PN
) {
2776 // Ensure that the PHI nodes are all grouped together at the top of the block.
2777 // This can be tested by checking whether the instruction before this is
2778 // either nonexistent (because this is begin()) or is a PHI node. If not,
2779 // then there is some other instruction before a PHI.
2780 Assert(&PN
== &PN
.getParent()->front() ||
2781 isa
<PHINode
>(--BasicBlock::iterator(&PN
)),
2782 "PHI nodes not grouped at top of basic block!", &PN
, PN
.getParent());
2784 // Check that a PHI doesn't yield a Token.
2785 Assert(!PN
.getType()->isTokenTy(), "PHI nodes cannot have token type!");
2787 // Check that all of the values of the PHI node have the same type as the
2788 // result, and that the incoming blocks are really basic blocks.
2789 for (Value
*IncValue
: PN
.incoming_values()) {
2790 Assert(PN
.getType() == IncValue
->getType(),
2791 "PHI node operands are not the same type as the result!", &PN
);
2794 // All other PHI node constraints are checked in the visitBasicBlock method.
2796 visitInstruction(PN
);
2799 void Verifier::visitCallBase(CallBase
&Call
) {
2800 Assert(Call
.getCalledValue()->getType()->isPointerTy(),
2801 "Called function must be a pointer!", Call
);
2802 PointerType
*FPTy
= cast
<PointerType
>(Call
.getCalledValue()->getType());
2804 Assert(FPTy
->getElementType()->isFunctionTy(),
2805 "Called function is not pointer to function type!", Call
);
2807 Assert(FPTy
->getElementType() == Call
.getFunctionType(),
2808 "Called function is not the same type as the call!", Call
);
2810 FunctionType
*FTy
= Call
.getFunctionType();
2812 // Verify that the correct number of arguments are being passed
2813 if (FTy
->isVarArg())
2814 Assert(Call
.arg_size() >= FTy
->getNumParams(),
2815 "Called function requires more parameters than were provided!",
2818 Assert(Call
.arg_size() == FTy
->getNumParams(),
2819 "Incorrect number of arguments passed to called function!", Call
);
2821 // Verify that all arguments to the call match the function type.
2822 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
)
2823 Assert(Call
.getArgOperand(i
)->getType() == FTy
->getParamType(i
),
2824 "Call parameter type does not match function signature!",
2825 Call
.getArgOperand(i
), FTy
->getParamType(i
), Call
);
2827 AttributeList Attrs
= Call
.getAttributes();
2829 Assert(verifyAttributeCount(Attrs
, Call
.arg_size()),
2830 "Attribute after last parameter!", Call
);
2832 bool IsIntrinsic
= Call
.getCalledFunction() &&
2833 Call
.getCalledFunction()->getName().startswith("llvm.");
2836 = dyn_cast
<Function
>(Call
.getCalledValue()->stripPointerCasts());
2838 if (Attrs
.hasAttribute(AttributeList::FunctionIndex
, Attribute::Speculatable
)) {
2839 // Don't allow speculatable on call sites, unless the underlying function
2840 // declaration is also speculatable.
2841 Assert(Callee
&& Callee
->isSpeculatable(),
2842 "speculatable attribute may not apply to call sites", Call
);
2845 // Verify call attributes.
2846 verifyFunctionAttrs(FTy
, Attrs
, &Call
, IsIntrinsic
);
2848 // Conservatively check the inalloca argument.
2849 // We have a bug if we can find that there is an underlying alloca without
2851 if (Call
.hasInAllocaArgument()) {
2852 Value
*InAllocaArg
= Call
.getArgOperand(FTy
->getNumParams() - 1);
2853 if (auto AI
= dyn_cast
<AllocaInst
>(InAllocaArg
->stripInBoundsOffsets()))
2854 Assert(AI
->isUsedWithInAlloca(),
2855 "inalloca argument for call has mismatched alloca", AI
, Call
);
2858 // For each argument of the callsite, if it has the swifterror argument,
2859 // make sure the underlying alloca/parameter it comes from has a swifterror as
2861 for (unsigned i
= 0, e
= FTy
->getNumParams(); i
!= e
; ++i
) {
2862 if (Call
.paramHasAttr(i
, Attribute::SwiftError
)) {
2863 Value
*SwiftErrorArg
= Call
.getArgOperand(i
);
2864 if (auto AI
= dyn_cast
<AllocaInst
>(SwiftErrorArg
->stripInBoundsOffsets())) {
2865 Assert(AI
->isSwiftError(),
2866 "swifterror argument for call has mismatched alloca", AI
, Call
);
2869 auto ArgI
= dyn_cast
<Argument
>(SwiftErrorArg
);
2871 "swifterror argument should come from an alloca or parameter",
2872 SwiftErrorArg
, Call
);
2873 Assert(ArgI
->hasSwiftErrorAttr(),
2874 "swifterror argument for call has mismatched parameter", ArgI
,
2878 if (Attrs
.hasParamAttribute(i
, Attribute::ImmArg
)) {
2879 // Don't allow immarg on call sites, unless the underlying declaration
2880 // also has the matching immarg.
2881 Assert(Callee
&& Callee
->hasParamAttribute(i
, Attribute::ImmArg
),
2882 "immarg may not apply only to call sites",
2883 Call
.getArgOperand(i
), Call
);
2886 if (Call
.paramHasAttr(i
, Attribute::ImmArg
)) {
2887 Value
*ArgVal
= Call
.getArgOperand(i
);
2888 Assert(isa
<ConstantInt
>(ArgVal
) || isa
<ConstantFP
>(ArgVal
),
2889 "immarg operand has non-immediate parameter", ArgVal
, Call
);
2893 if (FTy
->isVarArg()) {
2894 // FIXME? is 'nest' even legal here?
2895 bool SawNest
= false;
2896 bool SawReturned
= false;
2898 for (unsigned Idx
= 0; Idx
< FTy
->getNumParams(); ++Idx
) {
2899 if (Attrs
.hasParamAttribute(Idx
, Attribute::Nest
))
2901 if (Attrs
.hasParamAttribute(Idx
, Attribute::Returned
))
2905 // Check attributes on the varargs part.
2906 for (unsigned Idx
= FTy
->getNumParams(); Idx
< Call
.arg_size(); ++Idx
) {
2907 Type
*Ty
= Call
.getArgOperand(Idx
)->getType();
2908 AttributeSet ArgAttrs
= Attrs
.getParamAttributes(Idx
);
2909 verifyParameterAttrs(ArgAttrs
, Ty
, &Call
);
2911 if (ArgAttrs
.hasAttribute(Attribute::Nest
)) {
2912 Assert(!SawNest
, "More than one parameter has attribute nest!", Call
);
2916 if (ArgAttrs
.hasAttribute(Attribute::Returned
)) {
2917 Assert(!SawReturned
, "More than one parameter has attribute returned!",
2919 Assert(Ty
->canLosslesslyBitCastTo(FTy
->getReturnType()),
2920 "Incompatible argument and return types for 'returned' "
2926 // Statepoint intrinsic is vararg but the wrapped function may be not.
2927 // Allow sret here and check the wrapped function in verifyStatepoint.
2928 if (!Call
.getCalledFunction() ||
2929 Call
.getCalledFunction()->getIntrinsicID() !=
2930 Intrinsic::experimental_gc_statepoint
)
2931 Assert(!ArgAttrs
.hasAttribute(Attribute::StructRet
),
2932 "Attribute 'sret' cannot be used for vararg call arguments!",
2935 if (ArgAttrs
.hasAttribute(Attribute::InAlloca
))
2936 Assert(Idx
== Call
.arg_size() - 1,
2937 "inalloca isn't on the last argument!", Call
);
2941 // Verify that there's no metadata unless it's a direct call to an intrinsic.
2943 for (Type
*ParamTy
: FTy
->params()) {
2944 Assert(!ParamTy
->isMetadataTy(),
2945 "Function has metadata parameter but isn't an intrinsic", Call
);
2946 Assert(!ParamTy
->isTokenTy(),
2947 "Function has token parameter but isn't an intrinsic", Call
);
2951 // Verify that indirect calls don't return tokens.
2952 if (!Call
.getCalledFunction())
2953 Assert(!FTy
->getReturnType()->isTokenTy(),
2954 "Return type cannot be token for indirect call!");
2956 if (Function
*F
= Call
.getCalledFunction())
2957 if (Intrinsic::ID ID
= (Intrinsic::ID
)F
->getIntrinsicID())
2958 visitIntrinsicCall(ID
, Call
);
2960 // Verify that a callsite has at most one "deopt", at most one "funclet" and
2961 // at most one "gc-transition" operand bundle.
2962 bool FoundDeoptBundle
= false, FoundFuncletBundle
= false,
2963 FoundGCTransitionBundle
= false;
2964 for (unsigned i
= 0, e
= Call
.getNumOperandBundles(); i
< e
; ++i
) {
2965 OperandBundleUse BU
= Call
.getOperandBundleAt(i
);
2966 uint32_t Tag
= BU
.getTagID();
2967 if (Tag
== LLVMContext::OB_deopt
) {
2968 Assert(!FoundDeoptBundle
, "Multiple deopt operand bundles", Call
);
2969 FoundDeoptBundle
= true;
2970 } else if (Tag
== LLVMContext::OB_gc_transition
) {
2971 Assert(!FoundGCTransitionBundle
, "Multiple gc-transition operand bundles",
2973 FoundGCTransitionBundle
= true;
2974 } else if (Tag
== LLVMContext::OB_funclet
) {
2975 Assert(!FoundFuncletBundle
, "Multiple funclet operand bundles", Call
);
2976 FoundFuncletBundle
= true;
2977 Assert(BU
.Inputs
.size() == 1,
2978 "Expected exactly one funclet bundle operand", Call
);
2979 Assert(isa
<FuncletPadInst
>(BU
.Inputs
.front()),
2980 "Funclet bundle operands should correspond to a FuncletPadInst",
2985 // Verify that each inlinable callsite of a debug-info-bearing function in a
2986 // debug-info-bearing function has a debug location attached to it. Failure to
2987 // do so causes assertion failures when the inliner sets up inline scope info.
2988 if (Call
.getFunction()->getSubprogram() && Call
.getCalledFunction() &&
2989 Call
.getCalledFunction()->getSubprogram())
2990 AssertDI(Call
.getDebugLoc(),
2991 "inlinable function call in a function with "
2992 "debug info must have a !dbg location",
2995 visitInstruction(Call
);
2998 /// Two types are "congruent" if they are identical, or if they are both pointer
2999 /// types with different pointee types and the same address space.
3000 static bool isTypeCongruent(Type
*L
, Type
*R
) {
3003 PointerType
*PL
= dyn_cast
<PointerType
>(L
);
3004 PointerType
*PR
= dyn_cast
<PointerType
>(R
);
3007 return PL
->getAddressSpace() == PR
->getAddressSpace();
3010 static AttrBuilder
getParameterABIAttributes(int I
, AttributeList Attrs
) {
3011 static const Attribute::AttrKind ABIAttrs
[] = {
3012 Attribute::StructRet
, Attribute::ByVal
, Attribute::InAlloca
,
3013 Attribute::InReg
, Attribute::Returned
, Attribute::SwiftSelf
,
3014 Attribute::SwiftError
};
3016 for (auto AK
: ABIAttrs
) {
3017 if (Attrs
.hasParamAttribute(I
, AK
))
3018 Copy
.addAttribute(AK
);
3020 if (Attrs
.hasParamAttribute(I
, Attribute::Alignment
))
3021 Copy
.addAlignmentAttr(Attrs
.getParamAlignment(I
));
3025 void Verifier::verifyMustTailCall(CallInst
&CI
) {
3026 Assert(!CI
.isInlineAsm(), "cannot use musttail call with inline asm", &CI
);
3028 // - The caller and callee prototypes must match. Pointer types of
3029 // parameters or return types may differ in pointee type, but not
3031 Function
*F
= CI
.getParent()->getParent();
3032 FunctionType
*CallerTy
= F
->getFunctionType();
3033 FunctionType
*CalleeTy
= CI
.getFunctionType();
3034 if (!CI
.getCalledFunction() || !CI
.getCalledFunction()->isIntrinsic()) {
3035 Assert(CallerTy
->getNumParams() == CalleeTy
->getNumParams(),
3036 "cannot guarantee tail call due to mismatched parameter counts",
3038 for (int I
= 0, E
= CallerTy
->getNumParams(); I
!= E
; ++I
) {
3040 isTypeCongruent(CallerTy
->getParamType(I
), CalleeTy
->getParamType(I
)),
3041 "cannot guarantee tail call due to mismatched parameter types", &CI
);
3044 Assert(CallerTy
->isVarArg() == CalleeTy
->isVarArg(),
3045 "cannot guarantee tail call due to mismatched varargs", &CI
);
3046 Assert(isTypeCongruent(CallerTy
->getReturnType(), CalleeTy
->getReturnType()),
3047 "cannot guarantee tail call due to mismatched return types", &CI
);
3049 // - The calling conventions of the caller and callee must match.
3050 Assert(F
->getCallingConv() == CI
.getCallingConv(),
3051 "cannot guarantee tail call due to mismatched calling conv", &CI
);
3053 // - All ABI-impacting function attributes, such as sret, byval, inreg,
3054 // returned, and inalloca, must match.
3055 AttributeList CallerAttrs
= F
->getAttributes();
3056 AttributeList CalleeAttrs
= CI
.getAttributes();
3057 for (int I
= 0, E
= CallerTy
->getNumParams(); I
!= E
; ++I
) {
3058 AttrBuilder CallerABIAttrs
= getParameterABIAttributes(I
, CallerAttrs
);
3059 AttrBuilder CalleeABIAttrs
= getParameterABIAttributes(I
, CalleeAttrs
);
3060 Assert(CallerABIAttrs
== CalleeABIAttrs
,
3061 "cannot guarantee tail call due to mismatched ABI impacting "
3062 "function attributes",
3063 &CI
, CI
.getOperand(I
));
3066 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
3067 // or a pointer bitcast followed by a ret instruction.
3068 // - The ret instruction must return the (possibly bitcasted) value
3069 // produced by the call or void.
3070 Value
*RetVal
= &CI
;
3071 Instruction
*Next
= CI
.getNextNode();
3073 // Handle the optional bitcast.
3074 if (BitCastInst
*BI
= dyn_cast_or_null
<BitCastInst
>(Next
)) {
3075 Assert(BI
->getOperand(0) == RetVal
,
3076 "bitcast following musttail call must use the call", BI
);
3078 Next
= BI
->getNextNode();
3081 // Check the return.
3082 ReturnInst
*Ret
= dyn_cast_or_null
<ReturnInst
>(Next
);
3083 Assert(Ret
, "musttail call must precede a ret with an optional bitcast",
3085 Assert(!Ret
->getReturnValue() || Ret
->getReturnValue() == RetVal
,
3086 "musttail call result must be returned", Ret
);
3089 void Verifier::visitCallInst(CallInst
&CI
) {
3092 if (CI
.isMustTailCall())
3093 verifyMustTailCall(CI
);
3096 void Verifier::visitInvokeInst(InvokeInst
&II
) {
3099 // Verify that the first non-PHI instruction of the unwind destination is an
3100 // exception handling instruction.
3102 II
.getUnwindDest()->isEHPad(),
3103 "The unwind destination does not have an exception handling instruction!",
3106 visitTerminator(II
);
3109 /// visitUnaryOperator - Check the argument to the unary operator.
3111 void Verifier::visitUnaryOperator(UnaryOperator
&U
) {
3112 Assert(U
.getType() == U
.getOperand(0)->getType(),
3113 "Unary operators must have same type for"
3114 "operands and result!",
3117 switch (U
.getOpcode()) {
3118 // Check that floating-point arithmetic operators are only used with
3119 // floating-point operands.
3120 case Instruction::FNeg
:
3121 Assert(U
.getType()->isFPOrFPVectorTy(),
3122 "FNeg operator only works with float types!", &U
);
3125 llvm_unreachable("Unknown UnaryOperator opcode!");
3128 visitInstruction(U
);
3131 /// visitBinaryOperator - Check that both arguments to the binary operator are
3132 /// of the same type!
3134 void Verifier::visitBinaryOperator(BinaryOperator
&B
) {
3135 Assert(B
.getOperand(0)->getType() == B
.getOperand(1)->getType(),
3136 "Both operands to a binary operator are not of the same type!", &B
);
3138 switch (B
.getOpcode()) {
3139 // Check that integer arithmetic operators are only used with
3140 // integral operands.
3141 case Instruction::Add
:
3142 case Instruction::Sub
:
3143 case Instruction::Mul
:
3144 case Instruction::SDiv
:
3145 case Instruction::UDiv
:
3146 case Instruction::SRem
:
3147 case Instruction::URem
:
3148 Assert(B
.getType()->isIntOrIntVectorTy(),
3149 "Integer arithmetic operators only work with integral types!", &B
);
3150 Assert(B
.getType() == B
.getOperand(0)->getType(),
3151 "Integer arithmetic operators must have same type "
3152 "for operands and result!",
3155 // Check that floating-point arithmetic operators are only used with
3156 // floating-point operands.
3157 case Instruction::FAdd
:
3158 case Instruction::FSub
:
3159 case Instruction::FMul
:
3160 case Instruction::FDiv
:
3161 case Instruction::FRem
:
3162 Assert(B
.getType()->isFPOrFPVectorTy(),
3163 "Floating-point arithmetic operators only work with "
3164 "floating-point types!",
3166 Assert(B
.getType() == B
.getOperand(0)->getType(),
3167 "Floating-point arithmetic operators must have same type "
3168 "for operands and result!",
3171 // Check that logical operators are only used with integral operands.
3172 case Instruction::And
:
3173 case Instruction::Or
:
3174 case Instruction::Xor
:
3175 Assert(B
.getType()->isIntOrIntVectorTy(),
3176 "Logical operators only work with integral types!", &B
);
3177 Assert(B
.getType() == B
.getOperand(0)->getType(),
3178 "Logical operators must have same type for operands and result!",
3181 case Instruction::Shl
:
3182 case Instruction::LShr
:
3183 case Instruction::AShr
:
3184 Assert(B
.getType()->isIntOrIntVectorTy(),
3185 "Shifts only work with integral types!", &B
);
3186 Assert(B
.getType() == B
.getOperand(0)->getType(),
3187 "Shift return type must be same as operands!", &B
);
3190 llvm_unreachable("Unknown BinaryOperator opcode!");
3193 visitInstruction(B
);
3196 void Verifier::visitICmpInst(ICmpInst
&IC
) {
3197 // Check that the operands are the same type
3198 Type
*Op0Ty
= IC
.getOperand(0)->getType();
3199 Type
*Op1Ty
= IC
.getOperand(1)->getType();
3200 Assert(Op0Ty
== Op1Ty
,
3201 "Both operands to ICmp instruction are not of the same type!", &IC
);
3202 // Check that the operands are the right type
3203 Assert(Op0Ty
->isIntOrIntVectorTy() || Op0Ty
->isPtrOrPtrVectorTy(),
3204 "Invalid operand types for ICmp instruction", &IC
);
3205 // Check that the predicate is valid.
3206 Assert(IC
.isIntPredicate(),
3207 "Invalid predicate in ICmp instruction!", &IC
);
3209 visitInstruction(IC
);
3212 void Verifier::visitFCmpInst(FCmpInst
&FC
) {
3213 // Check that the operands are the same type
3214 Type
*Op0Ty
= FC
.getOperand(0)->getType();
3215 Type
*Op1Ty
= FC
.getOperand(1)->getType();
3216 Assert(Op0Ty
== Op1Ty
,
3217 "Both operands to FCmp instruction are not of the same type!", &FC
);
3218 // Check that the operands are the right type
3219 Assert(Op0Ty
->isFPOrFPVectorTy(),
3220 "Invalid operand types for FCmp instruction", &FC
);
3221 // Check that the predicate is valid.
3222 Assert(FC
.isFPPredicate(),
3223 "Invalid predicate in FCmp instruction!", &FC
);
3225 visitInstruction(FC
);
3228 void Verifier::visitExtractElementInst(ExtractElementInst
&EI
) {
3230 ExtractElementInst::isValidOperands(EI
.getOperand(0), EI
.getOperand(1)),
3231 "Invalid extractelement operands!", &EI
);
3232 visitInstruction(EI
);
3235 void Verifier::visitInsertElementInst(InsertElementInst
&IE
) {
3236 Assert(InsertElementInst::isValidOperands(IE
.getOperand(0), IE
.getOperand(1),
3238 "Invalid insertelement operands!", &IE
);
3239 visitInstruction(IE
);
3242 void Verifier::visitShuffleVectorInst(ShuffleVectorInst
&SV
) {
3243 Assert(ShuffleVectorInst::isValidOperands(SV
.getOperand(0), SV
.getOperand(1),
3245 "Invalid shufflevector operands!", &SV
);
3246 visitInstruction(SV
);
3249 void Verifier::visitGetElementPtrInst(GetElementPtrInst
&GEP
) {
3250 Type
*TargetTy
= GEP
.getPointerOperandType()->getScalarType();
3252 Assert(isa
<PointerType
>(TargetTy
),
3253 "GEP base pointer is not a vector or a vector of pointers", &GEP
);
3254 Assert(GEP
.getSourceElementType()->isSized(), "GEP into unsized type!", &GEP
);
3256 SmallVector
<Value
*, 16> Idxs(GEP
.idx_begin(), GEP
.idx_end());
3258 Idxs
, [](Value
* V
) { return V
->getType()->isIntOrIntVectorTy(); }),
3259 "GEP indexes must be integers", &GEP
);
3261 GetElementPtrInst::getIndexedType(GEP
.getSourceElementType(), Idxs
);
3262 Assert(ElTy
, "Invalid indices for GEP pointer type!", &GEP
);
3264 Assert(GEP
.getType()->isPtrOrPtrVectorTy() &&
3265 GEP
.getResultElementType() == ElTy
,
3266 "GEP is not of right type for indices!", &GEP
, ElTy
);
3268 if (GEP
.getType()->isVectorTy()) {
3269 // Additional checks for vector GEPs.
3270 unsigned GEPWidth
= GEP
.getType()->getVectorNumElements();
3271 if (GEP
.getPointerOperandType()->isVectorTy())
3272 Assert(GEPWidth
== GEP
.getPointerOperandType()->getVectorNumElements(),
3273 "Vector GEP result width doesn't match operand's", &GEP
);
3274 for (Value
*Idx
: Idxs
) {
3275 Type
*IndexTy
= Idx
->getType();
3276 if (IndexTy
->isVectorTy()) {
3277 unsigned IndexWidth
= IndexTy
->getVectorNumElements();
3278 Assert(IndexWidth
== GEPWidth
, "Invalid GEP index vector width", &GEP
);
3280 Assert(IndexTy
->isIntOrIntVectorTy(),
3281 "All GEP indices should be of integer type");
3285 if (auto *PTy
= dyn_cast
<PointerType
>(GEP
.getType())) {
3286 Assert(GEP
.getAddressSpace() == PTy
->getAddressSpace(),
3287 "GEP address space doesn't match type", &GEP
);
3290 visitInstruction(GEP
);
3293 static bool isContiguous(const ConstantRange
&A
, const ConstantRange
&B
) {
3294 return A
.getUpper() == B
.getLower() || A
.getLower() == B
.getUpper();
3297 void Verifier::visitRangeMetadata(Instruction
&I
, MDNode
*Range
, Type
*Ty
) {
3298 assert(Range
&& Range
== I
.getMetadata(LLVMContext::MD_range
) &&
3299 "precondition violation");
3301 unsigned NumOperands
= Range
->getNumOperands();
3302 Assert(NumOperands
% 2 == 0, "Unfinished range!", Range
);
3303 unsigned NumRanges
= NumOperands
/ 2;
3304 Assert(NumRanges
>= 1, "It should have at least one range!", Range
);
3306 ConstantRange
LastRange(1, true); // Dummy initial value
3307 for (unsigned i
= 0; i
< NumRanges
; ++i
) {
3309 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(2 * i
));
3310 Assert(Low
, "The lower limit must be an integer!", Low
);
3312 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(2 * i
+ 1));
3313 Assert(High
, "The upper limit must be an integer!", High
);
3314 Assert(High
->getType() == Low
->getType() && High
->getType() == Ty
,
3315 "Range types must match instruction type!", &I
);
3317 APInt HighV
= High
->getValue();
3318 APInt LowV
= Low
->getValue();
3319 ConstantRange
CurRange(LowV
, HighV
);
3320 Assert(!CurRange
.isEmptySet() && !CurRange
.isFullSet(),
3321 "Range must not be empty!", Range
);
3323 Assert(CurRange
.intersectWith(LastRange
).isEmptySet(),
3324 "Intervals are overlapping", Range
);
3325 Assert(LowV
.sgt(LastRange
.getLower()), "Intervals are not in order",
3327 Assert(!isContiguous(CurRange
, LastRange
), "Intervals are contiguous",
3330 LastRange
= ConstantRange(LowV
, HighV
);
3332 if (NumRanges
> 2) {
3334 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(0))->getValue();
3336 mdconst::dyn_extract
<ConstantInt
>(Range
->getOperand(1))->getValue();
3337 ConstantRange
FirstRange(FirstLow
, FirstHigh
);
3338 Assert(FirstRange
.intersectWith(LastRange
).isEmptySet(),
3339 "Intervals are overlapping", Range
);
3340 Assert(!isContiguous(FirstRange
, LastRange
), "Intervals are contiguous",
3345 void Verifier::checkAtomicMemAccessSize(Type
*Ty
, const Instruction
*I
) {
3346 unsigned Size
= DL
.getTypeSizeInBits(Ty
);
3347 Assert(Size
>= 8, "atomic memory access' size must be byte-sized", Ty
, I
);
3348 Assert(!(Size
& (Size
- 1)),
3349 "atomic memory access' operand must have a power-of-two size", Ty
, I
);
3352 void Verifier::visitLoadInst(LoadInst
&LI
) {
3353 PointerType
*PTy
= dyn_cast
<PointerType
>(LI
.getOperand(0)->getType());
3354 Assert(PTy
, "Load operand must be a pointer.", &LI
);
3355 Type
*ElTy
= LI
.getType();
3356 Assert(LI
.getAlignment() <= Value::MaximumAlignment
,
3357 "huge alignment values are unsupported", &LI
);
3358 Assert(ElTy
->isSized(), "loading unsized types is not allowed", &LI
);
3359 if (LI
.isAtomic()) {
3360 Assert(LI
.getOrdering() != AtomicOrdering::Release
&&
3361 LI
.getOrdering() != AtomicOrdering::AcquireRelease
,
3362 "Load cannot have Release ordering", &LI
);
3363 Assert(LI
.getAlignment() != 0,
3364 "Atomic load must specify explicit alignment", &LI
);
3365 Assert(ElTy
->isIntOrPtrTy() || ElTy
->isFloatingPointTy(),
3366 "atomic load operand must have integer, pointer, or floating point "
3369 checkAtomicMemAccessSize(ElTy
, &LI
);
3371 Assert(LI
.getSyncScopeID() == SyncScope::System
,
3372 "Non-atomic load cannot have SynchronizationScope specified", &LI
);
3375 visitInstruction(LI
);
3378 void Verifier::visitStoreInst(StoreInst
&SI
) {
3379 PointerType
*PTy
= dyn_cast
<PointerType
>(SI
.getOperand(1)->getType());
3380 Assert(PTy
, "Store operand must be a pointer.", &SI
);
3381 Type
*ElTy
= PTy
->getElementType();
3382 Assert(ElTy
== SI
.getOperand(0)->getType(),
3383 "Stored value type does not match pointer operand type!", &SI
, ElTy
);
3384 Assert(SI
.getAlignment() <= Value::MaximumAlignment
,
3385 "huge alignment values are unsupported", &SI
);
3386 Assert(ElTy
->isSized(), "storing unsized types is not allowed", &SI
);
3387 if (SI
.isAtomic()) {
3388 Assert(SI
.getOrdering() != AtomicOrdering::Acquire
&&
3389 SI
.getOrdering() != AtomicOrdering::AcquireRelease
,
3390 "Store cannot have Acquire ordering", &SI
);
3391 Assert(SI
.getAlignment() != 0,
3392 "Atomic store must specify explicit alignment", &SI
);
3393 Assert(ElTy
->isIntOrPtrTy() || ElTy
->isFloatingPointTy(),
3394 "atomic store operand must have integer, pointer, or floating point "
3397 checkAtomicMemAccessSize(ElTy
, &SI
);
3399 Assert(SI
.getSyncScopeID() == SyncScope::System
,
3400 "Non-atomic store cannot have SynchronizationScope specified", &SI
);
3402 visitInstruction(SI
);
3405 /// Check that SwiftErrorVal is used as a swifterror argument in CS.
3406 void Verifier::verifySwiftErrorCall(CallBase
&Call
,
3407 const Value
*SwiftErrorVal
) {
3409 for (auto I
= Call
.arg_begin(), E
= Call
.arg_end(); I
!= E
; ++I
, ++Idx
) {
3410 if (*I
== SwiftErrorVal
) {
3411 Assert(Call
.paramHasAttr(Idx
, Attribute::SwiftError
),
3412 "swifterror value when used in a callsite should be marked "
3413 "with swifterror attribute",
3414 SwiftErrorVal
, Call
);
3419 void Verifier::verifySwiftErrorValue(const Value
*SwiftErrorVal
) {
3420 // Check that swifterror value is only used by loads, stores, or as
3421 // a swifterror argument.
3422 for (const User
*U
: SwiftErrorVal
->users()) {
3423 Assert(isa
<LoadInst
>(U
) || isa
<StoreInst
>(U
) || isa
<CallInst
>(U
) ||
3425 "swifterror value can only be loaded and stored from, or "
3426 "as a swifterror argument!",
3428 // If it is used by a store, check it is the second operand.
3429 if (auto StoreI
= dyn_cast
<StoreInst
>(U
))
3430 Assert(StoreI
->getOperand(1) == SwiftErrorVal
,
3431 "swifterror value should be the second operand when used "
3432 "by stores", SwiftErrorVal
, U
);
3433 if (auto *Call
= dyn_cast
<CallBase
>(U
))
3434 verifySwiftErrorCall(*const_cast<CallBase
*>(Call
), SwiftErrorVal
);
3438 void Verifier::visitAllocaInst(AllocaInst
&AI
) {
3439 SmallPtrSet
<Type
*, 4> Visited
;
3440 PointerType
*PTy
= AI
.getType();
3441 // TODO: Relax this restriction?
3442 Assert(PTy
->getAddressSpace() == DL
.getAllocaAddrSpace(),
3443 "Allocation instruction pointer not in the stack address space!",
3445 Assert(AI
.getAllocatedType()->isSized(&Visited
),
3446 "Cannot allocate unsized type", &AI
);
3447 Assert(AI
.getArraySize()->getType()->isIntegerTy(),
3448 "Alloca array size must have integer type", &AI
);
3449 Assert(AI
.getAlignment() <= Value::MaximumAlignment
,
3450 "huge alignment values are unsupported", &AI
);
3452 if (AI
.isSwiftError()) {
3453 verifySwiftErrorValue(&AI
);
3456 visitInstruction(AI
);
3459 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst
&CXI
) {
3461 // FIXME: more conditions???
3462 Assert(CXI
.getSuccessOrdering() != AtomicOrdering::NotAtomic
,
3463 "cmpxchg instructions must be atomic.", &CXI
);
3464 Assert(CXI
.getFailureOrdering() != AtomicOrdering::NotAtomic
,
3465 "cmpxchg instructions must be atomic.", &CXI
);
3466 Assert(CXI
.getSuccessOrdering() != AtomicOrdering::Unordered
,
3467 "cmpxchg instructions cannot be unordered.", &CXI
);
3468 Assert(CXI
.getFailureOrdering() != AtomicOrdering::Unordered
,
3469 "cmpxchg instructions cannot be unordered.", &CXI
);
3470 Assert(!isStrongerThan(CXI
.getFailureOrdering(), CXI
.getSuccessOrdering()),
3471 "cmpxchg instructions failure argument shall be no stronger than the "
3474 Assert(CXI
.getFailureOrdering() != AtomicOrdering::Release
&&
3475 CXI
.getFailureOrdering() != AtomicOrdering::AcquireRelease
,
3476 "cmpxchg failure ordering cannot include release semantics", &CXI
);
3478 PointerType
*PTy
= dyn_cast
<PointerType
>(CXI
.getOperand(0)->getType());
3479 Assert(PTy
, "First cmpxchg operand must be a pointer.", &CXI
);
3480 Type
*ElTy
= PTy
->getElementType();
3481 Assert(ElTy
->isIntOrPtrTy(),
3482 "cmpxchg operand must have integer or pointer type", ElTy
, &CXI
);
3483 checkAtomicMemAccessSize(ElTy
, &CXI
);
3484 Assert(ElTy
== CXI
.getOperand(1)->getType(),
3485 "Expected value type does not match pointer operand type!", &CXI
,
3487 Assert(ElTy
== CXI
.getOperand(2)->getType(),
3488 "Stored value type does not match pointer operand type!", &CXI
, ElTy
);
3489 visitInstruction(CXI
);
3492 void Verifier::visitAtomicRMWInst(AtomicRMWInst
&RMWI
) {
3493 Assert(RMWI
.getOrdering() != AtomicOrdering::NotAtomic
,
3494 "atomicrmw instructions must be atomic.", &RMWI
);
3495 Assert(RMWI
.getOrdering() != AtomicOrdering::Unordered
,
3496 "atomicrmw instructions cannot be unordered.", &RMWI
);
3497 auto Op
= RMWI
.getOperation();
3498 PointerType
*PTy
= dyn_cast
<PointerType
>(RMWI
.getOperand(0)->getType());
3499 Assert(PTy
, "First atomicrmw operand must be a pointer.", &RMWI
);
3500 Type
*ElTy
= PTy
->getElementType();
3501 if (Op
== AtomicRMWInst::Xchg
) {
3502 Assert(ElTy
->isIntegerTy() || ElTy
->isFloatingPointTy(), "atomicrmw " +
3503 AtomicRMWInst::getOperationName(Op
) +
3504 " operand must have integer or floating point type!",
3506 } else if (AtomicRMWInst::isFPOperation(Op
)) {
3507 Assert(ElTy
->isFloatingPointTy(), "atomicrmw " +
3508 AtomicRMWInst::getOperationName(Op
) +
3509 " operand must have floating point type!",
3512 Assert(ElTy
->isIntegerTy(), "atomicrmw " +
3513 AtomicRMWInst::getOperationName(Op
) +
3514 " operand must have integer type!",
3517 checkAtomicMemAccessSize(ElTy
, &RMWI
);
3518 Assert(ElTy
== RMWI
.getOperand(1)->getType(),
3519 "Argument value type does not match pointer operand type!", &RMWI
,
3521 Assert(AtomicRMWInst::FIRST_BINOP
<= Op
&& Op
<= AtomicRMWInst::LAST_BINOP
,
3522 "Invalid binary operation!", &RMWI
);
3523 visitInstruction(RMWI
);
3526 void Verifier::visitFenceInst(FenceInst
&FI
) {
3527 const AtomicOrdering Ordering
= FI
.getOrdering();
3528 Assert(Ordering
== AtomicOrdering::Acquire
||
3529 Ordering
== AtomicOrdering::Release
||
3530 Ordering
== AtomicOrdering::AcquireRelease
||
3531 Ordering
== AtomicOrdering::SequentiallyConsistent
,
3532 "fence instructions may only have acquire, release, acq_rel, or "
3533 "seq_cst ordering.",
3535 visitInstruction(FI
);
3538 void Verifier::visitExtractValueInst(ExtractValueInst
&EVI
) {
3539 Assert(ExtractValueInst::getIndexedType(EVI
.getAggregateOperand()->getType(),
3540 EVI
.getIndices()) == EVI
.getType(),
3541 "Invalid ExtractValueInst operands!", &EVI
);
3543 visitInstruction(EVI
);
3546 void Verifier::visitInsertValueInst(InsertValueInst
&IVI
) {
3547 Assert(ExtractValueInst::getIndexedType(IVI
.getAggregateOperand()->getType(),
3548 IVI
.getIndices()) ==
3549 IVI
.getOperand(1)->getType(),
3550 "Invalid InsertValueInst operands!", &IVI
);
3552 visitInstruction(IVI
);
3555 static Value
*getParentPad(Value
*EHPad
) {
3556 if (auto *FPI
= dyn_cast
<FuncletPadInst
>(EHPad
))
3557 return FPI
->getParentPad();
3559 return cast
<CatchSwitchInst
>(EHPad
)->getParentPad();
3562 void Verifier::visitEHPadPredecessors(Instruction
&I
) {
3563 assert(I
.isEHPad());
3565 BasicBlock
*BB
= I
.getParent();
3566 Function
*F
= BB
->getParent();
3568 Assert(BB
!= &F
->getEntryBlock(), "EH pad cannot be in entry block.", &I
);
3570 if (auto *LPI
= dyn_cast
<LandingPadInst
>(&I
)) {
3571 // The landingpad instruction defines its parent as a landing pad block. The
3572 // landing pad block may be branched to only by the unwind edge of an
3574 for (BasicBlock
*PredBB
: predecessors(BB
)) {
3575 const auto *II
= dyn_cast
<InvokeInst
>(PredBB
->getTerminator());
3576 Assert(II
&& II
->getUnwindDest() == BB
&& II
->getNormalDest() != BB
,
3577 "Block containing LandingPadInst must be jumped to "
3578 "only by the unwind edge of an invoke.",
3583 if (auto *CPI
= dyn_cast
<CatchPadInst
>(&I
)) {
3584 if (!pred_empty(BB
))
3585 Assert(BB
->getUniquePredecessor() == CPI
->getCatchSwitch()->getParent(),
3586 "Block containg CatchPadInst must be jumped to "
3587 "only by its catchswitch.",
3589 Assert(BB
!= CPI
->getCatchSwitch()->getUnwindDest(),
3590 "Catchswitch cannot unwind to one of its catchpads",
3591 CPI
->getCatchSwitch(), CPI
);
3595 // Verify that each pred has a legal terminator with a legal to/from EH
3596 // pad relationship.
3597 Instruction
*ToPad
= &I
;
3598 Value
*ToPadParent
= getParentPad(ToPad
);
3599 for (BasicBlock
*PredBB
: predecessors(BB
)) {
3600 Instruction
*TI
= PredBB
->getTerminator();
3602 if (auto *II
= dyn_cast
<InvokeInst
>(TI
)) {
3603 Assert(II
->getUnwindDest() == BB
&& II
->getNormalDest() != BB
,
3604 "EH pad must be jumped to via an unwind edge", ToPad
, II
);
3605 if (auto Bundle
= II
->getOperandBundle(LLVMContext::OB_funclet
))
3606 FromPad
= Bundle
->Inputs
[0];
3608 FromPad
= ConstantTokenNone::get(II
->getContext());
3609 } else if (auto *CRI
= dyn_cast
<CleanupReturnInst
>(TI
)) {
3610 FromPad
= CRI
->getOperand(0);
3611 Assert(FromPad
!= ToPadParent
, "A cleanupret must exit its cleanup", CRI
);
3612 } else if (auto *CSI
= dyn_cast
<CatchSwitchInst
>(TI
)) {
3615 Assert(false, "EH pad must be jumped to via an unwind edge", ToPad
, TI
);
3618 // The edge may exit from zero or more nested pads.
3619 SmallSet
<Value
*, 8> Seen
;
3620 for (;; FromPad
= getParentPad(FromPad
)) {
3621 Assert(FromPad
!= ToPad
,
3622 "EH pad cannot handle exceptions raised within it", FromPad
, TI
);
3623 if (FromPad
== ToPadParent
) {
3624 // This is a legal unwind edge.
3627 Assert(!isa
<ConstantTokenNone
>(FromPad
),
3628 "A single unwind edge may only enter one EH pad", TI
);
3629 Assert(Seen
.insert(FromPad
).second
,
3630 "EH pad jumps through a cycle of pads", FromPad
);
3635 void Verifier::visitLandingPadInst(LandingPadInst
&LPI
) {
3636 // The landingpad instruction is ill-formed if it doesn't have any clauses and
3638 Assert(LPI
.getNumClauses() > 0 || LPI
.isCleanup(),
3639 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI
);
3641 visitEHPadPredecessors(LPI
);
3643 if (!LandingPadResultTy
)
3644 LandingPadResultTy
= LPI
.getType();
3646 Assert(LandingPadResultTy
== LPI
.getType(),
3647 "The landingpad instruction should have a consistent result type "
3648 "inside a function.",
3651 Function
*F
= LPI
.getParent()->getParent();
3652 Assert(F
->hasPersonalityFn(),
3653 "LandingPadInst needs to be in a function with a personality.", &LPI
);
3655 // The landingpad instruction must be the first non-PHI instruction in the
3657 Assert(LPI
.getParent()->getLandingPadInst() == &LPI
,
3658 "LandingPadInst not the first non-PHI instruction in the block.",
3661 for (unsigned i
= 0, e
= LPI
.getNumClauses(); i
< e
; ++i
) {
3662 Constant
*Clause
= LPI
.getClause(i
);
3663 if (LPI
.isCatch(i
)) {
3664 Assert(isa
<PointerType
>(Clause
->getType()),
3665 "Catch operand does not have pointer type!", &LPI
);
3667 Assert(LPI
.isFilter(i
), "Clause is neither catch nor filter!", &LPI
);
3668 Assert(isa
<ConstantArray
>(Clause
) || isa
<ConstantAggregateZero
>(Clause
),
3669 "Filter operand is not an array of constants!", &LPI
);
3673 visitInstruction(LPI
);
3676 void Verifier::visitResumeInst(ResumeInst
&RI
) {
3677 Assert(RI
.getFunction()->hasPersonalityFn(),
3678 "ResumeInst needs to be in a function with a personality.", &RI
);
3680 if (!LandingPadResultTy
)
3681 LandingPadResultTy
= RI
.getValue()->getType();
3683 Assert(LandingPadResultTy
== RI
.getValue()->getType(),
3684 "The resume instruction should have a consistent result type "
3685 "inside a function.",
3688 visitTerminator(RI
);
3691 void Verifier::visitCatchPadInst(CatchPadInst
&CPI
) {
3692 BasicBlock
*BB
= CPI
.getParent();
3694 Function
*F
= BB
->getParent();
3695 Assert(F
->hasPersonalityFn(),
3696 "CatchPadInst needs to be in a function with a personality.", &CPI
);
3698 Assert(isa
<CatchSwitchInst
>(CPI
.getParentPad()),
3699 "CatchPadInst needs to be directly nested in a CatchSwitchInst.",
3700 CPI
.getParentPad());
3702 // The catchpad instruction must be the first non-PHI instruction in the
3704 Assert(BB
->getFirstNonPHI() == &CPI
,
3705 "CatchPadInst not the first non-PHI instruction in the block.", &CPI
);
3707 visitEHPadPredecessors(CPI
);
3708 visitFuncletPadInst(CPI
);
3711 void Verifier::visitCatchReturnInst(CatchReturnInst
&CatchReturn
) {
3712 Assert(isa
<CatchPadInst
>(CatchReturn
.getOperand(0)),
3713 "CatchReturnInst needs to be provided a CatchPad", &CatchReturn
,
3714 CatchReturn
.getOperand(0));
3716 visitTerminator(CatchReturn
);
3719 void Verifier::visitCleanupPadInst(CleanupPadInst
&CPI
) {
3720 BasicBlock
*BB
= CPI
.getParent();
3722 Function
*F
= BB
->getParent();
3723 Assert(F
->hasPersonalityFn(),
3724 "CleanupPadInst needs to be in a function with a personality.", &CPI
);
3726 // The cleanuppad instruction must be the first non-PHI instruction in the
3728 Assert(BB
->getFirstNonPHI() == &CPI
,
3729 "CleanupPadInst not the first non-PHI instruction in the block.",
3732 auto *ParentPad
= CPI
.getParentPad();
3733 Assert(isa
<ConstantTokenNone
>(ParentPad
) || isa
<FuncletPadInst
>(ParentPad
),
3734 "CleanupPadInst has an invalid parent.", &CPI
);
3736 visitEHPadPredecessors(CPI
);
3737 visitFuncletPadInst(CPI
);
3740 void Verifier::visitFuncletPadInst(FuncletPadInst
&FPI
) {
3741 User
*FirstUser
= nullptr;
3742 Value
*FirstUnwindPad
= nullptr;
3743 SmallVector
<FuncletPadInst
*, 8> Worklist({&FPI
});
3744 SmallSet
<FuncletPadInst
*, 8> Seen
;
3746 while (!Worklist
.empty()) {
3747 FuncletPadInst
*CurrentPad
= Worklist
.pop_back_val();
3748 Assert(Seen
.insert(CurrentPad
).second
,
3749 "FuncletPadInst must not be nested within itself", CurrentPad
);
3750 Value
*UnresolvedAncestorPad
= nullptr;
3751 for (User
*U
: CurrentPad
->users()) {
3752 BasicBlock
*UnwindDest
;
3753 if (auto *CRI
= dyn_cast
<CleanupReturnInst
>(U
)) {
3754 UnwindDest
= CRI
->getUnwindDest();
3755 } else if (auto *CSI
= dyn_cast
<CatchSwitchInst
>(U
)) {
3756 // We allow catchswitch unwind to caller to nest
3757 // within an outer pad that unwinds somewhere else,
3758 // because catchswitch doesn't have a nounwind variant.
3759 // See e.g. SimplifyCFGOpt::SimplifyUnreachable.
3760 if (CSI
->unwindsToCaller())
3762 UnwindDest
= CSI
->getUnwindDest();
3763 } else if (auto *II
= dyn_cast
<InvokeInst
>(U
)) {
3764 UnwindDest
= II
->getUnwindDest();
3765 } else if (isa
<CallInst
>(U
)) {
3766 // Calls which don't unwind may be found inside funclet
3767 // pads that unwind somewhere else. We don't *require*
3768 // such calls to be annotated nounwind.
3770 } else if (auto *CPI
= dyn_cast
<CleanupPadInst
>(U
)) {
3771 // The unwind dest for a cleanup can only be found by
3772 // recursive search. Add it to the worklist, and we'll
3773 // search for its first use that determines where it unwinds.
3774 Worklist
.push_back(CPI
);
3777 Assert(isa
<CatchReturnInst
>(U
), "Bogus funclet pad use", U
);
3784 UnwindPad
= UnwindDest
->getFirstNonPHI();
3785 if (!cast
<Instruction
>(UnwindPad
)->isEHPad())
3787 Value
*UnwindParent
= getParentPad(UnwindPad
);
3788 // Ignore unwind edges that don't exit CurrentPad.
3789 if (UnwindParent
== CurrentPad
)
3791 // Determine whether the original funclet pad is exited,
3792 // and if we are scanning nested pads determine how many
3793 // of them are exited so we can stop searching their
3795 Value
*ExitedPad
= CurrentPad
;
3798 if (ExitedPad
== &FPI
) {
3800 // Now we can resolve any ancestors of CurrentPad up to
3801 // FPI, but not including FPI since we need to make sure
3802 // to check all direct users of FPI for consistency.
3803 UnresolvedAncestorPad
= &FPI
;
3806 Value
*ExitedParent
= getParentPad(ExitedPad
);
3807 if (ExitedParent
== UnwindParent
) {
3808 // ExitedPad is the ancestor-most pad which this unwind
3809 // edge exits, so we can resolve up to it, meaning that
3810 // ExitedParent is the first ancestor still unresolved.
3811 UnresolvedAncestorPad
= ExitedParent
;
3814 ExitedPad
= ExitedParent
;
3815 } while (!isa
<ConstantTokenNone
>(ExitedPad
));
3817 // Unwinding to caller exits all pads.
3818 UnwindPad
= ConstantTokenNone::get(FPI
.getContext());
3820 UnresolvedAncestorPad
= &FPI
;
3824 // This unwind edge exits FPI. Make sure it agrees with other
3827 Assert(UnwindPad
== FirstUnwindPad
, "Unwind edges out of a funclet "
3828 "pad must have the same unwind "
3830 &FPI
, U
, FirstUser
);
3833 FirstUnwindPad
= UnwindPad
;
3834 // Record cleanup sibling unwinds for verifySiblingFuncletUnwinds
3835 if (isa
<CleanupPadInst
>(&FPI
) && !isa
<ConstantTokenNone
>(UnwindPad
) &&
3836 getParentPad(UnwindPad
) == getParentPad(&FPI
))
3837 SiblingFuncletInfo
[&FPI
] = cast
<Instruction
>(U
);
3840 // Make sure we visit all uses of FPI, but for nested pads stop as
3841 // soon as we know where they unwind to.
3842 if (CurrentPad
!= &FPI
)
3845 if (UnresolvedAncestorPad
) {
3846 if (CurrentPad
== UnresolvedAncestorPad
) {
3847 // When CurrentPad is FPI itself, we don't mark it as resolved even if
3848 // we've found an unwind edge that exits it, because we need to verify
3849 // all direct uses of FPI.
3850 assert(CurrentPad
== &FPI
);
3853 // Pop off the worklist any nested pads that we've found an unwind
3854 // destination for. The pads on the worklist are the uncles,
3855 // great-uncles, etc. of CurrentPad. We've found an unwind destination
3856 // for all ancestors of CurrentPad up to but not including
3857 // UnresolvedAncestorPad.
3858 Value
*ResolvedPad
= CurrentPad
;
3859 while (!Worklist
.empty()) {
3860 Value
*UnclePad
= Worklist
.back();
3861 Value
*AncestorPad
= getParentPad(UnclePad
);
3862 // Walk ResolvedPad up the ancestor list until we either find the
3863 // uncle's parent or the last resolved ancestor.
3864 while (ResolvedPad
!= AncestorPad
) {
3865 Value
*ResolvedParent
= getParentPad(ResolvedPad
);
3866 if (ResolvedParent
== UnresolvedAncestorPad
) {
3869 ResolvedPad
= ResolvedParent
;
3871 // If the resolved ancestor search didn't find the uncle's parent,
3872 // then the uncle is not yet resolved.
3873 if (ResolvedPad
!= AncestorPad
)
3875 // This uncle is resolved, so pop it from the worklist.
3876 Worklist
.pop_back();
3881 if (FirstUnwindPad
) {
3882 if (auto *CatchSwitch
= dyn_cast
<CatchSwitchInst
>(FPI
.getParentPad())) {
3883 BasicBlock
*SwitchUnwindDest
= CatchSwitch
->getUnwindDest();
3884 Value
*SwitchUnwindPad
;
3885 if (SwitchUnwindDest
)
3886 SwitchUnwindPad
= SwitchUnwindDest
->getFirstNonPHI();
3888 SwitchUnwindPad
= ConstantTokenNone::get(FPI
.getContext());
3889 Assert(SwitchUnwindPad
== FirstUnwindPad
,
3890 "Unwind edges out of a catch must have the same unwind dest as "
3891 "the parent catchswitch",
3892 &FPI
, FirstUser
, CatchSwitch
);
3896 visitInstruction(FPI
);
3899 void Verifier::visitCatchSwitchInst(CatchSwitchInst
&CatchSwitch
) {
3900 BasicBlock
*BB
= CatchSwitch
.getParent();
3902 Function
*F
= BB
->getParent();
3903 Assert(F
->hasPersonalityFn(),
3904 "CatchSwitchInst needs to be in a function with a personality.",
3907 // The catchswitch instruction must be the first non-PHI instruction in the
3909 Assert(BB
->getFirstNonPHI() == &CatchSwitch
,
3910 "CatchSwitchInst not the first non-PHI instruction in the block.",
3913 auto *ParentPad
= CatchSwitch
.getParentPad();
3914 Assert(isa
<ConstantTokenNone
>(ParentPad
) || isa
<FuncletPadInst
>(ParentPad
),
3915 "CatchSwitchInst has an invalid parent.", ParentPad
);
3917 if (BasicBlock
*UnwindDest
= CatchSwitch
.getUnwindDest()) {
3918 Instruction
*I
= UnwindDest
->getFirstNonPHI();
3919 Assert(I
->isEHPad() && !isa
<LandingPadInst
>(I
),
3920 "CatchSwitchInst must unwind to an EH block which is not a "
3924 // Record catchswitch sibling unwinds for verifySiblingFuncletUnwinds
3925 if (getParentPad(I
) == ParentPad
)
3926 SiblingFuncletInfo
[&CatchSwitch
] = &CatchSwitch
;
3929 Assert(CatchSwitch
.getNumHandlers() != 0,
3930 "CatchSwitchInst cannot have empty handler list", &CatchSwitch
);
3932 for (BasicBlock
*Handler
: CatchSwitch
.handlers()) {
3933 Assert(isa
<CatchPadInst
>(Handler
->getFirstNonPHI()),
3934 "CatchSwitchInst handlers must be catchpads", &CatchSwitch
, Handler
);
3937 visitEHPadPredecessors(CatchSwitch
);
3938 visitTerminator(CatchSwitch
);
3941 void Verifier::visitCleanupReturnInst(CleanupReturnInst
&CRI
) {
3942 Assert(isa
<CleanupPadInst
>(CRI
.getOperand(0)),
3943 "CleanupReturnInst needs to be provided a CleanupPad", &CRI
,
3946 if (BasicBlock
*UnwindDest
= CRI
.getUnwindDest()) {
3947 Instruction
*I
= UnwindDest
->getFirstNonPHI();
3948 Assert(I
->isEHPad() && !isa
<LandingPadInst
>(I
),
3949 "CleanupReturnInst must unwind to an EH block which is not a "
3954 visitTerminator(CRI
);
3957 void Verifier::verifyDominatesUse(Instruction
&I
, unsigned i
) {
3958 Instruction
*Op
= cast
<Instruction
>(I
.getOperand(i
));
3959 // If the we have an invalid invoke, don't try to compute the dominance.
3960 // We already reject it in the invoke specific checks and the dominance
3961 // computation doesn't handle multiple edges.
3962 if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(Op
)) {
3963 if (II
->getNormalDest() == II
->getUnwindDest())
3967 // Quick check whether the def has already been encountered in the same block.
3968 // PHI nodes are not checked to prevent accepting preceding PHIs, because PHI
3969 // uses are defined to happen on the incoming edge, not at the instruction.
3971 // FIXME: If this operand is a MetadataAsValue (wrapping a LocalAsMetadata)
3972 // wrapping an SSA value, assert that we've already encountered it. See
3973 // related FIXME in Mapper::mapLocalAsMetadata in ValueMapper.cpp.
3974 if (!isa
<PHINode
>(I
) && InstsInThisBlock
.count(Op
))
3977 const Use
&U
= I
.getOperandUse(i
);
3978 Assert(DT
.dominates(Op
, U
),
3979 "Instruction does not dominate all uses!", Op
, &I
);
3982 void Verifier::visitDereferenceableMetadata(Instruction
& I
, MDNode
* MD
) {
3983 Assert(I
.getType()->isPointerTy(), "dereferenceable, dereferenceable_or_null "
3984 "apply only to pointer types", &I
);
3985 Assert(isa
<LoadInst
>(I
),
3986 "dereferenceable, dereferenceable_or_null apply only to load"
3987 " instructions, use attributes for calls or invokes", &I
);
3988 Assert(MD
->getNumOperands() == 1, "dereferenceable, dereferenceable_or_null "
3989 "take one operand!", &I
);
3990 ConstantInt
*CI
= mdconst::dyn_extract
<ConstantInt
>(MD
->getOperand(0));
3991 Assert(CI
&& CI
->getType()->isIntegerTy(64), "dereferenceable, "
3992 "dereferenceable_or_null metadata value must be an i64!", &I
);
3995 /// verifyInstruction - Verify that an instruction is well formed.
3997 void Verifier::visitInstruction(Instruction
&I
) {
3998 BasicBlock
*BB
= I
.getParent();
3999 Assert(BB
, "Instruction not embedded in basic block!", &I
);
4001 if (!isa
<PHINode
>(I
)) { // Check that non-phi nodes are not self referential
4002 for (User
*U
: I
.users()) {
4003 Assert(U
!= (User
*)&I
|| !DT
.isReachableFromEntry(BB
),
4004 "Only PHI nodes may reference their own value!", &I
);
4008 // Check that void typed values don't have names
4009 Assert(!I
.getType()->isVoidTy() || !I
.hasName(),
4010 "Instruction has a name, but provides a void value!", &I
);
4012 // Check that the return value of the instruction is either void or a legal
4014 Assert(I
.getType()->isVoidTy() || I
.getType()->isFirstClassType(),
4015 "Instruction returns a non-scalar type!", &I
);
4017 // Check that the instruction doesn't produce metadata. Calls are already
4018 // checked against the callee type.
4019 Assert(!I
.getType()->isMetadataTy() || isa
<CallInst
>(I
) || isa
<InvokeInst
>(I
),
4020 "Invalid use of metadata!", &I
);
4022 // Check that all uses of the instruction, if they are instructions
4023 // themselves, actually have parent basic blocks. If the use is not an
4024 // instruction, it is an error!
4025 for (Use
&U
: I
.uses()) {
4026 if (Instruction
*Used
= dyn_cast
<Instruction
>(U
.getUser()))
4027 Assert(Used
->getParent() != nullptr,
4028 "Instruction referencing"
4029 " instruction not embedded in a basic block!",
4032 CheckFailed("Use of instruction is not an instruction!", U
);
4037 // Get a pointer to the call base of the instruction if it is some form of
4039 const CallBase
*CBI
= dyn_cast
<CallBase
>(&I
);
4041 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
) {
4042 Assert(I
.getOperand(i
) != nullptr, "Instruction has null operand!", &I
);
4044 // Check to make sure that only first-class-values are operands to
4046 if (!I
.getOperand(i
)->getType()->isFirstClassType()) {
4047 Assert(false, "Instruction operands must be first-class values!", &I
);
4050 if (Function
*F
= dyn_cast
<Function
>(I
.getOperand(i
))) {
4051 // Check to make sure that the "address of" an intrinsic function is never
4053 Assert(!F
->isIntrinsic() ||
4054 (CBI
&& &CBI
->getCalledOperandUse() == &I
.getOperandUse(i
)),
4055 "Cannot take the address of an intrinsic!", &I
);
4057 !F
->isIntrinsic() || isa
<CallInst
>(I
) ||
4058 F
->getIntrinsicID() == Intrinsic::donothing
||
4059 F
->getIntrinsicID() == Intrinsic::coro_resume
||
4060 F
->getIntrinsicID() == Intrinsic::coro_destroy
||
4061 F
->getIntrinsicID() == Intrinsic::experimental_patchpoint_void
||
4062 F
->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64
||
4063 F
->getIntrinsicID() == Intrinsic::experimental_gc_statepoint
||
4064 F
->getIntrinsicID() == Intrinsic::wasm_rethrow_in_catch
,
4065 "Cannot invoke an intrinsic other than donothing, patchpoint, "
4066 "statepoint, coro_resume or coro_destroy",
4068 Assert(F
->getParent() == &M
, "Referencing function in another module!",
4069 &I
, &M
, F
, F
->getParent());
4070 } else if (BasicBlock
*OpBB
= dyn_cast
<BasicBlock
>(I
.getOperand(i
))) {
4071 Assert(OpBB
->getParent() == BB
->getParent(),
4072 "Referring to a basic block in another function!", &I
);
4073 } else if (Argument
*OpArg
= dyn_cast
<Argument
>(I
.getOperand(i
))) {
4074 Assert(OpArg
->getParent() == BB
->getParent(),
4075 "Referring to an argument in another function!", &I
);
4076 } else if (GlobalValue
*GV
= dyn_cast
<GlobalValue
>(I
.getOperand(i
))) {
4077 Assert(GV
->getParent() == &M
, "Referencing global in another module!", &I
,
4078 &M
, GV
, GV
->getParent());
4079 } else if (isa
<Instruction
>(I
.getOperand(i
))) {
4080 verifyDominatesUse(I
, i
);
4081 } else if (isa
<InlineAsm
>(I
.getOperand(i
))) {
4082 Assert(CBI
&& &CBI
->getCalledOperandUse() == &I
.getOperandUse(i
),
4083 "Cannot take the address of an inline asm!", &I
);
4084 } else if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(I
.getOperand(i
))) {
4085 if (CE
->getType()->isPtrOrPtrVectorTy() ||
4086 !DL
.getNonIntegralAddressSpaces().empty()) {
4087 // If we have a ConstantExpr pointer, we need to see if it came from an
4088 // illegal bitcast. If the datalayout string specifies non-integral
4089 // address spaces then we also need to check for illegal ptrtoint and
4090 // inttoptr expressions.
4091 visitConstantExprsRecursively(CE
);
4096 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_fpmath
)) {
4097 Assert(I
.getType()->isFPOrFPVectorTy(),
4098 "fpmath requires a floating point result!", &I
);
4099 Assert(MD
->getNumOperands() == 1, "fpmath takes one operand!", &I
);
4100 if (ConstantFP
*CFP0
=
4101 mdconst::dyn_extract_or_null
<ConstantFP
>(MD
->getOperand(0))) {
4102 const APFloat
&Accuracy
= CFP0
->getValueAPF();
4103 Assert(&Accuracy
.getSemantics() == &APFloat::IEEEsingle(),
4104 "fpmath accuracy must have float type", &I
);
4105 Assert(Accuracy
.isFiniteNonZero() && !Accuracy
.isNegative(),
4106 "fpmath accuracy not a positive number!", &I
);
4108 Assert(false, "invalid fpmath accuracy!", &I
);
4112 if (MDNode
*Range
= I
.getMetadata(LLVMContext::MD_range
)) {
4113 Assert(isa
<LoadInst
>(I
) || isa
<CallInst
>(I
) || isa
<InvokeInst
>(I
),
4114 "Ranges are only for loads, calls and invokes!", &I
);
4115 visitRangeMetadata(I
, Range
, I
.getType());
4118 if (I
.getMetadata(LLVMContext::MD_nonnull
)) {
4119 Assert(I
.getType()->isPointerTy(), "nonnull applies only to pointer types",
4121 Assert(isa
<LoadInst
>(I
),
4122 "nonnull applies only to load instructions, use attributes"
4123 " for calls or invokes",
4127 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_dereferenceable
))
4128 visitDereferenceableMetadata(I
, MD
);
4130 if (MDNode
*MD
= I
.getMetadata(LLVMContext::MD_dereferenceable_or_null
))
4131 visitDereferenceableMetadata(I
, MD
);
4133 if (MDNode
*TBAA
= I
.getMetadata(LLVMContext::MD_tbaa
))
4134 TBAAVerifyHelper
.visitTBAAMetadata(I
, TBAA
);
4136 if (MDNode
*AlignMD
= I
.getMetadata(LLVMContext::MD_align
)) {
4137 Assert(I
.getType()->isPointerTy(), "align applies only to pointer types",
4139 Assert(isa
<LoadInst
>(I
), "align applies only to load instructions, "
4140 "use attributes for calls or invokes", &I
);
4141 Assert(AlignMD
->getNumOperands() == 1, "align takes one operand!", &I
);
4142 ConstantInt
*CI
= mdconst::dyn_extract
<ConstantInt
>(AlignMD
->getOperand(0));
4143 Assert(CI
&& CI
->getType()->isIntegerTy(64),
4144 "align metadata value must be an i64!", &I
);
4145 uint64_t Align
= CI
->getZExtValue();
4146 Assert(isPowerOf2_64(Align
),
4147 "align metadata value must be a power of 2!", &I
);
4148 Assert(Align
<= Value::MaximumAlignment
,
4149 "alignment is larger that implementation defined limit", &I
);
4152 if (MDNode
*N
= I
.getDebugLoc().getAsMDNode()) {
4153 AssertDI(isa
<DILocation
>(N
), "invalid !dbg metadata attachment", &I
, N
);
4157 if (auto *DII
= dyn_cast
<DbgVariableIntrinsic
>(&I
))
4158 verifyFragmentExpression(*DII
);
4160 InstsInThisBlock
.insert(&I
);
4163 /// Allow intrinsics to be verified in different ways.
4164 void Verifier::visitIntrinsicCall(Intrinsic::ID ID
, CallBase
&Call
) {
4165 Function
*IF
= Call
.getCalledFunction();
4166 Assert(IF
->isDeclaration(), "Intrinsic functions should never be defined!",
4169 // Verify that the intrinsic prototype lines up with what the .td files
4171 FunctionType
*IFTy
= IF
->getFunctionType();
4172 bool IsVarArg
= IFTy
->isVarArg();
4174 SmallVector
<Intrinsic::IITDescriptor
, 8> Table
;
4175 getIntrinsicInfoTableEntries(ID
, Table
);
4176 ArrayRef
<Intrinsic::IITDescriptor
> TableRef
= Table
;
4178 // Walk the descriptors to extract overloaded types.
4179 SmallVector
<Type
*, 4> ArgTys
;
4180 Intrinsic::MatchIntrinsicTypesResult Res
=
4181 Intrinsic::matchIntrinsicSignature(IFTy
, TableRef
, ArgTys
);
4182 Assert(Res
!= Intrinsic::MatchIntrinsicTypes_NoMatchRet
,
4183 "Intrinsic has incorrect return type!", IF
);
4184 Assert(Res
!= Intrinsic::MatchIntrinsicTypes_NoMatchArg
,
4185 "Intrinsic has incorrect argument type!", IF
);
4187 // Verify if the intrinsic call matches the vararg property.
4189 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg
, TableRef
),
4190 "Intrinsic was not defined with variable arguments!", IF
);
4192 Assert(!Intrinsic::matchIntrinsicVarArg(IsVarArg
, TableRef
),
4193 "Callsite was not defined with variable arguments!", IF
);
4195 // All descriptors should be absorbed by now.
4196 Assert(TableRef
.empty(), "Intrinsic has too few arguments!", IF
);
4198 // Now that we have the intrinsic ID and the actual argument types (and we
4199 // know they are legal for the intrinsic!) get the intrinsic name through the
4200 // usual means. This allows us to verify the mangling of argument types into
4202 const std::string ExpectedName
= Intrinsic::getName(ID
, ArgTys
);
4203 Assert(ExpectedName
== IF
->getName(),
4204 "Intrinsic name not mangled correctly for type arguments! "
4209 // If the intrinsic takes MDNode arguments, verify that they are either global
4210 // or are local to *this* function.
4211 for (Value
*V
: Call
.args())
4212 if (auto *MD
= dyn_cast
<MetadataAsValue
>(V
))
4213 visitMetadataAsValue(*MD
, Call
.getCaller());
4218 case Intrinsic::coro_id
: {
4219 auto *InfoArg
= Call
.getArgOperand(3)->stripPointerCasts();
4220 if (isa
<ConstantPointerNull
>(InfoArg
))
4222 auto *GV
= dyn_cast
<GlobalVariable
>(InfoArg
);
4223 Assert(GV
&& GV
->isConstant() && GV
->hasDefinitiveInitializer(),
4224 "info argument of llvm.coro.begin must refer to an initialized "
4226 Constant
*Init
= GV
->getInitializer();
4227 Assert(isa
<ConstantStruct
>(Init
) || isa
<ConstantArray
>(Init
),
4228 "info argument of llvm.coro.begin must refer to either a struct or "
4232 case Intrinsic::experimental_constrained_fadd
:
4233 case Intrinsic::experimental_constrained_fsub
:
4234 case Intrinsic::experimental_constrained_fmul
:
4235 case Intrinsic::experimental_constrained_fdiv
:
4236 case Intrinsic::experimental_constrained_frem
:
4237 case Intrinsic::experimental_constrained_fma
:
4238 case Intrinsic::experimental_constrained_fptrunc
:
4239 case Intrinsic::experimental_constrained_fpext
:
4240 case Intrinsic::experimental_constrained_sqrt
:
4241 case Intrinsic::experimental_constrained_pow
:
4242 case Intrinsic::experimental_constrained_powi
:
4243 case Intrinsic::experimental_constrained_sin
:
4244 case Intrinsic::experimental_constrained_cos
:
4245 case Intrinsic::experimental_constrained_exp
:
4246 case Intrinsic::experimental_constrained_exp2
:
4247 case Intrinsic::experimental_constrained_log
:
4248 case Intrinsic::experimental_constrained_log10
:
4249 case Intrinsic::experimental_constrained_log2
:
4250 case Intrinsic::experimental_constrained_rint
:
4251 case Intrinsic::experimental_constrained_nearbyint
:
4252 case Intrinsic::experimental_constrained_maxnum
:
4253 case Intrinsic::experimental_constrained_minnum
:
4254 case Intrinsic::experimental_constrained_ceil
:
4255 case Intrinsic::experimental_constrained_floor
:
4256 case Intrinsic::experimental_constrained_round
:
4257 case Intrinsic::experimental_constrained_trunc
:
4258 visitConstrainedFPIntrinsic(cast
<ConstrainedFPIntrinsic
>(Call
));
4260 case Intrinsic::dbg_declare
: // llvm.dbg.declare
4261 Assert(isa
<MetadataAsValue
>(Call
.getArgOperand(0)),
4262 "invalid llvm.dbg.declare intrinsic call 1", Call
);
4263 visitDbgIntrinsic("declare", cast
<DbgVariableIntrinsic
>(Call
));
4265 case Intrinsic::dbg_addr
: // llvm.dbg.addr
4266 visitDbgIntrinsic("addr", cast
<DbgVariableIntrinsic
>(Call
));
4268 case Intrinsic::dbg_value
: // llvm.dbg.value
4269 visitDbgIntrinsic("value", cast
<DbgVariableIntrinsic
>(Call
));
4271 case Intrinsic::dbg_label
: // llvm.dbg.label
4272 visitDbgLabelIntrinsic("label", cast
<DbgLabelInst
>(Call
));
4274 case Intrinsic::memcpy
:
4275 case Intrinsic::memmove
:
4276 case Intrinsic::memset
: {
4277 const auto *MI
= cast
<MemIntrinsic
>(&Call
);
4278 auto IsValidAlignment
= [&](unsigned Alignment
) -> bool {
4279 return Alignment
== 0 || isPowerOf2_32(Alignment
);
4281 Assert(IsValidAlignment(MI
->getDestAlignment()),
4282 "alignment of arg 0 of memory intrinsic must be 0 or a power of 2",
4284 if (const auto *MTI
= dyn_cast
<MemTransferInst
>(MI
)) {
4285 Assert(IsValidAlignment(MTI
->getSourceAlignment()),
4286 "alignment of arg 1 of memory intrinsic must be 0 or a power of 2",
4292 case Intrinsic::memcpy_element_unordered_atomic
:
4293 case Intrinsic::memmove_element_unordered_atomic
:
4294 case Intrinsic::memset_element_unordered_atomic
: {
4295 const auto *AMI
= cast
<AtomicMemIntrinsic
>(&Call
);
4297 ConstantInt
*ElementSizeCI
=
4298 cast
<ConstantInt
>(AMI
->getRawElementSizeInBytes());
4299 const APInt
&ElementSizeVal
= ElementSizeCI
->getValue();
4300 Assert(ElementSizeVal
.isPowerOf2(),
4301 "element size of the element-wise atomic memory intrinsic "
4302 "must be a power of 2",
4305 if (auto *LengthCI
= dyn_cast
<ConstantInt
>(AMI
->getLength())) {
4306 uint64_t Length
= LengthCI
->getZExtValue();
4307 uint64_t ElementSize
= AMI
->getElementSizeInBytes();
4308 Assert((Length
% ElementSize
) == 0,
4309 "constant length must be a multiple of the element size in the "
4310 "element-wise atomic memory intrinsic",
4314 auto IsValidAlignment
= [&](uint64_t Alignment
) {
4315 return isPowerOf2_64(Alignment
) && ElementSizeVal
.ule(Alignment
);
4317 uint64_t DstAlignment
= AMI
->getDestAlignment();
4318 Assert(IsValidAlignment(DstAlignment
),
4319 "incorrect alignment of the destination argument", Call
);
4320 if (const auto *AMT
= dyn_cast
<AtomicMemTransferInst
>(AMI
)) {
4321 uint64_t SrcAlignment
= AMT
->getSourceAlignment();
4322 Assert(IsValidAlignment(SrcAlignment
),
4323 "incorrect alignment of the source argument", Call
);
4327 case Intrinsic::gcroot
:
4328 case Intrinsic::gcwrite
:
4329 case Intrinsic::gcread
:
4330 if (ID
== Intrinsic::gcroot
) {
4332 dyn_cast
<AllocaInst
>(Call
.getArgOperand(0)->stripPointerCasts());
4333 Assert(AI
, "llvm.gcroot parameter #1 must be an alloca.", Call
);
4334 Assert(isa
<Constant
>(Call
.getArgOperand(1)),
4335 "llvm.gcroot parameter #2 must be a constant.", Call
);
4336 if (!AI
->getAllocatedType()->isPointerTy()) {
4337 Assert(!isa
<ConstantPointerNull
>(Call
.getArgOperand(1)),
4338 "llvm.gcroot parameter #1 must either be a pointer alloca, "
4339 "or argument #2 must be a non-null constant.",
4344 Assert(Call
.getParent()->getParent()->hasGC(),
4345 "Enclosing function does not use GC.", Call
);
4347 case Intrinsic::init_trampoline
:
4348 Assert(isa
<Function
>(Call
.getArgOperand(1)->stripPointerCasts()),
4349 "llvm.init_trampoline parameter #2 must resolve to a function.",
4352 case Intrinsic::prefetch
:
4353 Assert(cast
<ConstantInt
>(Call
.getArgOperand(1))->getZExtValue() < 2 &&
4354 cast
<ConstantInt
>(Call
.getArgOperand(2))->getZExtValue() < 4,
4355 "invalid arguments to llvm.prefetch", Call
);
4357 case Intrinsic::stackprotector
:
4358 Assert(isa
<AllocaInst
>(Call
.getArgOperand(1)->stripPointerCasts()),
4359 "llvm.stackprotector parameter #2 must resolve to an alloca.", Call
);
4361 case Intrinsic::localescape
: {
4362 BasicBlock
*BB
= Call
.getParent();
4363 Assert(BB
== &BB
->getParent()->front(),
4364 "llvm.localescape used outside of entry block", Call
);
4365 Assert(!SawFrameEscape
,
4366 "multiple calls to llvm.localescape in one function", Call
);
4367 for (Value
*Arg
: Call
.args()) {
4368 if (isa
<ConstantPointerNull
>(Arg
))
4369 continue; // Null values are allowed as placeholders.
4370 auto *AI
= dyn_cast
<AllocaInst
>(Arg
->stripPointerCasts());
4371 Assert(AI
&& AI
->isStaticAlloca(),
4372 "llvm.localescape only accepts static allocas", Call
);
4374 FrameEscapeInfo
[BB
->getParent()].first
= Call
.getNumArgOperands();
4375 SawFrameEscape
= true;
4378 case Intrinsic::localrecover
: {
4379 Value
*FnArg
= Call
.getArgOperand(0)->stripPointerCasts();
4380 Function
*Fn
= dyn_cast
<Function
>(FnArg
);
4381 Assert(Fn
&& !Fn
->isDeclaration(),
4382 "llvm.localrecover first "
4383 "argument must be function defined in this module",
4385 auto *IdxArg
= cast
<ConstantInt
>(Call
.getArgOperand(2));
4386 auto &Entry
= FrameEscapeInfo
[Fn
];
4387 Entry
.second
= unsigned(
4388 std::max(uint64_t(Entry
.second
), IdxArg
->getLimitedValue(~0U) + 1));
4392 case Intrinsic::experimental_gc_statepoint
:
4393 if (auto *CI
= dyn_cast
<CallInst
>(&Call
))
4394 Assert(!CI
->isInlineAsm(),
4395 "gc.statepoint support for inline assembly unimplemented", CI
);
4396 Assert(Call
.getParent()->getParent()->hasGC(),
4397 "Enclosing function does not use GC.", Call
);
4399 verifyStatepoint(Call
);
4401 case Intrinsic::experimental_gc_result
: {
4402 Assert(Call
.getParent()->getParent()->hasGC(),
4403 "Enclosing function does not use GC.", Call
);
4404 // Are we tied to a statepoint properly?
4405 const auto *StatepointCall
= dyn_cast
<CallBase
>(Call
.getArgOperand(0));
4406 const Function
*StatepointFn
=
4407 StatepointCall
? StatepointCall
->getCalledFunction() : nullptr;
4408 Assert(StatepointFn
&& StatepointFn
->isDeclaration() &&
4409 StatepointFn
->getIntrinsicID() ==
4410 Intrinsic::experimental_gc_statepoint
,
4411 "gc.result operand #1 must be from a statepoint", Call
,
4412 Call
.getArgOperand(0));
4414 // Assert that result type matches wrapped callee.
4415 const Value
*Target
= StatepointCall
->getArgOperand(2);
4416 auto *PT
= cast
<PointerType
>(Target
->getType());
4417 auto *TargetFuncType
= cast
<FunctionType
>(PT
->getElementType());
4418 Assert(Call
.getType() == TargetFuncType
->getReturnType(),
4419 "gc.result result type does not match wrapped callee", Call
);
4422 case Intrinsic::experimental_gc_relocate
: {
4423 Assert(Call
.getNumArgOperands() == 3, "wrong number of arguments", Call
);
4425 Assert(isa
<PointerType
>(Call
.getType()->getScalarType()),
4426 "gc.relocate must return a pointer or a vector of pointers", Call
);
4428 // Check that this relocate is correctly tied to the statepoint
4430 // This is case for relocate on the unwinding path of an invoke statepoint
4431 if (LandingPadInst
*LandingPad
=
4432 dyn_cast
<LandingPadInst
>(Call
.getArgOperand(0))) {
4434 const BasicBlock
*InvokeBB
=
4435 LandingPad
->getParent()->getUniquePredecessor();
4437 // Landingpad relocates should have only one predecessor with invoke
4438 // statepoint terminator
4439 Assert(InvokeBB
, "safepoints should have unique landingpads",
4440 LandingPad
->getParent());
4441 Assert(InvokeBB
->getTerminator(), "safepoint block should be well formed",
4443 Assert(isStatepoint(InvokeBB
->getTerminator()),
4444 "gc relocate should be linked to a statepoint", InvokeBB
);
4446 // In all other cases relocate should be tied to the statepoint directly.
4447 // This covers relocates on a normal return path of invoke statepoint and
4448 // relocates of a call statepoint.
4449 auto Token
= Call
.getArgOperand(0);
4450 Assert(isa
<Instruction
>(Token
) && isStatepoint(cast
<Instruction
>(Token
)),
4451 "gc relocate is incorrectly tied to the statepoint", Call
, Token
);
4454 // Verify rest of the relocate arguments.
4455 const CallBase
&StatepointCall
=
4456 *cast
<CallBase
>(cast
<GCRelocateInst
>(Call
).getStatepoint());
4458 // Both the base and derived must be piped through the safepoint.
4459 Value
*Base
= Call
.getArgOperand(1);
4460 Assert(isa
<ConstantInt
>(Base
),
4461 "gc.relocate operand #2 must be integer offset", Call
);
4463 Value
*Derived
= Call
.getArgOperand(2);
4464 Assert(isa
<ConstantInt
>(Derived
),
4465 "gc.relocate operand #3 must be integer offset", Call
);
4467 const int BaseIndex
= cast
<ConstantInt
>(Base
)->getZExtValue();
4468 const int DerivedIndex
= cast
<ConstantInt
>(Derived
)->getZExtValue();
4470 Assert(0 <= BaseIndex
&& BaseIndex
< (int)StatepointCall
.arg_size(),
4471 "gc.relocate: statepoint base index out of bounds", Call
);
4472 Assert(0 <= DerivedIndex
&& DerivedIndex
< (int)StatepointCall
.arg_size(),
4473 "gc.relocate: statepoint derived index out of bounds", Call
);
4475 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
4476 // section of the statepoint's argument.
4477 Assert(StatepointCall
.arg_size() > 0,
4478 "gc.statepoint: insufficient arguments");
4479 Assert(isa
<ConstantInt
>(StatepointCall
.getArgOperand(3)),
4480 "gc.statement: number of call arguments must be constant integer");
4481 const unsigned NumCallArgs
=
4482 cast
<ConstantInt
>(StatepointCall
.getArgOperand(3))->getZExtValue();
4483 Assert(StatepointCall
.arg_size() > NumCallArgs
+ 5,
4484 "gc.statepoint: mismatch in number of call arguments");
4485 Assert(isa
<ConstantInt
>(StatepointCall
.getArgOperand(NumCallArgs
+ 5)),
4486 "gc.statepoint: number of transition arguments must be "
4487 "a constant integer");
4488 const int NumTransitionArgs
=
4489 cast
<ConstantInt
>(StatepointCall
.getArgOperand(NumCallArgs
+ 5))
4491 const int DeoptArgsStart
= 4 + NumCallArgs
+ 1 + NumTransitionArgs
+ 1;
4492 Assert(isa
<ConstantInt
>(StatepointCall
.getArgOperand(DeoptArgsStart
)),
4493 "gc.statepoint: number of deoptimization arguments must be "
4494 "a constant integer");
4495 const int NumDeoptArgs
=
4496 cast
<ConstantInt
>(StatepointCall
.getArgOperand(DeoptArgsStart
))
4498 const int GCParamArgsStart
= DeoptArgsStart
+ 1 + NumDeoptArgs
;
4499 const int GCParamArgsEnd
= StatepointCall
.arg_size();
4500 Assert(GCParamArgsStart
<= BaseIndex
&& BaseIndex
< GCParamArgsEnd
,
4501 "gc.relocate: statepoint base index doesn't fall within the "
4502 "'gc parameters' section of the statepoint call",
4504 Assert(GCParamArgsStart
<= DerivedIndex
&& DerivedIndex
< GCParamArgsEnd
,
4505 "gc.relocate: statepoint derived index doesn't fall within the "
4506 "'gc parameters' section of the statepoint call",
4509 // Relocated value must be either a pointer type or vector-of-pointer type,
4510 // but gc_relocate does not need to return the same pointer type as the
4511 // relocated pointer. It can be casted to the correct type later if it's
4512 // desired. However, they must have the same address space and 'vectorness'
4513 GCRelocateInst
&Relocate
= cast
<GCRelocateInst
>(Call
);
4514 Assert(Relocate
.getDerivedPtr()->getType()->isPtrOrPtrVectorTy(),
4515 "gc.relocate: relocated value must be a gc pointer", Call
);
4517 auto ResultType
= Call
.getType();
4518 auto DerivedType
= Relocate
.getDerivedPtr()->getType();
4519 Assert(ResultType
->isVectorTy() == DerivedType
->isVectorTy(),
4520 "gc.relocate: vector relocates to vector and pointer to pointer",
4523 ResultType
->getPointerAddressSpace() ==
4524 DerivedType
->getPointerAddressSpace(),
4525 "gc.relocate: relocating a pointer shouldn't change its address space",
4529 case Intrinsic::eh_exceptioncode
:
4530 case Intrinsic::eh_exceptionpointer
: {
4531 Assert(isa
<CatchPadInst
>(Call
.getArgOperand(0)),
4532 "eh.exceptionpointer argument must be a catchpad", Call
);
4535 case Intrinsic::masked_load
: {
4536 Assert(Call
.getType()->isVectorTy(), "masked_load: must return a vector",
4539 Value
*Ptr
= Call
.getArgOperand(0);
4540 ConstantInt
*Alignment
= cast
<ConstantInt
>(Call
.getArgOperand(1));
4541 Value
*Mask
= Call
.getArgOperand(2);
4542 Value
*PassThru
= Call
.getArgOperand(3);
4543 Assert(Mask
->getType()->isVectorTy(), "masked_load: mask must be vector",
4545 Assert(Alignment
->getValue().isPowerOf2(),
4546 "masked_load: alignment must be a power of 2", Call
);
4548 // DataTy is the overloaded type
4549 Type
*DataTy
= cast
<PointerType
>(Ptr
->getType())->getElementType();
4550 Assert(DataTy
== Call
.getType(),
4551 "masked_load: return must match pointer type", Call
);
4552 Assert(PassThru
->getType() == DataTy
,
4553 "masked_load: pass through and data type must match", Call
);
4554 Assert(Mask
->getType()->getVectorNumElements() ==
4555 DataTy
->getVectorNumElements(),
4556 "masked_load: vector mask must be same length as data", Call
);
4559 case Intrinsic::masked_store
: {
4560 Value
*Val
= Call
.getArgOperand(0);
4561 Value
*Ptr
= Call
.getArgOperand(1);
4562 ConstantInt
*Alignment
= cast
<ConstantInt
>(Call
.getArgOperand(2));
4563 Value
*Mask
= Call
.getArgOperand(3);
4564 Assert(Mask
->getType()->isVectorTy(), "masked_store: mask must be vector",
4566 Assert(Alignment
->getValue().isPowerOf2(),
4567 "masked_store: alignment must be a power of 2", Call
);
4569 // DataTy is the overloaded type
4570 Type
*DataTy
= cast
<PointerType
>(Ptr
->getType())->getElementType();
4571 Assert(DataTy
== Val
->getType(),
4572 "masked_store: storee must match pointer type", Call
);
4573 Assert(Mask
->getType()->getVectorNumElements() ==
4574 DataTy
->getVectorNumElements(),
4575 "masked_store: vector mask must be same length as data", Call
);
4579 case Intrinsic::experimental_guard
: {
4580 Assert(isa
<CallInst
>(Call
), "experimental_guard cannot be invoked", Call
);
4581 Assert(Call
.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1,
4582 "experimental_guard must have exactly one "
4583 "\"deopt\" operand bundle");
4587 case Intrinsic::experimental_deoptimize
: {
4588 Assert(isa
<CallInst
>(Call
), "experimental_deoptimize cannot be invoked",
4590 Assert(Call
.countOperandBundlesOfType(LLVMContext::OB_deopt
) == 1,
4591 "experimental_deoptimize must have exactly one "
4592 "\"deopt\" operand bundle");
4593 Assert(Call
.getType() == Call
.getFunction()->getReturnType(),
4594 "experimental_deoptimize return type must match caller return type");
4596 if (isa
<CallInst
>(Call
)) {
4597 auto *RI
= dyn_cast
<ReturnInst
>(Call
.getNextNode());
4599 "calls to experimental_deoptimize must be followed by a return");
4601 if (!Call
.getType()->isVoidTy() && RI
)
4602 Assert(RI
->getReturnValue() == &Call
,
4603 "calls to experimental_deoptimize must be followed by a return "
4604 "of the value computed by experimental_deoptimize");
4609 case Intrinsic::sadd_sat
:
4610 case Intrinsic::uadd_sat
:
4611 case Intrinsic::ssub_sat
:
4612 case Intrinsic::usub_sat
: {
4613 Value
*Op1
= Call
.getArgOperand(0);
4614 Value
*Op2
= Call
.getArgOperand(1);
4615 Assert(Op1
->getType()->isIntOrIntVectorTy(),
4616 "first operand of [us][add|sub]_sat must be an int type or vector "
4618 Assert(Op2
->getType()->isIntOrIntVectorTy(),
4619 "second operand of [us][add|sub]_sat must be an int type or vector "
4623 case Intrinsic::smul_fix
:
4624 case Intrinsic::smul_fix_sat
:
4625 case Intrinsic::umul_fix
: {
4626 Value
*Op1
= Call
.getArgOperand(0);
4627 Value
*Op2
= Call
.getArgOperand(1);
4628 Assert(Op1
->getType()->isIntOrIntVectorTy(),
4629 "first operand of [us]mul_fix[_sat] must be an int type or vector "
4631 Assert(Op2
->getType()->isIntOrIntVectorTy(),
4632 "second operand of [us]mul_fix_[sat] must be an int type or vector "
4635 auto *Op3
= cast
<ConstantInt
>(Call
.getArgOperand(2));
4636 Assert(Op3
->getType()->getBitWidth() <= 32,
4637 "third argument of [us]mul_fix[_sat] must fit within 32 bits");
4639 if (ID
== Intrinsic::smul_fix
|| ID
== Intrinsic::smul_fix_sat
) {
4641 Op3
->getZExtValue() < Op1
->getType()->getScalarSizeInBits(),
4642 "the scale of smul_fix[_sat] must be less than the width of the operands");
4644 Assert(Op3
->getZExtValue() <= Op1
->getType()->getScalarSizeInBits(),
4645 "the scale of umul_fix[_sat] must be less than or equal to the width of "
4650 case Intrinsic::lround
:
4651 case Intrinsic::llround
:
4652 case Intrinsic::lrint
:
4653 case Intrinsic::llrint
: {
4654 Type
*ValTy
= Call
.getArgOperand(0)->getType();
4655 Type
*ResultTy
= Call
.getType();
4656 Assert(!ValTy
->isVectorTy() && !ResultTy
->isVectorTy(),
4657 "Intrinsic does not support vectors", &Call
);
4663 /// Carefully grab the subprogram from a local scope.
4665 /// This carefully grabs the subprogram from a local scope, avoiding the
4666 /// built-in assertions that would typically fire.
4667 static DISubprogram
*getSubprogram(Metadata
*LocalScope
) {
4671 if (auto *SP
= dyn_cast
<DISubprogram
>(LocalScope
))
4674 if (auto *LB
= dyn_cast
<DILexicalBlockBase
>(LocalScope
))
4675 return getSubprogram(LB
->getRawScope());
4677 // Just return null; broken scope chains are checked elsewhere.
4678 assert(!isa
<DILocalScope
>(LocalScope
) && "Unknown type of local scope");
4682 void Verifier::visitConstrainedFPIntrinsic(ConstrainedFPIntrinsic
&FPI
) {
4683 unsigned NumOperands
= FPI
.getNumArgOperands();
4684 bool HasExceptionMD
= false;
4685 bool HasRoundingMD
= false;
4686 switch (FPI
.getIntrinsicID()) {
4687 case Intrinsic::experimental_constrained_sqrt
:
4688 case Intrinsic::experimental_constrained_sin
:
4689 case Intrinsic::experimental_constrained_cos
:
4690 case Intrinsic::experimental_constrained_exp
:
4691 case Intrinsic::experimental_constrained_exp2
:
4692 case Intrinsic::experimental_constrained_log
:
4693 case Intrinsic::experimental_constrained_log10
:
4694 case Intrinsic::experimental_constrained_log2
:
4695 case Intrinsic::experimental_constrained_rint
:
4696 case Intrinsic::experimental_constrained_nearbyint
:
4697 case Intrinsic::experimental_constrained_ceil
:
4698 case Intrinsic::experimental_constrained_floor
:
4699 case Intrinsic::experimental_constrained_round
:
4700 case Intrinsic::experimental_constrained_trunc
:
4701 Assert((NumOperands
== 3), "invalid arguments for constrained FP intrinsic",
4703 HasExceptionMD
= true;
4704 HasRoundingMD
= true;
4707 case Intrinsic::experimental_constrained_fma
:
4708 Assert((NumOperands
== 5), "invalid arguments for constrained FP intrinsic",
4710 HasExceptionMD
= true;
4711 HasRoundingMD
= true;
4714 case Intrinsic::experimental_constrained_fadd
:
4715 case Intrinsic::experimental_constrained_fsub
:
4716 case Intrinsic::experimental_constrained_fmul
:
4717 case Intrinsic::experimental_constrained_fdiv
:
4718 case Intrinsic::experimental_constrained_frem
:
4719 case Intrinsic::experimental_constrained_pow
:
4720 case Intrinsic::experimental_constrained_powi
:
4721 case Intrinsic::experimental_constrained_maxnum
:
4722 case Intrinsic::experimental_constrained_minnum
:
4723 Assert((NumOperands
== 4), "invalid arguments for constrained FP intrinsic",
4725 HasExceptionMD
= true;
4726 HasRoundingMD
= true;
4729 case Intrinsic::experimental_constrained_fptrunc
:
4730 case Intrinsic::experimental_constrained_fpext
: {
4731 if (FPI
.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc
) {
4732 Assert((NumOperands
== 3),
4733 "invalid arguments for constrained FP intrinsic", &FPI
);
4734 HasRoundingMD
= true;
4736 Assert((NumOperands
== 2),
4737 "invalid arguments for constrained FP intrinsic", &FPI
);
4739 HasExceptionMD
= true;
4741 Value
*Operand
= FPI
.getArgOperand(0);
4742 Type
*OperandTy
= Operand
->getType();
4743 Value
*Result
= &FPI
;
4744 Type
*ResultTy
= Result
->getType();
4745 Assert(OperandTy
->isFPOrFPVectorTy(),
4746 "Intrinsic first argument must be FP or FP vector", &FPI
);
4747 Assert(ResultTy
->isFPOrFPVectorTy(),
4748 "Intrinsic result must be FP or FP vector", &FPI
);
4749 Assert(OperandTy
->isVectorTy() == ResultTy
->isVectorTy(),
4750 "Intrinsic first argument and result disagree on vector use", &FPI
);
4751 if (OperandTy
->isVectorTy()) {
4752 auto *OperandVecTy
= cast
<VectorType
>(OperandTy
);
4753 auto *ResultVecTy
= cast
<VectorType
>(ResultTy
);
4754 Assert(OperandVecTy
->getNumElements() == ResultVecTy
->getNumElements(),
4755 "Intrinsic first argument and result vector lengths must be equal",
4758 if (FPI
.getIntrinsicID() == Intrinsic::experimental_constrained_fptrunc
) {
4759 Assert(OperandTy
->getScalarSizeInBits() > ResultTy
->getScalarSizeInBits(),
4760 "Intrinsic first argument's type must be larger than result type",
4763 Assert(OperandTy
->getScalarSizeInBits() < ResultTy
->getScalarSizeInBits(),
4764 "Intrinsic first argument's type must be smaller than result type",
4771 llvm_unreachable("Invalid constrained FP intrinsic!");
4774 // If a non-metadata argument is passed in a metadata slot then the
4775 // error will be caught earlier when the incorrect argument doesn't
4776 // match the specification in the intrinsic call table. Thus, no
4777 // argument type check is needed here.
4779 if (HasExceptionMD
) {
4780 Assert(FPI
.getExceptionBehavior().hasValue(),
4781 "invalid exception behavior argument", &FPI
);
4783 if (HasRoundingMD
) {
4784 Assert(FPI
.getRoundingMode().hasValue(),
4785 "invalid rounding mode argument", &FPI
);
4789 void Verifier::visitDbgIntrinsic(StringRef Kind
, DbgVariableIntrinsic
&DII
) {
4790 auto *MD
= cast
<MetadataAsValue
>(DII
.getArgOperand(0))->getMetadata();
4791 AssertDI(isa
<ValueAsMetadata
>(MD
) ||
4792 (isa
<MDNode
>(MD
) && !cast
<MDNode
>(MD
)->getNumOperands()),
4793 "invalid llvm.dbg." + Kind
+ " intrinsic address/value", &DII
, MD
);
4794 AssertDI(isa
<DILocalVariable
>(DII
.getRawVariable()),
4795 "invalid llvm.dbg." + Kind
+ " intrinsic variable", &DII
,
4796 DII
.getRawVariable());
4797 AssertDI(isa
<DIExpression
>(DII
.getRawExpression()),
4798 "invalid llvm.dbg." + Kind
+ " intrinsic expression", &DII
,
4799 DII
.getRawExpression());
4801 // Ignore broken !dbg attachments; they're checked elsewhere.
4802 if (MDNode
*N
= DII
.getDebugLoc().getAsMDNode())
4803 if (!isa
<DILocation
>(N
))
4806 BasicBlock
*BB
= DII
.getParent();
4807 Function
*F
= BB
? BB
->getParent() : nullptr;
4809 // The scopes for variables and !dbg attachments must agree.
4810 DILocalVariable
*Var
= DII
.getVariable();
4811 DILocation
*Loc
= DII
.getDebugLoc();
4812 AssertDI(Loc
, "llvm.dbg." + Kind
+ " intrinsic requires a !dbg attachment",
4815 DISubprogram
*VarSP
= getSubprogram(Var
->getRawScope());
4816 DISubprogram
*LocSP
= getSubprogram(Loc
->getRawScope());
4817 if (!VarSP
|| !LocSP
)
4818 return; // Broken scope chains are checked elsewhere.
4820 AssertDI(VarSP
== LocSP
, "mismatched subprogram between llvm.dbg." + Kind
+
4821 " variable and !dbg attachment",
4822 &DII
, BB
, F
, Var
, Var
->getScope()->getSubprogram(), Loc
,
4823 Loc
->getScope()->getSubprogram());
4825 // This check is redundant with one in visitLocalVariable().
4826 AssertDI(isType(Var
->getRawType()), "invalid type ref", Var
,
4828 if (auto *Type
= dyn_cast_or_null
<DIType
>(Var
->getRawType()))
4829 if (Type
->isBlockByrefStruct())
4830 AssertDI(DII
.getExpression() && DII
.getExpression()->getNumElements(),
4831 "BlockByRef variable without complex expression", Var
, &DII
);
4836 void Verifier::visitDbgLabelIntrinsic(StringRef Kind
, DbgLabelInst
&DLI
) {
4837 AssertDI(isa
<DILabel
>(DLI
.getRawLabel()),
4838 "invalid llvm.dbg." + Kind
+ " intrinsic variable", &DLI
,
4841 // Ignore broken !dbg attachments; they're checked elsewhere.
4842 if (MDNode
*N
= DLI
.getDebugLoc().getAsMDNode())
4843 if (!isa
<DILocation
>(N
))
4846 BasicBlock
*BB
= DLI
.getParent();
4847 Function
*F
= BB
? BB
->getParent() : nullptr;
4849 // The scopes for variables and !dbg attachments must agree.
4850 DILabel
*Label
= DLI
.getLabel();
4851 DILocation
*Loc
= DLI
.getDebugLoc();
4852 Assert(Loc
, "llvm.dbg." + Kind
+ " intrinsic requires a !dbg attachment",
4855 DISubprogram
*LabelSP
= getSubprogram(Label
->getRawScope());
4856 DISubprogram
*LocSP
= getSubprogram(Loc
->getRawScope());
4857 if (!LabelSP
|| !LocSP
)
4860 AssertDI(LabelSP
== LocSP
, "mismatched subprogram between llvm.dbg." + Kind
+
4861 " label and !dbg attachment",
4862 &DLI
, BB
, F
, Label
, Label
->getScope()->getSubprogram(), Loc
,
4863 Loc
->getScope()->getSubprogram());
4866 void Verifier::verifyFragmentExpression(const DbgVariableIntrinsic
&I
) {
4867 DILocalVariable
*V
= dyn_cast_or_null
<DILocalVariable
>(I
.getRawVariable());
4868 DIExpression
*E
= dyn_cast_or_null
<DIExpression
>(I
.getRawExpression());
4870 // We don't know whether this intrinsic verified correctly.
4871 if (!V
|| !E
|| !E
->isValid())
4874 // Nothing to do if this isn't a DW_OP_LLVM_fragment expression.
4875 auto Fragment
= E
->getFragmentInfo();
4879 // The frontend helps out GDB by emitting the members of local anonymous
4880 // unions as artificial local variables with shared storage. When SROA splits
4881 // the storage for artificial local variables that are smaller than the entire
4882 // union, the overhang piece will be outside of the allotted space for the
4883 // variable and this check fails.
4884 // FIXME: Remove this check as soon as clang stops doing this; it hides bugs.
4885 if (V
->isArtificial())
4888 verifyFragmentExpression(*V
, *Fragment
, &I
);
4891 template <typename ValueOrMetadata
>
4892 void Verifier::verifyFragmentExpression(const DIVariable
&V
,
4893 DIExpression::FragmentInfo Fragment
,
4894 ValueOrMetadata
*Desc
) {
4895 // If there's no size, the type is broken, but that should be checked
4897 auto VarSize
= V
.getSizeInBits();
4901 unsigned FragSize
= Fragment
.SizeInBits
;
4902 unsigned FragOffset
= Fragment
.OffsetInBits
;
4903 AssertDI(FragSize
+ FragOffset
<= *VarSize
,
4904 "fragment is larger than or outside of variable", Desc
, &V
);
4905 AssertDI(FragSize
!= *VarSize
, "fragment covers entire variable", Desc
, &V
);
4908 void Verifier::verifyFnArgs(const DbgVariableIntrinsic
&I
) {
4909 // This function does not take the scope of noninlined function arguments into
4910 // account. Don't run it if current function is nodebug, because it may
4911 // contain inlined debug intrinsics.
4915 // For performance reasons only check non-inlined ones.
4916 if (I
.getDebugLoc()->getInlinedAt())
4919 DILocalVariable
*Var
= I
.getVariable();
4920 AssertDI(Var
, "dbg intrinsic without variable");
4922 unsigned ArgNo
= Var
->getArg();
4926 // Verify there are no duplicate function argument debug info entries.
4927 // These will cause hard-to-debug assertions in the DWARF backend.
4928 if (DebugFnArgs
.size() < ArgNo
)
4929 DebugFnArgs
.resize(ArgNo
, nullptr);
4931 auto *Prev
= DebugFnArgs
[ArgNo
- 1];
4932 DebugFnArgs
[ArgNo
- 1] = Var
;
4933 AssertDI(!Prev
|| (Prev
== Var
), "conflicting debug info for argument", &I
,
4937 void Verifier::verifyCompileUnits() {
4938 // When more than one Module is imported into the same context, such as during
4939 // an LTO build before linking the modules, ODR type uniquing may cause types
4940 // to point to a different CU. This check does not make sense in this case.
4941 if (M
.getContext().isODRUniquingDebugTypes())
4943 auto *CUs
= M
.getNamedMetadata("llvm.dbg.cu");
4944 SmallPtrSet
<const Metadata
*, 2> Listed
;
4946 Listed
.insert(CUs
->op_begin(), CUs
->op_end());
4947 for (auto *CU
: CUVisited
)
4948 AssertDI(Listed
.count(CU
), "DICompileUnit not listed in llvm.dbg.cu", CU
);
4952 void Verifier::verifyDeoptimizeCallingConvs() {
4953 if (DeoptimizeDeclarations
.empty())
4956 const Function
*First
= DeoptimizeDeclarations
[0];
4957 for (auto *F
: makeArrayRef(DeoptimizeDeclarations
).slice(1)) {
4958 Assert(First
->getCallingConv() == F
->getCallingConv(),
4959 "All llvm.experimental.deoptimize declarations must have the same "
4960 "calling convention",
4965 void Verifier::verifySourceDebugInfo(const DICompileUnit
&U
, const DIFile
&F
) {
4966 bool HasSource
= F
.getSource().hasValue();
4967 if (!HasSourceDebugInfo
.count(&U
))
4968 HasSourceDebugInfo
[&U
] = HasSource
;
4969 AssertDI(HasSource
== HasSourceDebugInfo
[&U
],
4970 "inconsistent use of embedded source");
4973 //===----------------------------------------------------------------------===//
4974 // Implement the public interfaces to this file...
4975 //===----------------------------------------------------------------------===//
4977 bool llvm::verifyFunction(const Function
&f
, raw_ostream
*OS
) {
4978 Function
&F
= const_cast<Function
&>(f
);
4980 // Don't use a raw_null_ostream. Printing IR is expensive.
4981 Verifier
V(OS
, /*ShouldTreatBrokenDebugInfoAsError=*/true, *f
.getParent());
4983 // Note that this function's return value is inverted from what you would
4984 // expect of a function called "verify".
4985 return !V
.verify(F
);
4988 bool llvm::verifyModule(const Module
&M
, raw_ostream
*OS
,
4989 bool *BrokenDebugInfo
) {
4990 // Don't use a raw_null_ostream. Printing IR is expensive.
4991 Verifier
V(OS
, /*ShouldTreatBrokenDebugInfoAsError=*/!BrokenDebugInfo
, M
);
4993 bool Broken
= false;
4994 for (const Function
&F
: M
)
4995 Broken
|= !V
.verify(F
);
4997 Broken
|= !V
.verify();
4998 if (BrokenDebugInfo
)
4999 *BrokenDebugInfo
= V
.hasBrokenDebugInfo();
5000 // Note that this function's return value is inverted from what you would
5001 // expect of a function called "verify".
5007 struct VerifierLegacyPass
: public FunctionPass
{
5010 std::unique_ptr
<Verifier
> V
;
5011 bool FatalErrors
= true;
5013 VerifierLegacyPass() : FunctionPass(ID
) {
5014 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
5016 explicit VerifierLegacyPass(bool FatalErrors
)
5018 FatalErrors(FatalErrors
) {
5019 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
5022 bool doInitialization(Module
&M
) override
{
5023 V
= llvm::make_unique
<Verifier
>(
5024 &dbgs(), /*ShouldTreatBrokenDebugInfoAsError=*/false, M
);
5028 bool runOnFunction(Function
&F
) override
{
5029 if (!V
->verify(F
) && FatalErrors
) {
5030 errs() << "in function " << F
.getName() << '\n';
5031 report_fatal_error("Broken function found, compilation aborted!");
5036 bool doFinalization(Module
&M
) override
{
5037 bool HasErrors
= false;
5038 for (Function
&F
: M
)
5039 if (F
.isDeclaration())
5040 HasErrors
|= !V
->verify(F
);
5042 HasErrors
|= !V
->verify();
5043 if (FatalErrors
&& (HasErrors
|| V
->hasBrokenDebugInfo()))
5044 report_fatal_error("Broken module found, compilation aborted!");
5048 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
5049 AU
.setPreservesAll();
5053 } // end anonymous namespace
5055 /// Helper to issue failure from the TBAA verification
5056 template <typename
... Tys
> void TBAAVerifier::CheckFailed(Tys
&&... Args
) {
5058 return Diagnostic
->CheckFailed(Args
...);
5061 #define AssertTBAA(C, ...) \
5064 CheckFailed(__VA_ARGS__); \
5069 /// Verify that \p BaseNode can be used as the "base type" in the struct-path
5070 /// TBAA scheme. This means \p BaseNode is either a scalar node, or a
5071 /// struct-type node describing an aggregate data structure (like a struct).
5072 TBAAVerifier::TBAABaseNodeSummary
5073 TBAAVerifier::verifyTBAABaseNode(Instruction
&I
, const MDNode
*BaseNode
,
5075 if (BaseNode
->getNumOperands() < 2) {
5076 CheckFailed("Base nodes must have at least two operands", &I
, BaseNode
);
5080 auto Itr
= TBAABaseNodes
.find(BaseNode
);
5081 if (Itr
!= TBAABaseNodes
.end())
5084 auto Result
= verifyTBAABaseNodeImpl(I
, BaseNode
, IsNewFormat
);
5085 auto InsertResult
= TBAABaseNodes
.insert({BaseNode
, Result
});
5087 assert(InsertResult
.second
&& "We just checked!");
5091 TBAAVerifier::TBAABaseNodeSummary
5092 TBAAVerifier::verifyTBAABaseNodeImpl(Instruction
&I
, const MDNode
*BaseNode
,
5094 const TBAAVerifier::TBAABaseNodeSummary InvalidNode
= {true, ~0u};
5096 if (BaseNode
->getNumOperands() == 2) {
5097 // Scalar nodes can only be accessed at offset 0.
5098 return isValidScalarTBAANode(BaseNode
)
5099 ? TBAAVerifier::TBAABaseNodeSummary({false, 0})
5104 if (BaseNode
->getNumOperands() % 3 != 0) {
5105 CheckFailed("Access tag nodes must have the number of operands that is a "
5106 "multiple of 3!", BaseNode
);
5110 if (BaseNode
->getNumOperands() % 2 != 1) {
5111 CheckFailed("Struct tag nodes must have an odd number of operands!",
5117 // Check the type size field.
5119 auto *TypeSizeNode
= mdconst::dyn_extract_or_null
<ConstantInt
>(
5120 BaseNode
->getOperand(1));
5121 if (!TypeSizeNode
) {
5122 CheckFailed("Type size nodes must be constants!", &I
, BaseNode
);
5127 // Check the type name field. In the new format it can be anything.
5128 if (!IsNewFormat
&& !isa
<MDString
>(BaseNode
->getOperand(0))) {
5129 CheckFailed("Struct tag nodes have a string as their first operand",
5134 bool Failed
= false;
5136 Optional
<APInt
> PrevOffset
;
5137 unsigned BitWidth
= ~0u;
5139 // We've already checked that BaseNode is not a degenerate root node with one
5140 // operand in \c verifyTBAABaseNode, so this loop should run at least once.
5141 unsigned FirstFieldOpNo
= IsNewFormat
? 3 : 1;
5142 unsigned NumOpsPerField
= IsNewFormat
? 3 : 2;
5143 for (unsigned Idx
= FirstFieldOpNo
; Idx
< BaseNode
->getNumOperands();
5144 Idx
+= NumOpsPerField
) {
5145 const MDOperand
&FieldTy
= BaseNode
->getOperand(Idx
);
5146 const MDOperand
&FieldOffset
= BaseNode
->getOperand(Idx
+ 1);
5147 if (!isa
<MDNode
>(FieldTy
)) {
5148 CheckFailed("Incorrect field entry in struct type node!", &I
, BaseNode
);
5153 auto *OffsetEntryCI
=
5154 mdconst::dyn_extract_or_null
<ConstantInt
>(FieldOffset
);
5155 if (!OffsetEntryCI
) {
5156 CheckFailed("Offset entries must be constants!", &I
, BaseNode
);
5161 if (BitWidth
== ~0u)
5162 BitWidth
= OffsetEntryCI
->getBitWidth();
5164 if (OffsetEntryCI
->getBitWidth() != BitWidth
) {
5166 "Bitwidth between the offsets and struct type entries must match", &I
,
5172 // NB! As far as I can tell, we generate a non-strictly increasing offset
5173 // sequence only from structs that have zero size bit fields. When
5174 // recursing into a contained struct in \c getFieldNodeFromTBAABaseNode we
5175 // pick the field lexically the latest in struct type metadata node. This
5176 // mirrors the actual behavior of the alias analysis implementation.
5178 !PrevOffset
|| PrevOffset
->ule(OffsetEntryCI
->getValue());
5181 CheckFailed("Offsets must be increasing!", &I
, BaseNode
);
5185 PrevOffset
= OffsetEntryCI
->getValue();
5188 auto *MemberSizeNode
= mdconst::dyn_extract_or_null
<ConstantInt
>(
5189 BaseNode
->getOperand(Idx
+ 2));
5190 if (!MemberSizeNode
) {
5191 CheckFailed("Member size entries must be constants!", &I
, BaseNode
);
5198 return Failed
? InvalidNode
5199 : TBAAVerifier::TBAABaseNodeSummary(false, BitWidth
);
5202 static bool IsRootTBAANode(const MDNode
*MD
) {
5203 return MD
->getNumOperands() < 2;
5206 static bool IsScalarTBAANodeImpl(const MDNode
*MD
,
5207 SmallPtrSetImpl
<const MDNode
*> &Visited
) {
5208 if (MD
->getNumOperands() != 2 && MD
->getNumOperands() != 3)
5211 if (!isa
<MDString
>(MD
->getOperand(0)))
5214 if (MD
->getNumOperands() == 3) {
5215 auto *Offset
= mdconst::dyn_extract
<ConstantInt
>(MD
->getOperand(2));
5216 if (!(Offset
&& Offset
->isZero() && isa
<MDString
>(MD
->getOperand(0))))
5220 auto *Parent
= dyn_cast_or_null
<MDNode
>(MD
->getOperand(1));
5221 return Parent
&& Visited
.insert(Parent
).second
&&
5222 (IsRootTBAANode(Parent
) || IsScalarTBAANodeImpl(Parent
, Visited
));
5225 bool TBAAVerifier::isValidScalarTBAANode(const MDNode
*MD
) {
5226 auto ResultIt
= TBAAScalarNodes
.find(MD
);
5227 if (ResultIt
!= TBAAScalarNodes
.end())
5228 return ResultIt
->second
;
5230 SmallPtrSet
<const MDNode
*, 4> Visited
;
5231 bool Result
= IsScalarTBAANodeImpl(MD
, Visited
);
5232 auto InsertResult
= TBAAScalarNodes
.insert({MD
, Result
});
5234 assert(InsertResult
.second
&& "Just checked!");
5239 /// Returns the field node at the offset \p Offset in \p BaseNode. Update \p
5240 /// Offset in place to be the offset within the field node returned.
5242 /// We assume we've okayed \p BaseNode via \c verifyTBAABaseNode.
5243 MDNode
*TBAAVerifier::getFieldNodeFromTBAABaseNode(Instruction
&I
,
5244 const MDNode
*BaseNode
,
5247 assert(BaseNode
->getNumOperands() >= 2 && "Invalid base node!");
5249 // Scalar nodes have only one possible "field" -- their parent in the access
5250 // hierarchy. Offset must be zero at this point, but our caller is supposed
5252 if (BaseNode
->getNumOperands() == 2)
5253 return cast
<MDNode
>(BaseNode
->getOperand(1));
5255 unsigned FirstFieldOpNo
= IsNewFormat
? 3 : 1;
5256 unsigned NumOpsPerField
= IsNewFormat
? 3 : 2;
5257 for (unsigned Idx
= FirstFieldOpNo
; Idx
< BaseNode
->getNumOperands();
5258 Idx
+= NumOpsPerField
) {
5259 auto *OffsetEntryCI
=
5260 mdconst::extract
<ConstantInt
>(BaseNode
->getOperand(Idx
+ 1));
5261 if (OffsetEntryCI
->getValue().ugt(Offset
)) {
5262 if (Idx
== FirstFieldOpNo
) {
5263 CheckFailed("Could not find TBAA parent in struct type node", &I
,
5268 unsigned PrevIdx
= Idx
- NumOpsPerField
;
5269 auto *PrevOffsetEntryCI
=
5270 mdconst::extract
<ConstantInt
>(BaseNode
->getOperand(PrevIdx
+ 1));
5271 Offset
-= PrevOffsetEntryCI
->getValue();
5272 return cast
<MDNode
>(BaseNode
->getOperand(PrevIdx
));
5276 unsigned LastIdx
= BaseNode
->getNumOperands() - NumOpsPerField
;
5277 auto *LastOffsetEntryCI
= mdconst::extract
<ConstantInt
>(
5278 BaseNode
->getOperand(LastIdx
+ 1));
5279 Offset
-= LastOffsetEntryCI
->getValue();
5280 return cast
<MDNode
>(BaseNode
->getOperand(LastIdx
));
5283 static bool isNewFormatTBAATypeNode(llvm::MDNode
*Type
) {
5284 if (!Type
|| Type
->getNumOperands() < 3)
5287 // In the new format type nodes shall have a reference to the parent type as
5288 // its first operand.
5289 MDNode
*Parent
= dyn_cast_or_null
<MDNode
>(Type
->getOperand(0));
5296 bool TBAAVerifier::visitTBAAMetadata(Instruction
&I
, const MDNode
*MD
) {
5297 AssertTBAA(isa
<LoadInst
>(I
) || isa
<StoreInst
>(I
) || isa
<CallInst
>(I
) ||
5298 isa
<VAArgInst
>(I
) || isa
<AtomicRMWInst
>(I
) ||
5299 isa
<AtomicCmpXchgInst
>(I
),
5300 "This instruction shall not have a TBAA access tag!", &I
);
5302 bool IsStructPathTBAA
=
5303 isa
<MDNode
>(MD
->getOperand(0)) && MD
->getNumOperands() >= 3;
5307 "Old-style TBAA is no longer allowed, use struct-path TBAA instead", &I
);
5309 MDNode
*BaseNode
= dyn_cast_or_null
<MDNode
>(MD
->getOperand(0));
5310 MDNode
*AccessType
= dyn_cast_or_null
<MDNode
>(MD
->getOperand(1));
5312 bool IsNewFormat
= isNewFormatTBAATypeNode(AccessType
);
5315 AssertTBAA(MD
->getNumOperands() == 4 || MD
->getNumOperands() == 5,
5316 "Access tag metadata must have either 4 or 5 operands", &I
, MD
);
5318 AssertTBAA(MD
->getNumOperands() < 5,
5319 "Struct tag metadata must have either 3 or 4 operands", &I
, MD
);
5322 // Check the access size field.
5324 auto *AccessSizeNode
= mdconst::dyn_extract_or_null
<ConstantInt
>(
5326 AssertTBAA(AccessSizeNode
, "Access size field must be a constant", &I
, MD
);
5329 // Check the immutability flag.
5330 unsigned ImmutabilityFlagOpNo
= IsNewFormat
? 4 : 3;
5331 if (MD
->getNumOperands() == ImmutabilityFlagOpNo
+ 1) {
5332 auto *IsImmutableCI
= mdconst::dyn_extract_or_null
<ConstantInt
>(
5333 MD
->getOperand(ImmutabilityFlagOpNo
));
5334 AssertTBAA(IsImmutableCI
,
5335 "Immutability tag on struct tag metadata must be a constant",
5338 IsImmutableCI
->isZero() || IsImmutableCI
->isOne(),
5339 "Immutability part of the struct tag metadata must be either 0 or 1",
5343 AssertTBAA(BaseNode
&& AccessType
,
5344 "Malformed struct tag metadata: base and access-type "
5345 "should be non-null and point to Metadata nodes",
5346 &I
, MD
, BaseNode
, AccessType
);
5349 AssertTBAA(isValidScalarTBAANode(AccessType
),
5350 "Access type node must be a valid scalar type", &I
, MD
,
5354 auto *OffsetCI
= mdconst::dyn_extract_or_null
<ConstantInt
>(MD
->getOperand(2));
5355 AssertTBAA(OffsetCI
, "Offset must be constant integer", &I
, MD
);
5357 APInt Offset
= OffsetCI
->getValue();
5358 bool SeenAccessTypeInPath
= false;
5360 SmallPtrSet
<MDNode
*, 4> StructPath
;
5362 for (/* empty */; BaseNode
&& !IsRootTBAANode(BaseNode
);
5363 BaseNode
= getFieldNodeFromTBAABaseNode(I
, BaseNode
, Offset
,
5365 if (!StructPath
.insert(BaseNode
).second
) {
5366 CheckFailed("Cycle detected in struct path", &I
, MD
);
5371 unsigned BaseNodeBitWidth
;
5372 std::tie(Invalid
, BaseNodeBitWidth
) = verifyTBAABaseNode(I
, BaseNode
,
5375 // If the base node is invalid in itself, then we've already printed all the
5376 // errors we wanted to print.
5380 SeenAccessTypeInPath
|= BaseNode
== AccessType
;
5382 if (isValidScalarTBAANode(BaseNode
) || BaseNode
== AccessType
)
5383 AssertTBAA(Offset
== 0, "Offset not zero at the point of scalar access",
5386 AssertTBAA(BaseNodeBitWidth
== Offset
.getBitWidth() ||
5387 (BaseNodeBitWidth
== 0 && Offset
== 0) ||
5388 (IsNewFormat
&& BaseNodeBitWidth
== ~0u),
5389 "Access bit-width not the same as description bit-width", &I
, MD
,
5390 BaseNodeBitWidth
, Offset
.getBitWidth());
5392 if (IsNewFormat
&& SeenAccessTypeInPath
)
5396 AssertTBAA(SeenAccessTypeInPath
, "Did not see access type in access path!",
5401 char VerifierLegacyPass::ID
= 0;
5402 INITIALIZE_PASS(VerifierLegacyPass
, "verify", "Module Verifier", false, false)
5404 FunctionPass
*llvm::createVerifierPass(bool FatalErrors
) {
5405 return new VerifierLegacyPass(FatalErrors
);
5408 AnalysisKey
VerifierAnalysis::Key
;
5409 VerifierAnalysis::Result
VerifierAnalysis::run(Module
&M
,
5410 ModuleAnalysisManager
&) {
5412 Res
.IRBroken
= llvm::verifyModule(M
, &dbgs(), &Res
.DebugInfoBroken
);
5416 VerifierAnalysis::Result
VerifierAnalysis::run(Function
&F
,
5417 FunctionAnalysisManager
&) {
5418 return { llvm::verifyFunction(F
, &dbgs()), false };
5421 PreservedAnalyses
VerifierPass::run(Module
&M
, ModuleAnalysisManager
&AM
) {
5422 auto Res
= AM
.getResult
<VerifierAnalysis
>(M
);
5423 if (FatalErrors
&& (Res
.IRBroken
|| Res
.DebugInfoBroken
))
5424 report_fatal_error("Broken module found, compilation aborted!");
5426 return PreservedAnalyses::all();
5429 PreservedAnalyses
VerifierPass::run(Function
&F
, FunctionAnalysisManager
&AM
) {
5430 auto res
= AM
.getResult
<VerifierAnalysis
>(F
);
5431 if (res
.IRBroken
&& FatalErrors
)
5432 report_fatal_error("Broken function found, compilation aborted!");
5434 return PreservedAnalyses::all();