* Incorporate the contents of SymTabValue into Function and Module
[oota-llvm.git] / lib / VMCore / Verifier.cpp
1 //===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
2 //
3 // This file defines the function verifier interface, that can be used for some
4 // sanity checking of input to the system.
5 //
6 // Note that this does not provide full 'java style' security and verifications,
7 // instead it just tries to ensure that code is well formed.
8 //
9 //  . There are no duplicated names in a symbol table... ie there !exist a val
10 //    with the same name as something in the symbol table, but with a different
11 //    address as what is in the symbol table...
12 //  * Both of a binary operator's parameters are the same type
13 //  * Verify that the indices of mem access instructions match other operands
14 //  . Verify that arithmetic and other things are only performed on first class
15 //    types.  No adding structures or arrays.
16 //  . All of the constants in a switch statement are of the correct type
17 //  . The code is in valid SSA form
18 //  . It should be illegal to put a label into any other type (like a structure)
19 //    or to return one. [except constant arrays!]
20 //  * Only phi nodes can be self referential: 'add int %0, %0 ; <int>:0' is bad
21 //  * PHI nodes must have an entry for each predecessor, with no extras.
22 //  . All basic blocks should only end with terminator insts, not contain them
23 //  * The entry node to a function must not have predecessors
24 //  * All Instructions must be embeded into a basic block
25 //  . Verify that none of the Value getType()'s are null.
26 //  . Function's cannot take a void typed parameter
27 //  * Verify that a function's argument list agrees with it's declared type.
28 //  . Verify that arrays and structures have fixed elements: No unsized arrays.
29 //  * It is illegal to specify a name for a void value.
30 //  * It is illegal to have a internal function that is just a declaration
31 //  * It is illegal to have a ret instruction that returns a value that does not
32 //    agree with the function return value type.
33 //  * All other things that are tested by asserts spread about the code...
34 //
35 //===----------------------------------------------------------------------===//
36
37 #include "llvm/Analysis/Verifier.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Function.h"
40 #include "llvm/Module.h"
41 #include "llvm/BasicBlock.h"
42 #include "llvm/DerivedTypes.h"
43 #include "llvm/iPHINode.h"
44 #include "llvm/iTerminators.h"
45 #include "llvm/iOther.h"
46 #include "llvm/iMemory.h"
47 #include "llvm/Argument.h"
48 #include "llvm/SymbolTable.h"
49 #include "llvm/Support/CFG.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "Support/STLExtras.h"
52 #include <algorithm>
53
54 namespace {  // Anonymous namespace for class
55
56   struct Verifier : public FunctionPass, InstVisitor<Verifier> {
57     bool Broken;
58
59     Verifier() : Broken(false) {}
60
61     bool doInitialization(Module *M) {
62       verifySymbolTable(M->getSymbolTable());
63       return false;
64     }
65
66     bool runOnFunction(Function *F) {
67       visit(F);
68       return false;
69     }
70
71     bool doFinalization(Module *M) {
72       if (Broken) {
73         cerr << "Broken module found, compilation aborted!\n";
74         abort();
75       }
76       return false;
77     }
78
79     // Verification methods...
80     void verifySymbolTable(SymbolTable *ST);
81     void visitFunction(Function *F);
82     void visitBasicBlock(BasicBlock *BB);
83     void visitPHINode(PHINode *PN);
84     void visitBinaryOperator(BinaryOperator *B);
85     void visitCallInst(CallInst *CI);
86     void visitGetElementPtrInst(GetElementPtrInst *GEP);
87     void visitLoadInst(LoadInst *LI);
88     void visitStoreInst(StoreInst *SI);
89     void visitInstruction(Instruction *I);
90
91     // CheckFailed - A check failed, so print out the condition and the message
92     // that failed.  This provides a nice place to put a breakpoint if you want
93     // to see why something is not correct.
94     //
95     inline void CheckFailed(const char *Cond, const std::string &Message,
96                             const Value *V1 = 0, const Value *V2 = 0) {
97       std::cerr << Message << "\n";
98       if (V1) { std::cerr << V1 << "\n"; }
99       if (V2) { std::cerr << V2 << "\n"; }
100       Broken = true;
101     }
102   };
103 }
104
105 // Assert - We know that cond should be true, if not print an error message.
106 #define Assert(C, M) \
107   do { if (!(C)) { CheckFailed(#C, M); return; } } while (0)
108 #define Assert1(C, M, V1) \
109   do { if (!(C)) { CheckFailed(#C, M, V1); return; } } while (0)
110 #define Assert2(C, M, V1, V2) \
111   do { if (!(C)) { CheckFailed(#C, M, V1, V2); return; } } while (0)
112
113
114 // verifySymbolTable - Verify that a function or module symbol table is ok
115 //
116 void Verifier::verifySymbolTable(SymbolTable *ST) {
117   if (ST == 0) return;   // No symbol table to process
118
119   // Loop over all of the types in the symbol table...
120   for (SymbolTable::iterator TI = ST->begin(), TE = ST->end(); TI != TE; ++TI)
121     for (SymbolTable::type_iterator I = TI->second.begin(),
122            E = TI->second.end(); I != E; ++I) {
123       Value *V = I->second;
124
125       // Check that there are no void typed values in the symbol table.  Values
126       // with a void type cannot be put into symbol tables because they cannot
127       // have names!
128       Assert1(V->getType() != Type::VoidTy,
129               "Values with void type are not allowed to have names!\n", V);
130     }
131 }
132
133
134 // visitFunction - Verify that a function is ok.
135 //
136 void Verifier::visitFunction(Function *F) {
137   if (F->isExternal()) return;
138   verifySymbolTable(F->getSymbolTable());
139
140   // Check linkage of function...
141   Assert1(!F->isExternal() || F->hasExternalLinkage(),
142           "Function cannot be an 'internal' 'declare'ation!", F);
143
144   // Check function arguments...
145   const FunctionType *FT = F->getFunctionType();
146   const Function::ArgumentListType &ArgList = F->getArgumentList();
147
148   Assert2(!FT->isVarArg(), "Cannot define varargs functions in LLVM!", F, FT);
149   Assert2(FT->getParamTypes().size() == ArgList.size(),
150           "# formal arguments must match # of arguments for function type!",
151           F, FT);
152
153   // Check that the argument values match the function type for this function...
154   if (FT->getParamTypes().size() == ArgList.size()) {
155     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
156       Assert2(ArgList[i]->getType() == FT->getParamType(i),
157               "Argument value does not match function argument type!",
158               ArgList[i], FT->getParamType(i));
159   }
160
161   // Check the entry node
162   BasicBlock *Entry = F->getEntryNode();
163   Assert1(pred_begin(Entry) == pred_end(Entry),
164           "Entry block to function must not have predecessors!", Entry);
165 }
166
167
168 // verifyBasicBlock - Verify that a basic block is well formed...
169 //
170 void Verifier::visitBasicBlock(BasicBlock *BB) {
171   Assert1(BB->getTerminator(), "Basic Block does not have terminator!\n", BB);
172
173   // Check that the terminator is ok as well...
174   if (isa<ReturnInst>(BB->getTerminator())) {
175     Instruction *I = BB->getTerminator();
176     Function *F = I->getParent()->getParent();
177     if (I->getNumOperands() == 0)
178       Assert1(F->getReturnType() == Type::VoidTy,
179               "Function returns no value, but ret instruction found that does!",
180               I);
181     else
182       Assert2(F->getReturnType() == I->getOperand(0)->getType(),
183               "Function return type does not match operand "
184               "type of return inst!", I, F->getReturnType());
185   }
186 }
187
188
189 // visitPHINode - Ensure that a PHI node is well formed.
190 void Verifier::visitPHINode(PHINode *PN) {
191   std::vector<BasicBlock*> Preds(pred_begin(PN->getParent()),
192                                  pred_end(PN->getParent()));
193   // Loop over all of the incoming values, make sure that there are
194   // predecessors for each one...
195   //
196   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
197     // Make sure all of the incoming values are the right types...
198     Assert2(PN->getType() == PN->getIncomingValue(i)->getType(),
199             "PHI node argument type does not agree with PHI node type!",
200             PN, PN->getIncomingValue(i));
201
202     BasicBlock *BB = PN->getIncomingBlock(i);
203     std::vector<BasicBlock*>::iterator PI =
204       find(Preds.begin(), Preds.end(), BB);
205     Assert2(PI != Preds.end(), "PHI node has entry for basic block that"
206             " is not a predecessor!", PN, BB);
207     Preds.erase(PI);
208   }
209   
210   // There should be no entries left in the predecessor list...
211   for (std::vector<BasicBlock*>::iterator I = Preds.begin(),
212          E = Preds.end(); I != E; ++I)
213     Assert2(0, "PHI node does not have entry for a predecessor basic block!",
214             PN, *I);
215
216   visitInstruction(PN);
217 }
218
219 void Verifier::visitCallInst(CallInst *CI) {
220   Assert1(isa<PointerType>(CI->getOperand(0)->getType()),
221           "Called function must be a pointer!", CI);
222   PointerType *FPTy = cast<PointerType>(CI->getOperand(0)->getType());
223   Assert1(isa<FunctionType>(FPTy->getElementType()),
224           "Called function is not pointer to function type!", CI);
225 }
226
227 // visitBinaryOperator - Check that both arguments to the binary operator are
228 // of the same type!
229 //
230 void Verifier::visitBinaryOperator(BinaryOperator *B) {
231   Assert2(B->getOperand(0)->getType() == B->getOperand(1)->getType(),
232           "Both operands to a binary operator are not of the same type!",
233           B->getOperand(0), B->getOperand(1));
234
235   visitInstruction(B);
236 }
237
238 void Verifier::visitGetElementPtrInst(GetElementPtrInst *GEP) {
239   const Type *ElTy =MemAccessInst::getIndexedType(GEP->getOperand(0)->getType(),
240                                                   GEP->copyIndices(), true);
241   Assert1(ElTy, "Invalid indices for GEP pointer type!", GEP);
242   Assert2(PointerType::get(ElTy) == GEP->getType(),
243           "GEP is not of right type for indices!\n", GEP, ElTy);
244   visitInstruction(GEP);
245 }
246
247 void Verifier::visitLoadInst(LoadInst *LI) {
248   const Type *ElTy = LoadInst::getIndexedType(LI->getOperand(0)->getType(),
249                                               LI->copyIndices());
250   Assert1(ElTy, "Invalid indices for load pointer type!", LI);
251   Assert2(ElTy == LI->getType(),
252           "Load is not of right type for indices!\n", LI, ElTy);
253   visitInstruction(LI);
254 }
255
256 void Verifier::visitStoreInst(StoreInst *SI) {
257   const Type *ElTy = StoreInst::getIndexedType(SI->getOperand(1)->getType(),
258                                                SI->copyIndices());
259   Assert1(ElTy, "Invalid indices for store pointer type!", SI);
260   Assert2(ElTy == SI->getOperand(0)->getType(),
261           "Stored value is not of right type for indices!\n", SI, ElTy);
262   visitInstruction(SI);
263 }
264
265
266 // verifyInstruction - Verify that a non-terminator instruction is well formed.
267 //
268 void Verifier::visitInstruction(Instruction *I) {
269   assert(I->getParent() && "Instruction not embedded in basic block!");
270
271   // Check that all uses of the instruction, if they are instructions
272   // themselves, actually have parent basic blocks.  If the use is not an
273   // instruction, it is an error!
274   //
275   for (User::use_iterator UI = I->use_begin(), UE = I->use_end();
276        UI != UE; ++UI) {
277     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
278             *UI);
279     Instruction *Used = cast<Instruction>(*UI);
280     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
281             " embeded in a basic block!", I, Used);
282   }
283
284   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
285     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
286          UI != UE; ++UI)
287       Assert1(*UI != (User*)I,
288               "Only PHI nodes may reference their own value!", I);
289   }
290
291   Assert1(I->getType() != Type::VoidTy || !I->hasName(),
292           "Instruction has a name, but provides a void value!", I);
293 }
294
295
296 //===----------------------------------------------------------------------===//
297 //  Implement the public interfaces to this file...
298 //===----------------------------------------------------------------------===//
299
300 Pass *createVerifierPass() {
301   return new Verifier();
302 }
303
304 bool verifyFunction(const Function *F) {
305   Verifier V;
306   V.visit((Function*)F);
307   return V.Broken;
308 }
309
310 // verifyModule - Check a module for errors, printing messages on stderr.
311 // Return true if the module is corrupt.
312 //
313 bool verifyModule(const Module *M) {
314   Verifier V;
315   V.run((Module*)M);
316   return V.Broken;
317 }