1 //===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 int %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 // * All other things that are tested by asserts spread about the code...
40 //===----------------------------------------------------------------------===//
42 #include "llvm/Analysis/Verifier.h"
43 #include "llvm/Assembly/Writer.h"
44 #include "llvm/CallingConv.h"
45 #include "llvm/Constants.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Module.h"
48 #include "llvm/ModuleProvider.h"
49 #include "llvm/DerivedTypes.h"
50 #include "llvm/InlineAsm.h"
51 #include "llvm/Instructions.h"
52 #include "llvm/Intrinsics.h"
53 #include "llvm/PassManager.h"
54 #include "llvm/SymbolTable.h"
55 #include "llvm/Analysis/Dominators.h"
56 #include "llvm/Support/CFG.h"
57 #include "llvm/Support/InstVisitor.h"
58 #include "llvm/ADT/STLExtras.h"
64 namespace { // Anonymous namespace for class
66 struct Verifier : public FunctionPass, InstVisitor<Verifier> {
67 bool Broken; // Is this module found to be broken?
68 bool RealPass; // Are we not being run by a PassManager?
69 VerifierFailureAction action;
70 // What to do if verification fails.
71 Module *Mod; // Module we are verifying right now
72 ETForest *EF; // ET-Forest, caution can be null!
73 std::stringstream msgs; // A stringstream to collect messages
75 /// InstInThisBlock - when verifying a basic block, keep track of all of the
76 /// instructions we have seen so far. This allows us to do efficient
77 /// dominance checks for the case when an instruction has an operand that is
78 /// an instruction in the same block.
79 std::set<Instruction*> InstsInThisBlock;
82 : Broken(false), RealPass(true), action(AbortProcessAction),
83 EF(0), msgs( std::ios::app | std::ios::out ) {}
84 Verifier( VerifierFailureAction ctn )
85 : Broken(false), RealPass(true), action(ctn), EF(0),
86 msgs( std::ios::app | std::ios::out ) {}
88 : Broken(false), RealPass(true),
89 action( AB ? AbortProcessAction : PrintMessageAction), EF(0),
90 msgs( std::ios::app | std::ios::out ) {}
91 Verifier(ETForest &ef)
92 : Broken(false), RealPass(false), action(PrintMessageAction),
93 EF(&ef), msgs( std::ios::app | std::ios::out ) {}
96 bool doInitialization(Module &M) {
98 verifySymbolTable(M.getSymbolTable());
100 // If this is a real pass, in a pass manager, we must abort before
101 // returning back to the pass manager, or else the pass manager may try to
102 // run other passes on the broken module.
108 bool runOnFunction(Function &F) {
109 // Get dominator information if we are being run by PassManager
110 if (RealPass) EF = &getAnalysis<ETForest>();
112 InstsInThisBlock.clear();
114 // If this is a real pass, in a pass manager, we must abort before
115 // returning back to the pass manager, or else the pass manager may try to
116 // run other passes on the broken module.
123 bool doFinalization(Module &M) {
124 // Scan through, checking all of the external function's linkage now...
125 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
126 visitGlobalValue(*I);
128 // Check to make sure function prototypes are okay.
129 if (I->isExternal()) visitFunction(*I);
132 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
134 visitGlobalVariable(*I);
136 // If the module is broken, abort at this time.
141 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
142 AU.setPreservesAll();
144 AU.addRequired<ETForest>();
147 /// abortIfBroken - If the module is broken and we are supposed to abort on
148 /// this condition, do so.
150 void abortIfBroken() {
153 msgs << "Broken module found, ";
156 case AbortProcessAction:
157 msgs << "compilation aborted!\n";
158 std::cerr << msgs.str();
160 case ThrowExceptionAction:
161 msgs << "verification terminated.\n";
163 case PrintMessageAction:
164 msgs << "verification continues.\n";
165 std::cerr << msgs.str();
167 case ReturnStatusAction:
174 // Verification methods...
175 void verifySymbolTable(SymbolTable &ST);
176 void visitGlobalValue(GlobalValue &GV);
177 void visitGlobalVariable(GlobalVariable &GV);
178 void visitFunction(Function &F);
179 void visitBasicBlock(BasicBlock &BB);
180 void visitPHINode(PHINode &PN);
181 void visitBinaryOperator(BinaryOperator &B);
182 void visitShiftInst(ShiftInst &SI);
183 void visitExtractElementInst(ExtractElementInst &EI);
184 void visitInsertElementInst(InsertElementInst &EI);
185 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
186 void visitCallInst(CallInst &CI);
187 void visitGetElementPtrInst(GetElementPtrInst &GEP);
188 void visitLoadInst(LoadInst &LI);
189 void visitStoreInst(StoreInst &SI);
190 void visitInstruction(Instruction &I);
191 void visitTerminatorInst(TerminatorInst &I);
192 void visitReturnInst(ReturnInst &RI);
193 void visitSwitchInst(SwitchInst &SI);
194 void visitSelectInst(SelectInst &SI);
195 void visitUserOp1(Instruction &I);
196 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
197 void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
200 void WriteValue(const Value *V) {
202 if (isa<Instruction>(V)) {
205 WriteAsOperand (msgs, V, true, true, Mod);
210 void WriteType(const Type* T ) {
212 WriteTypeSymbolic(msgs, T, Mod );
216 // CheckFailed - A check failed, so print out the condition and the message
217 // that failed. This provides a nice place to put a breakpoint if you want
218 // to see why something is not correct.
219 void CheckFailed(const std::string &Message,
220 const Value *V1 = 0, const Value *V2 = 0,
221 const Value *V3 = 0, const Value *V4 = 0) {
222 msgs << Message << "\n";
230 void CheckFailed( const std::string& Message, const Value* V1,
231 const Type* T2, const Value* V3 = 0 ) {
232 msgs << Message << "\n";
240 RegisterOpt<Verifier> X("verify", "Module Verifier");
241 } // End anonymous namespace
244 // Assert - We know that cond should be true, if not print an error message.
245 #define Assert(C, M) \
246 do { if (!(C)) { CheckFailed(M); return; } } while (0)
247 #define Assert1(C, M, V1) \
248 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
249 #define Assert2(C, M, V1, V2) \
250 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
251 #define Assert3(C, M, V1, V2, V3) \
252 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
253 #define Assert4(C, M, V1, V2, V3, V4) \
254 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
257 void Verifier::visitGlobalValue(GlobalValue &GV) {
258 Assert1(!GV.isExternal() || GV.hasExternalLinkage(),
259 "Global is external, but doesn't have external linkage!", &GV);
260 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
261 "Only global variables can have appending linkage!", &GV);
263 if (GV.hasAppendingLinkage()) {
264 GlobalVariable &GVar = cast<GlobalVariable>(GV);
265 Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
266 "Only global arrays can have appending linkage!", &GV);
270 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
271 if (GV.hasInitializer())
272 Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
273 "Global variable initializer type does not match global "
274 "variable type!", &GV);
276 visitGlobalValue(GV);
280 // verifySymbolTable - Verify that a function or module symbol table is ok
282 void Verifier::verifySymbolTable(SymbolTable &ST) {
284 // Loop over all of the values in all type planes in the symbol table.
285 for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
286 PE = ST.plane_end(); PI != PE; ++PI)
287 for (SymbolTable::value_const_iterator VI = PI->second.begin(),
288 VE = PI->second.end(); VI != VE; ++VI) {
289 Value *V = VI->second;
290 // Check that there are no void typed values in the symbol table. Values
291 // with a void type cannot be put into symbol tables because they cannot
293 Assert1(V->getType() != Type::VoidTy,
294 "Values with void type are not allowed to have names!", V);
298 // visitFunction - Verify that a function is ok.
300 void Verifier::visitFunction(Function &F) {
301 Assert1(!F.isVarArg() || F.getCallingConv() == CallingConv::C,
302 "Varargs functions must have C calling conventions!", &F);
304 // Check function arguments.
305 const FunctionType *FT = F.getFunctionType();
306 unsigned NumArgs = F.getArgumentList().size();
308 Assert2(FT->getNumParams() == NumArgs,
309 "# formal arguments must match # of arguments for function type!",
311 Assert1(F.getReturnType()->isFirstClassType() ||
312 F.getReturnType() == Type::VoidTy,
313 "Functions cannot return aggregate values!", &F);
315 // Check that the argument values match the function type for this function...
317 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I, ++i) {
318 Assert2(I->getType() == FT->getParamType(i),
319 "Argument value does not match function argument type!",
320 I, FT->getParamType(i));
321 // Make sure no aggregates are passed by value.
322 Assert1(I->getType()->isFirstClassType(),
323 "Functions cannot take aggregates as arguments by value!", I);
326 if (!F.isExternal()) {
327 verifySymbolTable(F.getSymbolTable());
329 // Check the entry node
330 BasicBlock *Entry = &F.getEntryBlock();
331 Assert1(pred_begin(Entry) == pred_end(Entry),
332 "Entry block to function must not have predecessors!", Entry);
337 // verifyBasicBlock - Verify that a basic block is well formed...
339 void Verifier::visitBasicBlock(BasicBlock &BB) {
340 InstsInThisBlock.clear();
342 // Ensure that basic blocks have terminators!
343 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
345 // Check constraints that this basic block imposes on all of the PHI nodes in
347 if (isa<PHINode>(BB.front())) {
348 std::vector<BasicBlock*> Preds(pred_begin(&BB), pred_end(&BB));
349 std::sort(Preds.begin(), Preds.end());
351 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
353 // Ensure that PHI nodes have at least one entry!
354 Assert1(PN->getNumIncomingValues() != 0,
355 "PHI nodes must have at least one entry. If the block is dead, "
356 "the PHI should be removed!", PN);
357 Assert1(PN->getNumIncomingValues() == Preds.size(),
358 "PHINode should have one entry for each predecessor of its "
359 "parent basic block!", PN);
361 // Get and sort all incoming values in the PHI node...
362 std::vector<std::pair<BasicBlock*, Value*> > Values;
363 Values.reserve(PN->getNumIncomingValues());
364 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
365 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
366 PN->getIncomingValue(i)));
367 std::sort(Values.begin(), Values.end());
369 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
370 // Check to make sure that if there is more than one entry for a
371 // particular basic block in this PHI node, that the incoming values are
374 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
375 Values[i].second == Values[i-1].second,
376 "PHI node has multiple entries for the same basic block with "
377 "different incoming values!", PN, Values[i].first,
378 Values[i].second, Values[i-1].second);
380 // Check to make sure that the predecessors and PHI node entries are
382 Assert3(Values[i].first == Preds[i],
383 "PHI node entries do not match predecessors!", PN,
384 Values[i].first, Preds[i]);
390 void Verifier::visitTerminatorInst(TerminatorInst &I) {
391 // Ensure that terminators only exist at the end of the basic block.
392 Assert1(&I == I.getParent()->getTerminator(),
393 "Terminator found in the middle of a basic block!", I.getParent());
397 void Verifier::visitReturnInst(ReturnInst &RI) {
398 Function *F = RI.getParent()->getParent();
399 if (RI.getNumOperands() == 0)
400 Assert2(F->getReturnType() == Type::VoidTy,
401 "Found return instr that returns void in Function of non-void "
402 "return type!", &RI, F->getReturnType());
404 Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
405 "Function return type does not match operand "
406 "type of return inst!", &RI, F->getReturnType());
408 // Check to make sure that the return value has necessary properties for
410 visitTerminatorInst(RI);
413 void Verifier::visitSwitchInst(SwitchInst &SI) {
414 // Check to make sure that all of the constants in the switch instruction
415 // have the same type as the switched-on value.
416 const Type *SwitchTy = SI.getCondition()->getType();
417 for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
418 Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
419 "Switch constants must all be same type as switch value!", &SI);
421 visitTerminatorInst(SI);
424 void Verifier::visitSelectInst(SelectInst &SI) {
425 Assert1(SI.getCondition()->getType() == Type::BoolTy,
426 "Select condition type must be bool!", &SI);
427 Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
428 "Select values must have identical types!", &SI);
429 Assert1(SI.getTrueValue()->getType() == SI.getType(),
430 "Select values must have same type as select instruction!", &SI);
431 visitInstruction(SI);
435 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
436 /// a pass, if any exist, it's an error.
438 void Verifier::visitUserOp1(Instruction &I) {
439 Assert1(0, "User-defined operators should not live outside of a pass!",
443 /// visitPHINode - Ensure that a PHI node is well formed.
445 void Verifier::visitPHINode(PHINode &PN) {
446 // Ensure that the PHI nodes are all grouped together at the top of the block.
447 // This can be tested by checking whether the instruction before this is
448 // either nonexistent (because this is begin()) or is a PHI node. If not,
449 // then there is some other instruction before a PHI.
450 Assert2(&PN.getParent()->front() == &PN || isa<PHINode>(PN.getPrev()),
451 "PHI nodes not grouped at top of basic block!",
452 &PN, PN.getParent());
454 // Check that all of the operands of the PHI node have the same type as the
456 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
457 Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
458 "PHI node operands are not the same type as the result!", &PN);
460 // All other PHI node constraints are checked in the visitBasicBlock method.
462 visitInstruction(PN);
465 void Verifier::visitCallInst(CallInst &CI) {
466 Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
467 "Called function must be a pointer!", &CI);
468 const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
469 Assert1(isa<FunctionType>(FPTy->getElementType()),
470 "Called function is not pointer to function type!", &CI);
472 const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
474 // Verify that the correct number of arguments are being passed
476 Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
477 "Called function requires more parameters than were provided!",&CI);
479 Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
480 "Incorrect number of arguments passed to called function!", &CI);
482 // Verify that all arguments to the call match the function type...
483 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
484 Assert3(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
485 "Call parameter type does not match function signature!",
486 CI.getOperand(i+1), FTy->getParamType(i), &CI);
488 if (Function *F = CI.getCalledFunction())
489 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
490 visitIntrinsicFunctionCall(ID, CI);
492 visitInstruction(CI);
495 /// visitBinaryOperator - Check that both arguments to the binary operator are
496 /// of the same type!
498 void Verifier::visitBinaryOperator(BinaryOperator &B) {
499 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
500 "Both operands to a binary operator are not of the same type!", &B);
502 // Check that logical operators are only used with integral operands.
503 if (B.getOpcode() == Instruction::And || B.getOpcode() == Instruction::Or ||
504 B.getOpcode() == Instruction::Xor) {
505 Assert1(B.getType()->isIntegral() ||
506 (isa<PackedType>(B.getType()) &&
507 cast<PackedType>(B.getType())->getElementType()->isIntegral()),
508 "Logical operators only work with integral types!", &B);
509 Assert1(B.getType() == B.getOperand(0)->getType(),
510 "Logical operators must have same type for operands and result!",
512 } else if (isa<SetCondInst>(B)) {
513 // Check that setcc instructions return bool
514 Assert1(B.getType() == Type::BoolTy,
515 "setcc instructions must return boolean values!", &B);
517 // Arithmetic operators only work on integer or fp values
518 Assert1(B.getType() == B.getOperand(0)->getType(),
519 "Arithmetic operators must have same type for operands and result!",
521 Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
522 isa<PackedType>(B.getType()),
523 "Arithmetic operators must have integer, fp, or packed type!", &B);
529 void Verifier::visitShiftInst(ShiftInst &SI) {
530 Assert1(SI.getType()->isInteger(),
531 "Shift must return an integer result!", &SI);
532 Assert1(SI.getType() == SI.getOperand(0)->getType(),
533 "Shift return type must be same as first operand!", &SI);
534 Assert1(SI.getOperand(1)->getType() == Type::UByteTy,
535 "Second operand to shift must be ubyte type!", &SI);
536 visitInstruction(SI);
539 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
540 Assert1(isa<PackedType>(EI.getOperand(0)->getType()),
541 "First operand to extractelement must be packed type!", &EI);
542 Assert1(EI.getOperand(1)->getType() == Type::UIntTy,
543 "Second operand to extractelement must be uint type!", &EI);
544 Assert1(EI.getType() ==
545 cast<PackedType>(EI.getOperand(0)->getType())->getElementType(),
546 "Extractelement return type must match "
547 "first operand element type!", &EI);
548 visitInstruction(EI);
551 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
552 Assert1(isa<PackedType>(IE.getOperand(0)->getType()),
553 "First operand to insertelement must be packed type!", &IE);
554 Assert1(IE.getOperand(1)->getType() ==
555 cast<PackedType>(IE.getOperand(0)->getType())->getElementType(),
556 "Second operand to insertelement must match "
557 "first operand element type!", &IE);
558 Assert1(IE.getOperand(2)->getType() == Type::UIntTy,
559 "Third operand to insertelement must be uint type!", &IE);
560 visitInstruction(IE);
563 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
565 GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
566 std::vector<Value*>(GEP.idx_begin(), GEP.idx_end()), true);
567 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
568 Assert2(PointerType::get(ElTy) == GEP.getType(),
569 "GEP is not of right type for indices!", &GEP, ElTy);
570 visitInstruction(GEP);
573 void Verifier::visitLoadInst(LoadInst &LI) {
575 cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
576 Assert2(ElTy == LI.getType(),
577 "Load result type does not match pointer operand type!", &LI, ElTy);
578 visitInstruction(LI);
581 void Verifier::visitStoreInst(StoreInst &SI) {
583 cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
584 Assert2(ElTy == SI.getOperand(0)->getType(),
585 "Stored value type does not match pointer operand type!", &SI, ElTy);
586 visitInstruction(SI);
590 /// verifyInstruction - Verify that an instruction is well formed.
592 void Verifier::visitInstruction(Instruction &I) {
593 BasicBlock *BB = I.getParent();
594 Assert1(BB, "Instruction not embedded in basic block!", &I);
596 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
597 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
599 Assert1(*UI != (User*)&I ||
600 !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
601 "Only PHI nodes may reference their own value!", &I);
604 // Check that void typed values don't have names
605 Assert1(I.getType() != Type::VoidTy || !I.hasName(),
606 "Instruction has a name, but provides a void value!", &I);
608 // Check that the return value of the instruction is either void or a legal
610 Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType(),
611 "Instruction returns a non-scalar type!", &I);
613 // Check that all uses of the instruction, if they are instructions
614 // themselves, actually have parent basic blocks. If the use is not an
615 // instruction, it is an error!
616 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
618 Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
620 Instruction *Used = cast<Instruction>(*UI);
621 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
622 " embeded in a basic block!", &I, Used);
625 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
626 // Check to make sure that the "address of" an intrinsic function is never
628 Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
629 if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
630 Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
631 "Cannot take the address of an intrinsic!", &I);
632 } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
633 Assert1(OpBB->getParent() == BB->getParent(),
634 "Referring to a basic block in another function!", &I);
635 } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
636 Assert1(OpArg->getParent() == BB->getParent(),
637 "Referring to an argument in another function!", &I);
638 } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
639 BasicBlock *OpBlock = Op->getParent();
641 // Check that a definition dominates all of its uses.
642 if (!isa<PHINode>(I)) {
643 // Invoke results are only usable in the normal destination, not in the
644 // exceptional destination.
645 if (InvokeInst *II = dyn_cast<InvokeInst>(Op))
646 OpBlock = II->getNormalDest();
647 else if (OpBlock == BB) {
648 // If they are in the same basic block, make sure that the definition
649 // comes before the use.
650 Assert2(InstsInThisBlock.count(Op) ||
651 !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
652 "Instruction does not dominate all uses!", Op, &I);
655 // Definition must dominate use unless use is unreachable!
656 Assert2(EF->dominates(OpBlock, BB) ||
657 !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
658 "Instruction does not dominate all uses!", Op, &I);
660 // PHI nodes are more difficult than other nodes because they actually
661 // "use" the value in the predecessor basic blocks they correspond to.
662 BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
663 Assert2(EF->dominates(OpBlock, PredBB) ||
664 !EF->dominates(&BB->getParent()->getEntryBlock(), PredBB),
665 "Instruction does not dominate all uses!", Op, &I);
667 } else if (isa<InlineAsm>(I.getOperand(i))) {
668 Assert1(i == 0 && isa<CallInst>(I),
669 "Cannot take the address of an inline asm!", &I);
672 InstsInThisBlock.insert(&I);
675 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
677 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
678 Function *IF = CI.getCalledFunction();
679 const FunctionType *FT = IF->getFunctionType();
680 Assert1(IF->isExternal(), "Intrinsic functions should never be defined!", IF);
681 unsigned NumArgs = 0;
683 // FIXME: this should check the return type of each intrinsic as well, also
686 case Intrinsic::vastart:
687 Assert1(CI.getParent()->getParent()->getFunctionType()->isVarArg(),
688 "llvm.va_start intrinsic may only occur in function with variable"
692 case Intrinsic::vaend: NumArgs = 1; break;
693 case Intrinsic::vacopy: NumArgs = 2; break;
695 case Intrinsic::returnaddress:
696 case Intrinsic::frameaddress:
697 Assert1(isa<PointerType>(FT->getReturnType()),
698 "llvm.(frame|return)address must return pointers", IF);
699 Assert1(FT->getNumParams() == 1 && isa<ConstantInt>(CI.getOperand(1)),
700 "llvm.(frame|return)address require a single constant integer argument",
705 // Verify that read and write port have integral parameters of the correct
707 case Intrinsic::writeport:
708 Assert1(FT->getNumParams() == 2,
709 "Illegal # arguments for intrinsic function!", IF);
710 Assert1(FT->getParamType(0)->isIntegral(),
711 "First argument not unsigned int!", IF);
712 Assert1(FT->getParamType(1)->isUnsigned(),
713 "First argument not unsigned int!", IF);
717 case Intrinsic::writeio:
718 Assert1(FT->getNumParams() == 2,
719 "Illegal # arguments for intrinsic function!", IF);
720 Assert1(FT->getParamType(0)->isFirstClassType(),
721 "First argument not a first class type!", IF);
722 Assert1(isa<PointerType>(FT->getParamType(1)),
723 "Second argument not a pointer!", IF);
727 case Intrinsic::readport:
728 Assert1(FT->getNumParams() == 1,
729 "Illegal # arguments for intrinsic function!", IF);
730 Assert1(FT->getReturnType()->isFirstClassType(),
731 "Return type is not a first class type!", IF);
732 Assert1(FT->getParamType(0)->isUnsigned(),
733 "First argument not unsigned int!", IF);
737 case Intrinsic::readio: {
738 const PointerType *ParamType = dyn_cast<PointerType>(FT->getParamType(0));
739 const Type *ReturnType = FT->getReturnType();
741 Assert1(FT->getNumParams() == 1,
742 "Illegal # arguments for intrinsic function!", IF);
743 Assert1(ParamType, "First argument not a pointer!", IF);
744 Assert1(ParamType->getElementType() == ReturnType,
745 "Pointer type doesn't match return type!", IF);
750 case Intrinsic::isunordered_f32:
751 Assert1(FT->getNumParams() == 2,
752 "Illegal # arguments for intrinsic function!", IF);
753 Assert1(FT->getReturnType() == Type::BoolTy,
754 "Return type is not bool!", IF);
755 Assert1(FT->getParamType(0) == FT->getParamType(1),
756 "Arguments must be of the same type!", IF);
757 Assert1(FT->getParamType(0) == Type::FloatTy,
758 "Arguments must be a 32-bit floating point type!", IF);
762 case Intrinsic::isunordered_f64:
763 Assert1(FT->getNumParams() == 2,
764 "Illegal # arguments for intrinsic function!", IF);
765 Assert1(FT->getReturnType() == Type::BoolTy,
766 "Return type is not bool!", IF);
767 Assert1(FT->getParamType(0) == FT->getParamType(1),
768 "Arguments must be of the same type!", IF);
769 Assert1(FT->getParamType(0) == Type::DoubleTy,
770 "Argument is not a 64-bit floating point type!", IF);
774 case Intrinsic::readcyclecounter:
775 Assert1(FT->getNumParams() == 0,
776 "Illegal # arguments for intrinsic function!", IF);
777 Assert1(FT->getReturnType() == Type::ULongTy,
778 "Return type is not ulong!", IF);
782 case Intrinsic::bswap_i16:
783 Assert1(FT->getNumParams() == 1,
784 "Illegal # arguments for intrinsic function!", IF);
785 Assert1(FT->getReturnType() == FT->getParamType(0),
786 "Return type does not match source type", IF);
787 Assert1(FT->getReturnType() == Type::UShortTy,
788 "Return type is not ushort!", IF);
792 case Intrinsic::bswap_i32:
793 Assert1(FT->getNumParams() == 1,
794 "Illegal # arguments for intrinsic function!", IF);
795 Assert1(FT->getReturnType() == FT->getParamType(0),
796 "Return type does not match source type", IF);
797 Assert1(FT->getReturnType() == Type::UIntTy,
798 "Return type is not uint!", IF);
802 case Intrinsic::bswap_i64:
803 Assert1(FT->getNumParams() == 1,
804 "Illegal # arguments for intrinsic function!", IF);
805 Assert1(FT->getReturnType() == FT->getParamType(0),
806 "Return type does not match source type", IF);
807 Assert1(FT->getReturnType() == Type::ULongTy,
808 "Return type is not ulong!", IF);
812 case Intrinsic::ctpop_i8:
813 Assert1(FT->getNumParams() == 1,
814 "Illegal # arguments for intrinsic function!", IF);
815 Assert1(FT->getReturnType() == FT->getParamType(0),
816 "Return type does not match source type", IF);
817 Assert1(FT->getParamType(0) == Type::UByteTy,
818 "Argument is not ubyte!", IF);
822 case Intrinsic::ctpop_i16:
823 Assert1(FT->getNumParams() == 1,
824 "Illegal # arguments for intrinsic function!", IF);
825 Assert1(FT->getReturnType() == FT->getParamType(0),
826 "Return type does not match source type", IF);
827 Assert1(FT->getParamType(0) == Type::UShortTy,
828 "Argument is not ushort!", IF);
832 case Intrinsic::ctpop_i32:
833 Assert1(FT->getNumParams() == 1,
834 "Illegal # arguments for intrinsic function!", IF);
835 Assert1(FT->getReturnType() == FT->getParamType(0),
836 "Return type does not match source type", IF);
837 Assert1(FT->getParamType(0) == Type::UIntTy, "Argument is not uint!", IF);
841 case Intrinsic::ctpop_i64:
842 Assert1(FT->getNumParams() == 1,
843 "Illegal # arguments for intrinsic function!", IF);
844 Assert1(FT->getReturnType() == FT->getParamType(0),
845 "Return type does not match source type", IF);
846 Assert1(FT->getParamType(0) == Type::ULongTy, "Argument is not ulong!", IF);
850 case Intrinsic::ctlz_i8:
851 Assert1(FT->getNumParams() == 1,
852 "Illegal # arguments for intrinsic function!", IF);
853 Assert1(FT->getReturnType() == FT->getParamType(0),
854 "Return type does not match source type", IF);
855 Assert1(FT->getParamType(0) == Type::UByteTy, "Argument is not ubyte!", IF);
859 case Intrinsic::ctlz_i16:
860 Assert1(FT->getNumParams() == 1,
861 "Illegal # arguments for intrinsic function!", IF);
862 Assert1(FT->getReturnType() == FT->getParamType(0),
863 "Return type does not match source type", IF);
864 Assert1(FT->getParamType(0) == Type::UShortTy,
865 "Argument is not ushort!", IF);
868 case Intrinsic::ctlz_i32:
869 Assert1(FT->getNumParams() == 1,
870 "Illegal # arguments for intrinsic function!", IF);
871 Assert1(FT->getReturnType() == FT->getParamType(0),
872 "Return type does not match source type", IF);
873 Assert1(FT->getParamType(0) == Type::UIntTy, "Argument is not uint!", IF);
876 case Intrinsic::ctlz_i64:
877 Assert1(FT->getNumParams() == 1,
878 "Illegal # arguments for intrinsic function!", IF);
879 Assert1(FT->getReturnType() == FT->getParamType(0),
880 "Return type does not match source type", IF);
881 Assert1(FT->getParamType(0) == Type::ULongTy, "Argument is not ulong!", IF);
884 case Intrinsic::cttz_i8:
885 Assert1(FT->getNumParams() == 1,
886 "Illegal # arguments for intrinsic function!", IF);
887 Assert1(FT->getReturnType() == FT->getParamType(0),
888 "Return type does not match source type", IF);
889 Assert1(FT->getParamType(0) == Type::UByteTy, "Argument is not ubyte!", IF);
892 case Intrinsic::cttz_i16:
893 Assert1(FT->getNumParams() == 1,
894 "Illegal # arguments for intrinsic function!", IF);
895 Assert1(FT->getReturnType() == FT->getParamType(0),
896 "Return type does not match source type", IF);
897 Assert1(FT->getParamType(0) == Type::UShortTy,
898 "Argument is not ushort!", IF);
901 case Intrinsic::cttz_i32:
902 Assert1(FT->getNumParams() == 1,
903 "Illegal # arguments for intrinsic function!", IF);
904 Assert1(FT->getReturnType() == FT->getParamType(0),
905 "Return type does not match source type", IF);
906 Assert1(FT->getParamType(0) == Type::UIntTy, "Argument is not uint!", IF);
909 case Intrinsic::cttz_i64:
910 Assert1(FT->getNumParams() == 1,
911 "Illegal # arguments for intrinsic function!", IF);
912 Assert1(FT->getReturnType() == FT->getParamType(0),
913 "Return type does not match source type", IF);
914 Assert1(FT->getParamType(0) == Type::ULongTy, "Argument Is not ulong!", IF);
918 case Intrinsic::sqrt_f32:
919 Assert1(FT->getNumParams() == 1,
920 "Illegal # arguments for intrinsic function!", IF);
921 Assert1(FT->getParamType(0) == Type::FloatTy,
922 "Argument is not a 32-bit floating point type!", IF);
923 Assert1(FT->getReturnType() == FT->getParamType(0),
924 "Return type is not the same as argument type!", IF);
928 case Intrinsic::sqrt_f64:
929 Assert1(FT->getNumParams() == 1,
930 "Illegal # arguments for intrinsic function!", IF);
931 Assert1(FT->getParamType(0) == Type::DoubleTy,
932 "Argument is not a 64-bit floating point type!", IF);
933 Assert1(FT->getReturnType() == FT->getParamType(0),
934 "Return type is not the same as argument type!", IF);
938 case Intrinsic::setjmp: NumArgs = 1; break;
939 case Intrinsic::longjmp: NumArgs = 2; break;
940 case Intrinsic::sigsetjmp: NumArgs = 2; break;
941 case Intrinsic::siglongjmp: NumArgs = 2; break;
943 case Intrinsic::gcroot:
944 Assert1(FT->getNumParams() == 2,
945 "Illegal # arguments for intrinsic function!", IF);
946 Assert1(isa<Constant>(CI.getOperand(2)),
947 "Second argument to llvm.gcroot must be a constant!", &CI);
950 case Intrinsic::gcread: NumArgs = 2; break;
951 case Intrinsic::gcwrite: NumArgs = 3; break;
953 case Intrinsic::dbg_stoppoint: NumArgs = 4; break;
954 case Intrinsic::dbg_region_start:NumArgs = 1; break;
955 case Intrinsic::dbg_region_end: NumArgs = 1; break;
956 case Intrinsic::dbg_func_start: NumArgs = 1; break;
957 case Intrinsic::dbg_declare: NumArgs = 1; break;
959 case Intrinsic::memcpy_i32: NumArgs = 4; break;
960 case Intrinsic::memcpy_i64: NumArgs = 4; break;
961 case Intrinsic::memmove_i32: NumArgs = 4; break;
962 case Intrinsic::memmove_i64: NumArgs = 4; break;
963 case Intrinsic::memset_i32: NumArgs = 4; break;
964 case Intrinsic::memset_i64: NumArgs = 4; break;
966 case Intrinsic::stacksave:
968 Assert1(CI.getType() == PointerType::get(Type::SByteTy),
969 "llvm.stacksave must return an sbyte*", &CI);
971 case Intrinsic::stackrestore:
973 Assert1(CI.getOperand(1)->getType() == PointerType::get(Type::SByteTy),
974 "llvm.stackrestore must take an sbyte*", &CI);
975 Assert1(CI.getType() == Type::VoidTy,
976 "llvm.stackrestore return void", &CI);
978 case Intrinsic::prefetch: NumArgs = 3; break;
979 case Intrinsic::pcmarker:
981 Assert1(isa<Constant>(CI.getOperand(1)),
982 "First argument to llvm.pcmarker must be a constant!", &CI);
985 case Intrinsic::not_intrinsic:
986 assert(0 && "Invalid intrinsic!"); NumArgs = 0; break;
989 Assert1(FT->getNumParams() == NumArgs || (FT->getNumParams() < NumArgs &&
991 "Illegal # arguments for intrinsic function!", IF);
995 //===----------------------------------------------------------------------===//
996 // Implement the public interfaces to this file...
997 //===----------------------------------------------------------------------===//
999 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1000 return new Verifier(action);
1004 // verifyFunction - Create
1005 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1006 Function &F = const_cast<Function&>(f);
1007 assert(!F.isExternal() && "Cannot verify external functions");
1009 FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
1010 Verifier *V = new Verifier(action);
1016 /// verifyModule - Check a module for errors, printing messages on stderr.
1017 /// Return true if the module is corrupt.
1019 bool llvm::verifyModule(const Module &M, VerifierFailureAction action) {
1021 Verifier *V = new Verifier(action);