1 //===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
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/Analysis/Verifier.h"
49 #include "llvm/CallingConv.h"
50 #include "llvm/Constants.h"
51 #include "llvm/DerivedTypes.h"
52 #include "llvm/InlineAsm.h"
53 #include "llvm/IntrinsicInst.h"
54 #include "llvm/Metadata.h"
55 #include "llvm/Module.h"
56 #include "llvm/Pass.h"
57 #include "llvm/PassManager.h"
58 #include "llvm/Analysis/Dominators.h"
59 #include "llvm/Assembly/Writer.h"
60 #include "llvm/CodeGen/ValueTypes.h"
61 #include "llvm/Support/CallSite.h"
62 #include "llvm/Support/CFG.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/InstVisitor.h"
65 #include "llvm/ADT/SetVector.h"
66 #include "llvm/ADT/SmallPtrSet.h"
67 #include "llvm/ADT/SmallVector.h"
68 #include "llvm/ADT/StringExtras.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/raw_ostream.h"
76 namespace { // Anonymous namespace for class
77 struct PreVerifier : public FunctionPass {
78 static char ID; // Pass ID, replacement for typeid
80 PreVerifier() : FunctionPass(ID) {
81 initializePreVerifierPass(*PassRegistry::getPassRegistry());
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 // Check that the prerequisites for successful DominatorTree construction
90 bool runOnFunction(Function &F) {
93 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
94 if (I->empty() || !I->back().isTerminator()) {
95 dbgs() << "Basic Block in function '" << F.getName()
96 << "' does not have terminator!\n";
97 WriteAsOperand(dbgs(), I, true);
104 report_fatal_error("Broken module, no Basic Block terminator!");
111 char PreVerifier::ID = 0;
112 INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
114 static char &PreVerifyID = PreVerifier::ID;
117 struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
118 static char ID; // Pass ID, replacement for typeid
119 bool Broken; // Is this module found to be broken?
120 bool RealPass; // Are we not being run by a PassManager?
121 VerifierFailureAction action;
122 // What to do if verification fails.
123 Module *Mod; // Module we are verifying right now
124 LLVMContext *Context; // Context within which we are verifying
125 DominatorTree *DT; // Dominator Tree, caution can be null!
127 std::string Messages;
128 raw_string_ostream MessagesStr;
130 /// InstInThisBlock - when verifying a basic block, keep track of all of the
131 /// instructions we have seen so far. This allows us to do efficient
132 /// dominance checks for the case when an instruction has an operand that is
133 /// an instruction in the same block.
134 SmallPtrSet<Instruction*, 16> InstsInThisBlock;
136 /// MDNodes - keep track of the metadata nodes that have been checked
138 SmallPtrSet<MDNode *, 32> MDNodes;
140 /// PersonalityFn - The personality function referenced by the
141 /// LandingPadInsts. All LandingPadInsts within the same function must use
142 /// the same personality function.
143 const Value *PersonalityFn;
146 : FunctionPass(ID), Broken(false), RealPass(true),
147 action(AbortProcessAction), Mod(0), Context(0), DT(0),
148 MessagesStr(Messages), PersonalityFn(0) {
149 initializeVerifierPass(*PassRegistry::getPassRegistry());
151 explicit Verifier(VerifierFailureAction ctn)
152 : FunctionPass(ID), Broken(false), RealPass(true), action(ctn), Mod(0),
153 Context(0), DT(0), MessagesStr(Messages), PersonalityFn(0) {
154 initializeVerifierPass(*PassRegistry::getPassRegistry());
157 bool doInitialization(Module &M) {
159 Context = &M.getContext();
161 // If this is a real pass, in a pass manager, we must abort before
162 // returning back to the pass manager, or else the pass manager may try to
163 // run other passes on the broken module.
165 return abortIfBroken();
169 bool runOnFunction(Function &F) {
170 // Get dominator information if we are being run by PassManager
171 if (RealPass) DT = &getAnalysis<DominatorTree>();
174 if (!Context) Context = &F.getContext();
177 InstsInThisBlock.clear();
180 // If this is a real pass, in a pass manager, we must abort before
181 // returning back to the pass manager, or else the pass manager may try to
182 // run other passes on the broken module.
184 return abortIfBroken();
189 bool doFinalization(Module &M) {
190 // Scan through, checking all of the external function's linkage now...
191 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
192 visitGlobalValue(*I);
194 // Check to make sure function prototypes are okay.
195 if (I->isDeclaration()) visitFunction(*I);
198 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
200 visitGlobalVariable(*I);
202 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
204 visitGlobalAlias(*I);
206 for (Module::named_metadata_iterator I = M.named_metadata_begin(),
207 E = M.named_metadata_end(); I != E; ++I)
208 visitNamedMDNode(*I);
210 // If the module is broken, abort at this time.
211 return abortIfBroken();
214 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
215 AU.setPreservesAll();
216 AU.addRequiredID(PreVerifyID);
218 AU.addRequired<DominatorTree>();
221 /// abortIfBroken - If the module is broken and we are supposed to abort on
222 /// this condition, do so.
224 bool abortIfBroken() {
225 if (!Broken) return false;
226 MessagesStr << "Broken module found, ";
228 case AbortProcessAction:
229 MessagesStr << "compilation aborted!\n";
230 dbgs() << MessagesStr.str();
231 // Client should choose different reaction if abort is not desired
233 case PrintMessageAction:
234 MessagesStr << "verification continues.\n";
235 dbgs() << MessagesStr.str();
237 case ReturnStatusAction:
238 MessagesStr << "compilation terminated.\n";
241 llvm_unreachable("Invalid action");
245 // Verification methods...
246 void visitGlobalValue(GlobalValue &GV);
247 void visitGlobalVariable(GlobalVariable &GV);
248 void visitGlobalAlias(GlobalAlias &GA);
249 void visitNamedMDNode(NamedMDNode &NMD);
250 void visitMDNode(MDNode &MD, Function *F);
251 void visitFunction(Function &F);
252 void visitBasicBlock(BasicBlock &BB);
253 using InstVisitor<Verifier>::visit;
255 void visit(Instruction &I);
257 void visitTruncInst(TruncInst &I);
258 void visitZExtInst(ZExtInst &I);
259 void visitSExtInst(SExtInst &I);
260 void visitFPTruncInst(FPTruncInst &I);
261 void visitFPExtInst(FPExtInst &I);
262 void visitFPToUIInst(FPToUIInst &I);
263 void visitFPToSIInst(FPToSIInst &I);
264 void visitUIToFPInst(UIToFPInst &I);
265 void visitSIToFPInst(SIToFPInst &I);
266 void visitIntToPtrInst(IntToPtrInst &I);
267 void visitPtrToIntInst(PtrToIntInst &I);
268 void visitBitCastInst(BitCastInst &I);
269 void visitPHINode(PHINode &PN);
270 void visitBinaryOperator(BinaryOperator &B);
271 void visitICmpInst(ICmpInst &IC);
272 void visitFCmpInst(FCmpInst &FC);
273 void visitExtractElementInst(ExtractElementInst &EI);
274 void visitInsertElementInst(InsertElementInst &EI);
275 void visitShuffleVectorInst(ShuffleVectorInst &EI);
276 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
277 void visitCallInst(CallInst &CI);
278 void visitInvokeInst(InvokeInst &II);
279 void visitGetElementPtrInst(GetElementPtrInst &GEP);
280 void visitLoadInst(LoadInst &LI);
281 void visitStoreInst(StoreInst &SI);
282 void visitInstruction(Instruction &I);
283 void visitTerminatorInst(TerminatorInst &I);
284 void visitBranchInst(BranchInst &BI);
285 void visitReturnInst(ReturnInst &RI);
286 void visitSwitchInst(SwitchInst &SI);
287 void visitIndirectBrInst(IndirectBrInst &BI);
288 void visitSelectInst(SelectInst &SI);
289 void visitUserOp1(Instruction &I);
290 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
291 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
292 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
293 void visitAtomicRMWInst(AtomicRMWInst &RMWI);
294 void visitFenceInst(FenceInst &FI);
295 void visitAllocaInst(AllocaInst &AI);
296 void visitExtractValueInst(ExtractValueInst &EVI);
297 void visitInsertValueInst(InsertValueInst &IVI);
298 void visitLandingPadInst(LandingPadInst &LPI);
300 void VerifyCallSite(CallSite CS);
301 bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
302 int VT, unsigned ArgNo, std::string &Suffix);
303 void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
304 unsigned RetNum, unsigned ParamNum, ...);
305 void VerifyParameterAttrs(Attributes Attrs, Type *Ty,
306 bool isReturnValue, const Value *V);
307 void VerifyFunctionAttrs(FunctionType *FT, const AttrListPtr &Attrs,
310 void WriteValue(const Value *V) {
312 if (isa<Instruction>(V)) {
313 MessagesStr << *V << '\n';
315 WriteAsOperand(MessagesStr, V, true, Mod);
320 void WriteType(Type *T) {
322 MessagesStr << ' ' << *T;
326 // CheckFailed - A check failed, so print out the condition and the message
327 // that failed. This provides a nice place to put a breakpoint if you want
328 // to see why something is not correct.
329 void CheckFailed(const Twine &Message,
330 const Value *V1 = 0, const Value *V2 = 0,
331 const Value *V3 = 0, const Value *V4 = 0) {
332 MessagesStr << Message.str() << "\n";
340 void CheckFailed(const Twine &Message, const Value *V1,
341 Type *T2, const Value *V3 = 0) {
342 MessagesStr << Message.str() << "\n";
349 void CheckFailed(const Twine &Message, Type *T1,
350 Type *T2 = 0, Type *T3 = 0) {
351 MessagesStr << Message.str() << "\n";
358 } // End anonymous namespace
360 char Verifier::ID = 0;
361 INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
362 INITIALIZE_PASS_DEPENDENCY(PreVerifier)
363 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
364 INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
366 // Assert - We know that cond should be true, if not print an error message.
367 #define Assert(C, M) \
368 do { if (!(C)) { CheckFailed(M); return; } } while (0)
369 #define Assert1(C, M, V1) \
370 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
371 #define Assert2(C, M, V1, V2) \
372 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
373 #define Assert3(C, M, V1, V2, V3) \
374 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
375 #define Assert4(C, M, V1, V2, V3, V4) \
376 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
378 void Verifier::visit(Instruction &I) {
379 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
380 Assert1(I.getOperand(i) != 0, "Operand is null", &I);
381 InstVisitor<Verifier>::visit(I);
385 void Verifier::visitGlobalValue(GlobalValue &GV) {
386 Assert1(!GV.isDeclaration() ||
387 GV.isMaterializable() ||
388 GV.hasExternalLinkage() ||
389 GV.hasDLLImportLinkage() ||
390 GV.hasExternalWeakLinkage() ||
391 (isa<GlobalAlias>(GV) &&
392 (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
393 "Global is external, but doesn't have external or dllimport or weak linkage!",
396 Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
397 "Global is marked as dllimport, but not external", &GV);
399 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
400 "Only global variables can have appending linkage!", &GV);
402 if (GV.hasAppendingLinkage()) {
403 GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
404 Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
405 "Only global arrays can have appending linkage!", GVar);
408 Assert1(!GV.hasLinkerPrivateWeakDefAutoLinkage() || GV.hasDefaultVisibility(),
409 "linker_private_weak_def_auto can only have default visibility!",
413 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
414 if (GV.hasInitializer()) {
415 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
416 "Global variable initializer type does not match global "
417 "variable type!", &GV);
419 // If the global has common linkage, it must have a zero initializer and
420 // cannot be constant.
421 if (GV.hasCommonLinkage()) {
422 Assert1(GV.getInitializer()->isNullValue(),
423 "'common' global must have a zero initializer!", &GV);
424 Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
428 Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
429 GV.hasExternalWeakLinkage(),
430 "invalid linkage type for global declaration", &GV);
433 if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
434 GV.getName() == "llvm.global_dtors")) {
435 Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
436 "invalid linkage for intrinsic global variable", &GV);
437 // Don't worry about emitting an error for it not being an array,
438 // visitGlobalValue will complain on appending non-array.
439 if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
440 StructType *STy = dyn_cast<StructType>(ATy->getElementType());
441 PointerType *FuncPtrTy =
442 FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
443 Assert1(STy && STy->getNumElements() == 2 &&
444 STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
445 STy->getTypeAtIndex(1) == FuncPtrTy,
446 "wrong type for intrinsic global variable", &GV);
450 visitGlobalValue(GV);
453 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
454 Assert1(!GA.getName().empty(),
455 "Alias name cannot be empty!", &GA);
456 Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
458 "Alias should have external or external weak linkage!", &GA);
459 Assert1(GA.getAliasee(),
460 "Aliasee cannot be NULL!", &GA);
461 Assert1(GA.getType() == GA.getAliasee()->getType(),
462 "Alias and aliasee types should match!", &GA);
463 Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
465 if (!isa<GlobalValue>(GA.getAliasee())) {
466 const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
468 (CE->getOpcode() == Instruction::BitCast ||
469 CE->getOpcode() == Instruction::GetElementPtr) &&
470 isa<GlobalValue>(CE->getOperand(0)),
471 "Aliasee should be either GlobalValue or bitcast of GlobalValue",
475 const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
477 "Aliasing chain should end with function or global variable", &GA);
479 visitGlobalValue(GA);
482 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
483 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
484 MDNode *MD = NMD.getOperand(i);
488 Assert1(!MD->isFunctionLocal(),
489 "Named metadata operand cannot be function local!", MD);
494 void Verifier::visitMDNode(MDNode &MD, Function *F) {
495 // Only visit each node once. Metadata can be mutually recursive, so this
496 // avoids infinite recursion here, as well as being an optimization.
497 if (!MDNodes.insert(&MD))
500 for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
501 Value *Op = MD.getOperand(i);
504 if (isa<Constant>(Op) || isa<MDString>(Op))
506 if (MDNode *N = dyn_cast<MDNode>(Op)) {
507 Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
508 "Global metadata operand cannot be function local!", &MD, N);
512 Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
514 // If this was an instruction, bb, or argument, verify that it is in the
515 // function that we expect.
516 Function *ActualF = 0;
517 if (Instruction *I = dyn_cast<Instruction>(Op))
518 ActualF = I->getParent()->getParent();
519 else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
520 ActualF = BB->getParent();
521 else if (Argument *A = dyn_cast<Argument>(Op))
522 ActualF = A->getParent();
523 assert(ActualF && "Unimplemented function local metadata case!");
525 Assert2(ActualF == F, "function-local metadata used in wrong function",
530 // VerifyParameterAttrs - Check the given attributes for an argument or return
531 // value of the specified type. The value V is printed in error messages.
532 void Verifier::VerifyParameterAttrs(Attributes Attrs, Type *Ty,
533 bool isReturnValue, const Value *V) {
534 if (Attrs == Attribute::None)
537 Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
538 Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
539 " only applies to the function!", V);
542 Attributes RetI = Attrs & Attribute::ParameterOnly;
543 Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
544 " does not apply to return values!", V);
548 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
549 Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
550 Assert1(!(MutI & (MutI - 1)), "Attributes " +
551 Attribute::getAsString(MutI) + " are incompatible!", V);
554 Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
555 Assert1(!TypeI, "Wrong type for attribute " +
556 Attribute::getAsString(TypeI), V);
558 Attributes ByValI = Attrs & Attribute::ByVal;
559 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
560 Assert1(!ByValI || PTy->getElementType()->isSized(),
561 "Attribute " + Attribute::getAsString(ByValI) +
562 " does not support unsized types!", V);
565 "Attribute " + Attribute::getAsString(ByValI) +
566 " only applies to parameters with pointer type!", V);
570 // VerifyFunctionAttrs - Check parameter attributes against a function type.
571 // The value V is printed in error messages.
572 void Verifier::VerifyFunctionAttrs(FunctionType *FT,
573 const AttrListPtr &Attrs,
578 bool SawNest = false;
580 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
581 const AttributeWithIndex &Attr = Attrs.getSlot(i);
585 Ty = FT->getReturnType();
586 else if (Attr.Index-1 < FT->getNumParams())
587 Ty = FT->getParamType(Attr.Index-1);
589 break; // VarArgs attributes, verified elsewhere.
591 VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
593 if (Attr.Attrs & Attribute::Nest) {
594 Assert1(!SawNest, "More than one parameter has attribute nest!", V);
598 if (Attr.Attrs & Attribute::StructRet)
599 Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
602 Attributes FAttrs = Attrs.getFnAttributes();
603 Attributes NotFn = FAttrs & (~Attribute::FunctionOnly);
604 Assert1(!NotFn, "Attribute " + Attribute::getAsString(NotFn) +
605 " does not apply to the function!", V);
608 i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
609 Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
610 Assert1(!(MutI & (MutI - 1)), "Attributes " +
611 Attribute::getAsString(MutI) + " are incompatible!", V);
615 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
619 unsigned LastSlot = Attrs.getNumSlots() - 1;
620 unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
621 if (LastIndex <= Params
622 || (LastIndex == (unsigned)~0
623 && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))
629 // visitFunction - Verify that a function is ok.
631 void Verifier::visitFunction(Function &F) {
632 // Check function arguments.
633 FunctionType *FT = F.getFunctionType();
634 unsigned NumArgs = F.arg_size();
636 Assert1(Context == &F.getContext(),
637 "Function context does not match Module context!", &F);
639 Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
640 Assert2(FT->getNumParams() == NumArgs,
641 "# formal arguments must match # of arguments for function type!",
643 Assert1(F.getReturnType()->isFirstClassType() ||
644 F.getReturnType()->isVoidTy() ||
645 F.getReturnType()->isStructTy(),
646 "Functions cannot return aggregate values!", &F);
648 Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
649 "Invalid struct return type!", &F);
651 const AttrListPtr &Attrs = F.getAttributes();
653 Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
654 "Attributes after last parameter!", &F);
656 // Check function attributes.
657 VerifyFunctionAttrs(FT, Attrs, &F);
659 // Check that this function meets the restrictions on this calling convention.
660 switch (F.getCallingConv()) {
665 case CallingConv::Fast:
666 case CallingConv::Cold:
667 case CallingConv::X86_FastCall:
668 case CallingConv::X86_ThisCall:
669 case CallingConv::PTX_Kernel:
670 case CallingConv::PTX_Device:
671 Assert1(!F.isVarArg(),
672 "Varargs functions must have C calling conventions!", &F);
676 bool isLLVMdotName = F.getName().size() >= 5 &&
677 F.getName().substr(0, 5) == "llvm.";
679 // Check that the argument values match the function type for this function...
681 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
683 Assert2(I->getType() == FT->getParamType(i),
684 "Argument value does not match function argument type!",
685 I, FT->getParamType(i));
686 Assert1(I->getType()->isFirstClassType(),
687 "Function arguments must have first-class types!", I);
689 Assert2(!I->getType()->isMetadataTy(),
690 "Function takes metadata but isn't an intrinsic", I, &F);
693 if (F.isMaterializable()) {
694 // Function has a body somewhere we can't see.
695 } else if (F.isDeclaration()) {
696 Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
697 F.hasExternalWeakLinkage(),
698 "invalid linkage type for function declaration", &F);
700 // Verify that this function (which has a body) is not named "llvm.*". It
701 // is not legal to define intrinsics.
702 Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
704 // Check the entry node
705 BasicBlock *Entry = &F.getEntryBlock();
706 Assert1(pred_begin(Entry) == pred_end(Entry),
707 "Entry block to function must not have predecessors!", Entry);
709 // The address of the entry block cannot be taken, unless it is dead.
710 if (Entry->hasAddressTaken()) {
711 Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
712 "blockaddress may not be used with the entry block!", Entry);
716 // If this function is actually an intrinsic, verify that it is only used in
717 // direct call/invokes, never having its "address taken".
718 if (F.getIntrinsicID()) {
720 if (F.hasAddressTaken(&U))
721 Assert1(0, "Invalid user of intrinsic instruction!", U);
725 // verifyBasicBlock - Verify that a basic block is well formed...
727 void Verifier::visitBasicBlock(BasicBlock &BB) {
728 InstsInThisBlock.clear();
730 // Ensure that basic blocks have terminators!
731 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
733 // Check constraints that this basic block imposes on all of the PHI nodes in
735 if (isa<PHINode>(BB.front())) {
736 SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
737 SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
738 std::sort(Preds.begin(), Preds.end());
740 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
741 // Ensure that PHI nodes have at least one entry!
742 Assert1(PN->getNumIncomingValues() != 0,
743 "PHI nodes must have at least one entry. If the block is dead, "
744 "the PHI should be removed!", PN);
745 Assert1(PN->getNumIncomingValues() == Preds.size(),
746 "PHINode should have one entry for each predecessor of its "
747 "parent basic block!", PN);
749 // Get and sort all incoming values in the PHI node...
751 Values.reserve(PN->getNumIncomingValues());
752 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
753 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
754 PN->getIncomingValue(i)));
755 std::sort(Values.begin(), Values.end());
757 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
758 // Check to make sure that if there is more than one entry for a
759 // particular basic block in this PHI node, that the incoming values are
762 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
763 Values[i].second == Values[i-1].second,
764 "PHI node has multiple entries for the same basic block with "
765 "different incoming values!", PN, Values[i].first,
766 Values[i].second, Values[i-1].second);
768 // Check to make sure that the predecessors and PHI node entries are
770 Assert3(Values[i].first == Preds[i],
771 "PHI node entries do not match predecessors!", PN,
772 Values[i].first, Preds[i]);
778 void Verifier::visitTerminatorInst(TerminatorInst &I) {
779 // Ensure that terminators only exist at the end of the basic block.
780 Assert1(&I == I.getParent()->getTerminator(),
781 "Terminator found in the middle of a basic block!", I.getParent());
785 void Verifier::visitBranchInst(BranchInst &BI) {
786 if (BI.isConditional()) {
787 Assert2(BI.getCondition()->getType()->isIntegerTy(1),
788 "Branch condition is not 'i1' type!", &BI, BI.getCondition());
790 visitTerminatorInst(BI);
793 void Verifier::visitReturnInst(ReturnInst &RI) {
794 Function *F = RI.getParent()->getParent();
795 unsigned N = RI.getNumOperands();
796 if (F->getReturnType()->isVoidTy())
798 "Found return instr that returns non-void in Function of void "
799 "return type!", &RI, F->getReturnType());
801 Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
802 "Function return type does not match operand "
803 "type of return inst!", &RI, F->getReturnType());
805 // Check to make sure that the return value has necessary properties for
807 visitTerminatorInst(RI);
810 void Verifier::visitSwitchInst(SwitchInst &SI) {
811 // Check to make sure that all of the constants in the switch instruction
812 // have the same type as the switched-on value.
813 Type *SwitchTy = SI.getCondition()->getType();
814 SmallPtrSet<ConstantInt*, 32> Constants;
815 for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i) {
816 Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
817 "Switch constants must all be same type as switch value!", &SI);
818 Assert2(Constants.insert(SI.getCaseValue(i)),
819 "Duplicate integer as switch case", &SI, SI.getCaseValue(i));
822 visitTerminatorInst(SI);
825 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
826 Assert1(BI.getAddress()->getType()->isPointerTy(),
827 "Indirectbr operand must have pointer type!", &BI);
828 for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
829 Assert1(BI.getDestination(i)->getType()->isLabelTy(),
830 "Indirectbr destinations must all have pointer type!", &BI);
832 visitTerminatorInst(BI);
835 void Verifier::visitSelectInst(SelectInst &SI) {
836 Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
838 "Invalid operands for select instruction!", &SI);
840 Assert1(SI.getTrueValue()->getType() == SI.getType(),
841 "Select values must have same type as select instruction!", &SI);
842 visitInstruction(SI);
845 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
846 /// a pass, if any exist, it's an error.
848 void Verifier::visitUserOp1(Instruction &I) {
849 Assert1(0, "User-defined operators should not live outside of a pass!", &I);
852 void Verifier::visitTruncInst(TruncInst &I) {
853 // Get the source and destination types
854 Type *SrcTy = I.getOperand(0)->getType();
855 Type *DestTy = I.getType();
857 // Get the size of the types in bits, we'll need this later
858 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
859 unsigned DestBitSize = DestTy->getScalarSizeInBits();
861 Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
862 Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
863 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
864 "trunc source and destination must both be a vector or neither", &I);
865 Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
870 void Verifier::visitZExtInst(ZExtInst &I) {
871 // Get the source and destination types
872 Type *SrcTy = I.getOperand(0)->getType();
873 Type *DestTy = I.getType();
875 // Get the size of the types in bits, we'll need this later
876 Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
877 Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
878 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
879 "zext source and destination must both be a vector or neither", &I);
880 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
881 unsigned DestBitSize = DestTy->getScalarSizeInBits();
883 Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
888 void Verifier::visitSExtInst(SExtInst &I) {
889 // Get the source and destination types
890 Type *SrcTy = I.getOperand(0)->getType();
891 Type *DestTy = I.getType();
893 // Get the size of the types in bits, we'll need this later
894 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
895 unsigned DestBitSize = DestTy->getScalarSizeInBits();
897 Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
898 Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
899 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
900 "sext source and destination must both be a vector or neither", &I);
901 Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
906 void Verifier::visitFPTruncInst(FPTruncInst &I) {
907 // Get the source and destination types
908 Type *SrcTy = I.getOperand(0)->getType();
909 Type *DestTy = I.getType();
910 // Get the size of the types in bits, we'll need this later
911 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
912 unsigned DestBitSize = DestTy->getScalarSizeInBits();
914 Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
915 Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
916 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
917 "fptrunc source and destination must both be a vector or neither",&I);
918 Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
923 void Verifier::visitFPExtInst(FPExtInst &I) {
924 // Get the source and destination types
925 Type *SrcTy = I.getOperand(0)->getType();
926 Type *DestTy = I.getType();
928 // Get the size of the types in bits, we'll need this later
929 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
930 unsigned DestBitSize = DestTy->getScalarSizeInBits();
932 Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
933 Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
934 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
935 "fpext source and destination must both be a vector or neither", &I);
936 Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
941 void Verifier::visitUIToFPInst(UIToFPInst &I) {
942 // Get the source and destination types
943 Type *SrcTy = I.getOperand(0)->getType();
944 Type *DestTy = I.getType();
946 bool SrcVec = SrcTy->isVectorTy();
947 bool DstVec = DestTy->isVectorTy();
949 Assert1(SrcVec == DstVec,
950 "UIToFP source and dest must both be vector or scalar", &I);
951 Assert1(SrcTy->isIntOrIntVectorTy(),
952 "UIToFP source must be integer or integer vector", &I);
953 Assert1(DestTy->isFPOrFPVectorTy(),
954 "UIToFP result must be FP or FP vector", &I);
956 if (SrcVec && DstVec)
957 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
958 cast<VectorType>(DestTy)->getNumElements(),
959 "UIToFP source and dest vector length mismatch", &I);
964 void Verifier::visitSIToFPInst(SIToFPInst &I) {
965 // Get the source and destination types
966 Type *SrcTy = I.getOperand(0)->getType();
967 Type *DestTy = I.getType();
969 bool SrcVec = SrcTy->isVectorTy();
970 bool DstVec = DestTy->isVectorTy();
972 Assert1(SrcVec == DstVec,
973 "SIToFP source and dest must both be vector or scalar", &I);
974 Assert1(SrcTy->isIntOrIntVectorTy(),
975 "SIToFP source must be integer or integer vector", &I);
976 Assert1(DestTy->isFPOrFPVectorTy(),
977 "SIToFP result must be FP or FP vector", &I);
979 if (SrcVec && DstVec)
980 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
981 cast<VectorType>(DestTy)->getNumElements(),
982 "SIToFP source and dest vector length mismatch", &I);
987 void Verifier::visitFPToUIInst(FPToUIInst &I) {
988 // Get the source and destination types
989 Type *SrcTy = I.getOperand(0)->getType();
990 Type *DestTy = I.getType();
992 bool SrcVec = SrcTy->isVectorTy();
993 bool DstVec = DestTy->isVectorTy();
995 Assert1(SrcVec == DstVec,
996 "FPToUI source and dest must both be vector or scalar", &I);
997 Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
999 Assert1(DestTy->isIntOrIntVectorTy(),
1000 "FPToUI result must be integer or integer vector", &I);
1002 if (SrcVec && DstVec)
1003 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1004 cast<VectorType>(DestTy)->getNumElements(),
1005 "FPToUI source and dest vector length mismatch", &I);
1007 visitInstruction(I);
1010 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1011 // Get the source and destination types
1012 Type *SrcTy = I.getOperand(0)->getType();
1013 Type *DestTy = I.getType();
1015 bool SrcVec = SrcTy->isVectorTy();
1016 bool DstVec = DestTy->isVectorTy();
1018 Assert1(SrcVec == DstVec,
1019 "FPToSI source and dest must both be vector or scalar", &I);
1020 Assert1(SrcTy->isFPOrFPVectorTy(),
1021 "FPToSI source must be FP or FP vector", &I);
1022 Assert1(DestTy->isIntOrIntVectorTy(),
1023 "FPToSI result must be integer or integer vector", &I);
1025 if (SrcVec && DstVec)
1026 Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1027 cast<VectorType>(DestTy)->getNumElements(),
1028 "FPToSI source and dest vector length mismatch", &I);
1030 visitInstruction(I);
1033 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1034 // Get the source and destination types
1035 Type *SrcTy = I.getOperand(0)->getType();
1036 Type *DestTy = I.getType();
1038 Assert1(SrcTy->getScalarType()->isPointerTy(),
1039 "PtrToInt source must be pointer", &I);
1040 Assert1(DestTy->getScalarType()->isIntegerTy(),
1041 "PtrToInt result must be integral", &I);
1042 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1043 "PtrToInt type mismatch", &I);
1045 if (SrcTy->isVectorTy()) {
1046 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1047 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1048 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1049 "PtrToInt Vector width mismatch", &I);
1052 visitInstruction(I);
1055 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1056 // Get the source and destination types
1057 Type *SrcTy = I.getOperand(0)->getType();
1058 Type *DestTy = I.getType();
1060 Assert1(SrcTy->getScalarType()->isIntegerTy(),
1061 "IntToPtr source must be an integral", &I);
1062 Assert1(DestTy->getScalarType()->isPointerTy(),
1063 "IntToPtr result must be a pointer",&I);
1064 Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1065 "IntToPtr type mismatch", &I);
1066 if (SrcTy->isVectorTy()) {
1067 VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1068 VectorType *VDest = dyn_cast<VectorType>(DestTy);
1069 Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1070 "IntToPtr Vector width mismatch", &I);
1072 visitInstruction(I);
1075 void Verifier::visitBitCastInst(BitCastInst &I) {
1076 // Get the source and destination types
1077 Type *SrcTy = I.getOperand(0)->getType();
1078 Type *DestTy = I.getType();
1080 // Get the size of the types in bits, we'll need this later
1081 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1082 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1084 // BitCast implies a no-op cast of type only. No bits change.
1085 // However, you can't cast pointers to anything but pointers.
1086 Assert1(DestTy->isPointerTy() == DestTy->isPointerTy(),
1087 "Bitcast requires both operands to be pointer or neither", &I);
1088 Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1090 // Disallow aggregates.
1091 Assert1(!SrcTy->isAggregateType(),
1092 "Bitcast operand must not be aggregate", &I);
1093 Assert1(!DestTy->isAggregateType(),
1094 "Bitcast type must not be aggregate", &I);
1096 visitInstruction(I);
1099 /// visitPHINode - Ensure that a PHI node is well formed.
1101 void Verifier::visitPHINode(PHINode &PN) {
1102 // Ensure that the PHI nodes are all grouped together at the top of the block.
1103 // This can be tested by checking whether the instruction before this is
1104 // either nonexistent (because this is begin()) or is a PHI node. If not,
1105 // then there is some other instruction before a PHI.
1106 Assert2(&PN == &PN.getParent()->front() ||
1107 isa<PHINode>(--BasicBlock::iterator(&PN)),
1108 "PHI nodes not grouped at top of basic block!",
1109 &PN, PN.getParent());
1111 // Check that all of the values of the PHI node have the same type as the
1112 // result, and that the incoming blocks are really basic blocks.
1113 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1114 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1115 "PHI node operands are not the same type as the result!", &PN);
1118 // All other PHI node constraints are checked in the visitBasicBlock method.
1120 visitInstruction(PN);
1123 void Verifier::VerifyCallSite(CallSite CS) {
1124 Instruction *I = CS.getInstruction();
1126 Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1127 "Called function must be a pointer!", I);
1128 PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1130 Assert1(FPTy->getElementType()->isFunctionTy(),
1131 "Called function is not pointer to function type!", I);
1132 FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1134 // Verify that the correct number of arguments are being passed
1135 if (FTy->isVarArg())
1136 Assert1(CS.arg_size() >= FTy->getNumParams(),
1137 "Called function requires more parameters than were provided!",I);
1139 Assert1(CS.arg_size() == FTy->getNumParams(),
1140 "Incorrect number of arguments passed to called function!", I);
1142 // Verify that all arguments to the call match the function type.
1143 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1144 Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1145 "Call parameter type does not match function signature!",
1146 CS.getArgument(i), FTy->getParamType(i), I);
1148 const AttrListPtr &Attrs = CS.getAttributes();
1150 Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1151 "Attributes after last parameter!", I);
1153 // Verify call attributes.
1154 VerifyFunctionAttrs(FTy, Attrs, I);
1156 if (FTy->isVarArg())
1157 // Check attributes on the varargs part.
1158 for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1159 Attributes Attr = Attrs.getParamAttributes(Idx);
1161 VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1163 Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
1164 Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
1165 " cannot be used for vararg call arguments!", I);
1168 // Verify that there's no metadata unless it's a direct call to an intrinsic.
1169 if (CS.getCalledFunction() == 0 ||
1170 !CS.getCalledFunction()->getName().startswith("llvm.")) {
1171 for (FunctionType::param_iterator PI = FTy->param_begin(),
1172 PE = FTy->param_end(); PI != PE; ++PI)
1173 Assert1(!(*PI)->isMetadataTy(),
1174 "Function has metadata parameter but isn't an intrinsic", I);
1177 visitInstruction(*I);
1180 void Verifier::visitCallInst(CallInst &CI) {
1181 VerifyCallSite(&CI);
1183 if (Function *F = CI.getCalledFunction())
1184 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1185 visitIntrinsicFunctionCall(ID, CI);
1188 void Verifier::visitInvokeInst(InvokeInst &II) {
1189 VerifyCallSite(&II);
1191 // Verify that there is a landingpad instruction as the first non-PHI
1192 // instruction of the 'unwind' destination.
1193 Assert1(II.getUnwindDest()->isLandingPad(),
1194 "The unwind destination does not have a landingpad instruction!",&II);
1196 visitTerminatorInst(II);
1199 /// visitBinaryOperator - Check that both arguments to the binary operator are
1200 /// of the same type!
1202 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1203 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1204 "Both operands to a binary operator are not of the same type!", &B);
1206 switch (B.getOpcode()) {
1207 // Check that integer arithmetic operators are only used with
1208 // integral operands.
1209 case Instruction::Add:
1210 case Instruction::Sub:
1211 case Instruction::Mul:
1212 case Instruction::SDiv:
1213 case Instruction::UDiv:
1214 case Instruction::SRem:
1215 case Instruction::URem:
1216 Assert1(B.getType()->isIntOrIntVectorTy(),
1217 "Integer arithmetic operators only work with integral types!", &B);
1218 Assert1(B.getType() == B.getOperand(0)->getType(),
1219 "Integer arithmetic operators must have same type "
1220 "for operands and result!", &B);
1222 // Check that floating-point arithmetic operators are only used with
1223 // floating-point operands.
1224 case Instruction::FAdd:
1225 case Instruction::FSub:
1226 case Instruction::FMul:
1227 case Instruction::FDiv:
1228 case Instruction::FRem:
1229 Assert1(B.getType()->isFPOrFPVectorTy(),
1230 "Floating-point arithmetic operators only work with "
1231 "floating-point types!", &B);
1232 Assert1(B.getType() == B.getOperand(0)->getType(),
1233 "Floating-point arithmetic operators must have same type "
1234 "for operands and result!", &B);
1236 // Check that logical operators are only used with integral operands.
1237 case Instruction::And:
1238 case Instruction::Or:
1239 case Instruction::Xor:
1240 Assert1(B.getType()->isIntOrIntVectorTy(),
1241 "Logical operators only work with integral types!", &B);
1242 Assert1(B.getType() == B.getOperand(0)->getType(),
1243 "Logical operators must have same type for operands and result!",
1246 case Instruction::Shl:
1247 case Instruction::LShr:
1248 case Instruction::AShr:
1249 Assert1(B.getType()->isIntOrIntVectorTy(),
1250 "Shifts only work with integral types!", &B);
1251 Assert1(B.getType() == B.getOperand(0)->getType(),
1252 "Shift return type must be same as operands!", &B);
1255 llvm_unreachable("Unknown BinaryOperator opcode!");
1258 visitInstruction(B);
1261 void Verifier::visitICmpInst(ICmpInst &IC) {
1262 // Check that the operands are the same type
1263 Type *Op0Ty = IC.getOperand(0)->getType();
1264 Type *Op1Ty = IC.getOperand(1)->getType();
1265 Assert1(Op0Ty == Op1Ty,
1266 "Both operands to ICmp instruction are not of the same type!", &IC);
1267 // Check that the operands are the right type
1268 Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1269 "Invalid operand types for ICmp instruction", &IC);
1270 // Check that the predicate is valid.
1271 Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1272 IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1273 "Invalid predicate in ICmp instruction!", &IC);
1275 visitInstruction(IC);
1278 void Verifier::visitFCmpInst(FCmpInst &FC) {
1279 // Check that the operands are the same type
1280 Type *Op0Ty = FC.getOperand(0)->getType();
1281 Type *Op1Ty = FC.getOperand(1)->getType();
1282 Assert1(Op0Ty == Op1Ty,
1283 "Both operands to FCmp instruction are not of the same type!", &FC);
1284 // Check that the operands are the right type
1285 Assert1(Op0Ty->isFPOrFPVectorTy(),
1286 "Invalid operand types for FCmp instruction", &FC);
1287 // Check that the predicate is valid.
1288 Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1289 FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1290 "Invalid predicate in FCmp instruction!", &FC);
1292 visitInstruction(FC);
1295 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1296 Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1298 "Invalid extractelement operands!", &EI);
1299 visitInstruction(EI);
1302 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1303 Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1306 "Invalid insertelement operands!", &IE);
1307 visitInstruction(IE);
1310 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1311 Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1313 "Invalid shufflevector operands!", &SV);
1314 visitInstruction(SV);
1317 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1318 Type *TargetTy = GEP.getPointerOperandType();
1319 if (VectorType *VTy = dyn_cast<VectorType>(TargetTy))
1320 TargetTy = VTy->getElementType();
1322 Assert1(dyn_cast<PointerType>(TargetTy),
1323 "GEP base pointer is not a vector or a vector of pointers", &GEP);
1324 Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1325 "GEP into unsized type!", &GEP);
1327 SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1329 GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1330 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1332 if (GEP.getPointerOperandType()->isPointerTy()) {
1333 // Validate GEPs with scalar indices.
1334 Assert2(GEP.getType()->isPointerTy() &&
1335 cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1336 "GEP is not of right type for indices!", &GEP, ElTy);
1338 // Validate GEPs with a vector index.
1339 Assert1(Idxs.size() == 1, "Invalid number of indices!", &GEP);
1340 Value *Index = Idxs[0];
1341 Type *IndexTy = Index->getType();
1342 Assert1(IndexTy->isVectorTy(),
1343 "Vector GEP must have vector indices!", &GEP);
1344 Assert1(GEP.getType()->isVectorTy(),
1345 "Vector GEP must return a vector value", &GEP);
1346 Type *ElemPtr = cast<VectorType>(GEP.getType())->getElementType();
1347 Assert1(ElemPtr->isPointerTy(),
1348 "Vector GEP pointer operand is not a pointer!", &GEP);
1349 unsigned IndexWidth = cast<VectorType>(IndexTy)->getNumElements();
1350 unsigned GepWidth = cast<VectorType>(GEP.getType())->getNumElements();
1351 Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1352 Assert1(ElTy == cast<PointerType>(ElemPtr)->getElementType(),
1353 "Vector GEP type does not match pointer type!", &GEP);
1355 visitInstruction(GEP);
1358 void Verifier::visitLoadInst(LoadInst &LI) {
1359 PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1360 Assert1(PTy, "Load operand must be a pointer.", &LI);
1361 Type *ElTy = PTy->getElementType();
1362 Assert2(ElTy == LI.getType(),
1363 "Load result type does not match pointer operand type!", &LI, ElTy);
1364 if (LI.isAtomic()) {
1365 Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1366 "Load cannot have Release ordering", &LI);
1367 Assert1(LI.getAlignment() != 0,
1368 "Atomic load must specify explicit alignment", &LI);
1370 Assert1(LI.getSynchScope() == CrossThread,
1371 "Non-atomic load cannot have SynchronizationScope specified", &LI);
1373 visitInstruction(LI);
1376 void Verifier::visitStoreInst(StoreInst &SI) {
1377 PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1378 Assert1(PTy, "Store operand must be a pointer.", &SI);
1379 Type *ElTy = PTy->getElementType();
1380 Assert2(ElTy == SI.getOperand(0)->getType(),
1381 "Stored value type does not match pointer operand type!",
1383 if (SI.isAtomic()) {
1384 Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1385 "Store cannot have Acquire ordering", &SI);
1386 Assert1(SI.getAlignment() != 0,
1387 "Atomic store must specify explicit alignment", &SI);
1389 Assert1(SI.getSynchScope() == CrossThread,
1390 "Non-atomic store cannot have SynchronizationScope specified", &SI);
1392 visitInstruction(SI);
1395 void Verifier::visitAllocaInst(AllocaInst &AI) {
1396 PointerType *PTy = AI.getType();
1397 Assert1(PTy->getAddressSpace() == 0,
1398 "Allocation instruction pointer not in the generic address space!",
1400 Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1402 Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1403 "Alloca array size must have integer type", &AI);
1404 visitInstruction(AI);
1407 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1408 Assert1(CXI.getOrdering() != NotAtomic,
1409 "cmpxchg instructions must be atomic.", &CXI);
1410 Assert1(CXI.getOrdering() != Unordered,
1411 "cmpxchg instructions cannot be unordered.", &CXI);
1412 PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1413 Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1414 Type *ElTy = PTy->getElementType();
1415 Assert2(ElTy == CXI.getOperand(1)->getType(),
1416 "Expected value type does not match pointer operand type!",
1418 Assert2(ElTy == CXI.getOperand(2)->getType(),
1419 "Stored value type does not match pointer operand type!",
1421 visitInstruction(CXI);
1424 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1425 Assert1(RMWI.getOrdering() != NotAtomic,
1426 "atomicrmw instructions must be atomic.", &RMWI);
1427 Assert1(RMWI.getOrdering() != Unordered,
1428 "atomicrmw instructions cannot be unordered.", &RMWI);
1429 PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1430 Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1431 Type *ElTy = PTy->getElementType();
1432 Assert2(ElTy == RMWI.getOperand(1)->getType(),
1433 "Argument value type does not match pointer operand type!",
1435 Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1436 RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1437 "Invalid binary operation!", &RMWI);
1438 visitInstruction(RMWI);
1441 void Verifier::visitFenceInst(FenceInst &FI) {
1442 const AtomicOrdering Ordering = FI.getOrdering();
1443 Assert1(Ordering == Acquire || Ordering == Release ||
1444 Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1445 "fence instructions may only have "
1446 "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1447 visitInstruction(FI);
1450 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1451 Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1452 EVI.getIndices()) ==
1454 "Invalid ExtractValueInst operands!", &EVI);
1456 visitInstruction(EVI);
1459 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1460 Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1461 IVI.getIndices()) ==
1462 IVI.getOperand(1)->getType(),
1463 "Invalid InsertValueInst operands!", &IVI);
1465 visitInstruction(IVI);
1468 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1469 BasicBlock *BB = LPI.getParent();
1471 // The landingpad instruction is ill-formed if it doesn't have any clauses and
1473 Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1474 "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1476 // The landingpad instruction defines its parent as a landing pad block. The
1477 // landing pad block may be branched to only by the unwind edge of an invoke.
1478 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1479 const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1480 Assert1(II && II->getUnwindDest() == BB,
1481 "Block containing LandingPadInst must be jumped to "
1482 "only by the unwind edge of an invoke.", &LPI);
1485 // The landingpad instruction must be the first non-PHI instruction in the
1487 Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1488 "LandingPadInst not the first non-PHI instruction in the block.",
1491 // The personality functions for all landingpad instructions within the same
1492 // function should match.
1494 Assert1(LPI.getPersonalityFn() == PersonalityFn,
1495 "Personality function doesn't match others in function", &LPI);
1496 PersonalityFn = LPI.getPersonalityFn();
1498 // All operands must be constants.
1499 Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1501 for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1502 Value *Clause = LPI.getClause(i);
1503 Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1504 if (LPI.isCatch(i)) {
1505 Assert1(isa<PointerType>(Clause->getType()),
1506 "Catch operand does not have pointer type!", &LPI);
1508 Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1509 Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1510 "Filter operand is not an array of constants!", &LPI);
1514 visitInstruction(LPI);
1517 /// verifyInstruction - Verify that an instruction is well formed.
1519 void Verifier::visitInstruction(Instruction &I) {
1520 BasicBlock *BB = I.getParent();
1521 Assert1(BB, "Instruction not embedded in basic block!", &I);
1523 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
1524 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1526 Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1527 "Only PHI nodes may reference their own value!", &I);
1530 // Check that void typed values don't have names
1531 Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1532 "Instruction has a name, but provides a void value!", &I);
1534 // Check that the return value of the instruction is either void or a legal
1536 Assert1(I.getType()->isVoidTy() ||
1537 I.getType()->isFirstClassType(),
1538 "Instruction returns a non-scalar type!", &I);
1540 // Check that the instruction doesn't produce metadata. Calls are already
1541 // checked against the callee type.
1542 Assert1(!I.getType()->isMetadataTy() ||
1543 isa<CallInst>(I) || isa<InvokeInst>(I),
1544 "Invalid use of metadata!", &I);
1546 // Check that all uses of the instruction, if they are instructions
1547 // themselves, actually have parent basic blocks. If the use is not an
1548 // instruction, it is an error!
1549 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1551 if (Instruction *Used = dyn_cast<Instruction>(*UI))
1552 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1553 " embedded in a basic block!", &I, Used);
1555 CheckFailed("Use of instruction is not an instruction!", *UI);
1560 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1561 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1563 // Check to make sure that only first-class-values are operands to
1565 if (!I.getOperand(i)->getType()->isFirstClassType()) {
1566 Assert1(0, "Instruction operands must be first-class values!", &I);
1569 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1570 // Check to make sure that the "address of" an intrinsic function is never
1572 Assert1(!F->isIntrinsic() || (i + 1 == e && isa<CallInst>(I)),
1573 "Cannot take the address of an intrinsic!", &I);
1574 Assert1(F->getParent() == Mod, "Referencing function in another module!",
1576 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1577 Assert1(OpBB->getParent() == BB->getParent(),
1578 "Referring to a basic block in another function!", &I);
1579 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1580 Assert1(OpArg->getParent() == BB->getParent(),
1581 "Referring to an argument in another function!", &I);
1582 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1583 Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1585 } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1586 BasicBlock *OpBlock = Op->getParent();
1588 // Check that a definition dominates all of its uses.
1589 if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1590 // Invoke results are only usable in the normal destination, not in the
1591 // exceptional destination.
1592 BasicBlock *NormalDest = II->getNormalDest();
1594 Assert2(NormalDest != II->getUnwindDest(),
1595 "No uses of invoke possible due to dominance structure!",
1598 // PHI nodes differ from other nodes because they actually "use" the
1599 // value in the predecessor basic blocks they correspond to.
1600 BasicBlock *UseBlock = BB;
1601 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
1602 unsigned j = PHINode::getIncomingValueNumForOperand(i);
1603 UseBlock = PN->getIncomingBlock(j);
1605 Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB",
1608 if (isa<PHINode>(I) && UseBlock == OpBlock) {
1609 // Special case of a phi node in the normal destination or the unwind
1611 Assert2(BB == NormalDest || !DT->isReachableFromEntry(UseBlock),
1612 "Invoke result not available in the unwind destination!",
1615 Assert2(DT->dominates(NormalDest, UseBlock) ||
1616 !DT->isReachableFromEntry(UseBlock),
1617 "Invoke result does not dominate all uses!", Op, &I);
1619 // If the normal successor of an invoke instruction has multiple
1620 // predecessors, then the normal edge from the invoke is critical,
1621 // so the invoke value can only be live if the destination block
1622 // dominates all of it's predecessors (other than the invoke).
1623 if (!NormalDest->getSinglePredecessor() &&
1624 DT->isReachableFromEntry(UseBlock))
1625 // If it is used by something non-phi, then the other case is that
1626 // 'NormalDest' dominates all of its predecessors other than the
1627 // invoke. In this case, the invoke value can still be used.
1628 for (pred_iterator PI = pred_begin(NormalDest),
1629 E = pred_end(NormalDest); PI != E; ++PI)
1630 if (*PI != II->getParent() && !DT->dominates(NormalDest, *PI) &&
1631 DT->isReachableFromEntry(*PI)) {
1632 CheckFailed("Invoke result does not dominate all uses!", Op,&I);
1636 } else if (PHINode *PN = dyn_cast<PHINode>(&I)) {
1637 // PHI nodes are more difficult than other nodes because they actually
1638 // "use" the value in the predecessor basic blocks they correspond to.
1639 unsigned j = PHINode::getIncomingValueNumForOperand(i);
1640 BasicBlock *PredBB = PN->getIncomingBlock(j);
1641 Assert2(PredBB && (DT->dominates(OpBlock, PredBB) ||
1642 !DT->isReachableFromEntry(PredBB)),
1643 "Instruction does not dominate all uses!", Op, &I);
1645 if (OpBlock == BB) {
1646 // If they are in the same basic block, make sure that the definition
1647 // comes before the use.
1648 Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB),
1649 "Instruction does not dominate all uses!", Op, &I);
1652 // Definition must dominate use unless use is unreachable!
1653 Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1654 !DT->isReachableFromEntry(BB),
1655 "Instruction does not dominate all uses!", Op, &I);
1657 } else if (isa<InlineAsm>(I.getOperand(i))) {
1658 Assert1((i + 1 == e && isa<CallInst>(I)) ||
1659 (i + 3 == e && isa<InvokeInst>(I)),
1660 "Cannot take the address of an inline asm!", &I);
1663 InstsInThisBlock.insert(&I);
1666 // Flags used by TableGen to mark intrinsic parameters with the
1667 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
1668 static const unsigned ExtendedElementVectorType = 0x40000000;
1669 static const unsigned TruncatedElementVectorType = 0x20000000;
1671 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1673 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1674 Function *IF = CI.getCalledFunction();
1675 Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1678 #define GET_INTRINSIC_VERIFIER
1679 #include "llvm/Intrinsics.gen"
1680 #undef GET_INTRINSIC_VERIFIER
1682 // If the intrinsic takes MDNode arguments, verify that they are either global
1683 // or are local to *this* function.
1684 for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
1685 if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
1686 visitMDNode(*MD, CI.getParent()->getParent());
1691 case Intrinsic::ctlz: // llvm.ctlz
1692 case Intrinsic::cttz: // llvm.cttz
1693 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1694 "is_zero_undef argument of bit counting intrinsics must be a "
1695 "constant int", &CI);
1697 case Intrinsic::dbg_declare: { // llvm.dbg.declare
1698 Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
1699 "invalid llvm.dbg.declare intrinsic call 1", &CI);
1700 MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
1701 Assert1(MD->getNumOperands() == 1,
1702 "invalid llvm.dbg.declare intrinsic call 2", &CI);
1704 case Intrinsic::memcpy:
1705 case Intrinsic::memmove:
1706 case Intrinsic::memset:
1707 Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
1708 "alignment argument of memory intrinsics must be a constant int",
1710 Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
1711 "isvolatile argument of memory intrinsics must be a constant int",
1714 case Intrinsic::gcroot:
1715 case Intrinsic::gcwrite:
1716 case Intrinsic::gcread:
1717 if (ID == Intrinsic::gcroot) {
1719 dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
1720 Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
1721 Assert1(isa<Constant>(CI.getArgOperand(1)),
1722 "llvm.gcroot parameter #2 must be a constant.", &CI);
1723 if (!AI->getType()->getElementType()->isPointerTy()) {
1724 Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
1725 "llvm.gcroot parameter #1 must either be a pointer alloca, "
1726 "or argument #2 must be a non-null constant.", &CI);
1730 Assert1(CI.getParent()->getParent()->hasGC(),
1731 "Enclosing function does not use GC.", &CI);
1733 case Intrinsic::init_trampoline:
1734 Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
1735 "llvm.init_trampoline parameter #2 must resolve to a function.",
1738 case Intrinsic::prefetch:
1739 Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
1740 isa<ConstantInt>(CI.getArgOperand(2)) &&
1741 cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
1742 cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
1743 "invalid arguments to llvm.prefetch",
1746 case Intrinsic::stackprotector:
1747 Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
1748 "llvm.stackprotector parameter #2 must resolve to an alloca.",
1751 case Intrinsic::lifetime_start:
1752 case Intrinsic::lifetime_end:
1753 case Intrinsic::invariant_start:
1754 Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
1755 "size argument of memory use markers must be a constant integer",
1758 case Intrinsic::invariant_end:
1759 Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1760 "llvm.invariant.end parameter #2 must be a constant integer", &CI);
1765 /// Produce a string to identify an intrinsic parameter or return value.
1766 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the
1767 /// parameters beginning with NumRets.
1769 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
1770 if (ArgNo >= NumRets)
1771 return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
1773 return "Intrinsic result type";
1774 return "Intrinsic result type #" + utostr(ArgNo);
1777 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
1778 int VT, unsigned ArgNo, std::string &Suffix) {
1779 FunctionType *FTy = F->getFunctionType();
1781 unsigned NumElts = 0;
1783 VectorType *VTy = dyn_cast<VectorType>(Ty);
1785 EltTy = VTy->getElementType();
1786 NumElts = VTy->getNumElements();
1789 Type *RetTy = FTy->getReturnType();
1790 StructType *ST = dyn_cast<StructType>(RetTy);
1791 unsigned NumRetVals;
1792 if (RetTy->isVoidTy())
1795 NumRetVals = ST->getNumElements();
1802 // Check flags that indicate a type that is an integral vector type with
1803 // elements that are larger or smaller than the elements of the matched
1805 if ((Match & (ExtendedElementVectorType |
1806 TruncatedElementVectorType)) != 0) {
1807 IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
1808 if (!VTy || !IEltTy) {
1809 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1810 "an integral vector type.", F);
1813 // Adjust the current Ty (in the opposite direction) rather than
1814 // the type being matched against.
1815 if ((Match & ExtendedElementVectorType) != 0) {
1816 if ((IEltTy->getBitWidth() & 1) != 0) {
1817 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " vector "
1818 "element bit-width is odd.", F);
1821 Ty = VectorType::getTruncatedElementVectorType(VTy);
1823 Ty = VectorType::getExtendedElementVectorType(VTy);
1824 Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
1827 if (Match <= static_cast<int>(NumRetVals - 1)) {
1829 RetTy = ST->getElementType(Match);
1832 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1833 "match return type.", F);
1837 if (Ty != FTy->getParamType(Match - NumRetVals)) {
1838 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " does not "
1839 "match parameter %" + utostr(Match - NumRetVals) + ".", F);
1843 } else if (VT == MVT::iAny) {
1844 if (!EltTy->isIntegerTy()) {
1845 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1846 "an integer type.", F);
1850 unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1854 Suffix += "v" + utostr(NumElts);
1856 Suffix += "i" + utostr(GotBits);
1858 // Check some constraints on various intrinsics.
1860 default: break; // Not everything needs to be checked.
1861 case Intrinsic::bswap:
1862 if (GotBits < 16 || GotBits % 16 != 0) {
1863 CheckFailed("Intrinsic requires even byte width argument", F);
1868 } else if (VT == MVT::fAny) {
1869 if (!EltTy->isFloatingPointTy()) {
1870 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not "
1871 "a floating-point type.", F);
1878 Suffix += "v" + utostr(NumElts);
1880 Suffix += EVT::getEVT(EltTy).getEVTString();
1881 } else if (VT == MVT::vAny) {
1883 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a vector type.",
1887 Suffix += ".v" + utostr(NumElts) + EVT::getEVT(EltTy).getEVTString();
1888 } else if (VT == MVT::iPTR) {
1889 if (!Ty->isPointerTy()) {
1890 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1891 "pointer and a pointer is required.", F);
1894 } else if (VT == MVT::iPTRAny) {
1895 // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
1896 // and iPTR. In the verifier, we can not distinguish which case we have so
1897 // allow either case to be legal.
1898 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
1899 EVT PointeeVT = EVT::getEVT(PTyp->getElementType(), true);
1900 if (PointeeVT == MVT::Other) {
1901 CheckFailed("Intrinsic has pointer to complex type.");
1904 Suffix += ".p" + utostr(PTyp->getAddressSpace()) +
1905 PointeeVT.getEVTString();
1907 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is not a "
1908 "pointer and a pointer is required.", F);
1911 } else if (EVT((MVT::SimpleValueType)VT).isVector()) {
1912 EVT VVT = EVT((MVT::SimpleValueType)VT);
1914 // If this is a vector argument, verify the number and type of elements.
1915 if (VVT.getVectorElementType() != EVT::getEVT(EltTy)) {
1916 CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
1920 if (VVT.getVectorNumElements() != NumElts) {
1921 CheckFailed("Intrinsic prototype has incorrect number of "
1922 "vector elements!", F);
1925 } else if (EVT((MVT::SimpleValueType)VT).getTypeForEVT(Ty->getContext()) !=
1927 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is wrong!", F);
1929 } else if (EltTy != Ty) {
1930 CheckFailed(IntrinsicParam(ArgNo, NumRetVals) + " is a vector "
1931 "and a scalar is required.", F);
1938 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1939 /// Intrinsics.gen. This implements a little state machine that verifies the
1940 /// prototype of intrinsics.
1941 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
1942 unsigned NumRetVals,
1943 unsigned NumParams, ...) {
1945 va_start(VA, NumParams);
1946 FunctionType *FTy = F->getFunctionType();
1948 // For overloaded intrinsics, the Suffix of the function name must match the
1949 // types of the arguments. This variable keeps track of the expected
1950 // suffix, to be checked at the end.
1953 if (FTy->getNumParams() + FTy->isVarArg() != NumParams) {
1954 CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1958 Type *Ty = FTy->getReturnType();
1959 StructType *ST = dyn_cast<StructType>(Ty);
1961 if (NumRetVals == 0 && !Ty->isVoidTy()) {
1962 CheckFailed("Intrinsic should return void", F);
1966 // Verify the return types.
1967 if (ST && ST->getNumElements() != NumRetVals) {
1968 CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
1972 for (unsigned ArgNo = 0; ArgNo != NumRetVals; ++ArgNo) {
1973 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1975 if (ST) Ty = ST->getElementType(ArgNo);
1976 if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
1980 // Verify the parameter types.
1981 for (unsigned ArgNo = 0; ArgNo != NumParams; ++ArgNo) {
1982 int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1984 if (VT == MVT::isVoid && ArgNo > 0) {
1985 if (!FTy->isVarArg())
1986 CheckFailed("Intrinsic prototype has no '...'!", F);
1990 if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT,
1991 ArgNo + NumRetVals, Suffix))
1997 // For intrinsics without pointer arguments, if we computed a Suffix then the
1998 // intrinsic is overloaded and we need to make sure that the name of the
1999 // function is correct. We add the suffix to the name of the intrinsic and
2000 // compare against the given function name. If they are not the same, the
2001 // function name is invalid. This ensures that overloading of intrinsics
2002 // uses a sane and consistent naming convention. Note that intrinsics with
2003 // pointer argument may or may not be overloaded so we will check assuming it
2004 // has a suffix and not.
2005 if (!Suffix.empty()) {
2006 std::string Name(Intrinsic::getName(ID));
2007 if (Name + Suffix != F->getName()) {
2008 CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
2009 F->getName().substr(Name.length()) + "'. It should be '" +
2014 // Check parameter attributes.
2015 Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
2016 "Intrinsic has wrong parameter attributes!", F);
2020 //===----------------------------------------------------------------------===//
2021 // Implement the public interfaces to this file...
2022 //===----------------------------------------------------------------------===//
2024 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
2025 return new Verifier(action);
2029 /// verifyFunction - Check a function for errors, printing messages on stderr.
2030 /// Return true if the function is corrupt.
2032 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
2033 Function &F = const_cast<Function&>(f);
2034 assert(!F.isDeclaration() && "Cannot verify external functions");
2036 FunctionPassManager FPM(F.getParent());
2037 Verifier *V = new Verifier(action);
2043 /// verifyModule - Check a module for errors, printing messages on stderr.
2044 /// Return true if the module is corrupt.
2046 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
2047 std::string *ErrorInfo) {
2049 Verifier *V = new Verifier(action);
2051 PM.run(const_cast<Module&>(M));
2053 if (ErrorInfo && V->Broken)
2054 *ErrorInfo = V->MessagesStr.str();