1 //===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the function verifier interface, that can be used for some
11 // sanity checking of input to the system.
13 // Note that this does not provide full `Java style' security and verifications,
14 // instead it just tries to ensure that code is well-formed.
16 // * Both of a binary operator's parameters are of the same type
17 // * Verify that the indices of mem access instructions match other operands
18 // * Verify that arithmetic and other things are only performed on first-class
19 // types. Verify that shifts & logicals only happen on integrals f.e.
20 // * All of the constants in a switch statement are of the correct type
21 // * The code is in valid SSA form
22 // * It should be illegal to put a label into any other type (like a structure)
23 // or to return one. [except constant arrays!]
24 // * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
25 // * PHI nodes must have an entry for each predecessor, with no extras.
26 // * PHI nodes must be the first thing in a basic block, all grouped together
27 // * PHI nodes must have at least one entry
28 // * All basic blocks should only end with terminator insts, not contain them
29 // * The entry node to a function must not have predecessors
30 // * All Instructions must be embedded into a basic block
31 // * Functions cannot take a void-typed parameter
32 // * Verify that a function's argument list agrees with it's declared type.
33 // * It is illegal to specify a name for a void value.
34 // * It is illegal to have a internal global value with no initializer
35 // * It is illegal to have a ret instruction that returns a value that does not
36 // agree with the function return value type.
37 // * Function call argument types match the function prototype
38 // * A landing pad is defined by a landingpad instruction, and can be jumped to
39 // only by the unwind edge of an invoke instruction.
40 // * A landingpad instruction must be the first non-PHI instruction in the
42 // * All landingpad instructions must use the same personality function with
44 // * All other things that are tested by asserts spread about the code...
46 //===----------------------------------------------------------------------===//
48 #include "llvm/IR/Verifier.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/ADT/SetVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/ADT/StringExtras.h"
54 #include "llvm/IR/CFG.h"
55 #include "llvm/IR/CallSite.h"
56 #include "llvm/IR/CallingConv.h"
57 #include "llvm/IR/ConstantRange.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugInfo.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Dominators.h"
63 #include "llvm/IR/InlineAsm.h"
64 #include "llvm/IR/InstIterator.h"
65 #include "llvm/IR/InstVisitor.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/LLVMContext.h"
68 #include "llvm/IR/Metadata.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/PassManager.h"
71 #include "llvm/IR/Statepoint.h"
72 #include "llvm/Pass.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/raw_ostream.h"
81 static cl::opt<bool> VerifyDebugInfo("verify-debug-info", cl::init(true));
84 struct VerifierSupport {
88 /// \brief Track the brokenness of the module while recursively visiting.
92 explicit VerifierSupport(raw_ostream &OS)
93 : OS(OS), M(nullptr), Broken(false), EverBroken(false) {}
96 void Write(const Value *V) {
99 if (isa<Instruction>(V)) {
102 V->printAsOperand(OS, true, M);
107 void Write(const Metadata *MD) {
114 void Write(Type *T) {
120 void Write(const Comdat *C) {
126 template <typename T1, typename... Ts>
127 void WriteTs(const T1 &V1, const Ts &... Vs) {
132 template <typename... Ts> void WriteTs() {}
135 /// \brief A check failed, so printout out the condition and the message.
137 /// This provides a nice place to put a breakpoint if you want to see why
138 /// something is not correct.
139 void CheckFailed(const Twine &Message) {
140 OS << Message << '\n';
141 EverBroken = Broken = true;
144 /// \brief A check failed (with values to print).
146 /// This calls the Message-only version so that the above is easier to set a
148 template <typename T1, typename... Ts>
149 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
150 CheckFailed(Message);
155 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
156 friend class InstVisitor<Verifier>;
158 LLVMContext *Context;
161 /// \brief When verifying a basic block, keep track of all of the
162 /// instructions we have seen so far.
164 /// This allows us to do efficient dominance checks for the case when an
165 /// instruction has an operand that is an instruction in the same block.
166 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
168 /// \brief Keep track of the metadata nodes that have been checked already.
169 SmallPtrSet<const Metadata *, 32> MDNodes;
171 /// \brief The personality function referenced by the LandingPadInsts.
172 /// All LandingPadInsts within the same function must use the same
173 /// personality function.
174 const Value *PersonalityFn;
176 /// \brief Whether we've seen a call to @llvm.frameescape in this function
180 /// Stores the count of how many objects were passed to llvm.frameescape for a
181 /// given function and the largest index passed to llvm.framerecover.
182 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
185 explicit Verifier(raw_ostream &OS)
186 : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
187 SawFrameEscape(false) {}
189 bool verify(const Function &F) {
191 Context = &M->getContext();
193 // First ensure the function is well-enough formed to compute dominance
196 OS << "Function '" << F.getName()
197 << "' does not contain an entry block!\n";
200 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
201 if (I->empty() || !I->back().isTerminator()) {
202 OS << "Basic Block in function '" << F.getName()
203 << "' does not have terminator!\n";
204 I->printAsOperand(OS, true);
210 // Now directly compute a dominance tree. We don't rely on the pass
211 // manager to provide this as it isolates us from a potentially
212 // out-of-date dominator tree and makes it significantly more complex to
213 // run this code outside of a pass manager.
214 // FIXME: It's really gross that we have to cast away constness here.
215 DT.recalculate(const_cast<Function &>(F));
218 // FIXME: We strip const here because the inst visitor strips const.
219 visit(const_cast<Function &>(F));
220 InstsInThisBlock.clear();
221 PersonalityFn = nullptr;
222 SawFrameEscape = false;
227 bool verify(const Module &M) {
229 Context = &M.getContext();
232 // Scan through, checking all of the external function's linkage now...
233 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
234 visitGlobalValue(*I);
236 // Check to make sure function prototypes are okay.
237 if (I->isDeclaration())
241 // Now that we've visited every function, verify that we never asked to
242 // recover a frame index that wasn't escaped.
243 verifyFrameRecoverIndices();
245 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
247 visitGlobalVariable(*I);
249 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
251 visitGlobalAlias(*I);
253 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
254 E = M.named_metadata_end();
256 visitNamedMDNode(*I);
258 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
259 visitComdat(SMEC.getValue());
262 visitModuleIdents(M);
264 // Verify debug info last.
271 // Verification methods...
272 void visitGlobalValue(const GlobalValue &GV);
273 void visitGlobalVariable(const GlobalVariable &GV);
274 void visitGlobalAlias(const GlobalAlias &GA);
275 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
276 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
277 const GlobalAlias &A, const Constant &C);
278 void visitNamedMDNode(const NamedMDNode &NMD);
279 void visitMDNode(const MDNode &MD);
280 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
281 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
282 void visitComdat(const Comdat &C);
283 void visitModuleIdents(const Module &M);
284 void visitModuleFlags(const Module &M);
285 void visitModuleFlag(const MDNode *Op,
286 DenseMap<const MDString *, const MDNode *> &SeenIDs,
287 SmallVectorImpl<const MDNode *> &Requirements);
288 void visitFunction(const Function &F);
289 void visitBasicBlock(BasicBlock &BB);
290 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
292 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
293 #include "llvm/IR/Metadata.def"
295 // InstVisitor overrides...
296 using InstVisitor<Verifier>::visit;
297 void visit(Instruction &I);
299 void visitTruncInst(TruncInst &I);
300 void visitZExtInst(ZExtInst &I);
301 void visitSExtInst(SExtInst &I);
302 void visitFPTruncInst(FPTruncInst &I);
303 void visitFPExtInst(FPExtInst &I);
304 void visitFPToUIInst(FPToUIInst &I);
305 void visitFPToSIInst(FPToSIInst &I);
306 void visitUIToFPInst(UIToFPInst &I);
307 void visitSIToFPInst(SIToFPInst &I);
308 void visitIntToPtrInst(IntToPtrInst &I);
309 void visitPtrToIntInst(PtrToIntInst &I);
310 void visitBitCastInst(BitCastInst &I);
311 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
312 void visitPHINode(PHINode &PN);
313 void visitBinaryOperator(BinaryOperator &B);
314 void visitICmpInst(ICmpInst &IC);
315 void visitFCmpInst(FCmpInst &FC);
316 void visitExtractElementInst(ExtractElementInst &EI);
317 void visitInsertElementInst(InsertElementInst &EI);
318 void visitShuffleVectorInst(ShuffleVectorInst &EI);
319 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
320 void visitCallInst(CallInst &CI);
321 void visitInvokeInst(InvokeInst &II);
322 void visitGetElementPtrInst(GetElementPtrInst &GEP);
323 void visitLoadInst(LoadInst &LI);
324 void visitStoreInst(StoreInst &SI);
325 void verifyDominatesUse(Instruction &I, unsigned i);
326 void visitInstruction(Instruction &I);
327 void visitTerminatorInst(TerminatorInst &I);
328 void visitBranchInst(BranchInst &BI);
329 void visitReturnInst(ReturnInst &RI);
330 void visitSwitchInst(SwitchInst &SI);
331 void visitIndirectBrInst(IndirectBrInst &BI);
332 void visitSelectInst(SelectInst &SI);
333 void visitUserOp1(Instruction &I);
334 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
335 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
336 template <class DbgIntrinsicTy>
337 void visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII);
338 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
339 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
340 void visitFenceInst(FenceInst &FI);
341 void visitAllocaInst(AllocaInst &AI);
342 void visitExtractValueInst(ExtractValueInst &EVI);
343 void visitInsertValueInst(InsertValueInst &IVI);
344 void visitLandingPadInst(LandingPadInst &LPI);
346 void VerifyCallSite(CallSite CS);
347 void verifyMustTailCall(CallInst &CI);
348 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
349 unsigned ArgNo, std::string &Suffix);
350 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
351 SmallVectorImpl<Type *> &ArgTys);
352 bool VerifyIntrinsicIsVarArg(bool isVarArg,
353 ArrayRef<Intrinsic::IITDescriptor> &Infos);
354 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
355 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
357 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
358 bool isReturnValue, const Value *V);
359 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
362 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
363 void VerifyStatepoint(ImmutableCallSite CS);
364 void verifyFrameRecoverIndices();
366 // Module-level debug info verification...
367 void verifyDebugInfo();
368 void processInstructions(DebugInfoFinder &Finder);
369 void processCallInst(DebugInfoFinder &Finder, const CallInst &CI);
371 } // End anonymous namespace
373 // Assert - We know that cond should be true, if not print an error message.
374 #define Assert(C, ...) \
375 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
377 void Verifier::visit(Instruction &I) {
378 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
379 Assert(I.getOperand(i) != nullptr, "Operand is null", &I);
380 InstVisitor<Verifier>::visit(I);
384 void Verifier::visitGlobalValue(const GlobalValue &GV) {
385 Assert(!GV.isDeclaration() || GV.hasExternalLinkage() ||
386 GV.hasExternalWeakLinkage(),
387 "Global is external, but doesn't have external or weak linkage!", &GV);
389 Assert(GV.getAlignment() <= Value::MaximumAlignment,
390 "huge alignment values are unsupported", &GV);
391 Assert(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
392 "Only global variables can have appending linkage!", &GV);
394 if (GV.hasAppendingLinkage()) {
395 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
396 Assert(GVar && GVar->getType()->getElementType()->isArrayTy(),
397 "Only global arrays can have appending linkage!", GVar);
401 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
402 if (GV.hasInitializer()) {
403 Assert(GV.getInitializer()->getType() == GV.getType()->getElementType(),
404 "Global variable initializer type does not match global "
408 // If the global has common linkage, it must have a zero initializer and
409 // cannot be constant.
410 if (GV.hasCommonLinkage()) {
411 Assert(GV.getInitializer()->isNullValue(),
412 "'common' global must have a zero initializer!", &GV);
413 Assert(!GV.isConstant(), "'common' global may not be marked constant!",
415 Assert(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
418 Assert(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
419 "invalid linkage type for global declaration", &GV);
422 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
423 GV.getName() == "llvm.global_dtors")) {
424 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
425 "invalid linkage for intrinsic global variable", &GV);
426 // Don't worry about emitting an error for it not being an array,
427 // visitGlobalValue will complain on appending non-array.
428 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) {
429 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
430 PointerType *FuncPtrTy =
431 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
432 // FIXME: Reject the 2-field form in LLVM 4.0.
434 (STy->getNumElements() == 2 || STy->getNumElements() == 3) &&
435 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
436 STy->getTypeAtIndex(1) == FuncPtrTy,
437 "wrong type for intrinsic global variable", &GV);
438 if (STy->getNumElements() == 3) {
439 Type *ETy = STy->getTypeAtIndex(2);
440 Assert(ETy->isPointerTy() &&
441 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
442 "wrong type for intrinsic global variable", &GV);
447 if (GV.hasName() && (GV.getName() == "llvm.used" ||
448 GV.getName() == "llvm.compiler.used")) {
449 Assert(!GV.hasInitializer() || GV.hasAppendingLinkage(),
450 "invalid linkage for intrinsic global variable", &GV);
451 Type *GVType = GV.getType()->getElementType();
452 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
453 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
454 Assert(PTy, "wrong type for intrinsic global variable", &GV);
455 if (GV.hasInitializer()) {
456 const Constant *Init = GV.getInitializer();
457 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
458 Assert(InitArray, "wrong initalizer for intrinsic global variable",
460 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
461 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
462 Assert(isa<GlobalVariable>(V) || isa<Function>(V) ||
464 "invalid llvm.used member", V);
465 Assert(V->hasName(), "members of llvm.used must be named", V);
471 Assert(!GV.hasDLLImportStorageClass() ||
472 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
473 GV.hasAvailableExternallyLinkage(),
474 "Global is marked as dllimport, but not external", &GV);
476 if (!GV.hasInitializer()) {
477 visitGlobalValue(GV);
481 // Walk any aggregate initializers looking for bitcasts between address spaces
482 SmallPtrSet<const Value *, 4> Visited;
483 SmallVector<const Value *, 4> WorkStack;
484 WorkStack.push_back(cast<Value>(GV.getInitializer()));
486 while (!WorkStack.empty()) {
487 const Value *V = WorkStack.pop_back_val();
488 if (!Visited.insert(V).second)
491 if (const User *U = dyn_cast<User>(V)) {
492 WorkStack.append(U->op_begin(), U->op_end());
495 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
496 VerifyConstantExprBitcastType(CE);
502 visitGlobalValue(GV);
505 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
506 SmallPtrSet<const GlobalAlias*, 4> Visited;
508 visitAliaseeSubExpr(Visited, GA, C);
511 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
512 const GlobalAlias &GA, const Constant &C) {
513 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
514 Assert(!GV->isDeclaration(), "Alias must point to a definition", &GA);
516 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
517 Assert(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
519 Assert(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
522 // Only continue verifying subexpressions of GlobalAliases.
523 // Do not recurse into global initializers.
528 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
529 VerifyConstantExprBitcastType(CE);
531 for (const Use &U : C.operands()) {
533 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
534 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
535 else if (const auto *C2 = dyn_cast<Constant>(V))
536 visitAliaseeSubExpr(Visited, GA, *C2);
540 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
541 Assert(!GA.getName().empty(), "Alias name cannot be empty!", &GA);
542 Assert(GlobalAlias::isValidLinkage(GA.getLinkage()),
543 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
544 "weak_odr, or external linkage!",
546 const Constant *Aliasee = GA.getAliasee();
547 Assert(Aliasee, "Aliasee cannot be NULL!", &GA);
548 Assert(GA.getType() == Aliasee->getType(),
549 "Alias and aliasee types should match!", &GA);
551 Assert(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
552 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
554 visitAliaseeSubExpr(GA, *Aliasee);
556 visitGlobalValue(GA);
559 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
560 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
561 MDNode *MD = NMD.getOperand(i);
569 void Verifier::visitMDNode(const MDNode &MD) {
570 // Only visit each node once. Metadata can be mutually recursive, so this
571 // avoids infinite recursion here, as well as being an optimization.
572 if (!MDNodes.insert(&MD).second)
575 switch (MD.getMetadataID()) {
577 llvm_unreachable("Invalid MDNode subclass");
578 case Metadata::MDTupleKind:
580 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
581 case Metadata::CLASS##Kind: \
582 visit##CLASS(cast<CLASS>(MD)); \
584 #include "llvm/IR/Metadata.def"
587 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
588 Metadata *Op = MD.getOperand(i);
591 Assert(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
593 if (auto *N = dyn_cast<MDNode>(Op)) {
597 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
598 visitValueAsMetadata(*V, nullptr);
603 // Check these last, so we diagnose problems in operands first.
604 Assert(!MD.isTemporary(), "Expected no forward declarations!", &MD);
605 Assert(MD.isResolved(), "All nodes should be resolved!", &MD);
608 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
609 Assert(MD.getValue(), "Expected valid value", &MD);
610 Assert(!MD.getValue()->getType()->isMetadataTy(),
611 "Unexpected metadata round-trip through values", &MD, MD.getValue());
613 auto *L = dyn_cast<LocalAsMetadata>(&MD);
617 Assert(F, "function-local metadata used outside a function", L);
619 // If this was an instruction, bb, or argument, verify that it is in the
620 // function that we expect.
621 Function *ActualF = nullptr;
622 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
623 Assert(I->getParent(), "function-local metadata not in basic block", L, I);
624 ActualF = I->getParent()->getParent();
625 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
626 ActualF = BB->getParent();
627 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
628 ActualF = A->getParent();
629 assert(ActualF && "Unimplemented function local metadata case!");
631 Assert(ActualF == F, "function-local metadata used in wrong function", L);
634 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
635 Metadata *MD = MDV.getMetadata();
636 if (auto *N = dyn_cast<MDNode>(MD)) {
641 // Only visit each node once. Metadata can be mutually recursive, so this
642 // avoids infinite recursion here, as well as being an optimization.
643 if (!MDNodes.insert(MD).second)
646 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
647 visitValueAsMetadata(*V, F);
650 void Verifier::visitMDLocation(const MDLocation &N) {
651 Assert(N.getScope(), "location requires a valid scope", &N);
652 if (auto *IA = N.getInlinedAt())
653 Assert(isa<MDLocation>(IA), "inlined-at should be a location", &N, IA);
656 void Verifier::visitGenericDebugNode(const GenericDebugNode &N) {
657 Assert(N.getTag(), "invalid tag", &N);
660 void Verifier::visitMDSubrange(const MDSubrange &N) {
661 Assert(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
664 void Verifier::visitMDEnumerator(const MDEnumerator &N) {
665 Assert(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
668 void Verifier::visitMDBasicType(const MDBasicType &N) {
669 Assert(N.getTag() == dwarf::DW_TAG_base_type ||
670 N.getTag() == dwarf::DW_TAG_unspecified_type,
674 void Verifier::visitMDDerivedType(const MDDerivedType &N) {
675 Assert(N.getTag() == dwarf::DW_TAG_typedef ||
676 N.getTag() == dwarf::DW_TAG_pointer_type ||
677 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
678 N.getTag() == dwarf::DW_TAG_reference_type ||
679 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
680 N.getTag() == dwarf::DW_TAG_const_type ||
681 N.getTag() == dwarf::DW_TAG_volatile_type ||
682 N.getTag() == dwarf::DW_TAG_restrict_type ||
683 N.getTag() == dwarf::DW_TAG_member ||
684 N.getTag() == dwarf::DW_TAG_inheritance ||
685 N.getTag() == dwarf::DW_TAG_friend,
689 void Verifier::visitMDCompositeType(const MDCompositeType &N) {
690 Assert(N.getTag() == dwarf::DW_TAG_array_type ||
691 N.getTag() == dwarf::DW_TAG_structure_type ||
692 N.getTag() == dwarf::DW_TAG_union_type ||
693 N.getTag() == dwarf::DW_TAG_enumeration_type ||
694 N.getTag() == dwarf::DW_TAG_subroutine_type ||
695 N.getTag() == dwarf::DW_TAG_class_type,
699 void Verifier::visitMDSubroutineType(const MDSubroutineType &N) {
700 Assert(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
703 void Verifier::visitMDFile(const MDFile &N) {
704 Assert(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
707 void Verifier::visitMDCompileUnit(const MDCompileUnit &N) {
708 Assert(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
711 void Verifier::visitMDSubprogram(const MDSubprogram &N) {
712 Assert(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
715 void Verifier::visitMDLexicalBlock(const MDLexicalBlock &N) {
716 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
719 void Verifier::visitMDLexicalBlockFile(const MDLexicalBlockFile &N) {
720 Assert(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
723 void Verifier::visitMDNamespace(const MDNamespace &N) {
724 Assert(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
727 void Verifier::visitMDTemplateTypeParameter(const MDTemplateTypeParameter &N) {
728 Assert(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
732 void Verifier::visitMDTemplateValueParameter(
733 const MDTemplateValueParameter &N) {
734 Assert(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
735 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
736 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
740 void Verifier::visitMDGlobalVariable(const MDGlobalVariable &N) {
741 Assert(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
744 void Verifier::visitMDLocalVariable(const MDLocalVariable &N) {
745 Assert(N.getTag() == dwarf::DW_TAG_auto_variable ||
746 N.getTag() == dwarf::DW_TAG_arg_variable,
750 void Verifier::visitMDExpression(const MDExpression &N) {
751 Assert(N.isValid(), "invalid expression", &N);
754 void Verifier::visitMDObjCProperty(const MDObjCProperty &N) {
755 Assert(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
758 void Verifier::visitMDImportedEntity(const MDImportedEntity &N) {
759 Assert(N.getTag() == dwarf::DW_TAG_imported_module ||
760 N.getTag() == dwarf::DW_TAG_imported_declaration,
764 void Verifier::visitComdat(const Comdat &C) {
765 // The Module is invalid if the GlobalValue has private linkage. Entities
766 // with private linkage don't have entries in the symbol table.
767 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
768 Assert(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
772 void Verifier::visitModuleIdents(const Module &M) {
773 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
777 // llvm.ident takes a list of metadata entry. Each entry has only one string.
778 // Scan each llvm.ident entry and make sure that this requirement is met.
779 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
780 const MDNode *N = Idents->getOperand(i);
781 Assert(N->getNumOperands() == 1,
782 "incorrect number of operands in llvm.ident metadata", N);
783 Assert(dyn_cast_or_null<MDString>(N->getOperand(0)),
784 ("invalid value for llvm.ident metadata entry operand"
785 "(the operand should be a string)"),
790 void Verifier::visitModuleFlags(const Module &M) {
791 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
794 // Scan each flag, and track the flags and requirements.
795 DenseMap<const MDString*, const MDNode*> SeenIDs;
796 SmallVector<const MDNode*, 16> Requirements;
797 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
798 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
801 // Validate that the requirements in the module are valid.
802 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
803 const MDNode *Requirement = Requirements[I];
804 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
805 const Metadata *ReqValue = Requirement->getOperand(1);
807 const MDNode *Op = SeenIDs.lookup(Flag);
809 CheckFailed("invalid requirement on flag, flag is not present in module",
814 if (Op->getOperand(2) != ReqValue) {
815 CheckFailed(("invalid requirement on flag, "
816 "flag does not have the required value"),
824 Verifier::visitModuleFlag(const MDNode *Op,
825 DenseMap<const MDString *, const MDNode *> &SeenIDs,
826 SmallVectorImpl<const MDNode *> &Requirements) {
827 // Each module flag should have three arguments, the merge behavior (a
828 // constant int), the flag ID (an MDString), and the value.
829 Assert(Op->getNumOperands() == 3,
830 "incorrect number of operands in module flag", Op);
831 Module::ModFlagBehavior MFB;
832 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
834 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
835 "invalid behavior operand in module flag (expected constant integer)",
838 "invalid behavior operand in module flag (unexpected constant)",
841 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
842 Assert(ID, "invalid ID operand in module flag (expected metadata string)",
845 // Sanity check the values for behaviors with additional requirements.
848 case Module::Warning:
849 case Module::Override:
850 // These behavior types accept any value.
853 case Module::Require: {
854 // The value should itself be an MDNode with two operands, a flag ID (an
855 // MDString), and a value.
856 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
857 Assert(Value && Value->getNumOperands() == 2,
858 "invalid value for 'require' module flag (expected metadata pair)",
860 Assert(isa<MDString>(Value->getOperand(0)),
861 ("invalid value for 'require' module flag "
862 "(first value operand should be a string)"),
863 Value->getOperand(0));
865 // Append it to the list of requirements, to check once all module flags are
867 Requirements.push_back(Value);
872 case Module::AppendUnique: {
873 // These behavior types require the operand be an MDNode.
874 Assert(isa<MDNode>(Op->getOperand(2)),
875 "invalid value for 'append'-type module flag "
876 "(expected a metadata node)",
882 // Unless this is a "requires" flag, check the ID is unique.
883 if (MFB != Module::Require) {
884 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
886 "module flag identifiers must be unique (or of 'require' type)", ID);
890 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
891 bool isFunction, const Value *V) {
893 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
894 if (Attrs.getSlotIndex(I) == Idx) {
899 assert(Slot != ~0U && "Attribute set inconsistency!");
901 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
903 if (I->isStringAttribute())
906 if (I->getKindAsEnum() == Attribute::NoReturn ||
907 I->getKindAsEnum() == Attribute::NoUnwind ||
908 I->getKindAsEnum() == Attribute::NoInline ||
909 I->getKindAsEnum() == Attribute::AlwaysInline ||
910 I->getKindAsEnum() == Attribute::OptimizeForSize ||
911 I->getKindAsEnum() == Attribute::StackProtect ||
912 I->getKindAsEnum() == Attribute::StackProtectReq ||
913 I->getKindAsEnum() == Attribute::StackProtectStrong ||
914 I->getKindAsEnum() == Attribute::NoRedZone ||
915 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
916 I->getKindAsEnum() == Attribute::Naked ||
917 I->getKindAsEnum() == Attribute::InlineHint ||
918 I->getKindAsEnum() == Attribute::StackAlignment ||
919 I->getKindAsEnum() == Attribute::UWTable ||
920 I->getKindAsEnum() == Attribute::NonLazyBind ||
921 I->getKindAsEnum() == Attribute::ReturnsTwice ||
922 I->getKindAsEnum() == Attribute::SanitizeAddress ||
923 I->getKindAsEnum() == Attribute::SanitizeThread ||
924 I->getKindAsEnum() == Attribute::SanitizeMemory ||
925 I->getKindAsEnum() == Attribute::MinSize ||
926 I->getKindAsEnum() == Attribute::NoDuplicate ||
927 I->getKindAsEnum() == Attribute::Builtin ||
928 I->getKindAsEnum() == Attribute::NoBuiltin ||
929 I->getKindAsEnum() == Attribute::Cold ||
930 I->getKindAsEnum() == Attribute::OptimizeNone ||
931 I->getKindAsEnum() == Attribute::JumpTable) {
933 CheckFailed("Attribute '" + I->getAsString() +
934 "' only applies to functions!", V);
937 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
938 I->getKindAsEnum() == Attribute::ReadNone) {
940 CheckFailed("Attribute '" + I->getAsString() +
941 "' does not apply to function returns");
944 } else if (isFunction) {
945 CheckFailed("Attribute '" + I->getAsString() +
946 "' does not apply to functions!", V);
952 // VerifyParameterAttrs - Check the given attributes for an argument or return
953 // value of the specified type. The value V is printed in error messages.
954 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
955 bool isReturnValue, const Value *V) {
956 if (!Attrs.hasAttributes(Idx))
959 VerifyAttributeTypes(Attrs, Idx, false, V);
962 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
963 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
964 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
965 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
966 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
967 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
968 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
969 "'returned' do not apply to return values!",
972 // Check for mutually incompatible attributes. Only inreg is compatible with
974 unsigned AttrCount = 0;
975 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
976 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
977 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
978 Attrs.hasAttribute(Idx, Attribute::InReg);
979 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
980 Assert(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
981 "and 'sret' are incompatible!",
984 Assert(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
985 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
987 "'inalloca and readonly' are incompatible!",
990 Assert(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
991 Attrs.hasAttribute(Idx, Attribute::Returned)),
993 "'sret and returned' are incompatible!",
996 Assert(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
997 Attrs.hasAttribute(Idx, Attribute::SExt)),
999 "'zeroext and signext' are incompatible!",
1002 Assert(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1003 Attrs.hasAttribute(Idx, Attribute::ReadOnly)),
1005 "'readnone and readonly' are incompatible!",
1008 Assert(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1009 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)),
1011 "'noinline and alwaysinline' are incompatible!",
1014 Assert(!AttrBuilder(Attrs, Idx)
1015 .hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
1016 "Wrong types for attribute: " +
1017 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx),
1020 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1021 SmallPtrSet<const Type*, 4> Visited;
1022 if (!PTy->getElementType()->isSized(&Visited)) {
1023 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1024 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1025 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1029 Assert(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1030 "Attribute 'byval' only applies to parameters with pointer type!",
1035 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1036 // The value V is printed in error messages.
1037 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1039 if (Attrs.isEmpty())
1042 bool SawNest = false;
1043 bool SawReturned = false;
1044 bool SawSRet = false;
1046 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1047 unsigned Idx = Attrs.getSlotIndex(i);
1051 Ty = FT->getReturnType();
1052 else if (Idx-1 < FT->getNumParams())
1053 Ty = FT->getParamType(Idx-1);
1055 break; // VarArgs attributes, verified elsewhere.
1057 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1062 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1063 Assert(!SawNest, "More than one parameter has attribute nest!", V);
1067 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1068 Assert(!SawReturned, "More than one parameter has attribute returned!",
1070 Assert(Ty->canLosslesslyBitCastTo(FT->getReturnType()),
1072 "argument and return types for 'returned' attribute",
1077 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1078 Assert(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1079 Assert(Idx == 1 || Idx == 2,
1080 "Attribute 'sret' is not on first or second parameter!", V);
1084 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1085 Assert(Idx == FT->getNumParams(), "inalloca isn't on the last parameter!",
1090 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1093 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1096 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone) &&
1097 Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly)),
1098 "Attributes 'readnone and readonly' are incompatible!", V);
1101 !(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline) &&
1102 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1103 Attribute::AlwaysInline)),
1104 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1106 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1107 Attribute::OptimizeNone)) {
1108 Assert(Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::NoInline),
1109 "Attribute 'optnone' requires 'noinline'!", V);
1111 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1112 Attribute::OptimizeForSize),
1113 "Attributes 'optsize and optnone' are incompatible!", V);
1115 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize),
1116 "Attributes 'minsize and optnone' are incompatible!", V);
1119 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1120 Attribute::JumpTable)) {
1121 const GlobalValue *GV = cast<GlobalValue>(V);
1122 Assert(GV->hasUnnamedAddr(),
1123 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1127 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1128 if (CE->getOpcode() != Instruction::BitCast)
1131 Assert(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1133 "Invalid bitcast", CE);
1136 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1137 if (Attrs.getNumSlots() == 0)
1140 unsigned LastSlot = Attrs.getNumSlots() - 1;
1141 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1142 if (LastIndex <= Params
1143 || (LastIndex == AttributeSet::FunctionIndex
1144 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1150 /// \brief Verify that statepoint intrinsic is well formed.
1151 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1152 assert(CS.getCalledFunction() &&
1153 CS.getCalledFunction()->getIntrinsicID() ==
1154 Intrinsic::experimental_gc_statepoint);
1156 const Instruction &CI = *CS.getInstruction();
1158 Assert(!CS.doesNotAccessMemory() && !CS.onlyReadsMemory(),
1159 "gc.statepoint must read and write memory to preserve "
1160 "reordering restrictions required by safepoint semantics",
1163 const Value *Target = CS.getArgument(0);
1164 const PointerType *PT = dyn_cast<PointerType>(Target->getType());
1165 Assert(PT && PT->getElementType()->isFunctionTy(),
1166 "gc.statepoint callee must be of function pointer type", &CI, Target);
1167 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1169 const Value *NumCallArgsV = CS.getArgument(1);
1170 Assert(isa<ConstantInt>(NumCallArgsV),
1171 "gc.statepoint number of arguments to underlying call "
1172 "must be constant integer",
1174 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1175 Assert(NumCallArgs >= 0,
1176 "gc.statepoint number of arguments to underlying call "
1179 const int NumParams = (int)TargetFuncType->getNumParams();
1180 if (TargetFuncType->isVarArg()) {
1181 Assert(NumCallArgs >= NumParams,
1182 "gc.statepoint mismatch in number of vararg call args", &CI);
1184 // TODO: Remove this limitation
1185 Assert(TargetFuncType->getReturnType()->isVoidTy(),
1186 "gc.statepoint doesn't support wrapping non-void "
1187 "vararg functions yet",
1190 Assert(NumCallArgs == NumParams,
1191 "gc.statepoint mismatch in number of call args", &CI);
1193 const Value *Unused = CS.getArgument(2);
1194 Assert(isa<ConstantInt>(Unused) && cast<ConstantInt>(Unused)->isNullValue(),
1195 "gc.statepoint parameter #3 must be zero", &CI);
1197 // Verify that the types of the call parameter arguments match
1198 // the type of the wrapped callee.
1199 for (int i = 0; i < NumParams; i++) {
1200 Type *ParamType = TargetFuncType->getParamType(i);
1201 Type *ArgType = CS.getArgument(3+i)->getType();
1202 Assert(ArgType == ParamType,
1203 "gc.statepoint call argument does not match wrapped "
1207 const int EndCallArgsInx = 2+NumCallArgs;
1208 const Value *NumDeoptArgsV = CS.getArgument(EndCallArgsInx+1);
1209 Assert(isa<ConstantInt>(NumDeoptArgsV),
1210 "gc.statepoint number of deoptimization arguments "
1211 "must be constant integer",
1213 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1214 Assert(NumDeoptArgs >= 0, "gc.statepoint number of deoptimization arguments "
1218 Assert(4 + NumCallArgs + NumDeoptArgs <= (int)CS.arg_size(),
1219 "gc.statepoint too few arguments according to length fields", &CI);
1221 // Check that the only uses of this gc.statepoint are gc.result or
1222 // gc.relocate calls which are tied to this statepoint and thus part
1223 // of the same statepoint sequence
1224 for (const User *U : CI.users()) {
1225 const CallInst *Call = dyn_cast<const CallInst>(U);
1226 Assert(Call, "illegal use of statepoint token", &CI, U);
1227 if (!Call) continue;
1228 Assert(isGCRelocate(Call) || isGCResult(Call),
1229 "gc.result or gc.relocate are the only value uses"
1230 "of a gc.statepoint",
1232 if (isGCResult(Call)) {
1233 Assert(Call->getArgOperand(0) == &CI,
1234 "gc.result connected to wrong gc.statepoint", &CI, Call);
1235 } else if (isGCRelocate(Call)) {
1236 Assert(Call->getArgOperand(0) == &CI,
1237 "gc.relocate connected to wrong gc.statepoint", &CI, Call);
1241 // Note: It is legal for a single derived pointer to be listed multiple
1242 // times. It's non-optimal, but it is legal. It can also happen after
1243 // insertion if we strip a bitcast away.
1244 // Note: It is really tempting to check that each base is relocated and
1245 // that a derived pointer is never reused as a base pointer. This turns
1246 // out to be problematic since optimizations run after safepoint insertion
1247 // can recognize equality properties that the insertion logic doesn't know
1248 // about. See example statepoint.ll in the verifier subdirectory
1251 void Verifier::verifyFrameRecoverIndices() {
1252 for (auto &Counts : FrameEscapeInfo) {
1253 Function *F = Counts.first;
1254 unsigned EscapedObjectCount = Counts.second.first;
1255 unsigned MaxRecoveredIndex = Counts.second.second;
1256 Assert(MaxRecoveredIndex <= EscapedObjectCount,
1257 "all indices passed to llvm.framerecover must be less than the "
1258 "number of arguments passed ot llvm.frameescape in the parent "
1264 // visitFunction - Verify that a function is ok.
1266 void Verifier::visitFunction(const Function &F) {
1267 // Check function arguments.
1268 FunctionType *FT = F.getFunctionType();
1269 unsigned NumArgs = F.arg_size();
1271 Assert(Context == &F.getContext(),
1272 "Function context does not match Module context!", &F);
1274 Assert(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1275 Assert(FT->getNumParams() == NumArgs,
1276 "# formal arguments must match # of arguments for function type!", &F,
1278 Assert(F.getReturnType()->isFirstClassType() ||
1279 F.getReturnType()->isVoidTy() || F.getReturnType()->isStructTy(),
1280 "Functions cannot return aggregate values!", &F);
1282 Assert(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1283 "Invalid struct return type!", &F);
1285 AttributeSet Attrs = F.getAttributes();
1287 Assert(VerifyAttributeCount(Attrs, FT->getNumParams()),
1288 "Attribute after last parameter!", &F);
1290 // Check function attributes.
1291 VerifyFunctionAttrs(FT, Attrs, &F);
1293 // On function declarations/definitions, we do not support the builtin
1294 // attribute. We do not check this in VerifyFunctionAttrs since that is
1295 // checking for Attributes that can/can not ever be on functions.
1296 Assert(!Attrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::Builtin),
1297 "Attribute 'builtin' can only be applied to a callsite.", &F);
1299 // Check that this function meets the restrictions on this calling convention.
1300 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1301 // restrictions can be lifted.
1302 switch (F.getCallingConv()) {
1304 case CallingConv::C:
1306 case CallingConv::Fast:
1307 case CallingConv::Cold:
1308 case CallingConv::Intel_OCL_BI:
1309 case CallingConv::PTX_Kernel:
1310 case CallingConv::PTX_Device:
1311 Assert(!F.isVarArg(), "Calling convention does not support varargs or "
1312 "perfect forwarding!",
1317 bool isLLVMdotName = F.getName().size() >= 5 &&
1318 F.getName().substr(0, 5) == "llvm.";
1320 // Check that the argument values match the function type for this function...
1322 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1324 Assert(I->getType() == FT->getParamType(i),
1325 "Argument value does not match function argument type!", I,
1326 FT->getParamType(i));
1327 Assert(I->getType()->isFirstClassType(),
1328 "Function arguments must have first-class types!", I);
1330 Assert(!I->getType()->isMetadataTy(),
1331 "Function takes metadata but isn't an intrinsic", I, &F);
1334 if (F.isMaterializable()) {
1335 // Function has a body somewhere we can't see.
1336 } else if (F.isDeclaration()) {
1337 Assert(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1338 "invalid linkage type for function declaration", &F);
1340 // Verify that this function (which has a body) is not named "llvm.*". It
1341 // is not legal to define intrinsics.
1342 Assert(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1344 // Check the entry node
1345 const BasicBlock *Entry = &F.getEntryBlock();
1346 Assert(pred_empty(Entry),
1347 "Entry block to function must not have predecessors!", Entry);
1349 // The address of the entry block cannot be taken, unless it is dead.
1350 if (Entry->hasAddressTaken()) {
1351 Assert(!BlockAddress::lookup(Entry)->isConstantUsed(),
1352 "blockaddress may not be used with the entry block!", Entry);
1356 // If this function is actually an intrinsic, verify that it is only used in
1357 // direct call/invokes, never having its "address taken".
1358 if (F.getIntrinsicID()) {
1360 if (F.hasAddressTaken(&U))
1361 Assert(0, "Invalid user of intrinsic instruction!", U);
1364 Assert(!F.hasDLLImportStorageClass() ||
1365 (F.isDeclaration() && F.hasExternalLinkage()) ||
1366 F.hasAvailableExternallyLinkage(),
1367 "Function is marked as dllimport, but not external.", &F);
1370 // verifyBasicBlock - Verify that a basic block is well formed...
1372 void Verifier::visitBasicBlock(BasicBlock &BB) {
1373 InstsInThisBlock.clear();
1375 // Ensure that basic blocks have terminators!
1376 Assert(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1378 // Check constraints that this basic block imposes on all of the PHI nodes in
1380 if (isa<PHINode>(BB.front())) {
1381 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1382 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1383 std::sort(Preds.begin(), Preds.end());
1385 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1386 // Ensure that PHI nodes have at least one entry!
1387 Assert(PN->getNumIncomingValues() != 0,
1388 "PHI nodes must have at least one entry. If the block is dead, "
1389 "the PHI should be removed!",
1391 Assert(PN->getNumIncomingValues() == Preds.size(),
1392 "PHINode should have one entry for each predecessor of its "
1393 "parent basic block!",
1396 // Get and sort all incoming values in the PHI node...
1398 Values.reserve(PN->getNumIncomingValues());
1399 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1400 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1401 PN->getIncomingValue(i)));
1402 std::sort(Values.begin(), Values.end());
1404 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1405 // Check to make sure that if there is more than one entry for a
1406 // particular basic block in this PHI node, that the incoming values are
1409 Assert(i == 0 || Values[i].first != Values[i - 1].first ||
1410 Values[i].second == Values[i - 1].second,
1411 "PHI node has multiple entries for the same basic block with "
1412 "different incoming values!",
1413 PN, Values[i].first, Values[i].second, Values[i - 1].second);
1415 // Check to make sure that the predecessors and PHI node entries are
1417 Assert(Values[i].first == Preds[i],
1418 "PHI node entries do not match predecessors!", PN,
1419 Values[i].first, Preds[i]);
1424 // Check that all instructions have their parent pointers set up correctly.
1427 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1431 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1432 // Ensure that terminators only exist at the end of the basic block.
1433 Assert(&I == I.getParent()->getTerminator(),
1434 "Terminator found in the middle of a basic block!", I.getParent());
1435 visitInstruction(I);
1438 void Verifier::visitBranchInst(BranchInst &BI) {
1439 if (BI.isConditional()) {
1440 Assert(BI.getCondition()->getType()->isIntegerTy(1),
1441 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1443 visitTerminatorInst(BI);
1446 void Verifier::visitReturnInst(ReturnInst &RI) {
1447 Function *F = RI.getParent()->getParent();
1448 unsigned N = RI.getNumOperands();
1449 if (F->getReturnType()->isVoidTy())
1451 "Found return instr that returns non-void in Function of void "
1453 &RI, F->getReturnType());
1455 Assert(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1456 "Function return type does not match operand "
1457 "type of return inst!",
1458 &RI, F->getReturnType());
1460 // Check to make sure that the return value has necessary properties for
1462 visitTerminatorInst(RI);
1465 void Verifier::visitSwitchInst(SwitchInst &SI) {
1466 // Check to make sure that all of the constants in the switch instruction
1467 // have the same type as the switched-on value.
1468 Type *SwitchTy = SI.getCondition()->getType();
1469 SmallPtrSet<ConstantInt*, 32> Constants;
1470 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1471 Assert(i.getCaseValue()->getType() == SwitchTy,
1472 "Switch constants must all be same type as switch value!", &SI);
1473 Assert(Constants.insert(i.getCaseValue()).second,
1474 "Duplicate integer as switch case", &SI, i.getCaseValue());
1477 visitTerminatorInst(SI);
1480 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1481 Assert(BI.getAddress()->getType()->isPointerTy(),
1482 "Indirectbr operand must have pointer type!", &BI);
1483 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1484 Assert(BI.getDestination(i)->getType()->isLabelTy(),
1485 "Indirectbr destinations must all have pointer type!", &BI);
1487 visitTerminatorInst(BI);
1490 void Verifier::visitSelectInst(SelectInst &SI) {
1491 Assert(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1493 "Invalid operands for select instruction!", &SI);
1495 Assert(SI.getTrueValue()->getType() == SI.getType(),
1496 "Select values must have same type as select instruction!", &SI);
1497 visitInstruction(SI);
1500 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1501 /// a pass, if any exist, it's an error.
1503 void Verifier::visitUserOp1(Instruction &I) {
1504 Assert(0, "User-defined operators should not live outside of a pass!", &I);
1507 void Verifier::visitTruncInst(TruncInst &I) {
1508 // Get the source and destination types
1509 Type *SrcTy = I.getOperand(0)->getType();
1510 Type *DestTy = I.getType();
1512 // Get the size of the types in bits, we'll need this later
1513 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1514 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1516 Assert(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1517 Assert(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1518 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1519 "trunc source and destination must both be a vector or neither", &I);
1520 Assert(SrcBitSize > DestBitSize, "DestTy too big for Trunc", &I);
1522 visitInstruction(I);
1525 void Verifier::visitZExtInst(ZExtInst &I) {
1526 // Get the source and destination types
1527 Type *SrcTy = I.getOperand(0)->getType();
1528 Type *DestTy = I.getType();
1530 // Get the size of the types in bits, we'll need this later
1531 Assert(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1532 Assert(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1533 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1534 "zext source and destination must both be a vector or neither", &I);
1535 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1536 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1538 Assert(SrcBitSize < DestBitSize, "Type too small for ZExt", &I);
1540 visitInstruction(I);
1543 void Verifier::visitSExtInst(SExtInst &I) {
1544 // Get the source and destination types
1545 Type *SrcTy = I.getOperand(0)->getType();
1546 Type *DestTy = I.getType();
1548 // Get the size of the types in bits, we'll need this later
1549 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1550 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1552 Assert(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1553 Assert(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1554 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1555 "sext source and destination must both be a vector or neither", &I);
1556 Assert(SrcBitSize < DestBitSize, "Type too small for SExt", &I);
1558 visitInstruction(I);
1561 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1562 // Get the source and destination types
1563 Type *SrcTy = I.getOperand(0)->getType();
1564 Type *DestTy = I.getType();
1565 // Get the size of the types in bits, we'll need this later
1566 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1567 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1569 Assert(SrcTy->isFPOrFPVectorTy(), "FPTrunc only operates on FP", &I);
1570 Assert(DestTy->isFPOrFPVectorTy(), "FPTrunc only produces an FP", &I);
1571 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1572 "fptrunc source and destination must both be a vector or neither", &I);
1573 Assert(SrcBitSize > DestBitSize, "DestTy too big for FPTrunc", &I);
1575 visitInstruction(I);
1578 void Verifier::visitFPExtInst(FPExtInst &I) {
1579 // Get the source and destination types
1580 Type *SrcTy = I.getOperand(0)->getType();
1581 Type *DestTy = I.getType();
1583 // Get the size of the types in bits, we'll need this later
1584 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1585 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1587 Assert(SrcTy->isFPOrFPVectorTy(), "FPExt only operates on FP", &I);
1588 Assert(DestTy->isFPOrFPVectorTy(), "FPExt only produces an FP", &I);
1589 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1590 "fpext source and destination must both be a vector or neither", &I);
1591 Assert(SrcBitSize < DestBitSize, "DestTy too small for FPExt", &I);
1593 visitInstruction(I);
1596 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1597 // Get the source and destination types
1598 Type *SrcTy = I.getOperand(0)->getType();
1599 Type *DestTy = I.getType();
1601 bool SrcVec = SrcTy->isVectorTy();
1602 bool DstVec = DestTy->isVectorTy();
1604 Assert(SrcVec == DstVec,
1605 "UIToFP source and dest must both be vector or scalar", &I);
1606 Assert(SrcTy->isIntOrIntVectorTy(),
1607 "UIToFP source must be integer or integer vector", &I);
1608 Assert(DestTy->isFPOrFPVectorTy(), "UIToFP result must be FP or FP vector",
1611 if (SrcVec && DstVec)
1612 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1613 cast<VectorType>(DestTy)->getNumElements(),
1614 "UIToFP source and dest vector length mismatch", &I);
1616 visitInstruction(I);
1619 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1620 // Get the source and destination types
1621 Type *SrcTy = I.getOperand(0)->getType();
1622 Type *DestTy = I.getType();
1624 bool SrcVec = SrcTy->isVectorTy();
1625 bool DstVec = DestTy->isVectorTy();
1627 Assert(SrcVec == DstVec,
1628 "SIToFP source and dest must both be vector or scalar", &I);
1629 Assert(SrcTy->isIntOrIntVectorTy(),
1630 "SIToFP source must be integer or integer vector", &I);
1631 Assert(DestTy->isFPOrFPVectorTy(), "SIToFP result must be FP or FP vector",
1634 if (SrcVec && DstVec)
1635 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1636 cast<VectorType>(DestTy)->getNumElements(),
1637 "SIToFP source and dest vector length mismatch", &I);
1639 visitInstruction(I);
1642 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1643 // Get the source and destination types
1644 Type *SrcTy = I.getOperand(0)->getType();
1645 Type *DestTy = I.getType();
1647 bool SrcVec = SrcTy->isVectorTy();
1648 bool DstVec = DestTy->isVectorTy();
1650 Assert(SrcVec == DstVec,
1651 "FPToUI source and dest must both be vector or scalar", &I);
1652 Assert(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1654 Assert(DestTy->isIntOrIntVectorTy(),
1655 "FPToUI result must be integer or integer vector", &I);
1657 if (SrcVec && DstVec)
1658 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1659 cast<VectorType>(DestTy)->getNumElements(),
1660 "FPToUI source and dest vector length mismatch", &I);
1662 visitInstruction(I);
1665 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1666 // Get the source and destination types
1667 Type *SrcTy = I.getOperand(0)->getType();
1668 Type *DestTy = I.getType();
1670 bool SrcVec = SrcTy->isVectorTy();
1671 bool DstVec = DestTy->isVectorTy();
1673 Assert(SrcVec == DstVec,
1674 "FPToSI source and dest must both be vector or scalar", &I);
1675 Assert(SrcTy->isFPOrFPVectorTy(), "FPToSI source must be FP or FP vector",
1677 Assert(DestTy->isIntOrIntVectorTy(),
1678 "FPToSI result must be integer or integer vector", &I);
1680 if (SrcVec && DstVec)
1681 Assert(cast<VectorType>(SrcTy)->getNumElements() ==
1682 cast<VectorType>(DestTy)->getNumElements(),
1683 "FPToSI source and dest vector length mismatch", &I);
1685 visitInstruction(I);
1688 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1689 // Get the source and destination types
1690 Type *SrcTy = I.getOperand(0)->getType();
1691 Type *DestTy = I.getType();
1693 Assert(SrcTy->getScalarType()->isPointerTy(),
1694 "PtrToInt source must be pointer", &I);
1695 Assert(DestTy->getScalarType()->isIntegerTy(),
1696 "PtrToInt result must be integral", &I);
1697 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "PtrToInt type mismatch",
1700 if (SrcTy->isVectorTy()) {
1701 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1702 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1703 Assert(VSrc->getNumElements() == VDest->getNumElements(),
1704 "PtrToInt Vector width mismatch", &I);
1707 visitInstruction(I);
1710 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1711 // Get the source and destination types
1712 Type *SrcTy = I.getOperand(0)->getType();
1713 Type *DestTy = I.getType();
1715 Assert(SrcTy->getScalarType()->isIntegerTy(),
1716 "IntToPtr source must be an integral", &I);
1717 Assert(DestTy->getScalarType()->isPointerTy(),
1718 "IntToPtr result must be a pointer", &I);
1719 Assert(SrcTy->isVectorTy() == DestTy->isVectorTy(), "IntToPtr type mismatch",
1721 if (SrcTy->isVectorTy()) {
1722 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1723 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1724 Assert(VSrc->getNumElements() == VDest->getNumElements(),
1725 "IntToPtr Vector width mismatch", &I);
1727 visitInstruction(I);
1730 void Verifier::visitBitCastInst(BitCastInst &I) {
1732 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
1733 "Invalid bitcast", &I);
1734 visitInstruction(I);
1737 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1738 Type *SrcTy = I.getOperand(0)->getType();
1739 Type *DestTy = I.getType();
1741 Assert(SrcTy->isPtrOrPtrVectorTy(), "AddrSpaceCast source must be a pointer",
1743 Assert(DestTy->isPtrOrPtrVectorTy(), "AddrSpaceCast result must be a pointer",
1745 Assert(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1746 "AddrSpaceCast must be between different address spaces", &I);
1747 if (SrcTy->isVectorTy())
1748 Assert(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1749 "AddrSpaceCast vector pointer number of elements mismatch", &I);
1750 visitInstruction(I);
1753 /// visitPHINode - Ensure that a PHI node is well formed.
1755 void Verifier::visitPHINode(PHINode &PN) {
1756 // Ensure that the PHI nodes are all grouped together at the top of the block.
1757 // This can be tested by checking whether the instruction before this is
1758 // either nonexistent (because this is begin()) or is a PHI node. If not,
1759 // then there is some other instruction before a PHI.
1760 Assert(&PN == &PN.getParent()->front() ||
1761 isa<PHINode>(--BasicBlock::iterator(&PN)),
1762 "PHI nodes not grouped at top of basic block!", &PN, PN.getParent());
1764 // Check that all of the values of the PHI node have the same type as the
1765 // result, and that the incoming blocks are really basic blocks.
1766 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1767 Assert(PN.getType() == PN.getIncomingValue(i)->getType(),
1768 "PHI node operands are not the same type as the result!", &PN);
1771 // All other PHI node constraints are checked in the visitBasicBlock method.
1773 visitInstruction(PN);
1776 void Verifier::VerifyCallSite(CallSite CS) {
1777 Instruction *I = CS.getInstruction();
1779 Assert(CS.getCalledValue()->getType()->isPointerTy(),
1780 "Called function must be a pointer!", I);
1781 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1783 Assert(FPTy->getElementType()->isFunctionTy(),
1784 "Called function is not pointer to function type!", I);
1785 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1787 // Verify that the correct number of arguments are being passed
1788 if (FTy->isVarArg())
1789 Assert(CS.arg_size() >= FTy->getNumParams(),
1790 "Called function requires more parameters than were provided!", I);
1792 Assert(CS.arg_size() == FTy->getNumParams(),
1793 "Incorrect number of arguments passed to called function!", I);
1795 // Verify that all arguments to the call match the function type.
1796 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1797 Assert(CS.getArgument(i)->getType() == FTy->getParamType(i),
1798 "Call parameter type does not match function signature!",
1799 CS.getArgument(i), FTy->getParamType(i), I);
1801 AttributeSet Attrs = CS.getAttributes();
1803 Assert(VerifyAttributeCount(Attrs, CS.arg_size()),
1804 "Attribute after last parameter!", I);
1806 // Verify call attributes.
1807 VerifyFunctionAttrs(FTy, Attrs, I);
1809 // Conservatively check the inalloca argument.
1810 // We have a bug if we can find that there is an underlying alloca without
1812 if (CS.hasInAllocaArgument()) {
1813 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
1814 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
1815 Assert(AI->isUsedWithInAlloca(),
1816 "inalloca argument for call has mismatched alloca", AI, I);
1819 if (FTy->isVarArg()) {
1820 // FIXME? is 'nest' even legal here?
1821 bool SawNest = false;
1822 bool SawReturned = false;
1824 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1825 if (Attrs.hasAttribute(Idx, Attribute::Nest))
1827 if (Attrs.hasAttribute(Idx, Attribute::Returned))
1831 // Check attributes on the varargs part.
1832 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1833 Type *Ty = CS.getArgument(Idx-1)->getType();
1834 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1836 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1837 Assert(!SawNest, "More than one parameter has attribute nest!", I);
1841 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1842 Assert(!SawReturned, "More than one parameter has attribute returned!",
1844 Assert(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1845 "Incompatible argument and return types for 'returned' "
1851 Assert(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1852 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1854 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
1855 Assert(Idx == CS.arg_size(), "inalloca isn't on the last argument!", I);
1859 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1860 if (CS.getCalledFunction() == nullptr ||
1861 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1862 for (FunctionType::param_iterator PI = FTy->param_begin(),
1863 PE = FTy->param_end(); PI != PE; ++PI)
1864 Assert(!(*PI)->isMetadataTy(),
1865 "Function has metadata parameter but isn't an intrinsic", I);
1868 visitInstruction(*I);
1871 /// Two types are "congruent" if they are identical, or if they are both pointer
1872 /// types with different pointee types and the same address space.
1873 static bool isTypeCongruent(Type *L, Type *R) {
1876 PointerType *PL = dyn_cast<PointerType>(L);
1877 PointerType *PR = dyn_cast<PointerType>(R);
1880 return PL->getAddressSpace() == PR->getAddressSpace();
1883 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
1884 static const Attribute::AttrKind ABIAttrs[] = {
1885 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
1886 Attribute::InReg, Attribute::Returned};
1888 for (auto AK : ABIAttrs) {
1889 if (Attrs.hasAttribute(I + 1, AK))
1890 Copy.addAttribute(AK);
1892 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
1893 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
1897 void Verifier::verifyMustTailCall(CallInst &CI) {
1898 Assert(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
1900 // - The caller and callee prototypes must match. Pointer types of
1901 // parameters or return types may differ in pointee type, but not
1903 Function *F = CI.getParent()->getParent();
1904 auto GetFnTy = [](Value *V) {
1905 return cast<FunctionType>(
1906 cast<PointerType>(V->getType())->getElementType());
1908 FunctionType *CallerTy = GetFnTy(F);
1909 FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
1910 Assert(CallerTy->getNumParams() == CalleeTy->getNumParams(),
1911 "cannot guarantee tail call due to mismatched parameter counts", &CI);
1912 Assert(CallerTy->isVarArg() == CalleeTy->isVarArg(),
1913 "cannot guarantee tail call due to mismatched varargs", &CI);
1914 Assert(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
1915 "cannot guarantee tail call due to mismatched return types", &CI);
1916 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
1918 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
1919 "cannot guarantee tail call due to mismatched parameter types", &CI);
1922 // - The calling conventions of the caller and callee must match.
1923 Assert(F->getCallingConv() == CI.getCallingConv(),
1924 "cannot guarantee tail call due to mismatched calling conv", &CI);
1926 // - All ABI-impacting function attributes, such as sret, byval, inreg,
1927 // returned, and inalloca, must match.
1928 AttributeSet CallerAttrs = F->getAttributes();
1929 AttributeSet CalleeAttrs = CI.getAttributes();
1930 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
1931 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
1932 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
1933 Assert(CallerABIAttrs == CalleeABIAttrs,
1934 "cannot guarantee tail call due to mismatched ABI impacting "
1935 "function attributes",
1936 &CI, CI.getOperand(I));
1939 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
1940 // or a pointer bitcast followed by a ret instruction.
1941 // - The ret instruction must return the (possibly bitcasted) value
1942 // produced by the call or void.
1943 Value *RetVal = &CI;
1944 Instruction *Next = CI.getNextNode();
1946 // Handle the optional bitcast.
1947 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
1948 Assert(BI->getOperand(0) == RetVal,
1949 "bitcast following musttail call must use the call", BI);
1951 Next = BI->getNextNode();
1954 // Check the return.
1955 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
1956 Assert(Ret, "musttail call must be precede a ret with an optional bitcast",
1958 Assert(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
1959 "musttail call result must be returned", Ret);
1962 void Verifier::visitCallInst(CallInst &CI) {
1963 VerifyCallSite(&CI);
1965 if (CI.isMustTailCall())
1966 verifyMustTailCall(CI);
1968 if (Function *F = CI.getCalledFunction())
1969 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1970 visitIntrinsicFunctionCall(ID, CI);
1973 void Verifier::visitInvokeInst(InvokeInst &II) {
1974 VerifyCallSite(&II);
1976 // Verify that there is a landingpad instruction as the first non-PHI
1977 // instruction of the 'unwind' destination.
1978 Assert(II.getUnwindDest()->isLandingPad(),
1979 "The unwind destination does not have a landingpad instruction!", &II);
1981 if (Function *F = II.getCalledFunction())
1982 // TODO: Ideally we should use visitIntrinsicFunction here. But it uses
1983 // CallInst as an input parameter. It not woth updating this whole
1984 // function only to support statepoint verification.
1985 if (F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
1986 VerifyStatepoint(ImmutableCallSite(&II));
1988 visitTerminatorInst(II);
1991 /// visitBinaryOperator - Check that both arguments to the binary operator are
1992 /// of the same type!
1994 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1995 Assert(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1996 "Both operands to a binary operator are not of the same type!", &B);
1998 switch (B.getOpcode()) {
1999 // Check that integer arithmetic operators are only used with
2000 // integral operands.
2001 case Instruction::Add:
2002 case Instruction::Sub:
2003 case Instruction::Mul:
2004 case Instruction::SDiv:
2005 case Instruction::UDiv:
2006 case Instruction::SRem:
2007 case Instruction::URem:
2008 Assert(B.getType()->isIntOrIntVectorTy(),
2009 "Integer arithmetic operators only work with integral types!", &B);
2010 Assert(B.getType() == B.getOperand(0)->getType(),
2011 "Integer arithmetic operators must have same type "
2012 "for operands and result!",
2015 // Check that floating-point arithmetic operators are only used with
2016 // floating-point operands.
2017 case Instruction::FAdd:
2018 case Instruction::FSub:
2019 case Instruction::FMul:
2020 case Instruction::FDiv:
2021 case Instruction::FRem:
2022 Assert(B.getType()->isFPOrFPVectorTy(),
2023 "Floating-point arithmetic operators only work with "
2024 "floating-point types!",
2026 Assert(B.getType() == B.getOperand(0)->getType(),
2027 "Floating-point arithmetic operators must have same type "
2028 "for operands and result!",
2031 // Check that logical operators are only used with integral operands.
2032 case Instruction::And:
2033 case Instruction::Or:
2034 case Instruction::Xor:
2035 Assert(B.getType()->isIntOrIntVectorTy(),
2036 "Logical operators only work with integral types!", &B);
2037 Assert(B.getType() == B.getOperand(0)->getType(),
2038 "Logical operators must have same type for operands and result!",
2041 case Instruction::Shl:
2042 case Instruction::LShr:
2043 case Instruction::AShr:
2044 Assert(B.getType()->isIntOrIntVectorTy(),
2045 "Shifts only work with integral types!", &B);
2046 Assert(B.getType() == B.getOperand(0)->getType(),
2047 "Shift return type must be same as operands!", &B);
2050 llvm_unreachable("Unknown BinaryOperator opcode!");
2053 visitInstruction(B);
2056 void Verifier::visitICmpInst(ICmpInst &IC) {
2057 // Check that the operands are the same type
2058 Type *Op0Ty = IC.getOperand(0)->getType();
2059 Type *Op1Ty = IC.getOperand(1)->getType();
2060 Assert(Op0Ty == Op1Ty,
2061 "Both operands to ICmp instruction are not of the same type!", &IC);
2062 // Check that the operands are the right type
2063 Assert(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2064 "Invalid operand types for ICmp instruction", &IC);
2065 // Check that the predicate is valid.
2066 Assert(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2067 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2068 "Invalid predicate in ICmp instruction!", &IC);
2070 visitInstruction(IC);
2073 void Verifier::visitFCmpInst(FCmpInst &FC) {
2074 // Check that the operands are the same type
2075 Type *Op0Ty = FC.getOperand(0)->getType();
2076 Type *Op1Ty = FC.getOperand(1)->getType();
2077 Assert(Op0Ty == Op1Ty,
2078 "Both operands to FCmp instruction are not of the same type!", &FC);
2079 // Check that the operands are the right type
2080 Assert(Op0Ty->isFPOrFPVectorTy(),
2081 "Invalid operand types for FCmp instruction", &FC);
2082 // Check that the predicate is valid.
2083 Assert(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2084 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2085 "Invalid predicate in FCmp instruction!", &FC);
2087 visitInstruction(FC);
2090 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2092 ExtractElementInst::isValidOperands(EI.getOperand(0), EI.getOperand(1)),
2093 "Invalid extractelement operands!", &EI);
2094 visitInstruction(EI);
2097 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2098 Assert(InsertElementInst::isValidOperands(IE.getOperand(0), IE.getOperand(1),
2100 "Invalid insertelement operands!", &IE);
2101 visitInstruction(IE);
2104 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2105 Assert(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2107 "Invalid shufflevector operands!", &SV);
2108 visitInstruction(SV);
2111 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2112 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2114 Assert(isa<PointerType>(TargetTy),
2115 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2116 Assert(cast<PointerType>(TargetTy)->getElementType()->isSized(),
2117 "GEP into unsized type!", &GEP);
2118 Assert(GEP.getPointerOperandType()->isVectorTy() ==
2119 GEP.getType()->isVectorTy(),
2120 "Vector GEP must return a vector value", &GEP);
2122 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2124 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
2125 Assert(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2127 Assert(GEP.getType()->getScalarType()->isPointerTy() &&
2128 cast<PointerType>(GEP.getType()->getScalarType())
2129 ->getElementType() == ElTy,
2130 "GEP is not of right type for indices!", &GEP, ElTy);
2132 if (GEP.getPointerOperandType()->isVectorTy()) {
2133 // Additional checks for vector GEPs.
2134 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
2135 Assert(GepWidth == GEP.getType()->getVectorNumElements(),
2136 "Vector GEP result width doesn't match operand's", &GEP);
2137 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2138 Type *IndexTy = Idxs[i]->getType();
2139 Assert(IndexTy->isVectorTy(), "Vector GEP must have vector indices!",
2141 unsigned IndexWidth = IndexTy->getVectorNumElements();
2142 Assert(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
2145 visitInstruction(GEP);
2148 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2149 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2152 void Verifier::visitRangeMetadata(Instruction& I,
2153 MDNode* Range, Type* Ty) {
2155 Range == I.getMetadata(LLVMContext::MD_range) &&
2156 "precondition violation");
2158 unsigned NumOperands = Range->getNumOperands();
2159 Assert(NumOperands % 2 == 0, "Unfinished range!", Range);
2160 unsigned NumRanges = NumOperands / 2;
2161 Assert(NumRanges >= 1, "It should have at least one range!", Range);
2163 ConstantRange LastRange(1); // Dummy initial value
2164 for (unsigned i = 0; i < NumRanges; ++i) {
2166 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2167 Assert(Low, "The lower limit must be an integer!", Low);
2169 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2170 Assert(High, "The upper limit must be an integer!", High);
2171 Assert(High->getType() == Low->getType() && High->getType() == Ty,
2172 "Range types must match instruction type!", &I);
2174 APInt HighV = High->getValue();
2175 APInt LowV = Low->getValue();
2176 ConstantRange CurRange(LowV, HighV);
2177 Assert(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2178 "Range must not be empty!", Range);
2180 Assert(CurRange.intersectWith(LastRange).isEmptySet(),
2181 "Intervals are overlapping", Range);
2182 Assert(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2184 Assert(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2187 LastRange = ConstantRange(LowV, HighV);
2189 if (NumRanges > 2) {
2191 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2193 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2194 ConstantRange FirstRange(FirstLow, FirstHigh);
2195 Assert(FirstRange.intersectWith(LastRange).isEmptySet(),
2196 "Intervals are overlapping", Range);
2197 Assert(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2202 void Verifier::visitLoadInst(LoadInst &LI) {
2203 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2204 Assert(PTy, "Load operand must be a pointer.", &LI);
2205 Type *ElTy = PTy->getElementType();
2206 Assert(ElTy == LI.getType(),
2207 "Load result type does not match pointer operand type!", &LI, ElTy);
2208 Assert(LI.getAlignment() <= Value::MaximumAlignment,
2209 "huge alignment values are unsupported", &LI);
2210 if (LI.isAtomic()) {
2211 Assert(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2212 "Load cannot have Release ordering", &LI);
2213 Assert(LI.getAlignment() != 0,
2214 "Atomic load must specify explicit alignment", &LI);
2215 if (!ElTy->isPointerTy()) {
2216 Assert(ElTy->isIntegerTy(), "atomic load operand must have integer type!",
2218 unsigned Size = ElTy->getPrimitiveSizeInBits();
2219 Assert(Size >= 8 && !(Size & (Size - 1)),
2220 "atomic load operand must be power-of-two byte-sized integer", &LI,
2224 Assert(LI.getSynchScope() == CrossThread,
2225 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2228 visitInstruction(LI);
2231 void Verifier::visitStoreInst(StoreInst &SI) {
2232 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2233 Assert(PTy, "Store operand must be a pointer.", &SI);
2234 Type *ElTy = PTy->getElementType();
2235 Assert(ElTy == SI.getOperand(0)->getType(),
2236 "Stored value type does not match pointer operand type!", &SI, ElTy);
2237 Assert(SI.getAlignment() <= Value::MaximumAlignment,
2238 "huge alignment values are unsupported", &SI);
2239 if (SI.isAtomic()) {
2240 Assert(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2241 "Store cannot have Acquire ordering", &SI);
2242 Assert(SI.getAlignment() != 0,
2243 "Atomic store must specify explicit alignment", &SI);
2244 if (!ElTy->isPointerTy()) {
2245 Assert(ElTy->isIntegerTy(),
2246 "atomic store operand must have integer type!", &SI, ElTy);
2247 unsigned Size = ElTy->getPrimitiveSizeInBits();
2248 Assert(Size >= 8 && !(Size & (Size - 1)),
2249 "atomic store operand must be power-of-two byte-sized integer",
2253 Assert(SI.getSynchScope() == CrossThread,
2254 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2256 visitInstruction(SI);
2259 void Verifier::visitAllocaInst(AllocaInst &AI) {
2260 SmallPtrSet<const Type*, 4> Visited;
2261 PointerType *PTy = AI.getType();
2262 Assert(PTy->getAddressSpace() == 0,
2263 "Allocation instruction pointer not in the generic address space!",
2265 Assert(PTy->getElementType()->isSized(&Visited),
2266 "Cannot allocate unsized type", &AI);
2267 Assert(AI.getArraySize()->getType()->isIntegerTy(),
2268 "Alloca array size must have integer type", &AI);
2269 Assert(AI.getAlignment() <= Value::MaximumAlignment,
2270 "huge alignment values are unsupported", &AI);
2272 visitInstruction(AI);
2275 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2277 // FIXME: more conditions???
2278 Assert(CXI.getSuccessOrdering() != NotAtomic,
2279 "cmpxchg instructions must be atomic.", &CXI);
2280 Assert(CXI.getFailureOrdering() != NotAtomic,
2281 "cmpxchg instructions must be atomic.", &CXI);
2282 Assert(CXI.getSuccessOrdering() != Unordered,
2283 "cmpxchg instructions cannot be unordered.", &CXI);
2284 Assert(CXI.getFailureOrdering() != Unordered,
2285 "cmpxchg instructions cannot be unordered.", &CXI);
2286 Assert(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2287 "cmpxchg instructions be at least as constrained on success as fail",
2289 Assert(CXI.getFailureOrdering() != Release &&
2290 CXI.getFailureOrdering() != AcquireRelease,
2291 "cmpxchg failure ordering cannot include release semantics", &CXI);
2293 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2294 Assert(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2295 Type *ElTy = PTy->getElementType();
2296 Assert(ElTy->isIntegerTy(), "cmpxchg operand must have integer type!", &CXI,
2298 unsigned Size = ElTy->getPrimitiveSizeInBits();
2299 Assert(Size >= 8 && !(Size & (Size - 1)),
2300 "cmpxchg operand must be power-of-two byte-sized integer", &CXI, ElTy);
2301 Assert(ElTy == CXI.getOperand(1)->getType(),
2302 "Expected value type does not match pointer operand type!", &CXI,
2304 Assert(ElTy == CXI.getOperand(2)->getType(),
2305 "Stored value type does not match pointer operand type!", &CXI, ElTy);
2306 visitInstruction(CXI);
2309 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2310 Assert(RMWI.getOrdering() != NotAtomic,
2311 "atomicrmw instructions must be atomic.", &RMWI);
2312 Assert(RMWI.getOrdering() != Unordered,
2313 "atomicrmw instructions cannot be unordered.", &RMWI);
2314 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2315 Assert(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2316 Type *ElTy = PTy->getElementType();
2317 Assert(ElTy->isIntegerTy(), "atomicrmw operand must have integer type!",
2319 unsigned Size = ElTy->getPrimitiveSizeInBits();
2320 Assert(Size >= 8 && !(Size & (Size - 1)),
2321 "atomicrmw operand must be power-of-two byte-sized integer", &RMWI,
2323 Assert(ElTy == RMWI.getOperand(1)->getType(),
2324 "Argument value type does not match pointer operand type!", &RMWI,
2326 Assert(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2327 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2328 "Invalid binary operation!", &RMWI);
2329 visitInstruction(RMWI);
2332 void Verifier::visitFenceInst(FenceInst &FI) {
2333 const AtomicOrdering Ordering = FI.getOrdering();
2334 Assert(Ordering == Acquire || Ordering == Release ||
2335 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2336 "fence instructions may only have "
2337 "acquire, release, acq_rel, or seq_cst ordering.",
2339 visitInstruction(FI);
2342 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2343 Assert(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2344 EVI.getIndices()) == EVI.getType(),
2345 "Invalid ExtractValueInst operands!", &EVI);
2347 visitInstruction(EVI);
2350 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2351 Assert(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2352 IVI.getIndices()) ==
2353 IVI.getOperand(1)->getType(),
2354 "Invalid InsertValueInst operands!", &IVI);
2356 visitInstruction(IVI);
2359 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2360 BasicBlock *BB = LPI.getParent();
2362 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2364 Assert(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2365 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2367 // The landingpad instruction defines its parent as a landing pad block. The
2368 // landing pad block may be branched to only by the unwind edge of an invoke.
2369 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2370 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2371 Assert(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2372 "Block containing LandingPadInst must be jumped to "
2373 "only by the unwind edge of an invoke.",
2377 // The landingpad instruction must be the first non-PHI instruction in the
2379 Assert(LPI.getParent()->getLandingPadInst() == &LPI,
2380 "LandingPadInst not the first non-PHI instruction in the block.",
2383 // The personality functions for all landingpad instructions within the same
2384 // function should match.
2386 Assert(LPI.getPersonalityFn() == PersonalityFn,
2387 "Personality function doesn't match others in function", &LPI);
2388 PersonalityFn = LPI.getPersonalityFn();
2390 // All operands must be constants.
2391 Assert(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2393 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2394 Constant *Clause = LPI.getClause(i);
2395 if (LPI.isCatch(i)) {
2396 Assert(isa<PointerType>(Clause->getType()),
2397 "Catch operand does not have pointer type!", &LPI);
2399 Assert(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2400 Assert(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2401 "Filter operand is not an array of constants!", &LPI);
2405 visitInstruction(LPI);
2408 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2409 Instruction *Op = cast<Instruction>(I.getOperand(i));
2410 // If the we have an invalid invoke, don't try to compute the dominance.
2411 // We already reject it in the invoke specific checks and the dominance
2412 // computation doesn't handle multiple edges.
2413 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2414 if (II->getNormalDest() == II->getUnwindDest())
2418 const Use &U = I.getOperandUse(i);
2419 Assert(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2420 "Instruction does not dominate all uses!", Op, &I);
2423 /// verifyInstruction - Verify that an instruction is well formed.
2425 void Verifier::visitInstruction(Instruction &I) {
2426 BasicBlock *BB = I.getParent();
2427 Assert(BB, "Instruction not embedded in basic block!", &I);
2429 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
2430 for (User *U : I.users()) {
2431 Assert(U != (User *)&I || !DT.isReachableFromEntry(BB),
2432 "Only PHI nodes may reference their own value!", &I);
2436 // Check that void typed values don't have names
2437 Assert(!I.getType()->isVoidTy() || !I.hasName(),
2438 "Instruction has a name, but provides a void value!", &I);
2440 // Check that the return value of the instruction is either void or a legal
2442 Assert(I.getType()->isVoidTy() || I.getType()->isFirstClassType(),
2443 "Instruction returns a non-scalar type!", &I);
2445 // Check that the instruction doesn't produce metadata. Calls are already
2446 // checked against the callee type.
2447 Assert(!I.getType()->isMetadataTy() || isa<CallInst>(I) || isa<InvokeInst>(I),
2448 "Invalid use of metadata!", &I);
2450 // Check that all uses of the instruction, if they are instructions
2451 // themselves, actually have parent basic blocks. If the use is not an
2452 // instruction, it is an error!
2453 for (Use &U : I.uses()) {
2454 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2455 Assert(Used->getParent() != nullptr,
2456 "Instruction referencing"
2457 " instruction not embedded in a basic block!",
2460 CheckFailed("Use of instruction is not an instruction!", U);
2465 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2466 Assert(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2468 // Check to make sure that only first-class-values are operands to
2470 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2471 Assert(0, "Instruction operands must be first-class values!", &I);
2474 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2475 // Check to make sure that the "address of" an intrinsic function is never
2478 !F->isIntrinsic() ||
2479 i == (isa<CallInst>(I) ? e - 1 : isa<InvokeInst>(I) ? e - 3 : 0),
2480 "Cannot take the address of an intrinsic!", &I);
2482 !F->isIntrinsic() || isa<CallInst>(I) ||
2483 F->getIntrinsicID() == Intrinsic::donothing ||
2484 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
2485 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
2486 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
2487 "Cannot invoke an intrinsinc other than"
2488 " donothing or patchpoint",
2490 Assert(F->getParent() == M, "Referencing function in another module!",
2492 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2493 Assert(OpBB->getParent() == BB->getParent(),
2494 "Referring to a basic block in another function!", &I);
2495 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2496 Assert(OpArg->getParent() == BB->getParent(),
2497 "Referring to an argument in another function!", &I);
2498 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2499 Assert(GV->getParent() == M, "Referencing global in another module!", &I);
2500 } else if (isa<Instruction>(I.getOperand(i))) {
2501 verifyDominatesUse(I, i);
2502 } else if (isa<InlineAsm>(I.getOperand(i))) {
2503 Assert((i + 1 == e && isa<CallInst>(I)) ||
2504 (i + 3 == e && isa<InvokeInst>(I)),
2505 "Cannot take the address of an inline asm!", &I);
2506 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2507 if (CE->getType()->isPtrOrPtrVectorTy()) {
2508 // If we have a ConstantExpr pointer, we need to see if it came from an
2509 // illegal bitcast (inttoptr <constant int> )
2510 SmallVector<const ConstantExpr *, 4> Stack;
2511 SmallPtrSet<const ConstantExpr *, 4> Visited;
2512 Stack.push_back(CE);
2514 while (!Stack.empty()) {
2515 const ConstantExpr *V = Stack.pop_back_val();
2516 if (!Visited.insert(V).second)
2519 VerifyConstantExprBitcastType(V);
2521 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2522 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2523 Stack.push_back(Op);
2530 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2531 Assert(I.getType()->isFPOrFPVectorTy(),
2532 "fpmath requires a floating point result!", &I);
2533 Assert(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2534 if (ConstantFP *CFP0 =
2535 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
2536 APFloat Accuracy = CFP0->getValueAPF();
2537 Assert(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2538 "fpmath accuracy not a positive number!", &I);
2540 Assert(false, "invalid fpmath accuracy!", &I);
2544 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
2545 Assert(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
2546 "Ranges are only for loads, calls and invokes!", &I);
2547 visitRangeMetadata(I, Range, I.getType());
2550 if (I.getMetadata(LLVMContext::MD_nonnull)) {
2551 Assert(I.getType()->isPointerTy(), "nonnull applies only to pointer types",
2553 Assert(isa<LoadInst>(I),
2554 "nonnull applies only to load instructions, use attributes"
2555 " for calls or invokes",
2559 // Don't recurse into !dbg attachments (leave that for verifyDebugInfo()),
2560 // but at least check that it's a legal type.
2561 if (MDNode *N = I.getDebugLoc().getAsMDNode()) {
2562 Assert(isa<MDLocation>(N),
2563 "invalid !dbg metadata attachment", &I, N);
2566 InstsInThisBlock.insert(&I);
2569 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2570 /// intrinsic argument or return value) matches the type constraints specified
2571 /// by the .td file (e.g. an "any integer" argument really is an integer).
2573 /// This return true on error but does not print a message.
2574 bool Verifier::VerifyIntrinsicType(Type *Ty,
2575 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2576 SmallVectorImpl<Type*> &ArgTys) {
2577 using namespace Intrinsic;
2579 // If we ran out of descriptors, there are too many arguments.
2580 if (Infos.empty()) return true;
2581 IITDescriptor D = Infos.front();
2582 Infos = Infos.slice(1);
2585 case IITDescriptor::Void: return !Ty->isVoidTy();
2586 case IITDescriptor::VarArg: return true;
2587 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2588 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2589 case IITDescriptor::Half: return !Ty->isHalfTy();
2590 case IITDescriptor::Float: return !Ty->isFloatTy();
2591 case IITDescriptor::Double: return !Ty->isDoubleTy();
2592 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2593 case IITDescriptor::Vector: {
2594 VectorType *VT = dyn_cast<VectorType>(Ty);
2595 return !VT || VT->getNumElements() != D.Vector_Width ||
2596 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2598 case IITDescriptor::Pointer: {
2599 PointerType *PT = dyn_cast<PointerType>(Ty);
2600 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2601 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2604 case IITDescriptor::Struct: {
2605 StructType *ST = dyn_cast<StructType>(Ty);
2606 if (!ST || ST->getNumElements() != D.Struct_NumElements)
2609 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2610 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2615 case IITDescriptor::Argument:
2616 // Two cases here - If this is the second occurrence of an argument, verify
2617 // that the later instance matches the previous instance.
2618 if (D.getArgumentNumber() < ArgTys.size())
2619 return Ty != ArgTys[D.getArgumentNumber()];
2621 // Otherwise, if this is the first instance of an argument, record it and
2622 // verify the "Any" kind.
2623 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2624 ArgTys.push_back(Ty);
2626 switch (D.getArgumentKind()) {
2627 case IITDescriptor::AK_Any: return false; // Success
2628 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2629 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2630 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2631 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2633 llvm_unreachable("all argument kinds not covered");
2635 case IITDescriptor::ExtendArgument: {
2636 // This may only be used when referring to a previous vector argument.
2637 if (D.getArgumentNumber() >= ArgTys.size())
2640 Type *NewTy = ArgTys[D.getArgumentNumber()];
2641 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2642 NewTy = VectorType::getExtendedElementVectorType(VTy);
2643 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2644 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2650 case IITDescriptor::TruncArgument: {
2651 // This may only be used when referring to a previous vector argument.
2652 if (D.getArgumentNumber() >= ArgTys.size())
2655 Type *NewTy = ArgTys[D.getArgumentNumber()];
2656 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2657 NewTy = VectorType::getTruncatedElementVectorType(VTy);
2658 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2659 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
2665 case IITDescriptor::HalfVecArgument:
2666 // This may only be used when referring to a previous vector argument.
2667 return D.getArgumentNumber() >= ArgTys.size() ||
2668 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2669 VectorType::getHalfElementsVectorType(
2670 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2671 case IITDescriptor::SameVecWidthArgument: {
2672 if (D.getArgumentNumber() >= ArgTys.size())
2674 VectorType * ReferenceType =
2675 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
2676 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
2677 if (!ThisArgType || !ReferenceType ||
2678 (ReferenceType->getVectorNumElements() !=
2679 ThisArgType->getVectorNumElements()))
2681 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
2684 case IITDescriptor::PtrToArgument: {
2685 if (D.getArgumentNumber() >= ArgTys.size())
2687 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
2688 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
2689 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
2691 case IITDescriptor::VecOfPtrsToElt: {
2692 if (D.getArgumentNumber() >= ArgTys.size())
2694 VectorType * ReferenceType =
2695 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
2696 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
2697 if (!ThisArgVecTy || !ReferenceType ||
2698 (ReferenceType->getVectorNumElements() !=
2699 ThisArgVecTy->getVectorNumElements()))
2701 PointerType *ThisArgEltTy =
2702 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
2705 return (!(ThisArgEltTy->getElementType() ==
2706 ReferenceType->getVectorElementType()));
2709 llvm_unreachable("unhandled");
2712 /// \brief Verify if the intrinsic has variable arguments.
2713 /// This method is intended to be called after all the fixed arguments have been
2716 /// This method returns true on error and does not print an error message.
2718 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2719 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2720 using namespace Intrinsic;
2722 // If there are no descriptors left, then it can't be a vararg.
2726 // There should be only one descriptor remaining at this point.
2727 if (Infos.size() != 1)
2730 // Check and verify the descriptor.
2731 IITDescriptor D = Infos.front();
2732 Infos = Infos.slice(1);
2733 if (D.Kind == IITDescriptor::VarArg)
2739 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2741 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2742 Function *IF = CI.getCalledFunction();
2743 Assert(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2746 // Verify that the intrinsic prototype lines up with what the .td files
2748 FunctionType *IFTy = IF->getFunctionType();
2749 bool IsVarArg = IFTy->isVarArg();
2751 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2752 getIntrinsicInfoTableEntries(ID, Table);
2753 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2755 SmallVector<Type *, 4> ArgTys;
2756 Assert(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2757 "Intrinsic has incorrect return type!", IF);
2758 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2759 Assert(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2760 "Intrinsic has incorrect argument type!", IF);
2762 // Verify if the intrinsic call matches the vararg property.
2764 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2765 "Intrinsic was not defined with variable arguments!", IF);
2767 Assert(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2768 "Callsite was not defined with variable arguments!", IF);
2770 // All descriptors should be absorbed by now.
2771 Assert(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2773 // Now that we have the intrinsic ID and the actual argument types (and we
2774 // know they are legal for the intrinsic!) get the intrinsic name through the
2775 // usual means. This allows us to verify the mangling of argument types into
2777 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
2778 Assert(ExpectedName == IF->getName(),
2779 "Intrinsic name not mangled correctly for type arguments! "
2784 // If the intrinsic takes MDNode arguments, verify that they are either global
2785 // or are local to *this* function.
2786 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2787 if (auto *MD = dyn_cast<MetadataAsValue>(CI.getArgOperand(i)))
2788 visitMetadataAsValue(*MD, CI.getParent()->getParent());
2793 case Intrinsic::ctlz: // llvm.ctlz
2794 case Intrinsic::cttz: // llvm.cttz
2795 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
2796 "is_zero_undef argument of bit counting intrinsics must be a "
2800 case Intrinsic::dbg_declare: // llvm.dbg.declare
2801 Assert(isa<MetadataAsValue>(CI.getArgOperand(0)),
2802 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2803 visitDbgIntrinsic("declare", cast<DbgDeclareInst>(CI));
2805 case Intrinsic::dbg_value: // llvm.dbg.value
2806 visitDbgIntrinsic("value", cast<DbgValueInst>(CI));
2808 case Intrinsic::memcpy:
2809 case Intrinsic::memmove:
2810 case Intrinsic::memset: {
2811 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CI.getArgOperand(3));
2813 "alignment argument of memory intrinsics must be a constant int",
2815 const APInt &AlignVal = AlignCI->getValue();
2816 Assert(AlignCI->isZero() || AlignVal.isPowerOf2(),
2817 "alignment argument of memory intrinsics must be a power of 2", &CI);
2818 Assert(isa<ConstantInt>(CI.getArgOperand(4)),
2819 "isvolatile argument of memory intrinsics must be a constant int",
2823 case Intrinsic::gcroot:
2824 case Intrinsic::gcwrite:
2825 case Intrinsic::gcread:
2826 if (ID == Intrinsic::gcroot) {
2828 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2829 Assert(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2830 Assert(isa<Constant>(CI.getArgOperand(1)),
2831 "llvm.gcroot parameter #2 must be a constant.", &CI);
2832 if (!AI->getType()->getElementType()->isPointerTy()) {
2833 Assert(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2834 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2835 "or argument #2 must be a non-null constant.",
2840 Assert(CI.getParent()->getParent()->hasGC(),
2841 "Enclosing function does not use GC.", &CI);
2843 case Intrinsic::init_trampoline:
2844 Assert(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2845 "llvm.init_trampoline parameter #2 must resolve to a function.",
2848 case Intrinsic::prefetch:
2849 Assert(isa<ConstantInt>(CI.getArgOperand(1)) &&
2850 isa<ConstantInt>(CI.getArgOperand(2)) &&
2851 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2852 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2853 "invalid arguments to llvm.prefetch", &CI);
2855 case Intrinsic::stackprotector:
2856 Assert(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2857 "llvm.stackprotector parameter #2 must resolve to an alloca.", &CI);
2859 case Intrinsic::lifetime_start:
2860 case Intrinsic::lifetime_end:
2861 case Intrinsic::invariant_start:
2862 Assert(isa<ConstantInt>(CI.getArgOperand(0)),
2863 "size argument of memory use markers must be a constant integer",
2866 case Intrinsic::invariant_end:
2867 Assert(isa<ConstantInt>(CI.getArgOperand(1)),
2868 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2871 case Intrinsic::frameescape: {
2872 BasicBlock *BB = CI.getParent();
2873 Assert(BB == &BB->getParent()->front(),
2874 "llvm.frameescape used outside of entry block", &CI);
2875 Assert(!SawFrameEscape,
2876 "multiple calls to llvm.frameescape in one function", &CI);
2877 for (Value *Arg : CI.arg_operands()) {
2878 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2879 Assert(AI && AI->isStaticAlloca(),
2880 "llvm.frameescape only accepts static allocas", &CI);
2882 FrameEscapeInfo[BB->getParent()].first = CI.getNumArgOperands();
2883 SawFrameEscape = true;
2886 case Intrinsic::framerecover: {
2887 Value *FnArg = CI.getArgOperand(0)->stripPointerCasts();
2888 Function *Fn = dyn_cast<Function>(FnArg);
2889 Assert(Fn && !Fn->isDeclaration(),
2890 "llvm.framerecover first "
2891 "argument must be function defined in this module",
2893 auto *IdxArg = dyn_cast<ConstantInt>(CI.getArgOperand(2));
2894 Assert(IdxArg, "idx argument of llvm.framerecover must be a constant int",
2896 auto &Entry = FrameEscapeInfo[Fn];
2897 Entry.second = unsigned(
2898 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
2902 case Intrinsic::experimental_gc_statepoint:
2903 Assert(!CI.isInlineAsm(),
2904 "gc.statepoint support for inline assembly unimplemented", &CI);
2906 VerifyStatepoint(ImmutableCallSite(&CI));
2908 case Intrinsic::experimental_gc_result_int:
2909 case Intrinsic::experimental_gc_result_float:
2910 case Intrinsic::experimental_gc_result_ptr:
2911 case Intrinsic::experimental_gc_result: {
2912 // Are we tied to a statepoint properly?
2913 CallSite StatepointCS(CI.getArgOperand(0));
2914 const Function *StatepointFn =
2915 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
2916 Assert(StatepointFn && StatepointFn->isDeclaration() &&
2917 StatepointFn->getIntrinsicID() ==
2918 Intrinsic::experimental_gc_statepoint,
2919 "gc.result operand #1 must be from a statepoint", &CI,
2920 CI.getArgOperand(0));
2922 // Assert that result type matches wrapped callee.
2923 const Value *Target = StatepointCS.getArgument(0);
2924 const PointerType *PT = cast<PointerType>(Target->getType());
2925 const FunctionType *TargetFuncType =
2926 cast<FunctionType>(PT->getElementType());
2927 Assert(CI.getType() == TargetFuncType->getReturnType(),
2928 "gc.result result type does not match wrapped callee", &CI);
2931 case Intrinsic::experimental_gc_relocate: {
2932 Assert(CI.getNumArgOperands() == 3, "wrong number of arguments", &CI);
2934 // Check that this relocate is correctly tied to the statepoint
2936 // This is case for relocate on the unwinding path of an invoke statepoint
2937 if (ExtractValueInst *ExtractValue =
2938 dyn_cast<ExtractValueInst>(CI.getArgOperand(0))) {
2939 Assert(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
2940 "gc relocate on unwind path incorrectly linked to the statepoint",
2943 const BasicBlock *invokeBB =
2944 ExtractValue->getParent()->getUniquePredecessor();
2946 // Landingpad relocates should have only one predecessor with invoke
2947 // statepoint terminator
2948 Assert(invokeBB, "safepoints should have unique landingpads",
2949 ExtractValue->getParent());
2950 Assert(invokeBB->getTerminator(), "safepoint block should be well formed",
2952 Assert(isStatepoint(invokeBB->getTerminator()),
2953 "gc relocate should be linked to a statepoint", invokeBB);
2956 // In all other cases relocate should be tied to the statepoint directly.
2957 // This covers relocates on a normal return path of invoke statepoint and
2958 // relocates of a call statepoint
2959 auto Token = CI.getArgOperand(0);
2960 Assert(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
2961 "gc relocate is incorrectly tied to the statepoint", &CI, Token);
2964 // Verify rest of the relocate arguments
2966 GCRelocateOperands ops(&CI);
2967 ImmutableCallSite StatepointCS(ops.statepoint());
2969 // Both the base and derived must be piped through the safepoint
2970 Value* Base = CI.getArgOperand(1);
2971 Assert(isa<ConstantInt>(Base),
2972 "gc.relocate operand #2 must be integer offset", &CI);
2974 Value* Derived = CI.getArgOperand(2);
2975 Assert(isa<ConstantInt>(Derived),
2976 "gc.relocate operand #3 must be integer offset", &CI);
2978 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
2979 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
2981 Assert(0 <= BaseIndex && BaseIndex < (int)StatepointCS.arg_size(),
2982 "gc.relocate: statepoint base index out of bounds", &CI);
2983 Assert(0 <= DerivedIndex && DerivedIndex < (int)StatepointCS.arg_size(),
2984 "gc.relocate: statepoint derived index out of bounds", &CI);
2986 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
2987 // section of the statepoint's argument
2988 Assert(StatepointCS.arg_size() > 0,
2989 "gc.statepoint: insufficient arguments");
2990 Assert(isa<ConstantInt>(StatepointCS.getArgument(1)),
2991 "gc.statement: number of call arguments must be constant integer");
2992 const unsigned NumCallArgs =
2993 cast<ConstantInt>(StatepointCS.getArgument(1))->getZExtValue();
2994 Assert(StatepointCS.arg_size() > NumCallArgs+3,
2995 "gc.statepoint: mismatch in number of call arguments");
2996 Assert(isa<ConstantInt>(StatepointCS.getArgument(NumCallArgs+3)),
2997 "gc.statepoint: number of deoptimization arguments must be "
2998 "a constant integer");
2999 const int NumDeoptArgs =
3000 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 3))->getZExtValue();
3001 const int GCParamArgsStart = NumCallArgs + NumDeoptArgs + 4;
3002 const int GCParamArgsEnd = StatepointCS.arg_size();
3003 Assert(GCParamArgsStart <= BaseIndex && BaseIndex < GCParamArgsEnd,
3004 "gc.relocate: statepoint base index doesn't fall within the "
3005 "'gc parameters' section of the statepoint call",
3007 Assert(GCParamArgsStart <= DerivedIndex && DerivedIndex < GCParamArgsEnd,
3008 "gc.relocate: statepoint derived index doesn't fall within the "
3009 "'gc parameters' section of the statepoint call",
3012 // Assert that the result type matches the type of the relocated pointer
3013 GCRelocateOperands Operands(&CI);
3014 Assert(Operands.derivedPtr()->getType() == CI.getType(),
3015 "gc.relocate: relocating a pointer shouldn't change its type", &CI);
3021 template <class DbgIntrinsicTy>
3022 void Verifier::visitDbgIntrinsic(StringRef Kind, DbgIntrinsicTy &DII) {
3023 auto *MD = cast<MetadataAsValue>(DII.getArgOperand(0))->getMetadata();
3024 Assert(isa<ValueAsMetadata>(MD) ||
3025 (isa<MDNode>(MD) && !cast<MDNode>(MD)->getNumOperands()),
3026 "invalid llvm.dbg." + Kind + " intrinsic address/value", &DII, MD);
3027 Assert(isa<MDLocalVariable>(DII.getRawVariable()),
3028 "invalid llvm.dbg." + Kind + " intrinsic variable", &DII,
3029 DII.getRawVariable());
3030 Assert(isa<MDExpression>(DII.getRawExpression()),
3031 "invalid llvm.dbg." + Kind + " intrinsic expression", &DII,
3032 DII.getRawExpression());
3035 void Verifier::verifyDebugInfo() {
3036 // Run the debug info verifier only if the regular verifier succeeds, since
3037 // sometimes checks that have already failed will cause crashes here.
3038 if (EverBroken || !VerifyDebugInfo)
3041 DebugInfoFinder Finder;
3042 Finder.processModule(*M);
3043 processInstructions(Finder);
3045 // Verify Debug Info.
3047 // NOTE: The loud braces are necessary for MSVC compatibility.
3048 for (DICompileUnit CU : Finder.compile_units()) {
3049 Assert(CU.Verify(), "DICompileUnit does not Verify!", CU);
3051 for (DISubprogram S : Finder.subprograms()) {
3052 Assert(S.Verify(), "DISubprogram does not Verify!", S);
3054 for (DIGlobalVariable GV : Finder.global_variables()) {
3055 Assert(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
3057 for (DIType T : Finder.types()) {
3058 Assert(T.Verify(), "DIType does not Verify!", T);
3060 for (DIScope S : Finder.scopes()) {
3061 Assert(S.Verify(), "DIScope does not Verify!", S);
3065 void Verifier::processInstructions(DebugInfoFinder &Finder) {
3066 for (const Function &F : *M)
3067 for (auto I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
3068 if (MDNode *MD = I->getMetadata(LLVMContext::MD_dbg))
3069 Finder.processLocation(*M, DILocation(MD));
3070 if (const CallInst *CI = dyn_cast<CallInst>(&*I))
3071 processCallInst(Finder, *CI);
3075 void Verifier::processCallInst(DebugInfoFinder &Finder, const CallInst &CI) {
3076 if (Function *F = CI.getCalledFunction())
3077 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3079 case Intrinsic::dbg_declare:
3080 Finder.processDeclare(*M, cast<DbgDeclareInst>(&CI));
3082 case Intrinsic::dbg_value:
3083 Finder.processValue(*M, cast<DbgValueInst>(&CI));
3090 //===----------------------------------------------------------------------===//
3091 // Implement the public interfaces to this file...
3092 //===----------------------------------------------------------------------===//
3094 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3095 Function &F = const_cast<Function &>(f);
3096 assert(!F.isDeclaration() && "Cannot verify external functions");
3098 raw_null_ostream NullStr;
3099 Verifier V(OS ? *OS : NullStr);
3101 // Note that this function's return value is inverted from what you would
3102 // expect of a function called "verify".
3103 return !V.verify(F);
3106 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3107 raw_null_ostream NullStr;
3108 Verifier V(OS ? *OS : NullStr);
3110 bool Broken = false;
3111 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3112 if (!I->isDeclaration() && !I->isMaterializable())
3113 Broken |= !V.verify(*I);
3115 // Note that this function's return value is inverted from what you would
3116 // expect of a function called "verify".
3117 return !V.verify(M) || Broken;
3121 struct VerifierLegacyPass : public FunctionPass {
3127 VerifierLegacyPass() : FunctionPass(ID), V(dbgs()), FatalErrors(true) {
3128 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3130 explicit VerifierLegacyPass(bool FatalErrors)
3131 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3132 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3135 bool runOnFunction(Function &F) override {
3136 if (!V.verify(F) && FatalErrors)
3137 report_fatal_error("Broken function found, compilation aborted!");
3142 bool doFinalization(Module &M) override {
3143 if (!V.verify(M) && FatalErrors)
3144 report_fatal_error("Broken module found, compilation aborted!");
3149 void getAnalysisUsage(AnalysisUsage &AU) const override {
3150 AU.setPreservesAll();
3155 char VerifierLegacyPass::ID = 0;
3156 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
3158 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
3159 return new VerifierLegacyPass(FatalErrors);
3162 PreservedAnalyses VerifierPass::run(Module &M) {
3163 if (verifyModule(M, &dbgs()) && FatalErrors)
3164 report_fatal_error("Broken module found, compilation aborted!");
3166 return PreservedAnalyses::all();
3169 PreservedAnalyses VerifierPass::run(Function &F) {
3170 if (verifyFunction(F, &dbgs()) && FatalErrors)
3171 report_fatal_error("Broken function found, compilation aborted!");
3173 return PreservedAnalyses::all();