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(false));
84 struct VerifierSupport {
88 /// \brief Track the brokenness of the module while recursively visiting.
91 explicit VerifierSupport(raw_ostream &OS)
92 : OS(OS), M(nullptr), Broken(false) {}
94 void WriteValue(const Value *V) {
97 if (isa<Instruction>(V)) {
100 V->printAsOperand(OS, true, M);
105 void WriteMetadata(const Metadata *MD) {
108 MD->printAsOperand(OS, true, M);
112 void WriteType(Type *T) {
118 void WriteComdat(const Comdat *C) {
124 // CheckFailed - A check failed, so print out the condition and the message
125 // that failed. This provides a nice place to put a breakpoint if you want
126 // to see why something is not correct.
127 void CheckFailed(const Twine &Message, const Value *V1 = nullptr,
128 const Value *V2 = nullptr, const Value *V3 = nullptr,
129 const Value *V4 = nullptr) {
130 OS << Message.str() << "\n";
138 void CheckFailed(const Twine &Message, const Metadata *V1, const Metadata *V2,
139 const Metadata *V3 = nullptr, const Metadata *V4 = nullptr) {
140 OS << Message.str() << "\n";
148 void CheckFailed(const Twine &Message, const Metadata *V1,
149 const Value *V2 = nullptr) {
150 OS << Message.str() << "\n";
156 void CheckFailed(const Twine &Message, const Value *V1, Type *T2,
157 const Value *V3 = nullptr) {
158 OS << Message.str() << "\n";
165 void CheckFailed(const Twine &Message, Type *T1, Type *T2 = nullptr,
166 Type *T3 = nullptr) {
167 OS << Message.str() << "\n";
174 void CheckFailed(const Twine &Message, const Comdat *C) {
175 OS << Message.str() << "\n";
180 class Verifier : public InstVisitor<Verifier>, VerifierSupport {
181 friend class InstVisitor<Verifier>;
183 LLVMContext *Context;
186 /// \brief When verifying a basic block, keep track of all of the
187 /// instructions we have seen so far.
189 /// This allows us to do efficient dominance checks for the case when an
190 /// instruction has an operand that is an instruction in the same block.
191 SmallPtrSet<Instruction *, 16> InstsInThisBlock;
193 /// \brief Keep track of the metadata nodes that have been checked already.
194 SmallPtrSet<const Metadata *, 32> MDNodes;
196 /// \brief The personality function referenced by the LandingPadInsts.
197 /// All LandingPadInsts within the same function must use the same
198 /// personality function.
199 const Value *PersonalityFn;
201 /// \brief Whether we've seen a call to @llvm.frameescape in this function
205 /// Stores the count of how many objects were passed to llvm.frameescape for a
206 /// given function and the largest index passed to llvm.framerecover.
207 DenseMap<Function *, std::pair<unsigned, unsigned>> FrameEscapeInfo;
210 explicit Verifier(raw_ostream &OS = dbgs())
211 : VerifierSupport(OS), Context(nullptr), PersonalityFn(nullptr),
212 SawFrameEscape(false) {}
214 bool verify(const Function &F) {
216 Context = &M->getContext();
218 // First ensure the function is well-enough formed to compute dominance
221 OS << "Function '" << F.getName()
222 << "' does not contain an entry block!\n";
225 for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I) {
226 if (I->empty() || !I->back().isTerminator()) {
227 OS << "Basic Block in function '" << F.getName()
228 << "' does not have terminator!\n";
229 I->printAsOperand(OS, true);
235 // Now directly compute a dominance tree. We don't rely on the pass
236 // manager to provide this as it isolates us from a potentially
237 // out-of-date dominator tree and makes it significantly more complex to
238 // run this code outside of a pass manager.
239 // FIXME: It's really gross that we have to cast away constness here.
240 DT.recalculate(const_cast<Function &>(F));
243 // FIXME: We strip const here because the inst visitor strips const.
244 visit(const_cast<Function &>(F));
245 InstsInThisBlock.clear();
246 PersonalityFn = nullptr;
247 SawFrameEscape = false;
252 bool verify(const Module &M) {
254 Context = &M.getContext();
257 // Scan through, checking all of the external function's linkage now...
258 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
259 visitGlobalValue(*I);
261 // Check to make sure function prototypes are okay.
262 if (I->isDeclaration())
266 // Now that we've visited every function, verify that we never asked to
267 // recover a frame index that wasn't escaped.
268 verifyFrameRecoverIndices();
270 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
272 visitGlobalVariable(*I);
274 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
276 visitGlobalAlias(*I);
278 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
279 E = M.named_metadata_end();
281 visitNamedMDNode(*I);
283 for (const StringMapEntry<Comdat> &SMEC : M.getComdatSymbolTable())
284 visitComdat(SMEC.getValue());
287 visitModuleIdents(M);
293 // Verification methods...
294 void visitGlobalValue(const GlobalValue &GV);
295 void visitGlobalVariable(const GlobalVariable &GV);
296 void visitGlobalAlias(const GlobalAlias &GA);
297 void visitAliaseeSubExpr(const GlobalAlias &A, const Constant &C);
298 void visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias *> &Visited,
299 const GlobalAlias &A, const Constant &C);
300 void visitNamedMDNode(const NamedMDNode &NMD);
301 void visitMDNode(const MDNode &MD);
302 void visitMetadataAsValue(const MetadataAsValue &MD, Function *F);
303 void visitValueAsMetadata(const ValueAsMetadata &MD, Function *F);
304 void visitComdat(const Comdat &C);
305 void visitModuleIdents(const Module &M);
306 void visitModuleFlags(const Module &M);
307 void visitModuleFlag(const MDNode *Op,
308 DenseMap<const MDString *, const MDNode *> &SeenIDs,
309 SmallVectorImpl<const MDNode *> &Requirements);
310 void visitFunction(const Function &F);
311 void visitBasicBlock(BasicBlock &BB);
312 void visitRangeMetadata(Instruction& I, MDNode* Range, Type* Ty);
314 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) void visit##CLASS(const CLASS &N);
315 #include "llvm/IR/Metadata.def"
317 // InstVisitor overrides...
318 using InstVisitor<Verifier>::visit;
319 void visit(Instruction &I);
321 void visitTruncInst(TruncInst &I);
322 void visitZExtInst(ZExtInst &I);
323 void visitSExtInst(SExtInst &I);
324 void visitFPTruncInst(FPTruncInst &I);
325 void visitFPExtInst(FPExtInst &I);
326 void visitFPToUIInst(FPToUIInst &I);
327 void visitFPToSIInst(FPToSIInst &I);
328 void visitUIToFPInst(UIToFPInst &I);
329 void visitSIToFPInst(SIToFPInst &I);
330 void visitIntToPtrInst(IntToPtrInst &I);
331 void visitPtrToIntInst(PtrToIntInst &I);
332 void visitBitCastInst(BitCastInst &I);
333 void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
334 void visitPHINode(PHINode &PN);
335 void visitBinaryOperator(BinaryOperator &B);
336 void visitICmpInst(ICmpInst &IC);
337 void visitFCmpInst(FCmpInst &FC);
338 void visitExtractElementInst(ExtractElementInst &EI);
339 void visitInsertElementInst(InsertElementInst &EI);
340 void visitShuffleVectorInst(ShuffleVectorInst &EI);
341 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
342 void visitCallInst(CallInst &CI);
343 void visitInvokeInst(InvokeInst &II);
344 void visitGetElementPtrInst(GetElementPtrInst &GEP);
345 void visitLoadInst(LoadInst &LI);
346 void visitStoreInst(StoreInst &SI);
347 void verifyDominatesUse(Instruction &I, unsigned i);
348 void visitInstruction(Instruction &I);
349 void visitTerminatorInst(TerminatorInst &I);
350 void visitBranchInst(BranchInst &BI);
351 void visitReturnInst(ReturnInst &RI);
352 void visitSwitchInst(SwitchInst &SI);
353 void visitIndirectBrInst(IndirectBrInst &BI);
354 void visitSelectInst(SelectInst &SI);
355 void visitUserOp1(Instruction &I);
356 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
357 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
358 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
359 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
360 void visitFenceInst(FenceInst &FI);
361 void visitAllocaInst(AllocaInst &AI);
362 void visitExtractValueInst(ExtractValueInst &EVI);
363 void visitInsertValueInst(InsertValueInst &IVI);
364 void visitLandingPadInst(LandingPadInst &LPI);
366 void VerifyCallSite(CallSite CS);
367 void verifyMustTailCall(CallInst &CI);
368 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty, int VT,
369 unsigned ArgNo, std::string &Suffix);
370 bool VerifyIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
371 SmallVectorImpl<Type *> &ArgTys);
372 bool VerifyIntrinsicIsVarArg(bool isVarArg,
373 ArrayRef<Intrinsic::IITDescriptor> &Infos);
374 bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
375 void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx, bool isFunction,
377 void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
378 bool isReturnValue, const Value *V);
379 void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
382 void VerifyConstantExprBitcastType(const ConstantExpr *CE);
383 void VerifyStatepoint(ImmutableCallSite CS);
384 void verifyFrameRecoverIndices();
386 class DebugInfoVerifier : public VerifierSupport {
388 explicit DebugInfoVerifier(raw_ostream &OS = dbgs()) : VerifierSupport(OS) {}
390 bool verify(const Module &M) {
397 void verifyDebugInfo();
398 void processInstructions(DebugInfoFinder &Finder);
399 void processCallInst(DebugInfoFinder &Finder, const CallInst &CI);
401 } // End anonymous namespace
403 // Assert - We know that cond should be true, if not print an error message.
404 #define Assert(C, M) \
405 do { if (!(C)) { CheckFailed(M); return; } } while (0)
406 #define Assert1(C, M, V1) \
407 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
408 #define Assert2(C, M, V1, V2) \
409 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
410 #define Assert3(C, M, V1, V2, V3) \
411 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
412 #define Assert4(C, M, V1, V2, V3, V4) \
413 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
415 void Verifier::visit(Instruction &I) {
416 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
417 Assert1(I.getOperand(i) != nullptr, "Operand is null", &I);
418 InstVisitor<Verifier>::visit(I);
422 void Verifier::visitGlobalValue(const GlobalValue &GV) {
423 Assert1(!GV.isDeclaration() || GV.hasExternalLinkage() ||
424 GV.hasExternalWeakLinkage(),
425 "Global is external, but doesn't have external or weak linkage!",
428 Assert1(GV.getAlignment() <= Value::MaximumAlignment,
429 "huge alignment values are unsupported", &GV);
430 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
431 "Only global variables can have appending linkage!", &GV);
433 if (GV.hasAppendingLinkage()) {
434 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
435 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
436 "Only global arrays can have appending linkage!", GVar);
440 void Verifier::visitGlobalVariable(const GlobalVariable &GV) {
441 if (GV.hasInitializer()) {
442 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
443 "Global variable initializer type does not match global "
444 "variable type!", &GV);
446 // If the global has common linkage, it must have a zero initializer and
447 // cannot be constant.
448 if (GV.hasCommonLinkage()) {
449 Assert1(GV.getInitializer()->isNullValue(),
450 "'common' global must have a zero initializer!", &GV);
451 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
453 Assert1(!GV.hasComdat(), "'common' global may not be in a Comdat!", &GV);
456 Assert1(GV.hasExternalLinkage() || GV.hasExternalWeakLinkage(),
457 "invalid linkage type for global declaration", &GV);
460 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
461 GV.getName() == "llvm.global_dtors")) {
462 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
463 "invalid linkage for intrinsic global variable", &GV);
464 // Don't worry about emitting an error for it not being an array,
465 // visitGlobalValue will complain on appending non-array.
466 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType()->getElementType())) {
467 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
468 PointerType *FuncPtrTy =
469 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
470 // FIXME: Reject the 2-field form in LLVM 4.0.
471 Assert1(STy && (STy->getNumElements() == 2 ||
472 STy->getNumElements() == 3) &&
473 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
474 STy->getTypeAtIndex(1) == FuncPtrTy,
475 "wrong type for intrinsic global variable", &GV);
476 if (STy->getNumElements() == 3) {
477 Type *ETy = STy->getTypeAtIndex(2);
478 Assert1(ETy->isPointerTy() &&
479 cast<PointerType>(ETy)->getElementType()->isIntegerTy(8),
480 "wrong type for intrinsic global variable", &GV);
485 if (GV.hasName() && (GV.getName() == "llvm.used" ||
486 GV.getName() == "llvm.compiler.used")) {
487 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
488 "invalid linkage for intrinsic global variable", &GV);
489 Type *GVType = GV.getType()->getElementType();
490 if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
491 PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
492 Assert1(PTy, "wrong type for intrinsic global variable", &GV);
493 if (GV.hasInitializer()) {
494 const Constant *Init = GV.getInitializer();
495 const ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
496 Assert1(InitArray, "wrong initalizer for intrinsic global variable",
498 for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
499 Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
501 isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
502 "invalid llvm.used member", V);
503 Assert1(V->hasName(), "members of llvm.used must be named", V);
509 Assert1(!GV.hasDLLImportStorageClass() ||
510 (GV.isDeclaration() && GV.hasExternalLinkage()) ||
511 GV.hasAvailableExternallyLinkage(),
512 "Global is marked as dllimport, but not external", &GV);
514 if (!GV.hasInitializer()) {
515 visitGlobalValue(GV);
519 // Walk any aggregate initializers looking for bitcasts between address spaces
520 SmallPtrSet<const Value *, 4> Visited;
521 SmallVector<const Value *, 4> WorkStack;
522 WorkStack.push_back(cast<Value>(GV.getInitializer()));
524 while (!WorkStack.empty()) {
525 const Value *V = WorkStack.pop_back_val();
526 if (!Visited.insert(V).second)
529 if (const User *U = dyn_cast<User>(V)) {
530 WorkStack.append(U->op_begin(), U->op_end());
533 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
534 VerifyConstantExprBitcastType(CE);
540 visitGlobalValue(GV);
543 void Verifier::visitAliaseeSubExpr(const GlobalAlias &GA, const Constant &C) {
544 SmallPtrSet<const GlobalAlias*, 4> Visited;
546 visitAliaseeSubExpr(Visited, GA, C);
549 void Verifier::visitAliaseeSubExpr(SmallPtrSetImpl<const GlobalAlias*> &Visited,
550 const GlobalAlias &GA, const Constant &C) {
551 if (const auto *GV = dyn_cast<GlobalValue>(&C)) {
552 Assert1(!GV->isDeclaration(), "Alias must point to a definition", &GA);
554 if (const auto *GA2 = dyn_cast<GlobalAlias>(GV)) {
555 Assert1(Visited.insert(GA2).second, "Aliases cannot form a cycle", &GA);
557 Assert1(!GA2->mayBeOverridden(), "Alias cannot point to a weak alias",
560 // Only continue verifying subexpressions of GlobalAliases.
561 // Do not recurse into global initializers.
566 if (const auto *CE = dyn_cast<ConstantExpr>(&C))
567 VerifyConstantExprBitcastType(CE);
569 for (const Use &U : C.operands()) {
571 if (const auto *GA2 = dyn_cast<GlobalAlias>(V))
572 visitAliaseeSubExpr(Visited, GA, *GA2->getAliasee());
573 else if (const auto *C2 = dyn_cast<Constant>(V))
574 visitAliaseeSubExpr(Visited, GA, *C2);
578 void Verifier::visitGlobalAlias(const GlobalAlias &GA) {
579 Assert1(!GA.getName().empty(),
580 "Alias name cannot be empty!", &GA);
581 Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()),
582 "Alias should have private, internal, linkonce, weak, linkonce_odr, "
583 "weak_odr, or external linkage!",
585 const Constant *Aliasee = GA.getAliasee();
586 Assert1(Aliasee, "Aliasee cannot be NULL!", &GA);
587 Assert1(GA.getType() == Aliasee->getType(),
588 "Alias and aliasee types should match!", &GA);
590 Assert1(isa<GlobalValue>(Aliasee) || isa<ConstantExpr>(Aliasee),
591 "Aliasee should be either GlobalValue or ConstantExpr", &GA);
593 visitAliaseeSubExpr(GA, *Aliasee);
595 visitGlobalValue(GA);
598 void Verifier::visitNamedMDNode(const NamedMDNode &NMD) {
599 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
600 MDNode *MD = NMD.getOperand(i);
608 void Verifier::visitMDNode(const MDNode &MD) {
609 // Only visit each node once. Metadata can be mutually recursive, so this
610 // avoids infinite recursion here, as well as being an optimization.
611 if (!MDNodes.insert(&MD).second)
614 switch (MD.getMetadataID()) {
616 llvm_unreachable("Invalid MDNode subclass");
617 case Metadata::MDTupleKind:
619 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
620 case Metadata::CLASS##Kind: \
621 visit##CLASS(cast<CLASS>(MD)); \
623 #include "llvm/IR/Metadata.def"
626 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
627 Metadata *Op = MD.getOperand(i);
630 Assert2(!isa<LocalAsMetadata>(Op), "Invalid operand for global metadata!",
632 if (auto *N = dyn_cast<MDNode>(Op)) {
636 if (auto *V = dyn_cast<ValueAsMetadata>(Op)) {
637 visitValueAsMetadata(*V, nullptr);
642 // Check these last, so we diagnose problems in operands first.
643 Assert1(!MD.isTemporary(), "Expected no forward declarations!", &MD);
644 Assert1(MD.isResolved(), "All nodes should be resolved!", &MD);
647 void Verifier::visitValueAsMetadata(const ValueAsMetadata &MD, Function *F) {
648 Assert1(MD.getValue(), "Expected valid value", &MD);
649 Assert2(!MD.getValue()->getType()->isMetadataTy(),
650 "Unexpected metadata round-trip through values", &MD, MD.getValue());
652 auto *L = dyn_cast<LocalAsMetadata>(&MD);
656 Assert1(F, "function-local metadata used outside a function", L);
658 // If this was an instruction, bb, or argument, verify that it is in the
659 // function that we expect.
660 Function *ActualF = nullptr;
661 if (Instruction *I = dyn_cast<Instruction>(L->getValue())) {
662 Assert2(I->getParent(), "function-local metadata not in basic block", L, I);
663 ActualF = I->getParent()->getParent();
664 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(L->getValue()))
665 ActualF = BB->getParent();
666 else if (Argument *A = dyn_cast<Argument>(L->getValue()))
667 ActualF = A->getParent();
668 assert(ActualF && "Unimplemented function local metadata case!");
670 Assert1(ActualF == F, "function-local metadata used in wrong function", L);
673 void Verifier::visitMetadataAsValue(const MetadataAsValue &MDV, Function *F) {
674 Metadata *MD = MDV.getMetadata();
675 if (auto *N = dyn_cast<MDNode>(MD)) {
680 // Only visit each node once. Metadata can be mutually recursive, so this
681 // avoids infinite recursion here, as well as being an optimization.
682 if (!MDNodes.insert(MD).second)
685 if (auto *V = dyn_cast<ValueAsMetadata>(MD))
686 visitValueAsMetadata(*V, F);
689 void Verifier::visitMDLocation(const MDLocation &N) {
690 Assert1(N.getScope(), "location requires a valid scope", &N);
691 if (auto *IA = N.getInlinedAt())
692 Assert2(isa<MDLocation>(IA), "inlined-at should be a location", &N, IA);
695 void Verifier::visitGenericDebugNode(const GenericDebugNode &N) {
696 Assert1(N.getTag(), "invalid tag", &N);
699 void Verifier::visitMDSubrange(const MDSubrange &N) {
700 Assert1(N.getTag() == dwarf::DW_TAG_subrange_type, "invalid tag", &N);
703 void Verifier::visitMDEnumerator(const MDEnumerator &N) {
704 Assert1(N.getTag() == dwarf::DW_TAG_enumerator, "invalid tag", &N);
707 void Verifier::visitMDBasicType(const MDBasicType &N) {
708 Assert1(N.getTag() == dwarf::DW_TAG_base_type ||
709 N.getTag() == dwarf::DW_TAG_unspecified_type,
713 void Verifier::visitMDDerivedType(const MDDerivedType &N) {
714 Assert1(N.getTag() == dwarf::DW_TAG_typedef ||
715 N.getTag() == dwarf::DW_TAG_pointer_type ||
716 N.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
717 N.getTag() == dwarf::DW_TAG_reference_type ||
718 N.getTag() == dwarf::DW_TAG_rvalue_reference_type ||
719 N.getTag() == dwarf::DW_TAG_const_type ||
720 N.getTag() == dwarf::DW_TAG_volatile_type ||
721 N.getTag() == dwarf::DW_TAG_restrict_type ||
722 N.getTag() == dwarf::DW_TAG_member ||
723 N.getTag() == dwarf::DW_TAG_inheritance ||
724 N.getTag() == dwarf::DW_TAG_friend,
728 void Verifier::visitMDCompositeType(const MDCompositeType &N) {
729 Assert1(N.getTag() == dwarf::DW_TAG_array_type ||
730 N.getTag() == dwarf::DW_TAG_structure_type ||
731 N.getTag() == dwarf::DW_TAG_union_type ||
732 N.getTag() == dwarf::DW_TAG_enumeration_type ||
733 N.getTag() == dwarf::DW_TAG_subroutine_type ||
734 N.getTag() == dwarf::DW_TAG_class_type,
738 void Verifier::visitMDSubroutineType(const MDSubroutineType &N) {
739 Assert1(N.getTag() == dwarf::DW_TAG_subroutine_type, "invalid tag", &N);
742 void Verifier::visitMDFile(const MDFile &N) {
743 Assert1(N.getTag() == dwarf::DW_TAG_file_type, "invalid tag", &N);
746 void Verifier::visitMDCompileUnit(const MDCompileUnit &N) {
747 Assert1(N.getTag() == dwarf::DW_TAG_compile_unit, "invalid tag", &N);
750 void Verifier::visitMDSubprogram(const MDSubprogram &N) {
751 Assert1(N.getTag() == dwarf::DW_TAG_subprogram, "invalid tag", &N);
754 void Verifier::visitMDLexicalBlock(const MDLexicalBlock &N) {
755 Assert1(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
758 void Verifier::visitMDLexicalBlockFile(const MDLexicalBlockFile &N) {
759 Assert1(N.getTag() == dwarf::DW_TAG_lexical_block, "invalid tag", &N);
762 void Verifier::visitMDNamespace(const MDNamespace &N) {
763 Assert1(N.getTag() == dwarf::DW_TAG_namespace, "invalid tag", &N);
766 void Verifier::visitMDTemplateTypeParameter(const MDTemplateTypeParameter &N) {
767 Assert1(N.getTag() == dwarf::DW_TAG_template_type_parameter, "invalid tag",
771 void Verifier::visitMDTemplateValueParameter(
772 const MDTemplateValueParameter &N) {
773 Assert1(N.getTag() == dwarf::DW_TAG_template_value_parameter ||
774 N.getTag() == dwarf::DW_TAG_GNU_template_template_param ||
775 N.getTag() == dwarf::DW_TAG_GNU_template_parameter_pack,
779 void Verifier::visitMDGlobalVariable(const MDGlobalVariable &N) {
780 Assert1(N.getTag() == dwarf::DW_TAG_variable, "invalid tag", &N);
783 void Verifier::visitMDLocalVariable(const MDLocalVariable &N) {
784 Assert1(N.getTag() == dwarf::DW_TAG_auto_variable ||
785 N.getTag() == dwarf::DW_TAG_arg_variable,
789 void Verifier::visitMDExpression(const MDExpression &N) {
790 Assert1(N.getTag() == dwarf::DW_TAG_expression, "invalid tag", &N);
791 Assert1(N.isValid(), "invalid expression", &N);
794 void Verifier::visitMDObjCProperty(const MDObjCProperty &N) {
795 Assert1(N.getTag() == dwarf::DW_TAG_APPLE_property, "invalid tag", &N);
798 void Verifier::visitMDImportedEntity(const MDImportedEntity &N) {
799 Assert1(N.getTag() == dwarf::DW_TAG_imported_module ||
800 N.getTag() == dwarf::DW_TAG_imported_declaration,
804 void Verifier::visitComdat(const Comdat &C) {
805 // The Module is invalid if the GlobalValue has private linkage. Entities
806 // with private linkage don't have entries in the symbol table.
807 if (const GlobalValue *GV = M->getNamedValue(C.getName()))
808 Assert1(!GV->hasPrivateLinkage(), "comdat global value has private linkage",
812 void Verifier::visitModuleIdents(const Module &M) {
813 const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
817 // llvm.ident takes a list of metadata entry. Each entry has only one string.
818 // Scan each llvm.ident entry and make sure that this requirement is met.
819 for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
820 const MDNode *N = Idents->getOperand(i);
821 Assert1(N->getNumOperands() == 1,
822 "incorrect number of operands in llvm.ident metadata", N);
823 Assert1(dyn_cast_or_null<MDString>(N->getOperand(0)),
824 ("invalid value for llvm.ident metadata entry operand"
825 "(the operand should be a string)"),
830 void Verifier::visitModuleFlags(const Module &M) {
831 const NamedMDNode *Flags = M.getModuleFlagsMetadata();
834 // Scan each flag, and track the flags and requirements.
835 DenseMap<const MDString*, const MDNode*> SeenIDs;
836 SmallVector<const MDNode*, 16> Requirements;
837 for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
838 visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
841 // Validate that the requirements in the module are valid.
842 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
843 const MDNode *Requirement = Requirements[I];
844 const MDString *Flag = cast<MDString>(Requirement->getOperand(0));
845 const Metadata *ReqValue = Requirement->getOperand(1);
847 const MDNode *Op = SeenIDs.lookup(Flag);
849 CheckFailed("invalid requirement on flag, flag is not present in module",
854 if (Op->getOperand(2) != ReqValue) {
855 CheckFailed(("invalid requirement on flag, "
856 "flag does not have the required value"),
864 Verifier::visitModuleFlag(const MDNode *Op,
865 DenseMap<const MDString *, const MDNode *> &SeenIDs,
866 SmallVectorImpl<const MDNode *> &Requirements) {
867 // Each module flag should have three arguments, the merge behavior (a
868 // constant int), the flag ID (an MDString), and the value.
869 Assert1(Op->getNumOperands() == 3,
870 "incorrect number of operands in module flag", Op);
871 Module::ModFlagBehavior MFB;
872 if (!Module::isValidModFlagBehavior(Op->getOperand(0), MFB)) {
874 mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0)),
875 "invalid behavior operand in module flag (expected constant integer)",
878 "invalid behavior operand in module flag (unexpected constant)",
881 MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
883 "invalid ID operand in module flag (expected metadata string)",
886 // Sanity check the values for behaviors with additional requirements.
889 case Module::Warning:
890 case Module::Override:
891 // These behavior types accept any value.
894 case Module::Require: {
895 // The value should itself be an MDNode with two operands, a flag ID (an
896 // MDString), and a value.
897 MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
898 Assert1(Value && Value->getNumOperands() == 2,
899 "invalid value for 'require' module flag (expected metadata pair)",
901 Assert1(isa<MDString>(Value->getOperand(0)),
902 ("invalid value for 'require' module flag "
903 "(first value operand should be a string)"),
904 Value->getOperand(0));
906 // Append it to the list of requirements, to check once all module flags are
908 Requirements.push_back(Value);
913 case Module::AppendUnique: {
914 // These behavior types require the operand be an MDNode.
915 Assert1(isa<MDNode>(Op->getOperand(2)),
916 "invalid value for 'append'-type module flag "
917 "(expected a metadata node)", Op->getOperand(2));
922 // Unless this is a "requires" flag, check the ID is unique.
923 if (MFB != Module::Require) {
924 bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
926 "module flag identifiers must be unique (or of 'require' type)",
931 void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
932 bool isFunction, const Value *V) {
934 for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
935 if (Attrs.getSlotIndex(I) == Idx) {
940 assert(Slot != ~0U && "Attribute set inconsistency!");
942 for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
944 if (I->isStringAttribute())
947 if (I->getKindAsEnum() == Attribute::NoReturn ||
948 I->getKindAsEnum() == Attribute::NoUnwind ||
949 I->getKindAsEnum() == Attribute::NoInline ||
950 I->getKindAsEnum() == Attribute::AlwaysInline ||
951 I->getKindAsEnum() == Attribute::OptimizeForSize ||
952 I->getKindAsEnum() == Attribute::StackProtect ||
953 I->getKindAsEnum() == Attribute::StackProtectReq ||
954 I->getKindAsEnum() == Attribute::StackProtectStrong ||
955 I->getKindAsEnum() == Attribute::NoRedZone ||
956 I->getKindAsEnum() == Attribute::NoImplicitFloat ||
957 I->getKindAsEnum() == Attribute::Naked ||
958 I->getKindAsEnum() == Attribute::InlineHint ||
959 I->getKindAsEnum() == Attribute::StackAlignment ||
960 I->getKindAsEnum() == Attribute::UWTable ||
961 I->getKindAsEnum() == Attribute::NonLazyBind ||
962 I->getKindAsEnum() == Attribute::ReturnsTwice ||
963 I->getKindAsEnum() == Attribute::SanitizeAddress ||
964 I->getKindAsEnum() == Attribute::SanitizeThread ||
965 I->getKindAsEnum() == Attribute::SanitizeMemory ||
966 I->getKindAsEnum() == Attribute::MinSize ||
967 I->getKindAsEnum() == Attribute::NoDuplicate ||
968 I->getKindAsEnum() == Attribute::Builtin ||
969 I->getKindAsEnum() == Attribute::NoBuiltin ||
970 I->getKindAsEnum() == Attribute::Cold ||
971 I->getKindAsEnum() == Attribute::OptimizeNone ||
972 I->getKindAsEnum() == Attribute::JumpTable) {
974 CheckFailed("Attribute '" + I->getAsString() +
975 "' only applies to functions!", V);
978 } else if (I->getKindAsEnum() == Attribute::ReadOnly ||
979 I->getKindAsEnum() == Attribute::ReadNone) {
981 CheckFailed("Attribute '" + I->getAsString() +
982 "' does not apply to function returns");
985 } else if (isFunction) {
986 CheckFailed("Attribute '" + I->getAsString() +
987 "' does not apply to functions!", V);
993 // VerifyParameterAttrs - Check the given attributes for an argument or return
994 // value of the specified type. The value V is printed in error messages.
995 void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
996 bool isReturnValue, const Value *V) {
997 if (!Attrs.hasAttributes(Idx))
1000 VerifyAttributeTypes(Attrs, Idx, false, V);
1003 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1004 !Attrs.hasAttribute(Idx, Attribute::Nest) &&
1005 !Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1006 !Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
1007 !Attrs.hasAttribute(Idx, Attribute::Returned) &&
1008 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1009 "Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
1010 "'returned' do not apply to return values!", V);
1012 // Check for mutually incompatible attributes. Only inreg is compatible with
1014 unsigned AttrCount = 0;
1015 AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
1016 AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
1017 AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
1018 Attrs.hasAttribute(Idx, Attribute::InReg);
1019 AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
1020 Assert1(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
1021 "and 'sret' are incompatible!", V);
1023 Assert1(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
1024 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
1025 "'inalloca and readonly' are incompatible!", V);
1027 Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
1028 Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
1029 "'sret and returned' are incompatible!", V);
1031 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
1032 Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
1033 "'zeroext and signext' are incompatible!", V);
1035 Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
1036 Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
1037 "'readnone and readonly' are incompatible!", V);
1039 Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
1040 Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
1041 "'noinline and alwaysinline' are incompatible!", V);
1043 Assert1(!AttrBuilder(Attrs, Idx).
1044 hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
1045 "Wrong types for attribute: " +
1046 AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
1048 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1049 if (!PTy->getElementType()->isSized()) {
1050 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
1051 !Attrs.hasAttribute(Idx, Attribute::InAlloca),
1052 "Attributes 'byval' and 'inalloca' do not support unsized types!",
1056 Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
1057 "Attribute 'byval' only applies to parameters with pointer type!",
1062 // VerifyFunctionAttrs - Check parameter attributes against a function type.
1063 // The value V is printed in error messages.
1064 void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
1066 if (Attrs.isEmpty())
1069 bool SawNest = false;
1070 bool SawReturned = false;
1071 bool SawSRet = false;
1073 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1074 unsigned Idx = Attrs.getSlotIndex(i);
1078 Ty = FT->getReturnType();
1079 else if (Idx-1 < FT->getNumParams())
1080 Ty = FT->getParamType(Idx-1);
1082 break; // VarArgs attributes, verified elsewhere.
1084 VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
1089 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1090 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
1094 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1095 Assert1(!SawReturned, "More than one parameter has attribute returned!",
1097 Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
1098 "argument and return types for 'returned' attribute", V);
1102 if (Attrs.hasAttribute(Idx, Attribute::StructRet)) {
1103 Assert1(!SawSRet, "Cannot have multiple 'sret' parameters!", V);
1104 Assert1(Idx == 1 || Idx == 2,
1105 "Attribute 'sret' is not on first or second parameter!", V);
1109 if (Attrs.hasAttribute(Idx, Attribute::InAlloca)) {
1110 Assert1(Idx == FT->getNumParams(),
1111 "inalloca isn't on the last parameter!", V);
1115 if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
1118 VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
1120 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
1121 Attribute::ReadNone) &&
1122 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1123 Attribute::ReadOnly)),
1124 "Attributes 'readnone and readonly' are incompatible!", V);
1126 Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
1127 Attribute::NoInline) &&
1128 Attrs.hasAttribute(AttributeSet::FunctionIndex,
1129 Attribute::AlwaysInline)),
1130 "Attributes 'noinline and alwaysinline' are incompatible!", V);
1132 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1133 Attribute::OptimizeNone)) {
1134 Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex,
1135 Attribute::NoInline),
1136 "Attribute 'optnone' requires 'noinline'!", V);
1138 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1139 Attribute::OptimizeForSize),
1140 "Attributes 'optsize and optnone' are incompatible!", V);
1142 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1143 Attribute::MinSize),
1144 "Attributes 'minsize and optnone' are incompatible!", V);
1147 if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
1148 Attribute::JumpTable)) {
1149 const GlobalValue *GV = cast<GlobalValue>(V);
1150 Assert1(GV->hasUnnamedAddr(),
1151 "Attribute 'jumptable' requires 'unnamed_addr'", V);
1156 void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
1157 if (CE->getOpcode() != Instruction::BitCast)
1160 Assert1(CastInst::castIsValid(Instruction::BitCast, CE->getOperand(0),
1162 "Invalid bitcast", CE);
1165 bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
1166 if (Attrs.getNumSlots() == 0)
1169 unsigned LastSlot = Attrs.getNumSlots() - 1;
1170 unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
1171 if (LastIndex <= Params
1172 || (LastIndex == AttributeSet::FunctionIndex
1173 && (LastSlot == 0 || Attrs.getSlotIndex(LastSlot - 1) <= Params)))
1179 /// \brief Verify that statepoint intrinsic is well formed.
1180 void Verifier::VerifyStatepoint(ImmutableCallSite CS) {
1181 assert(CS.getCalledFunction() &&
1182 CS.getCalledFunction()->getIntrinsicID() ==
1183 Intrinsic::experimental_gc_statepoint);
1185 const Instruction &CI = *CS.getInstruction();
1187 Assert1(!CS.doesNotAccessMemory() &&
1188 !CS.onlyReadsMemory(),
1189 "gc.statepoint must read and write memory to preserve "
1190 "reordering restrictions required by safepoint semantics", &CI);
1192 const Value *Target = CS.getArgument(0);
1193 const PointerType *PT = dyn_cast<PointerType>(Target->getType());
1194 Assert2(PT && PT->getElementType()->isFunctionTy(),
1195 "gc.statepoint callee must be of function pointer type",
1197 FunctionType *TargetFuncType = cast<FunctionType>(PT->getElementType());
1199 const Value *NumCallArgsV = CS.getArgument(1);
1200 Assert1(isa<ConstantInt>(NumCallArgsV),
1201 "gc.statepoint number of arguments to underlying call "
1202 "must be constant integer", &CI);
1203 const int NumCallArgs = cast<ConstantInt>(NumCallArgsV)->getZExtValue();
1204 Assert1(NumCallArgs >= 0,
1205 "gc.statepoint number of arguments to underlying call "
1206 "must be positive", &CI);
1207 const int NumParams = (int)TargetFuncType->getNumParams();
1208 if (TargetFuncType->isVarArg()) {
1209 Assert1(NumCallArgs >= NumParams,
1210 "gc.statepoint mismatch in number of vararg call args", &CI);
1212 // TODO: Remove this limitation
1213 Assert1(TargetFuncType->getReturnType()->isVoidTy(),
1214 "gc.statepoint doesn't support wrapping non-void "
1215 "vararg functions yet", &CI);
1217 Assert1(NumCallArgs == NumParams,
1218 "gc.statepoint mismatch in number of call args", &CI);
1220 const Value *Unused = CS.getArgument(2);
1221 Assert1(isa<ConstantInt>(Unused) &&
1222 cast<ConstantInt>(Unused)->isNullValue(),
1223 "gc.statepoint parameter #3 must be zero", &CI);
1225 // Verify that the types of the call parameter arguments match
1226 // the type of the wrapped callee.
1227 for (int i = 0; i < NumParams; i++) {
1228 Type *ParamType = TargetFuncType->getParamType(i);
1229 Type *ArgType = CS.getArgument(3+i)->getType();
1230 Assert1(ArgType == ParamType,
1231 "gc.statepoint call argument does not match wrapped "
1232 "function type", &CI);
1234 const int EndCallArgsInx = 2+NumCallArgs;
1235 const Value *NumDeoptArgsV = CS.getArgument(EndCallArgsInx+1);
1236 Assert1(isa<ConstantInt>(NumDeoptArgsV),
1237 "gc.statepoint number of deoptimization arguments "
1238 "must be constant integer", &CI);
1239 const int NumDeoptArgs = cast<ConstantInt>(NumDeoptArgsV)->getZExtValue();
1240 Assert1(NumDeoptArgs >= 0,
1241 "gc.statepoint number of deoptimization arguments "
1242 "must be positive", &CI);
1244 Assert1(4 + NumCallArgs + NumDeoptArgs <= (int)CS.arg_size(),
1245 "gc.statepoint too few arguments according to length fields", &CI);
1247 // Check that the only uses of this gc.statepoint are gc.result or
1248 // gc.relocate calls which are tied to this statepoint and thus part
1249 // of the same statepoint sequence
1250 for (const User *U : CI.users()) {
1251 const CallInst *Call = dyn_cast<const CallInst>(U);
1252 Assert2(Call, "illegal use of statepoint token", &CI, U);
1253 if (!Call) continue;
1254 Assert2(isGCRelocate(Call) || isGCResult(Call),
1255 "gc.result or gc.relocate are the only value uses"
1256 "of a gc.statepoint", &CI, U);
1257 if (isGCResult(Call)) {
1258 Assert2(Call->getArgOperand(0) == &CI,
1259 "gc.result connected to wrong gc.statepoint",
1261 } else if (isGCRelocate(Call)) {
1262 Assert2(Call->getArgOperand(0) == &CI,
1263 "gc.relocate connected to wrong gc.statepoint",
1268 // Note: It is legal for a single derived pointer to be listed multiple
1269 // times. It's non-optimal, but it is legal. It can also happen after
1270 // insertion if we strip a bitcast away.
1271 // Note: It is really tempting to check that each base is relocated and
1272 // that a derived pointer is never reused as a base pointer. This turns
1273 // out to be problematic since optimizations run after safepoint insertion
1274 // can recognize equality properties that the insertion logic doesn't know
1275 // about. See example statepoint.ll in the verifier subdirectory
1278 void Verifier::verifyFrameRecoverIndices() {
1279 llvm::errs() << "verifyFrameRecoverIndices\n";
1280 for (auto &Counts : FrameEscapeInfo) {
1281 Function *F = Counts.first;
1282 unsigned EscapedObjectCount = Counts.second.first;
1283 unsigned MaxRecoveredIndex = Counts.second.second;
1284 Assert1(MaxRecoveredIndex <= EscapedObjectCount,
1285 "all indices passed to llvm.framerecover must be less than the "
1286 "number of arguments passed ot llvm.frameescape in the parent "
1292 // visitFunction - Verify that a function is ok.
1294 void Verifier::visitFunction(const Function &F) {
1295 // Check function arguments.
1296 FunctionType *FT = F.getFunctionType();
1297 unsigned NumArgs = F.arg_size();
1299 Assert1(Context == &F.getContext(),
1300 "Function context does not match Module context!", &F);
1302 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
1303 Assert2(FT->getNumParams() == NumArgs,
1304 "# formal arguments must match # of arguments for function type!",
1306 Assert1(F.getReturnType()->isFirstClassType() ||
1307 F.getReturnType()->isVoidTy() ||
1308 F.getReturnType()->isStructTy(),
1309 "Functions cannot return aggregate values!", &F);
1311 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
1312 "Invalid struct return type!", &F);
1314 AttributeSet Attrs = F.getAttributes();
1316 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
1317 "Attribute after last parameter!", &F);
1319 // Check function attributes.
1320 VerifyFunctionAttrs(FT, Attrs, &F);
1322 // On function declarations/definitions, we do not support the builtin
1323 // attribute. We do not check this in VerifyFunctionAttrs since that is
1324 // checking for Attributes that can/can not ever be on functions.
1325 Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
1326 Attribute::Builtin),
1327 "Attribute 'builtin' can only be applied to a callsite.", &F);
1329 // Check that this function meets the restrictions on this calling convention.
1330 // Sometimes varargs is used for perfectly forwarding thunks, so some of these
1331 // restrictions can be lifted.
1332 switch (F.getCallingConv()) {
1334 case CallingConv::C:
1336 case CallingConv::Fast:
1337 case CallingConv::Cold:
1338 case CallingConv::Intel_OCL_BI:
1339 case CallingConv::PTX_Kernel:
1340 case CallingConv::PTX_Device:
1341 Assert1(!F.isVarArg(), "Calling convention does not support varargs or "
1342 "perfect forwarding!", &F);
1346 bool isLLVMdotName = F.getName().size() >= 5 &&
1347 F.getName().substr(0, 5) == "llvm.";
1349 // Check that the argument values match the function type for this function...
1351 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
1353 Assert2(I->getType() == FT->getParamType(i),
1354 "Argument value does not match function argument type!",
1355 I, FT->getParamType(i));
1356 Assert1(I->getType()->isFirstClassType(),
1357 "Function arguments must have first-class types!", I);
1359 Assert2(!I->getType()->isMetadataTy(),
1360 "Function takes metadata but isn't an intrinsic", I, &F);
1363 if (F.isMaterializable()) {
1364 // Function has a body somewhere we can't see.
1365 } else if (F.isDeclaration()) {
1366 Assert1(F.hasExternalLinkage() || F.hasExternalWeakLinkage(),
1367 "invalid linkage type for function declaration", &F);
1369 // Verify that this function (which has a body) is not named "llvm.*". It
1370 // is not legal to define intrinsics.
1371 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
1373 // Check the entry node
1374 const BasicBlock *Entry = &F.getEntryBlock();
1375 Assert1(pred_empty(Entry),
1376 "Entry block to function must not have predecessors!", Entry);
1378 // The address of the entry block cannot be taken, unless it is dead.
1379 if (Entry->hasAddressTaken()) {
1380 Assert1(!BlockAddress::lookup(Entry)->isConstantUsed(),
1381 "blockaddress may not be used with the entry block!", Entry);
1385 // If this function is actually an intrinsic, verify that it is only used in
1386 // direct call/invokes, never having its "address taken".
1387 if (F.getIntrinsicID()) {
1389 if (F.hasAddressTaken(&U))
1390 Assert1(0, "Invalid user of intrinsic instruction!", U);
1393 Assert1(!F.hasDLLImportStorageClass() ||
1394 (F.isDeclaration() && F.hasExternalLinkage()) ||
1395 F.hasAvailableExternallyLinkage(),
1396 "Function is marked as dllimport, but not external.", &F);
1399 // verifyBasicBlock - Verify that a basic block is well formed...
1401 void Verifier::visitBasicBlock(BasicBlock &BB) {
1402 InstsInThisBlock.clear();
1404 // Ensure that basic blocks have terminators!
1405 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
1407 // Check constraints that this basic block imposes on all of the PHI nodes in
1409 if (isa<PHINode>(BB.front())) {
1410 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
1411 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
1412 std::sort(Preds.begin(), Preds.end());
1414 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
1415 // Ensure that PHI nodes have at least one entry!
1416 Assert1(PN->getNumIncomingValues() != 0,
1417 "PHI nodes must have at least one entry. If the block is dead, "
1418 "the PHI should be removed!", PN);
1419 Assert1(PN->getNumIncomingValues() == Preds.size(),
1420 "PHINode should have one entry for each predecessor of its "
1421 "parent basic block!", PN);
1423 // Get and sort all incoming values in the PHI node...
1425 Values.reserve(PN->getNumIncomingValues());
1426 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1427 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
1428 PN->getIncomingValue(i)));
1429 std::sort(Values.begin(), Values.end());
1431 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
1432 // Check to make sure that if there is more than one entry for a
1433 // particular basic block in this PHI node, that the incoming values are
1436 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
1437 Values[i].second == Values[i-1].second,
1438 "PHI node has multiple entries for the same basic block with "
1439 "different incoming values!", PN, Values[i].first,
1440 Values[i].second, Values[i-1].second);
1442 // Check to make sure that the predecessors and PHI node entries are
1444 Assert3(Values[i].first == Preds[i],
1445 "PHI node entries do not match predecessors!", PN,
1446 Values[i].first, Preds[i]);
1451 // Check that all instructions have their parent pointers set up correctly.
1454 Assert(I.getParent() == &BB, "Instruction has bogus parent pointer!");
1458 void Verifier::visitTerminatorInst(TerminatorInst &I) {
1459 // Ensure that terminators only exist at the end of the basic block.
1460 Assert1(&I == I.getParent()->getTerminator(),
1461 "Terminator found in the middle of a basic block!", I.getParent());
1462 visitInstruction(I);
1465 void Verifier::visitBranchInst(BranchInst &BI) {
1466 if (BI.isConditional()) {
1467 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
1468 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
1470 visitTerminatorInst(BI);
1473 void Verifier::visitReturnInst(ReturnInst &RI) {
1474 Function *F = RI.getParent()->getParent();
1475 unsigned N = RI.getNumOperands();
1476 if (F->getReturnType()->isVoidTy())
1478 "Found return instr that returns non-void in Function of void "
1479 "return type!", &RI, F->getReturnType());
1481 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
1482 "Function return type does not match operand "
1483 "type of return inst!", &RI, F->getReturnType());
1485 // Check to make sure that the return value has necessary properties for
1487 visitTerminatorInst(RI);
1490 void Verifier::visitSwitchInst(SwitchInst &SI) {
1491 // Check to make sure that all of the constants in the switch instruction
1492 // have the same type as the switched-on value.
1493 Type *SwitchTy = SI.getCondition()->getType();
1494 SmallPtrSet<ConstantInt*, 32> Constants;
1495 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
1496 Assert1(i.getCaseValue()->getType() == SwitchTy,
1497 "Switch constants must all be same type as switch value!", &SI);
1498 Assert2(Constants.insert(i.getCaseValue()).second,
1499 "Duplicate integer as switch case", &SI, i.getCaseValue());
1502 visitTerminatorInst(SI);
1505 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
1506 Assert1(BI.getAddress()->getType()->isPointerTy(),
1507 "Indirectbr operand must have pointer type!", &BI);
1508 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
1509 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
1510 "Indirectbr destinations must all have pointer type!", &BI);
1512 visitTerminatorInst(BI);
1515 void Verifier::visitSelectInst(SelectInst &SI) {
1516 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
1518 "Invalid operands for select instruction!", &SI);
1520 Assert1(SI.getTrueValue()->getType() == SI.getType(),
1521 "Select values must have same type as select instruction!", &SI);
1522 visitInstruction(SI);
1525 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
1526 /// a pass, if any exist, it's an error.
1528 void Verifier::visitUserOp1(Instruction &I) {
1529 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
1532 void Verifier::visitTruncInst(TruncInst &I) {
1533 // Get the source and destination types
1534 Type *SrcTy = I.getOperand(0)->getType();
1535 Type *DestTy = I.getType();
1537 // Get the size of the types in bits, we'll need this later
1538 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1539 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1541 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
1542 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
1543 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1544 "trunc source and destination must both be a vector or neither", &I);
1545 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
1547 visitInstruction(I);
1550 void Verifier::visitZExtInst(ZExtInst &I) {
1551 // Get the source and destination types
1552 Type *SrcTy = I.getOperand(0)->getType();
1553 Type *DestTy = I.getType();
1555 // Get the size of the types in bits, we'll need this later
1556 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
1557 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
1558 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1559 "zext source and destination must both be a vector or neither", &I);
1560 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1561 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1563 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
1565 visitInstruction(I);
1568 void Verifier::visitSExtInst(SExtInst &I) {
1569 // Get the source and destination types
1570 Type *SrcTy = I.getOperand(0)->getType();
1571 Type *DestTy = I.getType();
1573 // Get the size of the types in bits, we'll need this later
1574 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1575 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1577 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
1578 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
1579 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1580 "sext source and destination must both be a vector or neither", &I);
1581 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
1583 visitInstruction(I);
1586 void Verifier::visitFPTruncInst(FPTruncInst &I) {
1587 // Get the source and destination types
1588 Type *SrcTy = I.getOperand(0)->getType();
1589 Type *DestTy = I.getType();
1590 // Get the size of the types in bits, we'll need this later
1591 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1592 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1594 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
1595 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
1596 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1597 "fptrunc source and destination must both be a vector or neither",&I);
1598 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
1600 visitInstruction(I);
1603 void Verifier::visitFPExtInst(FPExtInst &I) {
1604 // Get the source and destination types
1605 Type *SrcTy = I.getOperand(0)->getType();
1606 Type *DestTy = I.getType();
1608 // Get the size of the types in bits, we'll need this later
1609 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
1610 unsigned DestBitSize = DestTy->getScalarSizeInBits();
1612 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
1613 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
1614 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1615 "fpext source and destination must both be a vector or neither", &I);
1616 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
1618 visitInstruction(I);
1621 void Verifier::visitUIToFPInst(UIToFPInst &I) {
1622 // Get the source and destination types
1623 Type *SrcTy = I.getOperand(0)->getType();
1624 Type *DestTy = I.getType();
1626 bool SrcVec = SrcTy->isVectorTy();
1627 bool DstVec = DestTy->isVectorTy();
1629 Assert1(SrcVec == DstVec,
1630 "UIToFP source and dest must both be vector or scalar", &I);
1631 Assert1(SrcTy->isIntOrIntVectorTy(),
1632 "UIToFP source must be integer or integer vector", &I);
1633 Assert1(DestTy->isFPOrFPVectorTy(),
1634 "UIToFP result must be FP or FP vector", &I);
1636 if (SrcVec && DstVec)
1637 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1638 cast<VectorType>(DestTy)->getNumElements(),
1639 "UIToFP source and dest vector length mismatch", &I);
1641 visitInstruction(I);
1644 void Verifier::visitSIToFPInst(SIToFPInst &I) {
1645 // Get the source and destination types
1646 Type *SrcTy = I.getOperand(0)->getType();
1647 Type *DestTy = I.getType();
1649 bool SrcVec = SrcTy->isVectorTy();
1650 bool DstVec = DestTy->isVectorTy();
1652 Assert1(SrcVec == DstVec,
1653 "SIToFP source and dest must both be vector or scalar", &I);
1654 Assert1(SrcTy->isIntOrIntVectorTy(),
1655 "SIToFP source must be integer or integer vector", &I);
1656 Assert1(DestTy->isFPOrFPVectorTy(),
1657 "SIToFP result must be FP or FP vector", &I);
1659 if (SrcVec && DstVec)
1660 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1661 cast<VectorType>(DestTy)->getNumElements(),
1662 "SIToFP source and dest vector length mismatch", &I);
1664 visitInstruction(I);
1667 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1668 // Get the source and destination types
1669 Type *SrcTy = I.getOperand(0)->getType();
1670 Type *DestTy = I.getType();
1672 bool SrcVec = SrcTy->isVectorTy();
1673 bool DstVec = DestTy->isVectorTy();
1675 Assert1(SrcVec == DstVec,
1676 "FPToUI source and dest must both be vector or scalar", &I);
1677 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1679 Assert1(DestTy->isIntOrIntVectorTy(),
1680 "FPToUI result must be integer or integer vector", &I);
1682 if (SrcVec && DstVec)
1683 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1684 cast<VectorType>(DestTy)->getNumElements(),
1685 "FPToUI source and dest vector length mismatch", &I);
1687 visitInstruction(I);
1690 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1691 // Get the source and destination types
1692 Type *SrcTy = I.getOperand(0)->getType();
1693 Type *DestTy = I.getType();
1695 bool SrcVec = SrcTy->isVectorTy();
1696 bool DstVec = DestTy->isVectorTy();
1698 Assert1(SrcVec == DstVec,
1699 "FPToSI source and dest must both be vector or scalar", &I);
1700 Assert1(SrcTy->isFPOrFPVectorTy(),
1701 "FPToSI source must be FP or FP vector", &I);
1702 Assert1(DestTy->isIntOrIntVectorTy(),
1703 "FPToSI result must be integer or integer vector", &I);
1705 if (SrcVec && DstVec)
1706 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1707 cast<VectorType>(DestTy)->getNumElements(),
1708 "FPToSI source and dest vector length mismatch", &I);
1710 visitInstruction(I);
1713 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1714 // Get the source and destination types
1715 Type *SrcTy = I.getOperand(0)->getType();
1716 Type *DestTy = I.getType();
1718 Assert1(SrcTy->getScalarType()->isPointerTy(),
1719 "PtrToInt source must be pointer", &I);
1720 Assert1(DestTy->getScalarType()->isIntegerTy(),
1721 "PtrToInt result must be integral", &I);
1722 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1723 "PtrToInt type mismatch", &I);
1725 if (SrcTy->isVectorTy()) {
1726 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1727 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1728 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1729 "PtrToInt Vector width mismatch", &I);
1732 visitInstruction(I);
1735 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1736 // Get the source and destination types
1737 Type *SrcTy = I.getOperand(0)->getType();
1738 Type *DestTy = I.getType();
1740 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1741 "IntToPtr source must be an integral", &I);
1742 Assert1(DestTy->getScalarType()->isPointerTy(),
1743 "IntToPtr result must be a pointer",&I);
1744 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1745 "IntToPtr type mismatch", &I);
1746 if (SrcTy->isVectorTy()) {
1747 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1748 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1749 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1750 "IntToPtr Vector width mismatch", &I);
1752 visitInstruction(I);
1755 void Verifier::visitBitCastInst(BitCastInst &I) {
1757 CastInst::castIsValid(Instruction::BitCast, I.getOperand(0), I.getType()),
1758 "Invalid bitcast", &I);
1759 visitInstruction(I);
1762 void Verifier::visitAddrSpaceCastInst(AddrSpaceCastInst &I) {
1763 Type *SrcTy = I.getOperand(0)->getType();
1764 Type *DestTy = I.getType();
1766 Assert1(SrcTy->isPtrOrPtrVectorTy(),
1767 "AddrSpaceCast source must be a pointer", &I);
1768 Assert1(DestTy->isPtrOrPtrVectorTy(),
1769 "AddrSpaceCast result must be a pointer", &I);
1770 Assert1(SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace(),
1771 "AddrSpaceCast must be between different address spaces", &I);
1772 if (SrcTy->isVectorTy())
1773 Assert1(SrcTy->getVectorNumElements() == DestTy->getVectorNumElements(),
1774 "AddrSpaceCast vector pointer number of elements mismatch", &I);
1775 visitInstruction(I);
1778 /// visitPHINode - Ensure that a PHI node is well formed.
1780 void Verifier::visitPHINode(PHINode &PN) {
1781 // Ensure that the PHI nodes are all grouped together at the top of the block.
1782 // This can be tested by checking whether the instruction before this is
1783 // either nonexistent (because this is begin()) or is a PHI node. If not,
1784 // then there is some other instruction before a PHI.
1785 Assert2(&PN == &PN.getParent()->front() ||
1786 isa<PHINode>(--BasicBlock::iterator(&PN)),
1787 "PHI nodes not grouped at top of basic block!",
1788 &PN, PN.getParent());
1790 // Check that all of the values of the PHI node have the same type as the
1791 // result, and that the incoming blocks are really basic blocks.
1792 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1793 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1794 "PHI node operands are not the same type as the result!", &PN);
1797 // All other PHI node constraints are checked in the visitBasicBlock method.
1799 visitInstruction(PN);
1802 void Verifier::VerifyCallSite(CallSite CS) {
1803 Instruction *I = CS.getInstruction();
1805 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1806 "Called function must be a pointer!", I);
1807 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1809 Assert1(FPTy->getElementType()->isFunctionTy(),
1810 "Called function is not pointer to function type!", I);
1811 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1813 // Verify that the correct number of arguments are being passed
1814 if (FTy->isVarArg())
1815 Assert1(CS.arg_size() >= FTy->getNumParams(),
1816 "Called function requires more parameters than were provided!",I);
1818 Assert1(CS.arg_size() == FTy->getNumParams(),
1819 "Incorrect number of arguments passed to called function!", I);
1821 // Verify that all arguments to the call match the function type.
1822 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1823 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1824 "Call parameter type does not match function signature!",
1825 CS.getArgument(i), FTy->getParamType(i), I);
1827 AttributeSet Attrs = CS.getAttributes();
1829 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1830 "Attribute after last parameter!", I);
1832 // Verify call attributes.
1833 VerifyFunctionAttrs(FTy, Attrs, I);
1835 // Conservatively check the inalloca argument.
1836 // We have a bug if we can find that there is an underlying alloca without
1838 if (CS.hasInAllocaArgument()) {
1839 Value *InAllocaArg = CS.getArgument(FTy->getNumParams() - 1);
1840 if (auto AI = dyn_cast<AllocaInst>(InAllocaArg->stripInBoundsOffsets()))
1841 Assert2(AI->isUsedWithInAlloca(),
1842 "inalloca argument for call has mismatched alloca", AI, I);
1845 if (FTy->isVarArg()) {
1846 // FIXME? is 'nest' even legal here?
1847 bool SawNest = false;
1848 bool SawReturned = false;
1850 for (unsigned Idx = 1; Idx < 1 + FTy->getNumParams(); ++Idx) {
1851 if (Attrs.hasAttribute(Idx, Attribute::Nest))
1853 if (Attrs.hasAttribute(Idx, Attribute::Returned))
1857 // Check attributes on the varargs part.
1858 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1859 Type *Ty = CS.getArgument(Idx-1)->getType();
1860 VerifyParameterAttrs(Attrs, Idx, Ty, false, I);
1862 if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
1863 Assert1(!SawNest, "More than one parameter has attribute nest!", I);
1867 if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
1868 Assert1(!SawReturned, "More than one parameter has attribute returned!",
1870 Assert1(Ty->canLosslesslyBitCastTo(FTy->getReturnType()),
1871 "Incompatible argument and return types for 'returned' "
1876 Assert1(!Attrs.hasAttribute(Idx, Attribute::StructRet),
1877 "Attribute 'sret' cannot be used for vararg call arguments!", I);
1879 if (Attrs.hasAttribute(Idx, Attribute::InAlloca))
1880 Assert1(Idx == CS.arg_size(), "inalloca isn't on the last argument!",
1885 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1886 if (CS.getCalledFunction() == nullptr ||
1887 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1888 for (FunctionType::param_iterator PI = FTy->param_begin(),
1889 PE = FTy->param_end(); PI != PE; ++PI)
1890 Assert1(!(*PI)->isMetadataTy(),
1891 "Function has metadata parameter but isn't an intrinsic", I);
1894 visitInstruction(*I);
1897 /// Two types are "congruent" if they are identical, or if they are both pointer
1898 /// types with different pointee types and the same address space.
1899 static bool isTypeCongruent(Type *L, Type *R) {
1902 PointerType *PL = dyn_cast<PointerType>(L);
1903 PointerType *PR = dyn_cast<PointerType>(R);
1906 return PL->getAddressSpace() == PR->getAddressSpace();
1909 static AttrBuilder getParameterABIAttributes(int I, AttributeSet Attrs) {
1910 static const Attribute::AttrKind ABIAttrs[] = {
1911 Attribute::StructRet, Attribute::ByVal, Attribute::InAlloca,
1912 Attribute::InReg, Attribute::Returned};
1914 for (auto AK : ABIAttrs) {
1915 if (Attrs.hasAttribute(I + 1, AK))
1916 Copy.addAttribute(AK);
1918 if (Attrs.hasAttribute(I + 1, Attribute::Alignment))
1919 Copy.addAlignmentAttr(Attrs.getParamAlignment(I + 1));
1923 void Verifier::verifyMustTailCall(CallInst &CI) {
1924 Assert1(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);
1926 // - The caller and callee prototypes must match. Pointer types of
1927 // parameters or return types may differ in pointee type, but not
1929 Function *F = CI.getParent()->getParent();
1930 auto GetFnTy = [](Value *V) {
1931 return cast<FunctionType>(
1932 cast<PointerType>(V->getType())->getElementType());
1934 FunctionType *CallerTy = GetFnTy(F);
1935 FunctionType *CalleeTy = GetFnTy(CI.getCalledValue());
1936 Assert1(CallerTy->getNumParams() == CalleeTy->getNumParams(),
1937 "cannot guarantee tail call due to mismatched parameter counts", &CI);
1938 Assert1(CallerTy->isVarArg() == CalleeTy->isVarArg(),
1939 "cannot guarantee tail call due to mismatched varargs", &CI);
1940 Assert1(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
1941 "cannot guarantee tail call due to mismatched return types", &CI);
1942 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
1944 isTypeCongruent(CallerTy->getParamType(I), CalleeTy->getParamType(I)),
1945 "cannot guarantee tail call due to mismatched parameter types", &CI);
1948 // - The calling conventions of the caller and callee must match.
1949 Assert1(F->getCallingConv() == CI.getCallingConv(),
1950 "cannot guarantee tail call due to mismatched calling conv", &CI);
1952 // - All ABI-impacting function attributes, such as sret, byval, inreg,
1953 // returned, and inalloca, must match.
1954 AttributeSet CallerAttrs = F->getAttributes();
1955 AttributeSet CalleeAttrs = CI.getAttributes();
1956 for (int I = 0, E = CallerTy->getNumParams(); I != E; ++I) {
1957 AttrBuilder CallerABIAttrs = getParameterABIAttributes(I, CallerAttrs);
1958 AttrBuilder CalleeABIAttrs = getParameterABIAttributes(I, CalleeAttrs);
1959 Assert2(CallerABIAttrs == CalleeABIAttrs,
1960 "cannot guarantee tail call due to mismatched ABI impacting "
1961 "function attributes", &CI, CI.getOperand(I));
1964 // - The call must immediately precede a :ref:`ret <i_ret>` instruction,
1965 // or a pointer bitcast followed by a ret instruction.
1966 // - The ret instruction must return the (possibly bitcasted) value
1967 // produced by the call or void.
1968 Value *RetVal = &CI;
1969 Instruction *Next = CI.getNextNode();
1971 // Handle the optional bitcast.
1972 if (BitCastInst *BI = dyn_cast_or_null<BitCastInst>(Next)) {
1973 Assert1(BI->getOperand(0) == RetVal,
1974 "bitcast following musttail call must use the call", BI);
1976 Next = BI->getNextNode();
1979 // Check the return.
1980 ReturnInst *Ret = dyn_cast_or_null<ReturnInst>(Next);
1981 Assert1(Ret, "musttail call must be precede a ret with an optional bitcast",
1983 Assert1(!Ret->getReturnValue() || Ret->getReturnValue() == RetVal,
1984 "musttail call result must be returned", Ret);
1987 void Verifier::visitCallInst(CallInst &CI) {
1988 VerifyCallSite(&CI);
1990 if (CI.isMustTailCall())
1991 verifyMustTailCall(CI);
1993 if (Function *F = CI.getCalledFunction())
1994 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1995 visitIntrinsicFunctionCall(ID, CI);
1998 void Verifier::visitInvokeInst(InvokeInst &II) {
1999 VerifyCallSite(&II);
2001 // Verify that there is a landingpad instruction as the first non-PHI
2002 // instruction of the 'unwind' destination.
2003 Assert1(II.getUnwindDest()->isLandingPad(),
2004 "The unwind destination does not have a landingpad instruction!",&II);
2006 if (Function *F = II.getCalledFunction())
2007 // TODO: Ideally we should use visitIntrinsicFunction here. But it uses
2008 // CallInst as an input parameter. It not woth updating this whole
2009 // function only to support statepoint verification.
2010 if (F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint)
2011 VerifyStatepoint(ImmutableCallSite(&II));
2013 visitTerminatorInst(II);
2016 /// visitBinaryOperator - Check that both arguments to the binary operator are
2017 /// of the same type!
2019 void Verifier::visitBinaryOperator(BinaryOperator &B) {
2020 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
2021 "Both operands to a binary operator are not of the same type!", &B);
2023 switch (B.getOpcode()) {
2024 // Check that integer arithmetic operators are only used with
2025 // integral operands.
2026 case Instruction::Add:
2027 case Instruction::Sub:
2028 case Instruction::Mul:
2029 case Instruction::SDiv:
2030 case Instruction::UDiv:
2031 case Instruction::SRem:
2032 case Instruction::URem:
2033 Assert1(B.getType()->isIntOrIntVectorTy(),
2034 "Integer arithmetic operators only work with integral types!", &B);
2035 Assert1(B.getType() == B.getOperand(0)->getType(),
2036 "Integer arithmetic operators must have same type "
2037 "for operands and result!", &B);
2039 // Check that floating-point arithmetic operators are only used with
2040 // floating-point operands.
2041 case Instruction::FAdd:
2042 case Instruction::FSub:
2043 case Instruction::FMul:
2044 case Instruction::FDiv:
2045 case Instruction::FRem:
2046 Assert1(B.getType()->isFPOrFPVectorTy(),
2047 "Floating-point arithmetic operators only work with "
2048 "floating-point types!", &B);
2049 Assert1(B.getType() == B.getOperand(0)->getType(),
2050 "Floating-point arithmetic operators must have same type "
2051 "for operands and result!", &B);
2053 // Check that logical operators are only used with integral operands.
2054 case Instruction::And:
2055 case Instruction::Or:
2056 case Instruction::Xor:
2057 Assert1(B.getType()->isIntOrIntVectorTy(),
2058 "Logical operators only work with integral types!", &B);
2059 Assert1(B.getType() == B.getOperand(0)->getType(),
2060 "Logical operators must have same type for operands and result!",
2063 case Instruction::Shl:
2064 case Instruction::LShr:
2065 case Instruction::AShr:
2066 Assert1(B.getType()->isIntOrIntVectorTy(),
2067 "Shifts only work with integral types!", &B);
2068 Assert1(B.getType() == B.getOperand(0)->getType(),
2069 "Shift return type must be same as operands!", &B);
2072 llvm_unreachable("Unknown BinaryOperator opcode!");
2075 visitInstruction(B);
2078 void Verifier::visitICmpInst(ICmpInst &IC) {
2079 // Check that the operands are the same type
2080 Type *Op0Ty = IC.getOperand(0)->getType();
2081 Type *Op1Ty = IC.getOperand(1)->getType();
2082 Assert1(Op0Ty == Op1Ty,
2083 "Both operands to ICmp instruction are not of the same type!", &IC);
2084 // Check that the operands are the right type
2085 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
2086 "Invalid operand types for ICmp instruction", &IC);
2087 // Check that the predicate is valid.
2088 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
2089 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
2090 "Invalid predicate in ICmp instruction!", &IC);
2092 visitInstruction(IC);
2095 void Verifier::visitFCmpInst(FCmpInst &FC) {
2096 // Check that the operands are the same type
2097 Type *Op0Ty = FC.getOperand(0)->getType();
2098 Type *Op1Ty = FC.getOperand(1)->getType();
2099 Assert1(Op0Ty == Op1Ty,
2100 "Both operands to FCmp instruction are not of the same type!", &FC);
2101 // Check that the operands are the right type
2102 Assert1(Op0Ty->isFPOrFPVectorTy(),
2103 "Invalid operand types for FCmp instruction", &FC);
2104 // Check that the predicate is valid.
2105 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
2106 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
2107 "Invalid predicate in FCmp instruction!", &FC);
2109 visitInstruction(FC);
2112 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
2113 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
2115 "Invalid extractelement operands!", &EI);
2116 visitInstruction(EI);
2119 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
2120 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
2123 "Invalid insertelement operands!", &IE);
2124 visitInstruction(IE);
2127 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
2128 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
2130 "Invalid shufflevector operands!", &SV);
2131 visitInstruction(SV);
2134 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
2135 Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
2137 Assert1(isa<PointerType>(TargetTy),
2138 "GEP base pointer is not a vector or a vector of pointers", &GEP);
2139 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
2140 "GEP into unsized type!", &GEP);
2141 Assert1(GEP.getPointerOperandType()->isVectorTy() ==
2142 GEP.getType()->isVectorTy(), "Vector GEP must return a vector value",
2145 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
2147 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
2148 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
2150 Assert2(GEP.getType()->getScalarType()->isPointerTy() &&
2151 cast<PointerType>(GEP.getType()->getScalarType())->getElementType()
2152 == ElTy, "GEP is not of right type for indices!", &GEP, ElTy);
2154 if (GEP.getPointerOperandType()->isVectorTy()) {
2155 // Additional checks for vector GEPs.
2156 unsigned GepWidth = GEP.getPointerOperandType()->getVectorNumElements();
2157 Assert1(GepWidth == GEP.getType()->getVectorNumElements(),
2158 "Vector GEP result width doesn't match operand's", &GEP);
2159 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
2160 Type *IndexTy = Idxs[i]->getType();
2161 Assert1(IndexTy->isVectorTy(),
2162 "Vector GEP must have vector indices!", &GEP);
2163 unsigned IndexWidth = IndexTy->getVectorNumElements();
2164 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
2167 visitInstruction(GEP);
2170 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
2171 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
2174 void Verifier::visitRangeMetadata(Instruction& I,
2175 MDNode* Range, Type* Ty) {
2177 Range == I.getMetadata(LLVMContext::MD_range) &&
2178 "precondition violation");
2180 unsigned NumOperands = Range->getNumOperands();
2181 Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
2182 unsigned NumRanges = NumOperands / 2;
2183 Assert1(NumRanges >= 1, "It should have at least one range!", Range);
2185 ConstantRange LastRange(1); // Dummy initial value
2186 for (unsigned i = 0; i < NumRanges; ++i) {
2188 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i));
2189 Assert1(Low, "The lower limit must be an integer!", Low);
2191 mdconst::dyn_extract<ConstantInt>(Range->getOperand(2 * i + 1));
2192 Assert1(High, "The upper limit must be an integer!", High);
2193 Assert1(High->getType() == Low->getType() &&
2194 High->getType() == Ty, "Range types must match instruction type!",
2197 APInt HighV = High->getValue();
2198 APInt LowV = Low->getValue();
2199 ConstantRange CurRange(LowV, HighV);
2200 Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
2201 "Range must not be empty!", Range);
2203 Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
2204 "Intervals are overlapping", Range);
2205 Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
2207 Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
2210 LastRange = ConstantRange(LowV, HighV);
2212 if (NumRanges > 2) {
2214 mdconst::dyn_extract<ConstantInt>(Range->getOperand(0))->getValue();
2216 mdconst::dyn_extract<ConstantInt>(Range->getOperand(1))->getValue();
2217 ConstantRange FirstRange(FirstLow, FirstHigh);
2218 Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
2219 "Intervals are overlapping", Range);
2220 Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
2225 void Verifier::visitLoadInst(LoadInst &LI) {
2226 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
2227 Assert1(PTy, "Load operand must be a pointer.", &LI);
2228 Type *ElTy = PTy->getElementType();
2229 Assert2(ElTy == LI.getType(),
2230 "Load result type does not match pointer operand type!", &LI, ElTy);
2231 Assert1(LI.getAlignment() <= Value::MaximumAlignment,
2232 "huge alignment values are unsupported", &LI);
2233 if (LI.isAtomic()) {
2234 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
2235 "Load cannot have Release ordering", &LI);
2236 Assert1(LI.getAlignment() != 0,
2237 "Atomic load must specify explicit alignment", &LI);
2238 if (!ElTy->isPointerTy()) {
2239 Assert2(ElTy->isIntegerTy(),
2240 "atomic load operand must have integer type!",
2242 unsigned Size = ElTy->getPrimitiveSizeInBits();
2243 Assert2(Size >= 8 && !(Size & (Size - 1)),
2244 "atomic load operand must be power-of-two byte-sized integer",
2248 Assert1(LI.getSynchScope() == CrossThread,
2249 "Non-atomic load cannot have SynchronizationScope specified", &LI);
2252 visitInstruction(LI);
2255 void Verifier::visitStoreInst(StoreInst &SI) {
2256 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
2257 Assert1(PTy, "Store operand must be a pointer.", &SI);
2258 Type *ElTy = PTy->getElementType();
2259 Assert2(ElTy == SI.getOperand(0)->getType(),
2260 "Stored value type does not match pointer operand type!",
2262 Assert1(SI.getAlignment() <= Value::MaximumAlignment,
2263 "huge alignment values are unsupported", &SI);
2264 if (SI.isAtomic()) {
2265 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
2266 "Store cannot have Acquire ordering", &SI);
2267 Assert1(SI.getAlignment() != 0,
2268 "Atomic store must specify explicit alignment", &SI);
2269 if (!ElTy->isPointerTy()) {
2270 Assert2(ElTy->isIntegerTy(),
2271 "atomic store operand must have integer type!",
2273 unsigned Size = ElTy->getPrimitiveSizeInBits();
2274 Assert2(Size >= 8 && !(Size & (Size - 1)),
2275 "atomic store operand must be power-of-two byte-sized integer",
2279 Assert1(SI.getSynchScope() == CrossThread,
2280 "Non-atomic store cannot have SynchronizationScope specified", &SI);
2282 visitInstruction(SI);
2285 void Verifier::visitAllocaInst(AllocaInst &AI) {
2286 SmallPtrSet<const Type*, 4> Visited;
2287 PointerType *PTy = AI.getType();
2288 Assert1(PTy->getAddressSpace() == 0,
2289 "Allocation instruction pointer not in the generic address space!",
2291 Assert1(PTy->getElementType()->isSized(&Visited), "Cannot allocate unsized type",
2293 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
2294 "Alloca array size must have integer type", &AI);
2295 Assert1(AI.getAlignment() <= Value::MaximumAlignment,
2296 "huge alignment values are unsupported", &AI);
2298 visitInstruction(AI);
2301 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
2303 // FIXME: more conditions???
2304 Assert1(CXI.getSuccessOrdering() != NotAtomic,
2305 "cmpxchg instructions must be atomic.", &CXI);
2306 Assert1(CXI.getFailureOrdering() != NotAtomic,
2307 "cmpxchg instructions must be atomic.", &CXI);
2308 Assert1(CXI.getSuccessOrdering() != Unordered,
2309 "cmpxchg instructions cannot be unordered.", &CXI);
2310 Assert1(CXI.getFailureOrdering() != Unordered,
2311 "cmpxchg instructions cannot be unordered.", &CXI);
2312 Assert1(CXI.getSuccessOrdering() >= CXI.getFailureOrdering(),
2313 "cmpxchg instructions be at least as constrained on success as fail",
2315 Assert1(CXI.getFailureOrdering() != Release &&
2316 CXI.getFailureOrdering() != AcquireRelease,
2317 "cmpxchg failure ordering cannot include release semantics", &CXI);
2319 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
2320 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
2321 Type *ElTy = PTy->getElementType();
2322 Assert2(ElTy->isIntegerTy(),
2323 "cmpxchg operand must have integer type!",
2325 unsigned Size = ElTy->getPrimitiveSizeInBits();
2326 Assert2(Size >= 8 && !(Size & (Size - 1)),
2327 "cmpxchg operand must be power-of-two byte-sized integer",
2329 Assert2(ElTy == CXI.getOperand(1)->getType(),
2330 "Expected value type does not match pointer operand type!",
2332 Assert2(ElTy == CXI.getOperand(2)->getType(),
2333 "Stored value type does not match pointer operand type!",
2335 visitInstruction(CXI);
2338 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
2339 Assert1(RMWI.getOrdering() != NotAtomic,
2340 "atomicrmw instructions must be atomic.", &RMWI);
2341 Assert1(RMWI.getOrdering() != Unordered,
2342 "atomicrmw instructions cannot be unordered.", &RMWI);
2343 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
2344 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
2345 Type *ElTy = PTy->getElementType();
2346 Assert2(ElTy->isIntegerTy(),
2347 "atomicrmw operand must have integer type!",
2349 unsigned Size = ElTy->getPrimitiveSizeInBits();
2350 Assert2(Size >= 8 && !(Size & (Size - 1)),
2351 "atomicrmw operand must be power-of-two byte-sized integer",
2353 Assert2(ElTy == RMWI.getOperand(1)->getType(),
2354 "Argument value type does not match pointer operand type!",
2356 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
2357 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
2358 "Invalid binary operation!", &RMWI);
2359 visitInstruction(RMWI);
2362 void Verifier::visitFenceInst(FenceInst &FI) {
2363 const AtomicOrdering Ordering = FI.getOrdering();
2364 Assert1(Ordering == Acquire || Ordering == Release ||
2365 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
2366 "fence instructions may only have "
2367 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
2368 visitInstruction(FI);
2371 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
2372 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
2373 EVI.getIndices()) ==
2375 "Invalid ExtractValueInst operands!", &EVI);
2377 visitInstruction(EVI);
2380 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
2381 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
2382 IVI.getIndices()) ==
2383 IVI.getOperand(1)->getType(),
2384 "Invalid InsertValueInst operands!", &IVI);
2386 visitInstruction(IVI);
2389 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
2390 BasicBlock *BB = LPI.getParent();
2392 // The landingpad instruction is ill-formed if it doesn't have any clauses and
2394 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
2395 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
2397 // The landingpad instruction defines its parent as a landing pad block. The
2398 // landing pad block may be branched to only by the unwind edge of an invoke.
2399 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
2400 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
2401 Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
2402 "Block containing LandingPadInst must be jumped to "
2403 "only by the unwind edge of an invoke.", &LPI);
2406 // The landingpad instruction must be the first non-PHI instruction in the
2408 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
2409 "LandingPadInst not the first non-PHI instruction in the block.",
2412 // The personality functions for all landingpad instructions within the same
2413 // function should match.
2415 Assert1(LPI.getPersonalityFn() == PersonalityFn,
2416 "Personality function doesn't match others in function", &LPI);
2417 PersonalityFn = LPI.getPersonalityFn();
2419 // All operands must be constants.
2420 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
2422 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
2423 Constant *Clause = LPI.getClause(i);
2424 if (LPI.isCatch(i)) {
2425 Assert1(isa<PointerType>(Clause->getType()),
2426 "Catch operand does not have pointer type!", &LPI);
2428 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
2429 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
2430 "Filter operand is not an array of constants!", &LPI);
2434 visitInstruction(LPI);
2437 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
2438 Instruction *Op = cast<Instruction>(I.getOperand(i));
2439 // If the we have an invalid invoke, don't try to compute the dominance.
2440 // We already reject it in the invoke specific checks and the dominance
2441 // computation doesn't handle multiple edges.
2442 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
2443 if (II->getNormalDest() == II->getUnwindDest())
2447 const Use &U = I.getOperandUse(i);
2448 Assert2(InstsInThisBlock.count(Op) || DT.dominates(Op, U),
2449 "Instruction does not dominate all uses!", Op, &I);
2452 /// verifyInstruction - Verify that an instruction is well formed.
2454 void Verifier::visitInstruction(Instruction &I) {
2455 BasicBlock *BB = I.getParent();
2456 Assert1(BB, "Instruction not embedded in basic block!", &I);
2458 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
2459 for (User *U : I.users()) {
2460 Assert1(U != (User*)&I || !DT.isReachableFromEntry(BB),
2461 "Only PHI nodes may reference their own value!", &I);
2465 // Check that void typed values don't have names
2466 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
2467 "Instruction has a name, but provides a void value!", &I);
2469 // Check that the return value of the instruction is either void or a legal
2471 Assert1(I.getType()->isVoidTy() ||
2472 I.getType()->isFirstClassType(),
2473 "Instruction returns a non-scalar type!", &I);
2475 // Check that the instruction doesn't produce metadata. Calls are already
2476 // checked against the callee type.
2477 Assert1(!I.getType()->isMetadataTy() ||
2478 isa<CallInst>(I) || isa<InvokeInst>(I),
2479 "Invalid use of metadata!", &I);
2481 // Check that all uses of the instruction, if they are instructions
2482 // themselves, actually have parent basic blocks. If the use is not an
2483 // instruction, it is an error!
2484 for (Use &U : I.uses()) {
2485 if (Instruction *Used = dyn_cast<Instruction>(U.getUser()))
2486 Assert2(Used->getParent() != nullptr, "Instruction referencing"
2487 " instruction not embedded in a basic block!", &I, Used);
2489 CheckFailed("Use of instruction is not an instruction!", U);
2494 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
2495 Assert1(I.getOperand(i) != nullptr, "Instruction has null operand!", &I);
2497 // Check to make sure that only first-class-values are operands to
2499 if (!I.getOperand(i)->getType()->isFirstClassType()) {
2500 Assert1(0, "Instruction operands must be first-class values!", &I);
2503 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
2504 // Check to make sure that the "address of" an intrinsic function is never
2506 Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 :
2507 isa<InvokeInst>(I) ? e-3 : 0),
2508 "Cannot take the address of an intrinsic!", &I);
2509 Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
2510 F->getIntrinsicID() == Intrinsic::donothing ||
2511 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_void ||
2512 F->getIntrinsicID() == Intrinsic::experimental_patchpoint_i64 ||
2513 F->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
2514 "Cannot invoke an intrinsinc other than"
2515 " donothing or patchpoint", &I);
2516 Assert1(F->getParent() == M, "Referencing function in another module!",
2518 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
2519 Assert1(OpBB->getParent() == BB->getParent(),
2520 "Referring to a basic block in another function!", &I);
2521 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
2522 Assert1(OpArg->getParent() == BB->getParent(),
2523 "Referring to an argument in another function!", &I);
2524 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
2525 Assert1(GV->getParent() == M, "Referencing global in another module!",
2527 } else if (isa<Instruction>(I.getOperand(i))) {
2528 verifyDominatesUse(I, i);
2529 } else if (isa<InlineAsm>(I.getOperand(i))) {
2530 Assert1((i + 1 == e && isa<CallInst>(I)) ||
2531 (i + 3 == e && isa<InvokeInst>(I)),
2532 "Cannot take the address of an inline asm!", &I);
2533 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i))) {
2534 if (CE->getType()->isPtrOrPtrVectorTy()) {
2535 // If we have a ConstantExpr pointer, we need to see if it came from an
2536 // illegal bitcast (inttoptr <constant int> )
2537 SmallVector<const ConstantExpr *, 4> Stack;
2538 SmallPtrSet<const ConstantExpr *, 4> Visited;
2539 Stack.push_back(CE);
2541 while (!Stack.empty()) {
2542 const ConstantExpr *V = Stack.pop_back_val();
2543 if (!Visited.insert(V).second)
2546 VerifyConstantExprBitcastType(V);
2548 for (unsigned I = 0, N = V->getNumOperands(); I != N; ++I) {
2549 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(V->getOperand(I)))
2550 Stack.push_back(Op);
2557 if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
2558 Assert1(I.getType()->isFPOrFPVectorTy(),
2559 "fpmath requires a floating point result!", &I);
2560 Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
2561 if (ConstantFP *CFP0 =
2562 mdconst::dyn_extract_or_null<ConstantFP>(MD->getOperand(0))) {
2563 APFloat Accuracy = CFP0->getValueAPF();
2564 Assert1(Accuracy.isFiniteNonZero() && !Accuracy.isNegative(),
2565 "fpmath accuracy not a positive number!", &I);
2567 Assert1(false, "invalid fpmath accuracy!", &I);
2571 if (MDNode *Range = I.getMetadata(LLVMContext::MD_range)) {
2572 Assert1(isa<LoadInst>(I) || isa<CallInst>(I) || isa<InvokeInst>(I),
2573 "Ranges are only for loads, calls and invokes!", &I);
2574 visitRangeMetadata(I, Range, I.getType());
2577 if (I.getMetadata(LLVMContext::MD_nonnull)) {
2578 Assert1(I.getType()->isPointerTy(),
2579 "nonnull applies only to pointer types", &I);
2580 Assert1(isa<LoadInst>(I),
2581 "nonnull applies only to load instructions, use attributes"
2582 " for calls or invokes", &I);
2585 InstsInThisBlock.insert(&I);
2588 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
2589 /// intrinsic argument or return value) matches the type constraints specified
2590 /// by the .td file (e.g. an "any integer" argument really is an integer).
2592 /// This return true on error but does not print a message.
2593 bool Verifier::VerifyIntrinsicType(Type *Ty,
2594 ArrayRef<Intrinsic::IITDescriptor> &Infos,
2595 SmallVectorImpl<Type*> &ArgTys) {
2596 using namespace Intrinsic;
2598 // If we ran out of descriptors, there are too many arguments.
2599 if (Infos.empty()) return true;
2600 IITDescriptor D = Infos.front();
2601 Infos = Infos.slice(1);
2604 case IITDescriptor::Void: return !Ty->isVoidTy();
2605 case IITDescriptor::VarArg: return true;
2606 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
2607 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
2608 case IITDescriptor::Half: return !Ty->isHalfTy();
2609 case IITDescriptor::Float: return !Ty->isFloatTy();
2610 case IITDescriptor::Double: return !Ty->isDoubleTy();
2611 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
2612 case IITDescriptor::Vector: {
2613 VectorType *VT = dyn_cast<VectorType>(Ty);
2614 return !VT || VT->getNumElements() != D.Vector_Width ||
2615 VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
2617 case IITDescriptor::Pointer: {
2618 PointerType *PT = dyn_cast<PointerType>(Ty);
2619 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
2620 VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
2623 case IITDescriptor::Struct: {
2624 StructType *ST = dyn_cast<StructType>(Ty);
2625 if (!ST || ST->getNumElements() != D.Struct_NumElements)
2628 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
2629 if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
2634 case IITDescriptor::Argument:
2635 // Two cases here - If this is the second occurrence of an argument, verify
2636 // that the later instance matches the previous instance.
2637 if (D.getArgumentNumber() < ArgTys.size())
2638 return Ty != ArgTys[D.getArgumentNumber()];
2640 // Otherwise, if this is the first instance of an argument, record it and
2641 // verify the "Any" kind.
2642 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
2643 ArgTys.push_back(Ty);
2645 switch (D.getArgumentKind()) {
2646 case IITDescriptor::AK_Any: return false; // Success
2647 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
2648 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
2649 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
2650 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
2652 llvm_unreachable("all argument kinds not covered");
2654 case IITDescriptor::ExtendArgument: {
2655 // This may only be used when referring to a previous vector argument.
2656 if (D.getArgumentNumber() >= ArgTys.size())
2659 Type *NewTy = ArgTys[D.getArgumentNumber()];
2660 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2661 NewTy = VectorType::getExtendedElementVectorType(VTy);
2662 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2663 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
2669 case IITDescriptor::TruncArgument: {
2670 // This may only be used when referring to a previous vector argument.
2671 if (D.getArgumentNumber() >= ArgTys.size())
2674 Type *NewTy = ArgTys[D.getArgumentNumber()];
2675 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
2676 NewTy = VectorType::getTruncatedElementVectorType(VTy);
2677 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
2678 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
2684 case IITDescriptor::HalfVecArgument:
2685 // This may only be used when referring to a previous vector argument.
2686 return D.getArgumentNumber() >= ArgTys.size() ||
2687 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
2688 VectorType::getHalfElementsVectorType(
2689 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
2690 case IITDescriptor::SameVecWidthArgument: {
2691 if (D.getArgumentNumber() >= ArgTys.size())
2693 VectorType * ReferenceType =
2694 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
2695 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
2696 if (!ThisArgType || !ReferenceType ||
2697 (ReferenceType->getVectorNumElements() !=
2698 ThisArgType->getVectorNumElements()))
2700 return VerifyIntrinsicType(ThisArgType->getVectorElementType(),
2703 case IITDescriptor::PtrToArgument: {
2704 if (D.getArgumentNumber() >= ArgTys.size())
2706 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
2707 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
2708 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
2710 case IITDescriptor::VecOfPtrsToElt: {
2711 if (D.getArgumentNumber() >= ArgTys.size())
2713 VectorType * ReferenceType =
2714 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
2715 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
2716 if (!ThisArgVecTy || !ReferenceType ||
2717 (ReferenceType->getVectorNumElements() !=
2718 ThisArgVecTy->getVectorNumElements()))
2720 PointerType *ThisArgEltTy =
2721 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
2724 return (!(ThisArgEltTy->getElementType() ==
2725 ReferenceType->getVectorElementType()));
2728 llvm_unreachable("unhandled");
2731 /// \brief Verify if the intrinsic has variable arguments.
2732 /// This method is intended to be called after all the fixed arguments have been
2735 /// This method returns true on error and does not print an error message.
2737 Verifier::VerifyIntrinsicIsVarArg(bool isVarArg,
2738 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
2739 using namespace Intrinsic;
2741 // If there are no descriptors left, then it can't be a vararg.
2743 return isVarArg ? true : false;
2745 // There should be only one descriptor remaining at this point.
2746 if (Infos.size() != 1)
2749 // Check and verify the descriptor.
2750 IITDescriptor D = Infos.front();
2751 Infos = Infos.slice(1);
2752 if (D.Kind == IITDescriptor::VarArg)
2753 return isVarArg ? false : true;
2758 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
2760 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
2761 Function *IF = CI.getCalledFunction();
2762 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
2765 // Verify that the intrinsic prototype lines up with what the .td files
2767 FunctionType *IFTy = IF->getFunctionType();
2768 bool IsVarArg = IFTy->isVarArg();
2770 SmallVector<Intrinsic::IITDescriptor, 8> Table;
2771 getIntrinsicInfoTableEntries(ID, Table);
2772 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
2774 SmallVector<Type *, 4> ArgTys;
2775 Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
2776 "Intrinsic has incorrect return type!", IF);
2777 for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
2778 Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
2779 "Intrinsic has incorrect argument type!", IF);
2781 // Verify if the intrinsic call matches the vararg property.
2783 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2784 "Intrinsic was not defined with variable arguments!", IF);
2786 Assert1(!VerifyIntrinsicIsVarArg(IsVarArg, TableRef),
2787 "Callsite was not defined with variable arguments!", IF);
2789 // All descriptors should be absorbed by now.
2790 Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
2792 // Now that we have the intrinsic ID and the actual argument types (and we
2793 // know they are legal for the intrinsic!) get the intrinsic name through the
2794 // usual means. This allows us to verify the mangling of argument types into
2796 const std::string ExpectedName = Intrinsic::getName(ID, ArgTys);
2797 Assert1(ExpectedName == IF->getName(),
2798 "Intrinsic name not mangled correctly for type arguments! "
2799 "Should be: " + ExpectedName, IF);
2801 // If the intrinsic takes MDNode arguments, verify that they are either global
2802 // or are local to *this* function.
2803 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
2804 if (auto *MD = dyn_cast<MetadataAsValue>(CI.getArgOperand(i)))
2805 visitMetadataAsValue(*MD, CI.getParent()->getParent());
2810 case Intrinsic::ctlz: // llvm.ctlz
2811 case Intrinsic::cttz: // llvm.cttz
2812 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2813 "is_zero_undef argument of bit counting intrinsics must be a "
2814 "constant int", &CI);
2816 case Intrinsic::dbg_declare: { // llvm.dbg.declare
2817 Assert1(CI.getArgOperand(0) && isa<MetadataAsValue>(CI.getArgOperand(0)),
2818 "invalid llvm.dbg.declare intrinsic call 1", &CI);
2820 case Intrinsic::memcpy:
2821 case Intrinsic::memmove:
2822 case Intrinsic::memset: {
2823 ConstantInt *AlignCI = dyn_cast<ConstantInt>(CI.getArgOperand(3));
2825 "alignment argument of memory intrinsics must be a constant int",
2827 const APInt &AlignVal = AlignCI->getValue();
2828 Assert1(AlignCI->isZero() || AlignVal.isPowerOf2(),
2829 "alignment argument of memory intrinsics must be a power of 2",
2831 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
2832 "isvolatile argument of memory intrinsics must be a constant int",
2836 case Intrinsic::gcroot:
2837 case Intrinsic::gcwrite:
2838 case Intrinsic::gcread:
2839 if (ID == Intrinsic::gcroot) {
2841 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
2842 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
2843 Assert1(isa<Constant>(CI.getArgOperand(1)),
2844 "llvm.gcroot parameter #2 must be a constant.", &CI);
2845 if (!AI->getType()->getElementType()->isPointerTy()) {
2846 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
2847 "llvm.gcroot parameter #1 must either be a pointer alloca, "
2848 "or argument #2 must be a non-null constant.", &CI);
2852 Assert1(CI.getParent()->getParent()->hasGC(),
2853 "Enclosing function does not use GC.", &CI);
2855 case Intrinsic::init_trampoline:
2856 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
2857 "llvm.init_trampoline parameter #2 must resolve to a function.",
2860 case Intrinsic::prefetch:
2861 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
2862 isa<ConstantInt>(CI.getArgOperand(2)) &&
2863 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
2864 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
2865 "invalid arguments to llvm.prefetch",
2868 case Intrinsic::stackprotector:
2869 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
2870 "llvm.stackprotector parameter #2 must resolve to an alloca.",
2873 case Intrinsic::lifetime_start:
2874 case Intrinsic::lifetime_end:
2875 case Intrinsic::invariant_start:
2876 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
2877 "size argument of memory use markers must be a constant integer",
2880 case Intrinsic::invariant_end:
2881 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
2882 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
2885 case Intrinsic::frameescape: {
2886 BasicBlock *BB = CI.getParent();
2887 Assert1(BB == &BB->getParent()->front(),
2888 "llvm.frameescape used outside of entry block", &CI);
2889 Assert1(!SawFrameEscape,
2890 "multiple calls to llvm.frameescape in one function", &CI);
2891 for (Value *Arg : CI.arg_operands()) {
2892 auto *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2893 Assert1(AI && AI->isStaticAlloca(),
2894 "llvm.frameescape only accepts static allocas", &CI);
2896 FrameEscapeInfo[BB->getParent()].first = CI.getNumArgOperands();
2897 SawFrameEscape = true;
2900 case Intrinsic::framerecover: {
2901 Value *FnArg = CI.getArgOperand(0)->stripPointerCasts();
2902 Function *Fn = dyn_cast<Function>(FnArg);
2903 Assert1(Fn && !Fn->isDeclaration(), "llvm.framerecover first "
2904 "argument must be function defined in this module", &CI);
2905 auto *IdxArg = dyn_cast<ConstantInt>(CI.getArgOperand(2));
2906 Assert1(IdxArg, "idx argument of llvm.framerecover must be a constant int",
2908 auto &Entry = FrameEscapeInfo[Fn];
2909 Entry.second = unsigned(
2910 std::max(uint64_t(Entry.second), IdxArg->getLimitedValue(~0U) + 1));
2914 case Intrinsic::experimental_gc_statepoint:
2915 Assert1(!CI.isInlineAsm(),
2916 "gc.statepoint support for inline assembly unimplemented", &CI);
2918 VerifyStatepoint(ImmutableCallSite(&CI));
2920 case Intrinsic::experimental_gc_result_int:
2921 case Intrinsic::experimental_gc_result_float:
2922 case Intrinsic::experimental_gc_result_ptr:
2923 case Intrinsic::experimental_gc_result: {
2924 // Are we tied to a statepoint properly?
2925 CallSite StatepointCS(CI.getArgOperand(0));
2926 const Function *StatepointFn =
2927 StatepointCS.getInstruction() ? StatepointCS.getCalledFunction() : nullptr;
2928 Assert2(StatepointFn && StatepointFn->isDeclaration() &&
2929 StatepointFn->getIntrinsicID() == Intrinsic::experimental_gc_statepoint,
2930 "gc.result operand #1 must be from a statepoint",
2931 &CI, CI.getArgOperand(0));
2933 // Assert that result type matches wrapped callee.
2934 const Value *Target = StatepointCS.getArgument(0);
2935 const PointerType *PT = cast<PointerType>(Target->getType());
2936 const FunctionType *TargetFuncType =
2937 cast<FunctionType>(PT->getElementType());
2938 Assert1(CI.getType() == TargetFuncType->getReturnType(),
2939 "gc.result result type does not match wrapped callee",
2943 case Intrinsic::experimental_gc_relocate: {
2944 Assert1(CI.getNumArgOperands() == 3, "wrong number of arguments", &CI);
2946 // Check that this relocate is correctly tied to the statepoint
2948 // This is case for relocate on the unwinding path of an invoke statepoint
2949 if (ExtractValueInst *ExtractValue =
2950 dyn_cast<ExtractValueInst>(CI.getArgOperand(0))) {
2951 Assert1(isa<LandingPadInst>(ExtractValue->getAggregateOperand()),
2952 "gc relocate on unwind path incorrectly linked to the statepoint",
2955 const BasicBlock *invokeBB =
2956 ExtractValue->getParent()->getUniquePredecessor();
2958 // Landingpad relocates should have only one predecessor with invoke
2959 // statepoint terminator
2961 "safepoints should have unique landingpads",
2962 ExtractValue->getParent());
2963 Assert1(invokeBB->getTerminator(),
2964 "safepoint block should be well formed",
2966 Assert1(isStatepoint(invokeBB->getTerminator()),
2967 "gc relocate should be linked to a statepoint",
2971 // In all other cases relocate should be tied to the statepoint directly.
2972 // This covers relocates on a normal return path of invoke statepoint and
2973 // relocates of a call statepoint
2974 auto Token = CI.getArgOperand(0);
2975 Assert2(isa<Instruction>(Token) && isStatepoint(cast<Instruction>(Token)),
2976 "gc relocate is incorrectly tied to the statepoint",
2980 // Verify rest of the relocate arguments
2982 GCRelocateOperands ops(&CI);
2983 ImmutableCallSite StatepointCS(ops.statepoint());
2985 // Both the base and derived must be piped through the safepoint
2986 Value* Base = CI.getArgOperand(1);
2987 Assert1(isa<ConstantInt>(Base),
2988 "gc.relocate operand #2 must be integer offset", &CI);
2990 Value* Derived = CI.getArgOperand(2);
2991 Assert1(isa<ConstantInt>(Derived),
2992 "gc.relocate operand #3 must be integer offset", &CI);
2994 const int BaseIndex = cast<ConstantInt>(Base)->getZExtValue();
2995 const int DerivedIndex = cast<ConstantInt>(Derived)->getZExtValue();
2997 Assert1(0 <= BaseIndex &&
2998 BaseIndex < (int)StatepointCS.arg_size(),
2999 "gc.relocate: statepoint base index out of bounds", &CI);
3000 Assert1(0 <= DerivedIndex &&
3001 DerivedIndex < (int)StatepointCS.arg_size(),
3002 "gc.relocate: statepoint derived index out of bounds", &CI);
3004 // Check that BaseIndex and DerivedIndex fall within the 'gc parameters'
3005 // section of the statepoint's argument
3006 const int NumCallArgs =
3007 cast<ConstantInt>(StatepointCS.getArgument(1))->getZExtValue();
3008 const int NumDeoptArgs =
3009 cast<ConstantInt>(StatepointCS.getArgument(NumCallArgs + 3))->getZExtValue();
3010 const int GCParamArgsStart = NumCallArgs + NumDeoptArgs + 4;
3011 const int GCParamArgsEnd = StatepointCS.arg_size();
3012 Assert1(GCParamArgsStart <= BaseIndex &&
3013 BaseIndex < GCParamArgsEnd,
3014 "gc.relocate: statepoint base index doesn't fall within the "
3015 "'gc parameters' section of the statepoint call", &CI);
3016 Assert1(GCParamArgsStart <= DerivedIndex &&
3017 DerivedIndex < GCParamArgsEnd,
3018 "gc.relocate: statepoint derived index doesn't fall within the "
3019 "'gc parameters' section of the statepoint call", &CI);
3022 // Assert that the result type matches the type of the relocated pointer
3023 GCRelocateOperands Operands(&CI);
3024 Assert1(Operands.derivedPtr()->getType() == CI.getType(),
3025 "gc.relocate: relocating a pointer shouldn't change its type",
3032 void DebugInfoVerifier::verifyDebugInfo() {
3033 if (!VerifyDebugInfo)
3036 DebugInfoFinder Finder;
3037 Finder.processModule(*M);
3038 processInstructions(Finder);
3040 // Verify Debug Info.
3042 // NOTE: The loud braces are necessary for MSVC compatibility.
3043 for (DICompileUnit CU : Finder.compile_units()) {
3044 Assert1(CU.Verify(), "DICompileUnit does not Verify!", CU);
3046 for (DISubprogram S : Finder.subprograms()) {
3047 Assert1(S.Verify(), "DISubprogram does not Verify!", S);
3049 for (DIGlobalVariable GV : Finder.global_variables()) {
3050 Assert1(GV.Verify(), "DIGlobalVariable does not Verify!", GV);
3052 for (DIType T : Finder.types()) {
3053 Assert1(T.Verify(), "DIType does not Verify!", T);
3055 for (DIScope S : Finder.scopes()) {
3056 Assert1(S.Verify(), "DIScope does not Verify!", S);
3060 void DebugInfoVerifier::processInstructions(DebugInfoFinder &Finder) {
3061 for (const Function &F : *M)
3062 for (auto I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
3063 if (MDNode *MD = I->getMetadata(LLVMContext::MD_dbg))
3064 Finder.processLocation(*M, DILocation(MD));
3065 if (const CallInst *CI = dyn_cast<CallInst>(&*I))
3066 processCallInst(Finder, *CI);
3070 void DebugInfoVerifier::processCallInst(DebugInfoFinder &Finder,
3071 const CallInst &CI) {
3072 if (Function *F = CI.getCalledFunction())
3073 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
3075 case Intrinsic::dbg_declare: {
3076 auto *DDI = cast<DbgDeclareInst>(&CI);
3077 Finder.processDeclare(*M, DDI);
3078 if (auto E = DDI->getExpression())
3079 Assert1(DIExpression(E).Verify(), "DIExpression does not Verify!", E);
3082 case Intrinsic::dbg_value: {
3083 auto *DVI = cast<DbgValueInst>(&CI);
3084 Finder.processValue(*M, DVI);
3085 if (auto E = DVI->getExpression())
3086 Assert1(DIExpression(E).Verify(), "DIExpression does not Verify!", E);
3094 //===----------------------------------------------------------------------===//
3095 // Implement the public interfaces to this file...
3096 //===----------------------------------------------------------------------===//
3098 bool llvm::verifyFunction(const Function &f, raw_ostream *OS) {
3099 Function &F = const_cast<Function &>(f);
3100 assert(!F.isDeclaration() && "Cannot verify external functions");
3102 raw_null_ostream NullStr;
3103 Verifier V(OS ? *OS : NullStr);
3105 // Note that this function's return value is inverted from what you would
3106 // expect of a function called "verify".
3107 return !V.verify(F);
3110 bool llvm::verifyModule(const Module &M, raw_ostream *OS) {
3111 raw_null_ostream NullStr;
3112 Verifier V(OS ? *OS : NullStr);
3114 bool Broken = false;
3115 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
3116 if (!I->isDeclaration() && !I->isMaterializable())
3117 Broken |= !V.verify(*I);
3119 // Note that this function's return value is inverted from what you would
3120 // expect of a function called "verify".
3121 DebugInfoVerifier DIV(OS ? *OS : NullStr);
3122 return !V.verify(M) || !DIV.verify(M) || Broken;
3126 struct VerifierLegacyPass : public FunctionPass {
3132 VerifierLegacyPass() : FunctionPass(ID), FatalErrors(true) {
3133 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3135 explicit VerifierLegacyPass(bool FatalErrors)
3136 : FunctionPass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3137 initializeVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3140 bool runOnFunction(Function &F) override {
3141 if (!V.verify(F) && FatalErrors)
3142 report_fatal_error("Broken function found, compilation aborted!");
3147 bool doFinalization(Module &M) override {
3148 if (!V.verify(M) && FatalErrors)
3149 report_fatal_error("Broken module found, compilation aborted!");
3154 void getAnalysisUsage(AnalysisUsage &AU) const override {
3155 AU.setPreservesAll();
3158 struct DebugInfoVerifierLegacyPass : public ModulePass {
3161 DebugInfoVerifier V;
3164 DebugInfoVerifierLegacyPass() : ModulePass(ID), FatalErrors(true) {
3165 initializeDebugInfoVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3167 explicit DebugInfoVerifierLegacyPass(bool FatalErrors)
3168 : ModulePass(ID), V(dbgs()), FatalErrors(FatalErrors) {
3169 initializeDebugInfoVerifierLegacyPassPass(*PassRegistry::getPassRegistry());
3172 bool runOnModule(Module &M) override {
3173 if (!V.verify(M) && FatalErrors)
3174 report_fatal_error("Broken debug info found, compilation aborted!");
3179 void getAnalysisUsage(AnalysisUsage &AU) const override {
3180 AU.setPreservesAll();
3185 char VerifierLegacyPass::ID = 0;
3186 INITIALIZE_PASS(VerifierLegacyPass, "verify", "Module Verifier", false, false)
3188 char DebugInfoVerifierLegacyPass::ID = 0;
3189 INITIALIZE_PASS(DebugInfoVerifierLegacyPass, "verify-di", "Debug Info Verifier",
3192 FunctionPass *llvm::createVerifierPass(bool FatalErrors) {
3193 return new VerifierLegacyPass(FatalErrors);
3196 ModulePass *llvm::createDebugInfoVerifierPass(bool FatalErrors) {
3197 return new DebugInfoVerifierLegacyPass(FatalErrors);
3200 PreservedAnalyses VerifierPass::run(Module &M) {
3201 if (verifyModule(M, &dbgs()) && FatalErrors)
3202 report_fatal_error("Broken module found, compilation aborted!");
3204 return PreservedAnalyses::all();
3207 PreservedAnalyses VerifierPass::run(Function &F) {
3208 if (verifyFunction(F, &dbgs()) && FatalErrors)
3209 report_fatal_error("Broken function found, compilation aborted!");
3211 return PreservedAnalyses::all();