The check to see if an external function was marked internal was not reachable!
[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       // Scan through, checking all of the external function's linkage now...
73       for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
74         if ((*I)->isExternal() && (*I)->hasInternalLinkage())
75           CheckFailed("", "Function Declaration has Internal Linkage!", (*I));
76
77       if (Broken) {
78         cerr << "Broken module found, compilation aborted!\n";
79         abort();
80       }
81       return false;
82     }
83
84     // Verification methods...
85     void verifySymbolTable(SymbolTable *ST);
86     void visitFunction(Function *F);
87     void visitBasicBlock(BasicBlock *BB);
88     void visitPHINode(PHINode *PN);
89     void visitBinaryOperator(BinaryOperator *B);
90     void visitCallInst(CallInst *CI);
91     void visitGetElementPtrInst(GetElementPtrInst *GEP);
92     void visitLoadInst(LoadInst *LI);
93     void visitStoreInst(StoreInst *SI);
94     void visitInstruction(Instruction *I);
95
96     // CheckFailed - A check failed, so print out the condition and the message
97     // that failed.  This provides a nice place to put a breakpoint if you want
98     // to see why something is not correct.
99     //
100     inline void CheckFailed(const char *Cond, const std::string &Message,
101                             const Value *V1 = 0, const Value *V2 = 0) {
102       std::cerr << Message << "\n";
103       if (V1) { std::cerr << V1 << "\n"; }
104       if (V2) { std::cerr << V2 << "\n"; }
105       Broken = true;
106     }
107   };
108 }
109
110 // Assert - We know that cond should be true, if not print an error message.
111 #define Assert(C, M) \
112   do { if (!(C)) { CheckFailed(#C, M); return; } } while (0)
113 #define Assert1(C, M, V1) \
114   do { if (!(C)) { CheckFailed(#C, M, V1); return; } } while (0)
115 #define Assert2(C, M, V1, V2) \
116   do { if (!(C)) { CheckFailed(#C, M, V1, V2); return; } } while (0)
117
118
119 // verifySymbolTable - Verify that a function or module symbol table is ok
120 //
121 void Verifier::verifySymbolTable(SymbolTable *ST) {
122   if (ST == 0) return;   // No symbol table to process
123
124   // Loop over all of the types in the symbol table...
125   for (SymbolTable::iterator TI = ST->begin(), TE = ST->end(); TI != TE; ++TI)
126     for (SymbolTable::type_iterator I = TI->second.begin(),
127            E = TI->second.end(); I != E; ++I) {
128       Value *V = I->second;
129
130       // Check that there are no void typed values in the symbol table.  Values
131       // with a void type cannot be put into symbol tables because they cannot
132       // have names!
133       Assert1(V->getType() != Type::VoidTy,
134               "Values with void type are not allowed to have names!\n", V);
135     }
136 }
137
138
139 // visitFunction - Verify that a function is ok.
140 //
141 void Verifier::visitFunction(Function *F) {
142   if (F->isExternal()) return;
143
144   verifySymbolTable(F->getSymbolTable());
145
146   // Check function arguments...
147   const FunctionType *FT = F->getFunctionType();
148   const Function::ArgumentListType &ArgList = F->getArgumentList();
149
150   Assert2(!FT->isVarArg(), "Cannot define varargs functions in LLVM!", F, FT);
151   Assert2(FT->getParamTypes().size() == ArgList.size(),
152           "# formal arguments must match # of arguments for function type!",
153           F, FT);
154
155   // Check that the argument values match the function type for this function...
156   if (FT->getParamTypes().size() == ArgList.size()) {
157     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
158       Assert2(ArgList[i]->getType() == FT->getParamType(i),
159               "Argument value does not match function argument type!",
160               ArgList[i], FT->getParamType(i));
161   }
162
163   // Check the entry node
164   BasicBlock *Entry = F->getEntryNode();
165   Assert1(pred_begin(Entry) == pred_end(Entry),
166           "Entry block to function must not have predecessors!", Entry);
167 }
168
169
170 // verifyBasicBlock - Verify that a basic block is well formed...
171 //
172 void Verifier::visitBasicBlock(BasicBlock *BB) {
173   Assert1(BB->getTerminator(), "Basic Block does not have terminator!\n", BB);
174
175   // Check that the terminator is ok as well...
176   if (isa<ReturnInst>(BB->getTerminator())) {
177     Instruction *I = BB->getTerminator();
178     Function *F = I->getParent()->getParent();
179     if (I->getNumOperands() == 0)
180       Assert1(F->getReturnType() == Type::VoidTy,
181               "Function returns no value, but ret instruction found that does!",
182               I);
183     else
184       Assert2(F->getReturnType() == I->getOperand(0)->getType(),
185               "Function return type does not match operand "
186               "type of return inst!", I, F->getReturnType());
187   }
188 }
189
190
191 // visitPHINode - Ensure that a PHI node is well formed.
192 void Verifier::visitPHINode(PHINode *PN) {
193   std::vector<BasicBlock*> Preds(pred_begin(PN->getParent()),
194                                  pred_end(PN->getParent()));
195   // Loop over all of the incoming values, make sure that there are
196   // predecessors for each one...
197   //
198   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
199     // Make sure all of the incoming values are the right types...
200     Assert2(PN->getType() == PN->getIncomingValue(i)->getType(),
201             "PHI node argument type does not agree with PHI node type!",
202             PN, PN->getIncomingValue(i));
203
204     BasicBlock *BB = PN->getIncomingBlock(i);
205     std::vector<BasicBlock*>::iterator PI =
206       find(Preds.begin(), Preds.end(), BB);
207     Assert2(PI != Preds.end(), "PHI node has entry for basic block that"
208             " is not a predecessor!", PN, BB);
209     Preds.erase(PI);
210   }
211   
212   // There should be no entries left in the predecessor list...
213   for (std::vector<BasicBlock*>::iterator I = Preds.begin(),
214          E = Preds.end(); I != E; ++I)
215     Assert2(0, "PHI node does not have entry for a predecessor basic block!",
216             PN, *I);
217
218   visitInstruction(PN);
219 }
220
221 void Verifier::visitCallInst(CallInst *CI) {
222   Assert1(isa<PointerType>(CI->getOperand(0)->getType()),
223           "Called function must be a pointer!", CI);
224   PointerType *FPTy = cast<PointerType>(CI->getOperand(0)->getType());
225   Assert1(isa<FunctionType>(FPTy->getElementType()),
226           "Called function is not pointer to function type!", CI);
227 }
228
229 // visitBinaryOperator - Check that both arguments to the binary operator are
230 // of the same type!
231 //
232 void Verifier::visitBinaryOperator(BinaryOperator *B) {
233   Assert2(B->getOperand(0)->getType() == B->getOperand(1)->getType(),
234           "Both operands to a binary operator are not of the same type!",
235           B->getOperand(0), B->getOperand(1));
236
237   visitInstruction(B);
238 }
239
240 void Verifier::visitGetElementPtrInst(GetElementPtrInst *GEP) {
241   const Type *ElTy =MemAccessInst::getIndexedType(GEP->getOperand(0)->getType(),
242                                                   GEP->copyIndices(), true);
243   Assert1(ElTy, "Invalid indices for GEP pointer type!", GEP);
244   Assert2(PointerType::get(ElTy) == GEP->getType(),
245           "GEP is not of right type for indices!\n", GEP, ElTy);
246   visitInstruction(GEP);
247 }
248
249 void Verifier::visitLoadInst(LoadInst *LI) {
250   const Type *ElTy = LoadInst::getIndexedType(LI->getOperand(0)->getType(),
251                                               LI->copyIndices());
252   Assert1(ElTy, "Invalid indices for load pointer type!", LI);
253   Assert2(ElTy == LI->getType(),
254           "Load is not of right type for indices!\n", LI, ElTy);
255   visitInstruction(LI);
256 }
257
258 void Verifier::visitStoreInst(StoreInst *SI) {
259   const Type *ElTy = StoreInst::getIndexedType(SI->getOperand(1)->getType(),
260                                                SI->copyIndices());
261   Assert1(ElTy, "Invalid indices for store pointer type!", SI);
262   Assert2(ElTy == SI->getOperand(0)->getType(),
263           "Stored value is not of right type for indices!\n", SI, ElTy);
264   visitInstruction(SI);
265 }
266
267
268 // verifyInstruction - Verify that a non-terminator instruction is well formed.
269 //
270 void Verifier::visitInstruction(Instruction *I) {
271   assert(I->getParent() && "Instruction not embedded in basic block!");
272
273   // Check that all uses of the instruction, if they are instructions
274   // themselves, actually have parent basic blocks.  If the use is not an
275   // instruction, it is an error!
276   //
277   for (User::use_iterator UI = I->use_begin(), UE = I->use_end();
278        UI != UE; ++UI) {
279     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
280             *UI);
281     Instruction *Used = cast<Instruction>(*UI);
282     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
283             " embeded in a basic block!", I, Used);
284   }
285
286   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
287     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
288          UI != UE; ++UI)
289       Assert1(*UI != (User*)I,
290               "Only PHI nodes may reference their own value!", I);
291   }
292
293   Assert1(I->getType() != Type::VoidTy || !I->hasName(),
294           "Instruction has a name, but provides a void value!", I);
295 }
296
297
298 //===----------------------------------------------------------------------===//
299 //  Implement the public interfaces to this file...
300 //===----------------------------------------------------------------------===//
301
302 Pass *createVerifierPass() {
303   return new Verifier();
304 }
305
306 bool verifyFunction(const Function *F) {
307   Verifier V;
308   V.visit((Function*)F);
309   return V.Broken;
310 }
311
312 // verifyModule - Check a module for errors, printing messages on stderr.
313 // Return true if the module is corrupt.
314 //
315 bool verifyModule(const Module *M) {
316   Verifier V;
317   V.run((Module*)M);
318   return V.Broken;
319 }