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 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 // . Function's 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/Pass.h"
44 #include "llvm/Module.h"
45 #include "llvm/DerivedTypes.h"
46 #include "llvm/iPHINode.h"
47 #include "llvm/iTerminators.h"
48 #include "llvm/iOther.h"
49 #include "llvm/iOperators.h"
50 #include "llvm/iMemory.h"
51 #include "llvm/SymbolTable.h"
52 #include "llvm/PassManager.h"
53 #include "llvm/Intrinsics.h"
54 #include "llvm/Analysis/Dominators.h"
55 #include "llvm/Support/CFG.h"
56 #include "llvm/Support/InstVisitor.h"
57 #include "Support/STLExtras.h"
60 namespace { // Anonymous namespace for class
62 struct Verifier : public FunctionPass, InstVisitor<Verifier> {
63 bool Broken; // Is this module found to be broken?
64 bool RealPass; // Are we not being run by a PassManager?
65 bool AbortBroken; // If broken, should it or should it not abort?
67 DominatorSet *DS; // Dominator set, caution can be null!
69 Verifier() : Broken(false), RealPass(true), AbortBroken(true), DS(0) {}
70 Verifier(bool AB) : Broken(false), RealPass(true), AbortBroken(AB), DS(0) {}
71 Verifier(DominatorSet &ds)
72 : Broken(false), RealPass(false), AbortBroken(false), DS(&ds) {}
75 bool doInitialization(Module &M) {
76 verifySymbolTable(M.getSymbolTable());
78 // If this is a real pass, in a pass manager, we must abort before
79 // returning back to the pass manager, or else the pass manager may try to
80 // run other passes on the broken module.
87 bool runOnFunction(Function &F) {
88 // Get dominator information if we are being run by PassManager
89 if (RealPass) DS = &getAnalysis<DominatorSet>();
92 // If this is a real pass, in a pass manager, we must abort before
93 // returning back to the pass manager, or else the pass manager may try to
94 // run other passes on the broken module.
102 bool doFinalization(Module &M) {
103 // Scan through, checking all of the external function's linkage now...
104 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
105 visitGlobalValue(*I);
107 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
108 if (I->isExternal() && I->hasInternalLinkage())
109 CheckFailed("Global Variable is external with internal linkage!", I);
111 // If the module is broken, abort at this time.
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117 AU.setPreservesAll();
119 AU.addRequired<DominatorSet>();
122 // abortIfBroken - If the module is broken and we are supposed to abort on
123 // this condition, do so.
125 void abortIfBroken() const {
126 if (Broken && AbortBroken) {
127 std::cerr << "Broken module found, compilation aborted!\n";
133 // Verification methods...
134 void verifySymbolTable(SymbolTable &ST);
135 void visitGlobalValue(GlobalValue &GV);
136 void visitFunction(Function &F);
137 void visitBasicBlock(BasicBlock &BB);
138 void visitPHINode(PHINode &PN);
139 void visitBinaryOperator(BinaryOperator &B);
140 void visitShiftInst(ShiftInst &SI);
141 void visitVANextInst(VANextInst &VAN) { visitInstruction(VAN); }
142 void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
143 void visitCallInst(CallInst &CI);
144 void visitGetElementPtrInst(GetElementPtrInst &GEP);
145 void visitLoadInst(LoadInst &LI);
146 void visitStoreInst(StoreInst &SI);
147 void visitInstruction(Instruction &I);
148 void visitTerminatorInst(TerminatorInst &I);
149 void visitReturnInst(ReturnInst &RI);
150 void visitUserOp1(Instruction &I);
151 void visitUserOp2(Instruction &I) { visitUserOp1(I); }
152 void visitIntrinsicFunctionCall(LLVMIntrinsic::ID ID, CallInst &CI);
154 // CheckFailed - A check failed, so print out the condition and the message
155 // that failed. This provides a nice place to put a breakpoint if you want
156 // to see why something is not correct.
158 inline void CheckFailed(const std::string &Message,
159 const Value *V1 = 0, const Value *V2 = 0,
160 const Value *V3 = 0, const Value *V4 = 0) {
161 std::cerr << Message << "\n";
162 if (V1) std::cerr << *V1 << "\n";
163 if (V2) std::cerr << *V2 << "\n";
164 if (V3) std::cerr << *V3 << "\n";
165 if (V4) std::cerr << *V4 << "\n";
170 RegisterPass<Verifier> X("verify", "Module Verifier");
173 // Assert - We know that cond should be true, if not print an error message.
174 #define Assert(C, M) \
175 do { if (!(C)) { CheckFailed(M); return; } } while (0)
176 #define Assert1(C, M, V1) \
177 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
178 #define Assert2(C, M, V1, V2) \
179 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
180 #define Assert3(C, M, V1, V2, V3) \
181 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
182 #define Assert4(C, M, V1, V2, V3, V4) \
183 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
186 void Verifier::visitGlobalValue(GlobalValue &GV) {
187 Assert1(!GV.isExternal() || GV.hasExternalLinkage(),
188 "Global value has Internal Linkage!", &GV);
189 Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
190 "Only global variables can have appending linkage!", &GV);
192 if (GV.hasAppendingLinkage()) {
193 GlobalVariable &GVar = cast<GlobalVariable>(GV);
194 Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
195 "Only global arrays can have appending linkage!", &GV);
199 // verifySymbolTable - Verify that a function or module symbol table is ok
201 void Verifier::verifySymbolTable(SymbolTable &ST) {
202 // Loop over all of the types in the symbol table...
203 for (SymbolTable::iterator TI = ST.begin(), TE = ST.end(); TI != TE; ++TI)
204 for (SymbolTable::type_iterator I = TI->second.begin(),
205 E = TI->second.end(); I != E; ++I) {
206 Value *V = I->second;
208 // Check that there are no void typed values in the symbol table. Values
209 // with a void type cannot be put into symbol tables because they cannot
211 Assert1(V->getType() != Type::VoidTy,
212 "Values with void type are not allowed to have names!", V);
217 // visitFunction - Verify that a function is ok.
219 void Verifier::visitFunction(Function &F) {
220 // Check function arguments...
221 const FunctionType *FT = F.getFunctionType();
222 unsigned NumArgs = F.getArgumentList().size();
224 Assert2(FT->getNumParams() == NumArgs,
225 "# formal arguments must match # of arguments for function type!",
228 // Check that the argument values match the function type for this function...
230 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++i)
231 Assert2(I->getType() == FT->getParamType(i),
232 "Argument value does not match function argument type!",
233 I, FT->getParamType(i));
235 if (!F.isExternal()) {
236 verifySymbolTable(F.getSymbolTable());
238 // Check the entry node
239 BasicBlock *Entry = &F.getEntryBlock();
240 Assert1(pred_begin(Entry) == pred_end(Entry),
241 "Entry block to function must not have predecessors!", Entry);
246 // verifyBasicBlock - Verify that a basic block is well formed...
248 void Verifier::visitBasicBlock(BasicBlock &BB) {
249 // Check constraints that this basic block imposes on all of the PHI nodes in
251 if (isa<PHINode>(BB.front())) {
252 std::vector<BasicBlock*> Preds(pred_begin(&BB), pred_end(&BB));
253 std::sort(Preds.begin(), Preds.end());
255 for (BasicBlock::iterator I = BB.begin();
256 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
258 // Ensure that PHI nodes have at least one entry!
259 Assert1(PN->getNumIncomingValues() != 0,
260 "PHI nodes must have at least one entry. If the block is dead, "
261 "the PHI should be removed!", PN);
262 Assert1(PN->getNumIncomingValues() >= Preds.size(),
263 "PHINode has more entries than the basic block has predecessors!",
265 Assert1(PN->getNumIncomingValues() <= Preds.size(),
266 "PHINode has less entries than the basic block has predecessors!",
269 // Get and sort all incoming values in the PHI node...
270 std::vector<std::pair<BasicBlock*, Value*> > Values;
271 Values.reserve(PN->getNumIncomingValues());
272 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
273 Values.push_back(std::make_pair(PN->getIncomingBlock(i),
274 PN->getIncomingValue(i)));
275 std::sort(Values.begin(), Values.end());
277 for (unsigned i = 0, e = Values.size(); i != e; ++i) {
278 // Check to make sure that if there is more than one entry for a
279 // particular basic block in this PHI node, that the incoming values are
282 Assert4(i == 0 || Values[i].first != Values[i-1].first ||
283 Values[i].second == Values[i-1].second,
284 "PHI node has multiple entries for the same basic block with "
285 "different incoming values!", PN, Values[i].first,
286 Values[i].second, Values[i-1].second);
288 // Check to make sure that the predecessors and PHI node entries are
290 Assert3(Values[i].first == Preds[i],
291 "PHI node entries do not match predecessors!", PN,
292 Values[i].first, Preds[i]);
297 // Ensure that basic blocks have terminators!
298 Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
301 void Verifier::visitTerminatorInst(TerminatorInst &I) {
302 // Ensure that terminators only exist at the end of the basic block.
303 Assert1(&I == I.getParent()->getTerminator(),
304 "Terminator found in the middle of a basic block!", I.getParent());
308 void Verifier::visitReturnInst(ReturnInst &RI) {
309 Function *F = RI.getParent()->getParent();
310 if (RI.getNumOperands() == 0)
311 Assert1(F->getReturnType() == Type::VoidTy,
312 "Function returns no value, but ret instruction found that does!",
315 Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
316 "Function return type does not match operand "
317 "type of return inst!", &RI, F->getReturnType());
319 // Check to make sure that the return value has necessary properties for
321 visitTerminatorInst(RI);
324 // visitUserOp1 - User defined operators shouldn't live beyond the lifetime of a
325 // pass, if any exist, it's an error.
327 void Verifier::visitUserOp1(Instruction &I) {
328 Assert1(0, "User-defined operators should not live outside of a pass!",
332 // visitPHINode - Ensure that a PHI node is well formed.
333 void Verifier::visitPHINode(PHINode &PN) {
334 // Ensure that the PHI nodes are all grouped together at the top of the block.
335 // This can be tested by checking whether the instruction before this is
336 // either nonexistent (because this is begin()) or is a PHI node. If not,
337 // then there is some other instruction before a PHI.
338 Assert2(&PN.getParent()->front() == &PN || isa<PHINode>(PN.getPrev()),
339 "PHI nodes not grouped at top of basic block!",
340 &PN, PN.getParent());
342 // All other PHI node constraints are checked in the visitBasicBlock method.
344 visitInstruction(PN);
347 void Verifier::visitCallInst(CallInst &CI) {
348 Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
349 "Called function must be a pointer!", &CI);
350 const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
351 Assert1(isa<FunctionType>(FPTy->getElementType()),
352 "Called function is not pointer to function type!", &CI);
354 const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
356 // Verify that the correct number of arguments are being passed
358 Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
359 "Called function requires more parameters than were provided!",&CI);
361 Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
362 "Incorrect number of arguments passed to called function!", &CI);
364 // Verify that all arguments to the call match the function type...
365 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
366 Assert2(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
367 "Call parameter type does not match function signature!",
368 CI.getOperand(i+1), FTy->getParamType(i));
370 if (Function *F = CI.getCalledFunction())
371 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID())
372 visitIntrinsicFunctionCall(ID, CI);
374 visitInstruction(CI);
377 // visitBinaryOperator - Check that both arguments to the binary operator are
380 void Verifier::visitBinaryOperator(BinaryOperator &B) {
381 Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
382 "Both operands to a binary operator are not of the same type!", &B);
384 // Check that logical operators are only used with integral operands.
385 if (B.getOpcode() == Instruction::And || B.getOpcode() == Instruction::Or ||
386 B.getOpcode() == Instruction::Xor) {
387 Assert1(B.getType()->isIntegral(),
388 "Logical operators only work with integral types!", &B);
389 Assert1(B.getType() == B.getOperand(0)->getType(),
390 "Logical operators must have same type for operands and result!",
392 } else if (isa<SetCondInst>(B)) {
393 // Check that setcc instructions return bool
394 Assert1(B.getType() == Type::BoolTy,
395 "setcc instructions must return boolean values!", &B);
397 // Arithmetic operators only work on integer or fp values
398 Assert1(B.getType() == B.getOperand(0)->getType(),
399 "Arithmetic operators must have same type for operands and result!",
401 Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint(),
402 "Arithmetic operators must have integer or fp type!", &B);
408 void Verifier::visitShiftInst(ShiftInst &SI) {
409 Assert1(SI.getType()->isInteger(),
410 "Shift must return an integer result!", &SI);
411 Assert1(SI.getType() == SI.getOperand(0)->getType(),
412 "Shift return type must be same as first operand!", &SI);
413 Assert1(SI.getOperand(1)->getType() == Type::UByteTy,
414 "Second operand to shift must be ubyte type!", &SI);
415 visitInstruction(SI);
418 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
420 GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
421 std::vector<Value*>(GEP.idx_begin(), GEP.idx_end()), true);
422 Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
423 Assert2(PointerType::get(ElTy) == GEP.getType(),
424 "GEP is not of right type for indices!", &GEP, ElTy);
425 visitInstruction(GEP);
428 void Verifier::visitLoadInst(LoadInst &LI) {
430 cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
431 Assert2(ElTy == LI.getType(),
432 "Load is not of right type for indices!", &LI, ElTy);
433 visitInstruction(LI);
436 void Verifier::visitStoreInst(StoreInst &SI) {
438 cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
439 Assert2(ElTy == SI.getOperand(0)->getType(),
440 "Stored value is not of right type for indices!", &SI, ElTy);
441 visitInstruction(SI);
445 // verifyInstruction - Verify that an instruction is well formed.
447 void Verifier::visitInstruction(Instruction &I) {
448 BasicBlock *BB = I.getParent();
449 Assert1(BB, "Instruction not embedded in basic block!", &I);
451 if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential
452 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
454 Assert1(*UI != (User*)&I,
455 "Only PHI nodes may reference their own value!", &I);
458 // Check that void typed values don't have names
459 Assert1(I.getType() != Type::VoidTy || !I.hasName(),
460 "Instruction has a name, but provides a void value!", &I);
462 // Check that all uses of the instruction, if they are instructions
463 // themselves, actually have parent basic blocks. If the use is not an
464 // instruction, it is an error!
466 for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
468 Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
470 Instruction *Used = cast<Instruction>(*UI);
471 Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
472 " embeded in a basic block!", &I, Used);
475 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
476 // Check to make sure that the "address of" an intrinsic function is never
478 if (Function *F = dyn_cast<Function>(I.getOperand(i)))
479 Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
480 "Cannot take the address of an intrinsic!", &I);
482 else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
483 // Check that a definition dominates all of its uses.
485 if (!isa<PHINode>(I)) {
486 // Definition must dominate use unless use is unreachable!
487 Assert2(DS->dominates(Op->getParent(), BB) ||
488 !DS->dominates(&BB->getParent()->getEntryBlock(), BB),
489 "Instruction does not dominate all uses!", Op, &I);
491 // PHI nodes are more difficult than other nodes because they actually
492 // "use" the value in the predecessor basic blocks they correspond to.
493 BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
494 Assert2(DS->dominates(Op->getParent(), PredBB) ||
495 !DS->dominates(&BB->getParent()->getEntryBlock(), PredBB),
496 "Instruction does not dominate all uses!", Op, &I);
502 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
503 void Verifier::visitIntrinsicFunctionCall(LLVMIntrinsic::ID ID, CallInst &CI) {
504 Function *IF = CI.getCalledFunction();
505 const FunctionType *FT = IF->getFunctionType();
506 Assert1(IF->isExternal(), "Intrinsic functions should never be defined!", IF);
507 unsigned NumArgs = 0;
509 // FIXME: this should check the return type of each intrinsic as well, also
512 case LLVMIntrinsic::va_start:
513 Assert1(CI.getParent()->getParent()->getFunctionType()->isVarArg(),
514 "llvm.va_start intrinsic may only occur in function with variable"
518 case LLVMIntrinsic::va_end: NumArgs = 1; break;
519 case LLVMIntrinsic::va_copy: NumArgs = 1; break;
521 case LLVMIntrinsic::setjmp: NumArgs = 1; break;
522 case LLVMIntrinsic::longjmp: NumArgs = 2; break;
523 case LLVMIntrinsic::sigsetjmp: NumArgs = 2; break;
524 case LLVMIntrinsic::siglongjmp: NumArgs = 2; break;
526 case LLVMIntrinsic::alpha_ctlz: NumArgs = 1; break;
527 case LLVMIntrinsic::alpha_cttz: NumArgs = 1; break;
528 case LLVMIntrinsic::alpha_ctpop: NumArgs = 1; break;
529 case LLVMIntrinsic::alpha_umulh: NumArgs = 2; break;
530 case LLVMIntrinsic::alpha_vecop: NumArgs = 4; break;
531 case LLVMIntrinsic::alpha_pup: NumArgs = 3; break;
532 case LLVMIntrinsic::alpha_bytezap: NumArgs = 2; break;
533 case LLVMIntrinsic::alpha_bytemanip: NumArgs = 3; break;
534 case LLVMIntrinsic::alpha_dfpbop: NumArgs = 3; break;
535 case LLVMIntrinsic::alpha_dfpuop: NumArgs = 2; break;
536 case LLVMIntrinsic::alpha_unordered: NumArgs = 2; break;
537 case LLVMIntrinsic::alpha_uqtodfp: NumArgs = 2; break;
538 case LLVMIntrinsic::alpha_uqtosfp: NumArgs = 2; break;
539 case LLVMIntrinsic::alpha_dfptosq: NumArgs = 2; break;
540 case LLVMIntrinsic::alpha_sfptosq: NumArgs = 2; break;
542 case LLVMIntrinsic::not_intrinsic:
543 assert(0 && "Invalid intrinsic!"); NumArgs = 0; break;
546 Assert1(FT->getNumParams() == NumArgs || (FT->getNumParams() < NumArgs &&
548 "Illegal # arguments for intrinsic function!", IF);
552 //===----------------------------------------------------------------------===//
553 // Implement the public interfaces to this file...
554 //===----------------------------------------------------------------------===//
556 FunctionPass *createVerifierPass() {
557 return new Verifier();
561 // verifyFunction - Create
562 bool verifyFunction(const Function &f) {
563 Function &F = (Function&)f;
564 assert(!F.isExternal() && "Cannot verify external functions");
567 DS.doInitialization(*F.getParent());
573 DS.doFinalization(*F.getParent());
578 // verifyModule - Check a module for errors, printing messages on stderr.
579 // Return true if the module is corrupt.
581 bool verifyModule(const Module &M) {
583 Verifier *V = new Verifier();