Implement a simple optimization for the termination condition of the loop.
[oota-llvm.git] / lib / VMCore / Verifier.cpp
1 //===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the function verifier interface, that can be used for some
11 // sanity checking of input to the system.
12 //
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.
15 //
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...
39 //
40 //===----------------------------------------------------------------------===//
41
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/Instructions.h"
51 #include "llvm/Intrinsics.h"
52 #include "llvm/PassManager.h"
53 #include "llvm/SymbolTable.h"
54 #include "llvm/Analysis/Dominators.h"
55 #include "llvm/Support/CFG.h"
56 #include "llvm/Support/InstVisitor.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include <algorithm>
59 #include <iostream>
60 #include <sstream>
61 using namespace llvm;
62
63 namespace {  // Anonymous namespace for class
64
65   struct Verifier : public FunctionPass, InstVisitor<Verifier> {
66     bool Broken;          // Is this module found to be broken?
67     bool RealPass;        // Are we not being run by a PassManager?
68     VerifierFailureAction action;
69                           // What to do if verification fails.
70     Module *Mod;          // Module we are verifying right now
71     DominatorSet *DS;     // Dominator set, caution can be null!
72     std::stringstream msgs;  // A stringstream to collect messages
73
74     /// InstInThisBlock - when verifying a basic block, keep track of all of the
75     /// instructions we have seen so far.  This allows us to do efficient
76     /// dominance checks for the case when an instruction has an operand that is
77     /// an instruction in the same block.
78     std::set<Instruction*> InstsInThisBlock;
79
80     Verifier()
81         : Broken(false), RealPass(true), action(AbortProcessAction),
82           DS(0), msgs( std::ios::app | std::ios::out ) {}
83     Verifier( VerifierFailureAction ctn )
84         : Broken(false), RealPass(true), action(ctn), DS(0),
85           msgs( std::ios::app | std::ios::out ) {}
86     Verifier(bool AB )
87         : Broken(false), RealPass(true),
88           action( AB ? AbortProcessAction : PrintMessageAction), DS(0),
89           msgs( std::ios::app | std::ios::out ) {}
90     Verifier(DominatorSet &ds)
91       : Broken(false), RealPass(false), action(PrintMessageAction),
92         DS(&ds), msgs( std::ios::app | std::ios::out ) {}
93
94
95     bool doInitialization(Module &M) {
96       Mod = &M;
97       verifySymbolTable(M.getSymbolTable());
98
99       // If this is a real pass, in a pass manager, we must abort before
100       // returning back to the pass manager, or else the pass manager may try to
101       // run other passes on the broken module.
102       if (RealPass)
103         abortIfBroken();
104       return false;
105     }
106
107     bool runOnFunction(Function &F) {
108       // Get dominator information if we are being run by PassManager
109       if (RealPass) DS = &getAnalysis<DominatorSet>();
110       visit(F);
111       InstsInThisBlock.clear();
112
113       // If this is a real pass, in a pass manager, we must abort before
114       // returning back to the pass manager, or else the pass manager may try to
115       // run other passes on the broken module.
116       if (RealPass)
117         abortIfBroken();
118
119       return false;
120     }
121
122     bool doFinalization(Module &M) {
123       // Scan through, checking all of the external function's linkage now...
124       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
125         visitGlobalValue(*I);
126
127         // Check to make sure function prototypes are okay.
128         if (I->isExternal()) visitFunction(*I);
129       }
130
131       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
132         visitGlobalVariable(*I);
133
134       // If the module is broken, abort at this time.
135       abortIfBroken();
136       return false;
137     }
138
139     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
140       AU.setPreservesAll();
141       if (RealPass)
142         AU.addRequired<DominatorSet>();
143     }
144
145     /// abortIfBroken - If the module is broken and we are supposed to abort on
146     /// this condition, do so.
147     ///
148     void abortIfBroken() {
149       if (Broken)
150       {
151         msgs << "Broken module found, ";
152         switch (action)
153         {
154           case AbortProcessAction:
155             msgs << "compilation aborted!\n";
156             std::cerr << msgs.str();
157             abort();
158           case ThrowExceptionAction:
159             msgs << "verification terminated.\n";
160             throw msgs.str();
161           case PrintMessageAction:
162             msgs << "verification continues.\n";
163             std::cerr << msgs.str();
164             break;
165           case ReturnStatusAction:
166             break;
167         }
168       }
169     }
170
171
172     // Verification methods...
173     void verifySymbolTable(SymbolTable &ST);
174     void visitGlobalValue(GlobalValue &GV);
175     void visitGlobalVariable(GlobalVariable &GV);
176     void visitFunction(Function &F);
177     void visitBasicBlock(BasicBlock &BB);
178     void visitPHINode(PHINode &PN);
179     void visitBinaryOperator(BinaryOperator &B);
180     void visitShiftInst(ShiftInst &SI);
181     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
182     void visitCallInst(CallInst &CI);
183     void visitGetElementPtrInst(GetElementPtrInst &GEP);
184     void visitLoadInst(LoadInst &LI);
185     void visitStoreInst(StoreInst &SI);
186     void visitInstruction(Instruction &I);
187     void visitTerminatorInst(TerminatorInst &I);
188     void visitReturnInst(ReturnInst &RI);
189     void visitSwitchInst(SwitchInst &SI);
190     void visitSelectInst(SelectInst &SI);
191     void visitUserOp1(Instruction &I);
192     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
193     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
194
195
196     void WriteValue(const Value *V) {
197       if (!V) return;
198       if (isa<Instruction>(V)) {
199         msgs << *V;
200       } else {
201         WriteAsOperand (msgs, V, true, true, Mod);
202         msgs << "\n";
203       }
204     }
205
206     void WriteType(const Type* T ) {
207       if ( !T ) return;
208       WriteTypeSymbolic(msgs, T, Mod );
209     }
210
211
212     // CheckFailed - A check failed, so print out the condition and the message
213     // that failed.  This provides a nice place to put a breakpoint if you want
214     // to see why something is not correct.
215     void CheckFailed(const std::string &Message,
216                      const Value *V1 = 0, const Value *V2 = 0,
217                      const Value *V3 = 0, const Value *V4 = 0) {
218       msgs << Message << "\n";
219       WriteValue(V1);
220       WriteValue(V2);
221       WriteValue(V3);
222       WriteValue(V4);
223       Broken = true;
224     }
225
226     void CheckFailed( const std::string& Message, const Value* V1,
227                       const Type* T2, const Value* V3 = 0 ) {
228       msgs << Message << "\n";
229       WriteValue(V1);
230       WriteType(T2);
231       WriteValue(V3);
232       Broken = true;
233     }
234   };
235
236   RegisterOpt<Verifier> X("verify", "Module Verifier");
237 } // End anonymous namespace
238
239
240 // Assert - We know that cond should be true, if not print an error message.
241 #define Assert(C, M) \
242   do { if (!(C)) { CheckFailed(M); return; } } while (0)
243 #define Assert1(C, M, V1) \
244   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
245 #define Assert2(C, M, V1, V2) \
246   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
247 #define Assert3(C, M, V1, V2, V3) \
248   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
249 #define Assert4(C, M, V1, V2, V3, V4) \
250   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
251
252
253 void Verifier::visitGlobalValue(GlobalValue &GV) {
254   Assert1(!GV.isExternal() || GV.hasExternalLinkage(),
255           "Global is external, but doesn't have external linkage!", &GV);
256   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
257           "Only global variables can have appending linkage!", &GV);
258
259   if (GV.hasAppendingLinkage()) {
260     GlobalVariable &GVar = cast<GlobalVariable>(GV);
261     Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
262             "Only global arrays can have appending linkage!", &GV);
263   }
264 }
265
266 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
267   if (GV.hasInitializer())
268     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
269             "Global variable initializer type does not match global "
270             "variable type!", &GV);
271
272   visitGlobalValue(GV);
273 }
274
275
276 // verifySymbolTable - Verify that a function or module symbol table is ok
277 //
278 void Verifier::verifySymbolTable(SymbolTable &ST) {
279
280   // Loop over all of the values in all type planes in the symbol table.
281   for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
282        PE = ST.plane_end(); PI != PE; ++PI)
283     for (SymbolTable::value_const_iterator VI = PI->second.begin(),
284          VE = PI->second.end(); VI != VE; ++VI) {
285       Value *V = VI->second;
286       // Check that there are no void typed values in the symbol table.  Values
287       // with a void type cannot be put into symbol tables because they cannot
288       // have names!
289       Assert1(V->getType() != Type::VoidTy,
290         "Values with void type are not allowed to have names!", V);
291     }
292 }
293
294 // visitFunction - Verify that a function is ok.
295 //
296 void Verifier::visitFunction(Function &F) {
297   Assert1(!F.isVarArg() || F.getCallingConv() == CallingConv::C,
298           "Varargs functions must have C calling conventions!", &F);
299
300   // Check function arguments.
301   const FunctionType *FT = F.getFunctionType();
302   unsigned NumArgs = F.getArgumentList().size();
303
304   Assert2(FT->getNumParams() == NumArgs,
305           "# formal arguments must match # of arguments for function type!",
306           &F, FT);
307   Assert1(F.getReturnType()->isFirstClassType() ||
308           F.getReturnType() == Type::VoidTy,
309           "Functions cannot return aggregate values!", &F);
310
311   // Check that the argument values match the function type for this function...
312   unsigned i = 0;
313   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I, ++i) {
314     Assert2(I->getType() == FT->getParamType(i),
315             "Argument value does not match function argument type!",
316             I, FT->getParamType(i));
317     // Make sure no aggregates are passed by value.
318     Assert1(I->getType()->isFirstClassType(),
319             "Functions cannot take aggregates as arguments by value!", I);
320    }
321
322   if (!F.isExternal()) {
323     verifySymbolTable(F.getSymbolTable());
324
325     // Check the entry node
326     BasicBlock *Entry = &F.getEntryBlock();
327     Assert1(pred_begin(Entry) == pred_end(Entry),
328             "Entry block to function must not have predecessors!", Entry);
329   }
330 }
331
332
333 // verifyBasicBlock - Verify that a basic block is well formed...
334 //
335 void Verifier::visitBasicBlock(BasicBlock &BB) {
336   InstsInThisBlock.clear();
337
338   // Ensure that basic blocks have terminators!
339   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
340
341   // Check constraints that this basic block imposes on all of the PHI nodes in
342   // it.
343   if (isa<PHINode>(BB.front())) {
344     std::vector<BasicBlock*> Preds(pred_begin(&BB), pred_end(&BB));
345     std::sort(Preds.begin(), Preds.end());
346     PHINode *PN;
347     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
348
349       // Ensure that PHI nodes have at least one entry!
350       Assert1(PN->getNumIncomingValues() != 0,
351               "PHI nodes must have at least one entry.  If the block is dead, "
352               "the PHI should be removed!", PN);
353       Assert1(PN->getNumIncomingValues() == Preds.size(),
354               "PHINode should have one entry for each predecessor of its "
355               "parent basic block!", PN);
356
357       // Get and sort all incoming values in the PHI node...
358       std::vector<std::pair<BasicBlock*, Value*> > Values;
359       Values.reserve(PN->getNumIncomingValues());
360       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
361         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
362                                         PN->getIncomingValue(i)));
363       std::sort(Values.begin(), Values.end());
364
365       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
366         // Check to make sure that if there is more than one entry for a
367         // particular basic block in this PHI node, that the incoming values are
368         // all identical.
369         //
370         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
371                 Values[i].second == Values[i-1].second,
372                 "PHI node has multiple entries for the same basic block with "
373                 "different incoming values!", PN, Values[i].first,
374                 Values[i].second, Values[i-1].second);
375
376         // Check to make sure that the predecessors and PHI node entries are
377         // matched up.
378         Assert3(Values[i].first == Preds[i],
379                 "PHI node entries do not match predecessors!", PN,
380                 Values[i].first, Preds[i]);
381       }
382     }
383   }
384 }
385
386 void Verifier::visitTerminatorInst(TerminatorInst &I) {
387   // Ensure that terminators only exist at the end of the basic block.
388   Assert1(&I == I.getParent()->getTerminator(),
389           "Terminator found in the middle of a basic block!", I.getParent());
390   visitInstruction(I);
391 }
392
393 void Verifier::visitReturnInst(ReturnInst &RI) {
394   Function *F = RI.getParent()->getParent();
395   if (RI.getNumOperands() == 0)
396     Assert2(F->getReturnType() == Type::VoidTy,
397             "Found return instr that returns void in Function of non-void "
398             "return type!", &RI, F->getReturnType());
399   else
400     Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
401             "Function return type does not match operand "
402             "type of return inst!", &RI, F->getReturnType());
403
404   // Check to make sure that the return value has necessary properties for
405   // terminators...
406   visitTerminatorInst(RI);
407 }
408
409 void Verifier::visitSwitchInst(SwitchInst &SI) {
410   // Check to make sure that all of the constants in the switch instruction
411   // have the same type as the switched-on value.
412   const Type *SwitchTy = SI.getCondition()->getType();
413   for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
414     Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
415             "Switch constants must all be same type as switch value!", &SI);
416
417   visitTerminatorInst(SI);
418 }
419
420 void Verifier::visitSelectInst(SelectInst &SI) {
421   Assert1(SI.getCondition()->getType() == Type::BoolTy,
422           "Select condition type must be bool!", &SI);
423   Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
424           "Select values must have identical types!", &SI);
425   Assert1(SI.getTrueValue()->getType() == SI.getType(),
426           "Select values must have same type as select instruction!", &SI);
427   visitInstruction(SI);
428 }
429
430
431 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
432 /// a pass, if any exist, it's an error.
433 ///
434 void Verifier::visitUserOp1(Instruction &I) {
435   Assert1(0, "User-defined operators should not live outside of a pass!",
436           &I);
437 }
438
439 /// visitPHINode - Ensure that a PHI node is well formed.
440 ///
441 void Verifier::visitPHINode(PHINode &PN) {
442   // Ensure that the PHI nodes are all grouped together at the top of the block.
443   // This can be tested by checking whether the instruction before this is
444   // either nonexistent (because this is begin()) or is a PHI node.  If not,
445   // then there is some other instruction before a PHI.
446   Assert2(&PN.getParent()->front() == &PN || isa<PHINode>(PN.getPrev()),
447           "PHI nodes not grouped at top of basic block!",
448           &PN, PN.getParent());
449
450   // Check that all of the operands of the PHI node have the same type as the
451   // result.
452   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
453     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
454             "PHI node operands are not the same type as the result!", &PN);
455
456   // All other PHI node constraints are checked in the visitBasicBlock method.
457
458   visitInstruction(PN);
459 }
460
461 void Verifier::visitCallInst(CallInst &CI) {
462   Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
463           "Called function must be a pointer!", &CI);
464   const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
465   Assert1(isa<FunctionType>(FPTy->getElementType()),
466           "Called function is not pointer to function type!", &CI);
467
468   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
469
470   // Verify that the correct number of arguments are being passed
471   if (FTy->isVarArg())
472     Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
473             "Called function requires more parameters than were provided!",&CI);
474   else
475     Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
476             "Incorrect number of arguments passed to called function!", &CI);
477
478   // Verify that all arguments to the call match the function type...
479   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
480     Assert3(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
481             "Call parameter type does not match function signature!",
482             CI.getOperand(i+1), FTy->getParamType(i), &CI);
483
484   if (Function *F = CI.getCalledFunction())
485     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
486       visitIntrinsicFunctionCall(ID, CI);
487
488   visitInstruction(CI);
489 }
490
491 /// visitBinaryOperator - Check that both arguments to the binary operator are
492 /// of the same type!
493 ///
494 void Verifier::visitBinaryOperator(BinaryOperator &B) {
495   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
496           "Both operands to a binary operator are not of the same type!", &B);
497
498   // Check that logical operators are only used with integral operands.
499   if (B.getOpcode() == Instruction::And || B.getOpcode() == Instruction::Or ||
500       B.getOpcode() == Instruction::Xor) {
501     Assert1(B.getType()->isIntegral(),
502             "Logical operators only work with integral types!", &B);
503     Assert1(B.getType() == B.getOperand(0)->getType(),
504             "Logical operators must have same type for operands and result!",
505             &B);
506   } else if (isa<SetCondInst>(B)) {
507     // Check that setcc instructions return bool
508     Assert1(B.getType() == Type::BoolTy,
509             "setcc instructions must return boolean values!", &B);
510   } else {
511     // Arithmetic operators only work on integer or fp values
512     Assert1(B.getType() == B.getOperand(0)->getType(),
513             "Arithmetic operators must have same type for operands and result!",
514             &B);
515     Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
516             isa<PackedType>(B.getType()),
517             "Arithmetic operators must have integer, fp, or packed type!", &B);
518   }
519
520   visitInstruction(B);
521 }
522
523 void Verifier::visitShiftInst(ShiftInst &SI) {
524   Assert1(SI.getType()->isInteger(),
525           "Shift must return an integer result!", &SI);
526   Assert1(SI.getType() == SI.getOperand(0)->getType(),
527           "Shift return type must be same as first operand!", &SI);
528   Assert1(SI.getOperand(1)->getType() == Type::UByteTy,
529           "Second operand to shift must be ubyte type!", &SI);
530   visitInstruction(SI);
531 }
532
533 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
534   const Type *ElTy =
535     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
536                    std::vector<Value*>(GEP.idx_begin(), GEP.idx_end()), true);
537   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
538   Assert2(PointerType::get(ElTy) == GEP.getType(),
539           "GEP is not of right type for indices!", &GEP, ElTy);
540   visitInstruction(GEP);
541 }
542
543 void Verifier::visitLoadInst(LoadInst &LI) {
544   const Type *ElTy =
545     cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
546   Assert2(ElTy == LI.getType(),
547           "Load result type does not match pointer operand type!", &LI, ElTy);
548   visitInstruction(LI);
549 }
550
551 void Verifier::visitStoreInst(StoreInst &SI) {
552   const Type *ElTy =
553     cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
554   Assert2(ElTy == SI.getOperand(0)->getType(),
555           "Stored value type does not match pointer operand type!", &SI, ElTy);
556   visitInstruction(SI);
557 }
558
559
560 /// verifyInstruction - Verify that an instruction is well formed.
561 ///
562 void Verifier::visitInstruction(Instruction &I) {
563   BasicBlock *BB = I.getParent();
564   Assert1(BB, "Instruction not embedded in basic block!", &I);
565
566   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
567     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
568          UI != UE; ++UI)
569       Assert1(*UI != (User*)&I ||
570               !DS->dominates(&BB->getParent()->getEntryBlock(), BB),
571               "Only PHI nodes may reference their own value!", &I);
572   }
573
574   // Check that void typed values don't have names
575   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
576           "Instruction has a name, but provides a void value!", &I);
577
578   // Check that the return value of the instruction is either void or a legal
579   // value type.
580   Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType(),
581           "Instruction returns a non-scalar type!", &I);
582
583   // Check that all uses of the instruction, if they are instructions
584   // themselves, actually have parent basic blocks.  If the use is not an
585   // instruction, it is an error!
586   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
587        UI != UE; ++UI) {
588     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
589             *UI);
590     Instruction *Used = cast<Instruction>(*UI);
591     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
592             " embeded in a basic block!", &I, Used);
593   }
594
595   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
596     // Check to make sure that the "address of" an intrinsic function is never
597     // taken.
598     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
599     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
600       Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
601               "Cannot take the address of an intrinsic!", &I);
602     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
603       Assert1(OpBB->getParent() == BB->getParent(),
604               "Referring to a basic block in another function!", &I);
605     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
606       Assert1(OpArg->getParent() == BB->getParent(),
607               "Referring to an argument in another function!", &I);
608     } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
609       BasicBlock *OpBlock = Op->getParent();
610
611       // Check that a definition dominates all of its uses.
612       if (!isa<PHINode>(I)) {
613         // Invoke results are only usable in the normal destination, not in the
614         // exceptional destination.
615         if (InvokeInst *II = dyn_cast<InvokeInst>(Op))
616           OpBlock = II->getNormalDest();
617         else if (OpBlock == BB) {
618           // If they are in the same basic block, make sure that the definition
619           // comes before the use.
620           Assert2(InstsInThisBlock.count(Op) ||
621                   !DS->dominates(&BB->getParent()->getEntryBlock(), BB),
622                   "Instruction does not dominate all uses!", Op, &I);
623         }
624
625         // Definition must dominate use unless use is unreachable!
626         Assert2(DS->dominates(OpBlock, BB) ||
627                 !DS->dominates(&BB->getParent()->getEntryBlock(), BB),
628                 "Instruction does not dominate all uses!", Op, &I);
629       } else {
630         // PHI nodes are more difficult than other nodes because they actually
631         // "use" the value in the predecessor basic blocks they correspond to.
632         BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
633         Assert2(DS->dominates(OpBlock, PredBB) ||
634                 !DS->dominates(&BB->getParent()->getEntryBlock(), PredBB),
635                 "Instruction does not dominate all uses!", Op, &I);
636       }
637     }
638   }
639   InstsInThisBlock.insert(&I);
640 }
641
642 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
643 ///
644 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
645   Function *IF = CI.getCalledFunction();
646   const FunctionType *FT = IF->getFunctionType();
647   Assert1(IF->isExternal(), "Intrinsic functions should never be defined!", IF);
648   unsigned NumArgs = 0;
649
650   // FIXME: this should check the return type of each intrinsic as well, also
651   // arguments!
652   switch (ID) {
653   case Intrinsic::vastart:
654     Assert1(CI.getParent()->getParent()->getFunctionType()->isVarArg(),
655             "llvm.va_start intrinsic may only occur in function with variable"
656             " args!", &CI);
657     NumArgs = 1;
658     break;
659   case Intrinsic::vaend:          NumArgs = 1; break;
660   case Intrinsic::vacopy:         NumArgs = 2; break;
661
662   case Intrinsic::returnaddress:
663   case Intrinsic::frameaddress:
664     Assert1(isa<PointerType>(FT->getReturnType()),
665             "llvm.(frame|return)address must return pointers", IF);
666     Assert1(FT->getNumParams() == 1 && isa<ConstantInt>(CI.getOperand(1)),
667        "llvm.(frame|return)address require a single constant integer argument",
668             &CI);
669     NumArgs = 1;
670     break;
671
672   // Verify that read and write port have integral parameters of the correct
673   // signed-ness.
674   case Intrinsic::writeport:
675     Assert1(FT->getNumParams() == 2,
676             "Illegal # arguments for intrinsic function!", IF);
677     Assert1(FT->getParamType(0)->isIntegral(),
678             "First argument not unsigned int!", IF);
679     Assert1(FT->getParamType(1)->isUnsigned(),
680             "First argument not unsigned int!", IF);
681     NumArgs = 2;
682     break;
683
684   case Intrinsic::writeio:
685     Assert1(FT->getNumParams() == 2,
686             "Illegal # arguments for intrinsic function!", IF);
687     Assert1(FT->getParamType(0)->isFirstClassType(),
688             "First argument not a first class type!", IF);
689     Assert1(isa<PointerType>(FT->getParamType(1)),
690             "Second argument not a pointer!", IF);
691     NumArgs = 2;
692     break;
693
694   case Intrinsic::readport:
695     Assert1(FT->getNumParams() == 1,
696             "Illegal # arguments for intrinsic function!", IF);
697     Assert1(FT->getReturnType()->isFirstClassType(),
698             "Return type is not a first class type!", IF);
699     Assert1(FT->getParamType(0)->isUnsigned(),
700             "First argument not unsigned int!", IF);
701     NumArgs = 1;
702     break;
703
704   case Intrinsic::readio: {
705     const PointerType *ParamType = dyn_cast<PointerType>(FT->getParamType(0));
706     const Type *ReturnType = FT->getReturnType();
707
708     Assert1(FT->getNumParams() == 1,
709             "Illegal # arguments for intrinsic function!", IF);
710     Assert1(ParamType, "First argument not a pointer!", IF);
711     Assert1(ParamType->getElementType() == ReturnType,
712             "Pointer type doesn't match return type!", IF);
713     NumArgs = 1;
714     break;
715   }
716
717   case Intrinsic::isunordered:
718     Assert1(FT->getNumParams() == 2,
719             "Illegal # arguments for intrinsic function!", IF);
720     Assert1(FT->getReturnType() == Type::BoolTy,
721             "Return type is not bool!", IF);
722     Assert1(FT->getParamType(0) == FT->getParamType(1),
723             "Arguments must be of the same type!", IF);
724     Assert1(FT->getParamType(0)->isFloatingPoint(),
725             "Argument is not a floating point type!", IF);
726     NumArgs = 2;
727     break;
728
729   case Intrinsic::ctpop:
730   case Intrinsic::ctlz:
731   case Intrinsic::cttz:
732     Assert1(FT->getNumParams() == 1,
733             "Illegal # arguments for intrinsic function!", IF);
734     Assert1(FT->getReturnType() == FT->getParamType(0),
735             "Return type does not match source type", IF);
736     Assert1(FT->getParamType(0)->isIntegral(),
737             "Argument must be of an int type!", IF);
738     NumArgs = 1;
739     break;
740
741   case Intrinsic::sqrt:
742     Assert1(FT->getNumParams() == 1,
743             "Illegal # arguments for intrinsic function!", IF);
744     Assert1(FT->getParamType(0)->isFloatingPoint(),
745             "Argument is not a floating point type!", IF);
746     Assert1(FT->getReturnType() == FT->getParamType(0),
747             "Return type is not the same as argument type!", IF);
748     NumArgs = 1;
749     break;
750
751   case Intrinsic::setjmp:          NumArgs = 1; break;
752   case Intrinsic::longjmp:         NumArgs = 2; break;
753   case Intrinsic::sigsetjmp:       NumArgs = 2; break;
754   case Intrinsic::siglongjmp:      NumArgs = 2; break;
755
756   case Intrinsic::gcroot:
757     Assert1(FT->getNumParams() == 2,
758             "Illegal # arguments for intrinsic function!", IF);
759     Assert1(isa<Constant>(CI.getOperand(2)),
760             "Second argument to llvm.gcroot must be a constant!", &CI);
761     NumArgs = 2;
762     break;
763   case Intrinsic::gcread:          NumArgs = 2; break;
764   case Intrinsic::gcwrite:         NumArgs = 3; break;
765
766   case Intrinsic::dbg_stoppoint:   NumArgs = 4; break;
767   case Intrinsic::dbg_region_start:NumArgs = 1; break;
768   case Intrinsic::dbg_region_end:  NumArgs = 1; break;
769   case Intrinsic::dbg_func_start:  NumArgs = 1; break;
770   case Intrinsic::dbg_declare:     NumArgs = 1; break;
771
772   case Intrinsic::memcpy:          NumArgs = 4; break;
773   case Intrinsic::memmove:         NumArgs = 4; break;
774   case Intrinsic::memset:          NumArgs = 4; break;
775
776   case Intrinsic::prefetch:        NumArgs = 3; break;
777   case Intrinsic::pcmarker:
778     NumArgs = 1;
779     Assert1(isa<Constant>(CI.getOperand(1)),
780             "First argument to llvm.pcmarker must be a constant!", &CI);
781     break;
782
783   case Intrinsic::not_intrinsic:
784     assert(0 && "Invalid intrinsic!"); NumArgs = 0; break;
785   }
786
787   Assert1(FT->getNumParams() == NumArgs || (FT->getNumParams() < NumArgs &&
788                                              FT->isVarArg()),
789           "Illegal # arguments for intrinsic function!", IF);
790 }
791
792
793 //===----------------------------------------------------------------------===//
794 //  Implement the public interfaces to this file...
795 //===----------------------------------------------------------------------===//
796
797 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
798   return new Verifier(action);
799 }
800
801
802 // verifyFunction - Create
803 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
804   Function &F = const_cast<Function&>(f);
805   assert(!F.isExternal() && "Cannot verify external functions");
806
807   FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
808   Verifier *V = new Verifier(action);
809   FPM.add(V);
810   FPM.run(F);
811   return V->Broken;
812 }
813
814 /// verifyModule - Check a module for errors, printing messages on stderr.
815 /// Return true if the module is corrupt.
816 ///
817 bool llvm::verifyModule(const Module &M, VerifierFailureAction action) {
818   PassManager PM;
819   Verifier *V = new Verifier(action);
820   PM.add(V);
821   PM.run((Module&)M);
822   return V->Broken;
823 }
824
825 // vim: sw=2