Add new check of return value type matching ret instruction values types
[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 arithmetic and other things are only performed on first class
14 //    types.  No adding structures or arrays.
15 //  . All of the constants in a switch statement are of the correct type
16 //  . The code is in valid SSA form
17 //  . It should be illegal to put a label into any other type (like a structure)
18 //    or to return one. [except constant arrays!]
19 //  . Right now 'add bool 0, 0' is valid.  This isn't particularly good.
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/Type.h"
43 #include "llvm/iPHINode.h"
44 #include "llvm/iTerminators.h"
45 #include "llvm/SymbolTable.h"
46 #include "llvm/Support/CFG.h"
47 #include "Support/STLExtras.h"
48 #include <algorithm>
49
50 #if 0
51 #define t(x) (1 << (unsigned)Type::x)
52 #define SignedIntegralTypes (t(SByteTyID) | t(ShortTyID) |  \
53                              t(IntTyID)   | t(LongTyID))
54 static long UnsignedIntegralTypes = t(UByteTyID) | t(UShortTyID) | 
55                                           t(UIntTyID)  | t(ULongTyID);
56 static const long FloatingPointTypes    = t(FloatTyID) | t(DoubleTyID);
57
58 static const long IntegralTypes = SignedIntegralTypes | UnsignedIntegralTypes;
59
60 static long ValidTypes[Type::FirstDerivedTyID] = {
61   [(unsigned)Instruction::UnaryOps::Not] t(BoolTyID),
62   //[Instruction::UnaryOps::Add] = IntegralTypes,
63   //  [Instruction::Sub] = IntegralTypes,
64 };
65 #undef t
66 #endif
67
68 // CheckFailed - A check failed, so print out the condition and the message that
69 // failed.  This provides a nice place to put a breakpoint if you want to see
70 // why something is not correct.
71 //
72 static inline void CheckFailed(const char *Cond, const std::string &Message,
73                                const Value *V1 = 0, const Value *V2 = 0) {
74   std::cerr << Message << "\n";
75   if (V1) { std::cerr << V1 << "\n"; }
76   if (V2) { std::cerr << V2 << "\n"; }
77 }
78
79 // Assert - We know that cond should be true, if not print an error message.
80 #define Assert(C, M) \
81   do { if (!(C)) { CheckFailed(#C, M); Broken = true; } } while (0)
82 #define Assert1(C, M, V1) \
83   do { if (!(C)) { CheckFailed(#C, M, V1); Broken = true; } } while (0)
84 #define Assert2(C, M, V1, V2) \
85   do { if (!(C)) { CheckFailed(#C, M, V1, V2); Broken = true; } } while (0)
86
87
88 // verifyInstruction - Verify that a non-terminator instruction is well formed.
89 //
90 static bool verifyInstruction(const Instruction *I) {
91   bool Broken = false;
92   assert(I->getParent() && "Instruction not embedded in basic block!");
93   Assert1(!isa<TerminatorInst>(I),
94           "Terminator instruction found embedded in basic block!\n", I);
95
96   if (isa<ReturnInst>(I)) {
97     const Function *F = I->getParent()->getParent();
98     if (I->getNumOperands() == 0)
99       Assert1(F->getReturnType() == Type::VoidTy,
100               "Function returns no value, but ret instruction found that does!",
101               I);
102     else
103       Assert2(F->getReturnType() == I->getOperand(0)->getType(),
104               "Function return type does not match operand "
105               "type of return inst!", I, F->getReturnType());
106   }
107
108   // Check that all uses of the instruction, if they are instructions
109   // themselves, actually have parent basic blocks.
110   //
111   for (User::use_const_iterator UI = I->use_begin(), UE = I->use_end();
112        UI != UE; ++UI) {
113     if (Instruction *Used = dyn_cast<Instruction>(*UI))
114       Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
115               " embeded in a basic block!", I, Used);
116   }
117
118   // Check that PHI nodes look ok
119   if (const PHINode *PN = dyn_cast<PHINode>(I)) {
120     std::vector<const BasicBlock*> Preds(pred_begin(I->getParent()),
121                                          pred_end(I->getParent()));
122     // Loop over all of the incoming values, make sure that there are
123     // predecessors for each one...
124     //
125     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
126       const BasicBlock *BB = PN->getIncomingBlock(i);
127       std::vector<const BasicBlock*>::iterator PI =
128         find(Preds.begin(), Preds.end(), BB);
129       Assert2(PI != Preds.end(), "PHI node has entry for basic block that"
130               " is not a predecessor!", PN, BB);
131       if (PI != Preds.end()) Preds.erase(PI);
132     }
133
134     // There should be no entries left in the predecessor list...
135     for (std::vector<const BasicBlock*>::iterator I = Preds.begin(),
136            E = Preds.end(); I != E; ++I)
137       Assert2(0, "PHI node does not have entry for a predecessor basic block!",
138               PN, *I);
139   } else {
140     // Check that non-phi nodes are not self referential...
141     for (Value::use_const_iterator UI = I->use_begin(), UE = I->use_end();
142          UI != UE; ++UI)
143       Assert1(*UI != (const User*)I,
144               "Only PHI nodes may reference their own value!", I);
145   }
146
147   return Broken;
148 }
149
150
151 // verifyBasicBlock - Verify that a basic block is well formed...
152 //
153 static bool verifyBasicBlock(const BasicBlock *BB) {
154   bool Broken = false;
155   Assert1(BB->getTerminator(), "Basic Block does not have terminator!\n", BB);
156
157   // Verify all instructions, except the terminator...
158   Broken |= reduce_apply_bool(BB->begin(), BB->end()-1, verifyInstruction);
159   return Broken;
160 }
161
162 // verifySymbolTable - Verify that a method or module symbol table is ok
163 //
164 static bool verifySymbolTable(const SymbolTable *ST) {
165   if (ST == 0) return false;
166   bool Broken = false;
167
168   // Loop over all of the types in the symbol table...
169   for (SymbolTable::const_iterator TI = ST->begin(), TE = ST->end();
170        TI != TE; ++TI)
171     for (SymbolTable::type_const_iterator I = TI->second.begin(),
172            E = TI->second.end(); I != E; ++I) {
173       Value *V = I->second;
174
175       // Check that there are no void typed values in the symbol table.  Values
176       // with a void type cannot be put into symbol tables because they cannot
177       // have names!
178       Assert1(V->getType() != Type::VoidTy,
179               "Values with void type are not allowed to have names!\n", V);
180     }
181
182   return Broken;
183 }
184
185 // verifyMethod - Verify that a method is ok.  Return true if not so that
186 // verifyModule and direct clients of the verifyMethod function are correctly
187 // informed.
188 //
189 bool verifyMethod(const Function *F) {
190   if (F->isExternal()) return false;  // Can happen if called by verifyModule
191   bool Broken = verifySymbolTable(F->getSymbolTable());
192
193   Assert1(!F->isExternal() || F->hasExternalLinkage(),
194           "Function cannot be an 'internal' 'declare'ation!", F);
195
196   const BasicBlock *Entry = F->getEntryNode();
197   Assert1(pred_begin(Entry) == pred_end(Entry),
198           "Entry block to method must not have predecessors!", Entry);
199
200   Broken |= reduce_apply_bool(F->begin(), F->end(), verifyBasicBlock);
201   return Broken;
202 }
203
204
205 namespace {  // Anonymous namespace for class
206   struct VerifierPass : public MethodPass {
207
208     bool doInitialization(Module *M) {
209       verifySymbolTable(M->getSymbolTable());
210       return false;
211     }
212     bool runOnMethod(Function *F) { verifyMethod(F); return false; }
213   };
214 }
215
216 Pass *createVerifierPass() {
217   return new VerifierPass();
218 }
219
220 // verifyModule - Check a module for errors, printing messages on stderr.
221 // Return true if the module is corrupt.
222 //
223 bool verifyModule(const Module *M) {
224   return verifySymbolTable(M->getSymbolTable()) |
225          reduce_apply_bool(M->begin(), M->end(), verifyMethod);
226 }