0aef414a68142980c025d46d4fc2aae16784eb31
[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 is distributed under the University of Illinois Open Source
6 // 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 i32 %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/CallingConv.h"
44 #include "llvm/Constants.h"
45 #include "llvm/DerivedTypes.h"
46 #include "llvm/InlineAsm.h"
47 #include "llvm/IntrinsicInst.h"
48 #include "llvm/Module.h"
49 #include "llvm/ModuleProvider.h"
50 #include "llvm/Pass.h"
51 #include "llvm/PassManager.h"
52 #include "llvm/Analysis/Dominators.h"
53 #include "llvm/Assembly/Writer.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/Support/CallSite.h"
56 #include "llvm/Support/CFG.h"
57 #include "llvm/Support/InstVisitor.h"
58 #include "llvm/Support/Streams.h"
59 #include "llvm/ADT/SmallPtrSet.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/StringExtras.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include "llvm/Support/Compiler.h"
64 #include <algorithm>
65 #include <sstream>
66 #include <cstdarg>
67 using namespace llvm;
68
69 namespace {  // Anonymous namespace for class
70   struct VISIBILITY_HIDDEN PreVerifier : public FunctionPass {
71     static char ID; // Pass ID, replacement for typeid
72
73     PreVerifier() : FunctionPass((intptr_t)&ID) { }
74
75     // Check that the prerequisites for successful DominatorTree construction
76     // are satisfied.
77     bool runOnFunction(Function &F) {
78       bool Broken = false;
79
80       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
81         if (I->empty() || !I->back().isTerminator()) {
82           cerr << "Basic Block does not have terminator!\n";
83           WriteAsOperand(*cerr, I, true);
84           cerr << "\n";
85           Broken = true;
86         }
87       }
88
89       if (Broken)
90         abort();
91
92       return false;
93     }
94   };
95 }
96
97 char PreVerifier::ID = 0;
98 static RegisterPass<PreVerifier>
99 PreVer("preverify", "Preliminary module verification");
100 static const PassInfo *const PreVerifyID = &PreVer;
101
102 namespace {
103   struct VISIBILITY_HIDDEN
104      Verifier : public FunctionPass, InstVisitor<Verifier> {
105     static char ID; // Pass ID, replacement for typeid
106     bool Broken;          // Is this module found to be broken?
107     bool RealPass;        // Are we not being run by a PassManager?
108     VerifierFailureAction action;
109                           // What to do if verification fails.
110     Module *Mod;          // Module we are verifying right now
111     DominatorTree *DT; // Dominator Tree, caution can be null!
112     std::stringstream msgs;  // A stringstream to collect messages
113
114     /// InstInThisBlock - when verifying a basic block, keep track of all of the
115     /// instructions we have seen so far.  This allows us to do efficient
116     /// dominance checks for the case when an instruction has an operand that is
117     /// an instruction in the same block.
118     SmallPtrSet<Instruction*, 16> InstsInThisBlock;
119
120     Verifier()
121       : FunctionPass((intptr_t)&ID), 
122       Broken(false), RealPass(true), action(AbortProcessAction),
123       DT(0), msgs( std::ios::app | std::ios::out ) {}
124     explicit Verifier(VerifierFailureAction ctn)
125       : FunctionPass((intptr_t)&ID), 
126       Broken(false), RealPass(true), action(ctn), DT(0),
127       msgs( std::ios::app | std::ios::out ) {}
128     explicit Verifier(bool AB)
129       : FunctionPass((intptr_t)&ID), 
130       Broken(false), RealPass(true),
131       action( AB ? AbortProcessAction : PrintMessageAction), DT(0),
132       msgs( std::ios::app | std::ios::out ) {}
133     explicit Verifier(DominatorTree &dt)
134       : FunctionPass((intptr_t)&ID), 
135       Broken(false), RealPass(false), action(PrintMessageAction),
136       DT(&dt), msgs( std::ios::app | std::ios::out ) {}
137
138
139     bool doInitialization(Module &M) {
140       Mod = &M;
141       verifyTypeSymbolTable(M.getTypeSymbolTable());
142
143       // If this is a real pass, in a pass manager, we must abort before
144       // returning back to the pass manager, or else the pass manager may try to
145       // run other passes on the broken module.
146       if (RealPass)
147         return abortIfBroken();
148       return false;
149     }
150
151     bool runOnFunction(Function &F) {
152       // Get dominator information if we are being run by PassManager
153       if (RealPass) DT = &getAnalysis<DominatorTree>();
154
155       Mod = F.getParent();
156
157       visit(F);
158       InstsInThisBlock.clear();
159
160       // If this is a real pass, in a pass manager, we must abort before
161       // returning back to the pass manager, or else the pass manager may try to
162       // run other passes on the broken module.
163       if (RealPass)
164         return abortIfBroken();
165
166       return false;
167     }
168
169     bool doFinalization(Module &M) {
170       // Scan through, checking all of the external function's linkage now...
171       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
172         visitGlobalValue(*I);
173
174         // Check to make sure function prototypes are okay.
175         if (I->isDeclaration()) visitFunction(*I);
176       }
177
178       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
179            I != E; ++I)
180         visitGlobalVariable(*I);
181
182       for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 
183            I != E; ++I)
184         visitGlobalAlias(*I);
185
186       // If the module is broken, abort at this time.
187       return abortIfBroken();
188     }
189
190     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
191       AU.setPreservesAll();
192       AU.addRequiredID(PreVerifyID);
193       if (RealPass)
194         AU.addRequired<DominatorTree>();
195     }
196
197     /// abortIfBroken - If the module is broken and we are supposed to abort on
198     /// this condition, do so.
199     ///
200     bool abortIfBroken() {
201       if (Broken) {
202         msgs << "Broken module found, ";
203         switch (action) {
204           case AbortProcessAction:
205             msgs << "compilation aborted!\n";
206             cerr << msgs.str();
207             abort();
208           case PrintMessageAction:
209             msgs << "verification continues.\n";
210             cerr << msgs.str();
211             return false;
212           case ReturnStatusAction:
213             msgs << "compilation terminated.\n";
214             return Broken;
215         }
216       }
217       return false;
218     }
219
220
221     // Verification methods...
222     void verifyTypeSymbolTable(TypeSymbolTable &ST);
223     void visitGlobalValue(GlobalValue &GV);
224     void visitGlobalVariable(GlobalVariable &GV);
225     void visitGlobalAlias(GlobalAlias &GA);
226     void visitFunction(Function &F);
227     void visitBasicBlock(BasicBlock &BB);
228     void visitTruncInst(TruncInst &I);
229     void visitZExtInst(ZExtInst &I);
230     void visitSExtInst(SExtInst &I);
231     void visitFPTruncInst(FPTruncInst &I);
232     void visitFPExtInst(FPExtInst &I);
233     void visitFPToUIInst(FPToUIInst &I);
234     void visitFPToSIInst(FPToSIInst &I);
235     void visitUIToFPInst(UIToFPInst &I);
236     void visitSIToFPInst(SIToFPInst &I);
237     void visitIntToPtrInst(IntToPtrInst &I);
238     void visitPtrToIntInst(PtrToIntInst &I);
239     void visitBitCastInst(BitCastInst &I);
240     void visitPHINode(PHINode &PN);
241     void visitBinaryOperator(BinaryOperator &B);
242     void visitICmpInst(ICmpInst &IC);
243     void visitFCmpInst(FCmpInst &FC);
244     void visitExtractElementInst(ExtractElementInst &EI);
245     void visitInsertElementInst(InsertElementInst &EI);
246     void visitShuffleVectorInst(ShuffleVectorInst &EI);
247     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
248     void visitCallInst(CallInst &CI);
249     void visitInvokeInst(InvokeInst &II);
250     void visitGetElementPtrInst(GetElementPtrInst &GEP);
251     void visitLoadInst(LoadInst &LI);
252     void visitStoreInst(StoreInst &SI);
253     void visitInstruction(Instruction &I);
254     void visitTerminatorInst(TerminatorInst &I);
255     void visitReturnInst(ReturnInst &RI);
256     void visitSwitchInst(SwitchInst &SI);
257     void visitSelectInst(SelectInst &SI);
258     void visitUserOp1(Instruction &I);
259     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
260     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
261     void visitAllocationInst(AllocationInst &AI);
262     void visitExtractValueInst(ExtractValueInst &EVI);
263     void visitInsertValueInst(InsertValueInst &IVI);
264
265     void VerifyCallSite(CallSite CS);
266     void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
267                                   unsigned Count, ...);
268     void VerifyAttrs(ParameterAttributes Attrs, const Type *Ty,
269                      bool isReturnValue, const Value *V);
270     void VerifyFunctionAttrs(const FunctionType *FT, const PAListPtr &Attrs,
271                              const Value *V);
272
273     void WriteValue(const Value *V) {
274       if (!V) return;
275       if (isa<Instruction>(V)) {
276         msgs << *V;
277       } else {
278         WriteAsOperand(msgs, V, true, Mod);
279         msgs << "\n";
280       }
281     }
282
283     void WriteType(const Type* T ) {
284       if ( !T ) return;
285       WriteTypeSymbolic(msgs, T, Mod );
286     }
287
288
289     // CheckFailed - A check failed, so print out the condition and the message
290     // that failed.  This provides a nice place to put a breakpoint if you want
291     // to see why something is not correct.
292     void CheckFailed(const std::string &Message,
293                      const Value *V1 = 0, const Value *V2 = 0,
294                      const Value *V3 = 0, const Value *V4 = 0) {
295       msgs << Message << "\n";
296       WriteValue(V1);
297       WriteValue(V2);
298       WriteValue(V3);
299       WriteValue(V4);
300       Broken = true;
301     }
302
303     void CheckFailed( const std::string& Message, const Value* V1,
304                       const Type* T2, const Value* V3 = 0 ) {
305       msgs << Message << "\n";
306       WriteValue(V1);
307       WriteType(T2);
308       WriteValue(V3);
309       Broken = true;
310     }
311   };
312 } // End anonymous namespace
313
314 char Verifier::ID = 0;
315 static RegisterPass<Verifier> X("verify", "Module Verifier");
316
317 // Assert - We know that cond should be true, if not print an error message.
318 #define Assert(C, M) \
319   do { if (!(C)) { CheckFailed(M); return; } } while (0)
320 #define Assert1(C, M, V1) \
321   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
322 #define Assert2(C, M, V1, V2) \
323   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
324 #define Assert3(C, M, V1, V2, V3) \
325   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
326 #define Assert4(C, M, V1, V2, V3, V4) \
327   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
328
329
330 void Verifier::visitGlobalValue(GlobalValue &GV) {
331   Assert1(!GV.isDeclaration() ||
332           GV.hasExternalLinkage() ||
333           GV.hasDLLImportLinkage() ||
334           GV.hasExternalWeakLinkage() ||
335           (isa<GlobalAlias>(GV) &&
336            (GV.hasInternalLinkage() || GV.hasWeakLinkage())),
337   "Global is external, but doesn't have external or dllimport or weak linkage!",
338           &GV);
339
340   Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
341           "Global is marked as dllimport, but not external", &GV);
342   
343   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
344           "Only global variables can have appending linkage!", &GV);
345
346   if (GV.hasAppendingLinkage()) {
347     GlobalVariable &GVar = cast<GlobalVariable>(GV);
348     Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
349             "Only global arrays can have appending linkage!", &GV);
350   }
351 }
352
353 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
354   if (GV.hasInitializer()) {
355     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
356             "Global variable initializer type does not match global "
357             "variable type!", &GV);
358   } else {
359     Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
360             GV.hasExternalWeakLinkage(),
361             "invalid linkage type for global declaration", &GV);
362   }
363
364   visitGlobalValue(GV);
365 }
366
367 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
368   Assert1(!GA.getName().empty(),
369           "Alias name cannot be empty!", &GA);
370   Assert1(GA.hasExternalLinkage() || GA.hasInternalLinkage() ||
371           GA.hasWeakLinkage(),
372           "Alias should have external or external weak linkage!", &GA);
373   Assert1(GA.getAliasee(),
374           "Aliasee cannot be NULL!", &GA);
375   Assert1(GA.getType() == GA.getAliasee()->getType(),
376           "Alias and aliasee types should match!", &GA);
377
378   if (!isa<GlobalValue>(GA.getAliasee())) {
379     const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
380     Assert1(CE && CE->getOpcode() == Instruction::BitCast &&
381             isa<GlobalValue>(CE->getOperand(0)),
382             "Aliasee should be either GlobalValue or bitcast of GlobalValue",
383             &GA);
384   }
385
386   const GlobalValue* Aliasee = GA.resolveAliasedGlobal();
387   Assert1(Aliasee,
388           "Aliasing chain should end with function or global variable", &GA);
389
390   visitGlobalValue(GA);
391 }
392
393 void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
394 }
395
396 // VerifyAttrs - Check the given parameter attributes for an argument or return
397 // value of the specified type.  The value V is printed in error messages.
398 void Verifier::VerifyAttrs(ParameterAttributes Attrs, const Type *Ty, 
399                            bool isReturnValue, const Value *V) {
400   if (Attrs == ParamAttr::None)
401     return;
402
403   if (isReturnValue) {
404     ParameterAttributes RetI = Attrs & ParamAttr::ParameterOnly;
405     Assert1(!RetI, "Attribute " + ParamAttr::getAsString(RetI) +
406             "does not apply to return values!", V);
407   } else {
408     ParameterAttributes ParmI = Attrs & ParamAttr::ReturnOnly;
409     Assert1(!ParmI, "Attribute " + ParamAttr::getAsString(ParmI) +
410             "only applies to return values!", V);
411   }
412
413   for (unsigned i = 0;
414        i < array_lengthof(ParamAttr::MutuallyIncompatible); ++i) {
415     ParameterAttributes MutI = Attrs & ParamAttr::MutuallyIncompatible[i];
416     Assert1(!(MutI & (MutI - 1)), "Attributes " +
417             ParamAttr::getAsString(MutI) + "are incompatible!", V);
418   }
419
420   ParameterAttributes TypeI = Attrs & ParamAttr::typeIncompatible(Ty);
421   Assert1(!TypeI, "Wrong type for attribute " +
422           ParamAttr::getAsString(TypeI), V);
423 }
424
425 // VerifyFunctionAttrs - Check parameter attributes against a function type.
426 // The value V is printed in error messages.
427 void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
428                                    const PAListPtr &Attrs,
429                                    const Value *V) {
430   if (Attrs.isEmpty())
431     return;
432
433   bool SawNest = false;
434
435   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
436     const ParamAttrsWithIndex &Attr = Attrs.getSlot(i);
437
438     const Type *Ty;
439     if (Attr.Index == 0)
440       Ty = FT->getReturnType();
441     else if (Attr.Index-1 < FT->getNumParams())
442       Ty = FT->getParamType(Attr.Index-1);
443     else
444       break;  // VarArgs attributes, don't verify.
445     
446     VerifyAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
447
448     if (Attr.Attrs & ParamAttr::Nest) {
449       Assert1(!SawNest, "More than one parameter has attribute nest!", V);
450       SawNest = true;
451     }
452
453     if (Attr.Attrs & ParamAttr::StructRet)
454       Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
455   }
456 }
457
458 // visitFunction - Verify that a function is ok.
459 //
460 void Verifier::visitFunction(Function &F) {
461   // Check function arguments.
462   const FunctionType *FT = F.getFunctionType();
463   unsigned NumArgs = F.arg_size();
464
465   Assert2(FT->getNumParams() == NumArgs,
466           "# formal arguments must match # of arguments for function type!",
467           &F, FT);
468   Assert1(F.getReturnType()->isFirstClassType() ||
469           F.getReturnType() == Type::VoidTy || 
470           isa<StructType>(F.getReturnType()),
471           "Functions cannot return aggregate values!", &F);
472
473   Assert1(!F.hasStructRetAttr() || F.getReturnType() == Type::VoidTy,
474           "Invalid struct return type!", &F);
475
476   const PAListPtr &Attrs = F.getParamAttrs();
477
478   Assert1(Attrs.isEmpty() ||
479           Attrs.getSlot(Attrs.getNumSlots()-1).Index <= FT->getNumParams(),
480           "Attributes after last parameter!", &F);
481
482   // Check function attributes.
483   VerifyFunctionAttrs(FT, Attrs, &F);
484
485   // Check that this function meets the restrictions on this calling convention.
486   switch (F.getCallingConv()) {
487   default:
488     break;
489   case CallingConv::C:
490     break;
491   case CallingConv::Fast:
492   case CallingConv::Cold:
493   case CallingConv::X86_FastCall:
494     Assert1(!F.isVarArg(),
495             "Varargs functions must have C calling conventions!", &F);
496     break;
497   }
498   
499   // Check that the argument values match the function type for this function...
500   unsigned i = 0;
501   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
502        I != E; ++I, ++i) {
503     Assert2(I->getType() == FT->getParamType(i),
504             "Argument value does not match function argument type!",
505             I, FT->getParamType(i));
506     // Make sure no aggregates are passed by value.
507     Assert1(I->getType()->isFirstClassType(),
508             "Functions cannot take aggregates as arguments by value!", I);
509    }
510
511   if (F.isDeclaration()) {
512     Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
513             F.hasExternalWeakLinkage(),
514             "invalid linkage type for function declaration", &F);
515   } else {
516     // Verify that this function (which has a body) is not named "llvm.*".  It
517     // is not legal to define intrinsics.
518     if (F.getName().size() >= 5)
519       Assert1(F.getName().substr(0, 5) != "llvm.",
520               "llvm intrinsics cannot be defined!", &F);
521     
522     // Check the entry node
523     BasicBlock *Entry = &F.getEntryBlock();
524     Assert1(pred_begin(Entry) == pred_end(Entry),
525             "Entry block to function must not have predecessors!", Entry);
526   }
527 }
528
529
530 // verifyBasicBlock - Verify that a basic block is well formed...
531 //
532 void Verifier::visitBasicBlock(BasicBlock &BB) {
533   InstsInThisBlock.clear();
534
535   // Ensure that basic blocks have terminators!
536   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
537
538   // Check constraints that this basic block imposes on all of the PHI nodes in
539   // it.
540   if (isa<PHINode>(BB.front())) {
541     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
542     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
543     std::sort(Preds.begin(), Preds.end());
544     PHINode *PN;
545     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
546
547       // Ensure that PHI nodes have at least one entry!
548       Assert1(PN->getNumIncomingValues() != 0,
549               "PHI nodes must have at least one entry.  If the block is dead, "
550               "the PHI should be removed!", PN);
551       Assert1(PN->getNumIncomingValues() == Preds.size(),
552               "PHINode should have one entry for each predecessor of its "
553               "parent basic block!", PN);
554
555       // Get and sort all incoming values in the PHI node...
556       Values.clear();
557       Values.reserve(PN->getNumIncomingValues());
558       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
559         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
560                                         PN->getIncomingValue(i)));
561       std::sort(Values.begin(), Values.end());
562
563       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
564         // Check to make sure that if there is more than one entry for a
565         // particular basic block in this PHI node, that the incoming values are
566         // all identical.
567         //
568         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
569                 Values[i].second == Values[i-1].second,
570                 "PHI node has multiple entries for the same basic block with "
571                 "different incoming values!", PN, Values[i].first,
572                 Values[i].second, Values[i-1].second);
573
574         // Check to make sure that the predecessors and PHI node entries are
575         // matched up.
576         Assert3(Values[i].first == Preds[i],
577                 "PHI node entries do not match predecessors!", PN,
578                 Values[i].first, Preds[i]);
579       }
580     }
581   }
582 }
583
584 void Verifier::visitTerminatorInst(TerminatorInst &I) {
585   // Ensure that terminators only exist at the end of the basic block.
586   Assert1(&I == I.getParent()->getTerminator(),
587           "Terminator found in the middle of a basic block!", I.getParent());
588   visitInstruction(I);
589 }
590
591 void Verifier::visitReturnInst(ReturnInst &RI) {
592   Function *F = RI.getParent()->getParent();
593   unsigned N = RI.getNumOperands();
594   if (F->getReturnType() == Type::VoidTy) 
595     Assert2(N == 0,
596             "Found return instr that returns void in Function of non-void "
597             "return type!", &RI, F->getReturnType());
598   else if (N == 1 && F->getReturnType() == RI.getOperand(0)->getType()) {
599     // Exactly one return value and it matches the return type. Good.
600   } else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
601     // The return type is a struct; check for multiple return values.
602     Assert2(STy->getNumElements() == N,
603             "Incorrect number of return values in ret instruction!",
604             &RI, F->getReturnType());
605     for (unsigned i = 0; i != N; ++i)
606       Assert2(STy->getElementType(i) == RI.getOperand(i)->getType(),
607               "Function return type does not match operand "
608               "type of return inst!", &RI, F->getReturnType());
609   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(F->getReturnType())) {
610     // The return type is an array; check for multiple return values.
611     Assert2(ATy->getNumElements() == N,
612             "Incorrect number of return values in ret instruction!",
613             &RI, F->getReturnType());
614     for (unsigned i = 0; i != N; ++i)
615       Assert2(ATy->getElementType() == RI.getOperand(i)->getType(),
616               "Function return type does not match operand "
617               "type of return inst!", &RI, F->getReturnType());
618   } else {
619     CheckFailed("Function return type does not match operand "
620                 "type of return inst!", &RI, F->getReturnType());
621   }
622   
623   // Check to make sure that the return value has necessary properties for
624   // terminators...
625   visitTerminatorInst(RI);
626 }
627
628 void Verifier::visitSwitchInst(SwitchInst &SI) {
629   // Check to make sure that all of the constants in the switch instruction
630   // have the same type as the switched-on value.
631   const Type *SwitchTy = SI.getCondition()->getType();
632   for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
633     Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
634             "Switch constants must all be same type as switch value!", &SI);
635
636   visitTerminatorInst(SI);
637 }
638
639 void Verifier::visitSelectInst(SelectInst &SI) {
640   Assert1(SI.getCondition()->getType() == Type::Int1Ty,
641           "Select condition type must be bool!", &SI);
642   Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
643           "Select values must have identical types!", &SI);
644   Assert1(SI.getTrueValue()->getType() == SI.getType(),
645           "Select values must have same type as select instruction!", &SI);
646   visitInstruction(SI);
647 }
648
649
650 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
651 /// a pass, if any exist, it's an error.
652 ///
653 void Verifier::visitUserOp1(Instruction &I) {
654   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
655 }
656
657 void Verifier::visitTruncInst(TruncInst &I) {
658   // Get the source and destination types
659   const Type *SrcTy = I.getOperand(0)->getType();
660   const Type *DestTy = I.getType();
661
662   // Get the size of the types in bits, we'll need this later
663   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
664   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
665
666   Assert1(SrcTy->isInteger(), "Trunc only operates on integer", &I);
667   Assert1(DestTy->isInteger(), "Trunc only produces integer", &I);
668   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
669
670   visitInstruction(I);
671 }
672
673 void Verifier::visitZExtInst(ZExtInst &I) {
674   // Get the source and destination types
675   const Type *SrcTy = I.getOperand(0)->getType();
676   const Type *DestTy = I.getType();
677
678   // Get the size of the types in bits, we'll need this later
679   Assert1(SrcTy->isInteger(), "ZExt only operates on integer", &I);
680   Assert1(DestTy->isInteger(), "ZExt only produces an integer", &I);
681   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
682   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
683
684   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
685
686   visitInstruction(I);
687 }
688
689 void Verifier::visitSExtInst(SExtInst &I) {
690   // Get the source and destination types
691   const Type *SrcTy = I.getOperand(0)->getType();
692   const Type *DestTy = I.getType();
693
694   // Get the size of the types in bits, we'll need this later
695   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
696   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
697
698   Assert1(SrcTy->isInteger(), "SExt only operates on integer", &I);
699   Assert1(DestTy->isInteger(), "SExt only produces an integer", &I);
700   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
701
702   visitInstruction(I);
703 }
704
705 void Verifier::visitFPTruncInst(FPTruncInst &I) {
706   // Get the source and destination types
707   const Type *SrcTy = I.getOperand(0)->getType();
708   const Type *DestTy = I.getType();
709   // Get the size of the types in bits, we'll need this later
710   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
711   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
712
713   Assert1(SrcTy->isFloatingPoint(),"FPTrunc only operates on FP", &I);
714   Assert1(DestTy->isFloatingPoint(),"FPTrunc only produces an FP", &I);
715   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
716
717   visitInstruction(I);
718 }
719
720 void Verifier::visitFPExtInst(FPExtInst &I) {
721   // Get the source and destination types
722   const Type *SrcTy = I.getOperand(0)->getType();
723   const Type *DestTy = I.getType();
724
725   // Get the size of the types in bits, we'll need this later
726   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
727   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
728
729   Assert1(SrcTy->isFloatingPoint(),"FPExt only operates on FP", &I);
730   Assert1(DestTy->isFloatingPoint(),"FPExt only produces an FP", &I);
731   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
732
733   visitInstruction(I);
734 }
735
736 void Verifier::visitUIToFPInst(UIToFPInst &I) {
737   // Get the source and destination types
738   const Type *SrcTy = I.getOperand(0)->getType();
739   const Type *DestTy = I.getType();
740
741   bool SrcVec = isa<VectorType>(SrcTy);
742   bool DstVec = isa<VectorType>(DestTy);
743
744   Assert1(SrcVec == DstVec,
745           "UIToFP source and dest must both be vector or scalar", &I);
746   Assert1(SrcTy->isIntOrIntVector(),
747           "UIToFP source must be integer or integer vector", &I);
748   Assert1(DestTy->isFPOrFPVector(),
749           "UIToFP result must be FP or FP vector", &I);
750
751   if (SrcVec && DstVec)
752     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
753             cast<VectorType>(DestTy)->getNumElements(),
754             "UIToFP source and dest vector length mismatch", &I);
755
756   visitInstruction(I);
757 }
758
759 void Verifier::visitSIToFPInst(SIToFPInst &I) {
760   // Get the source and destination types
761   const Type *SrcTy = I.getOperand(0)->getType();
762   const Type *DestTy = I.getType();
763
764   bool SrcVec = SrcTy->getTypeID() == Type::VectorTyID;
765   bool DstVec = DestTy->getTypeID() == Type::VectorTyID;
766
767   Assert1(SrcVec == DstVec,
768           "SIToFP source and dest must both be vector or scalar", &I);
769   Assert1(SrcTy->isIntOrIntVector(),
770           "SIToFP source must be integer or integer vector", &I);
771   Assert1(DestTy->isFPOrFPVector(),
772           "SIToFP result must be FP or FP vector", &I);
773
774   if (SrcVec && DstVec)
775     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
776             cast<VectorType>(DestTy)->getNumElements(),
777             "SIToFP source and dest vector length mismatch", &I);
778
779   visitInstruction(I);
780 }
781
782 void Verifier::visitFPToUIInst(FPToUIInst &I) {
783   // Get the source and destination types
784   const Type *SrcTy = I.getOperand(0)->getType();
785   const Type *DestTy = I.getType();
786
787   bool SrcVec = isa<VectorType>(SrcTy);
788   bool DstVec = isa<VectorType>(DestTy);
789
790   Assert1(SrcVec == DstVec,
791           "FPToUI source and dest must both be vector or scalar", &I);
792   Assert1(SrcTy->isFPOrFPVector(), "FPToUI source must be FP or FP vector", &I);
793   Assert1(DestTy->isIntOrIntVector(),
794           "FPToUI result must be integer or integer vector", &I);
795
796   if (SrcVec && DstVec)
797     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
798             cast<VectorType>(DestTy)->getNumElements(),
799             "FPToUI source and dest vector length mismatch", &I);
800
801   visitInstruction(I);
802 }
803
804 void Verifier::visitFPToSIInst(FPToSIInst &I) {
805   // Get the source and destination types
806   const Type *SrcTy = I.getOperand(0)->getType();
807   const Type *DestTy = I.getType();
808
809   bool SrcVec = isa<VectorType>(SrcTy);
810   bool DstVec = isa<VectorType>(DestTy);
811
812   Assert1(SrcVec == DstVec,
813           "FPToSI source and dest must both be vector or scalar", &I);
814   Assert1(SrcTy->isFPOrFPVector(),
815           "FPToSI source must be FP or FP vector", &I);
816   Assert1(DestTy->isIntOrIntVector(),
817           "FPToSI result must be integer or integer vector", &I);
818
819   if (SrcVec && DstVec)
820     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
821             cast<VectorType>(DestTy)->getNumElements(),
822             "FPToSI source and dest vector length mismatch", &I);
823
824   visitInstruction(I);
825 }
826
827 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
828   // Get the source and destination types
829   const Type *SrcTy = I.getOperand(0)->getType();
830   const Type *DestTy = I.getType();
831
832   Assert1(isa<PointerType>(SrcTy), "PtrToInt source must be pointer", &I);
833   Assert1(DestTy->isInteger(), "PtrToInt result must be integral", &I);
834
835   visitInstruction(I);
836 }
837
838 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
839   // Get the source and destination types
840   const Type *SrcTy = I.getOperand(0)->getType();
841   const Type *DestTy = I.getType();
842
843   Assert1(SrcTy->isInteger(), "IntToPtr source must be an integral", &I);
844   Assert1(isa<PointerType>(DestTy), "IntToPtr result must be a pointer",&I);
845
846   visitInstruction(I);
847 }
848
849 void Verifier::visitBitCastInst(BitCastInst &I) {
850   // Get the source and destination types
851   const Type *SrcTy = I.getOperand(0)->getType();
852   const Type *DestTy = I.getType();
853
854   // Get the size of the types in bits, we'll need this later
855   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
856   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
857
858   // BitCast implies a no-op cast of type only. No bits change.
859   // However, you can't cast pointers to anything but pointers.
860   Assert1(isa<PointerType>(DestTy) == isa<PointerType>(DestTy),
861           "Bitcast requires both operands to be pointer or neither", &I);
862   Assert1(SrcBitSize == DestBitSize, "Bitcast requies types of same width", &I);
863
864   visitInstruction(I);
865 }
866
867 /// visitPHINode - Ensure that a PHI node is well formed.
868 ///
869 void Verifier::visitPHINode(PHINode &PN) {
870   // Ensure that the PHI nodes are all grouped together at the top of the block.
871   // This can be tested by checking whether the instruction before this is
872   // either nonexistent (because this is begin()) or is a PHI node.  If not,
873   // then there is some other instruction before a PHI.
874   Assert2(&PN == &PN.getParent()->front() || 
875           isa<PHINode>(--BasicBlock::iterator(&PN)),
876           "PHI nodes not grouped at top of basic block!",
877           &PN, PN.getParent());
878
879   // Check that all of the operands of the PHI node have the same type as the
880   // result.
881   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
882     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
883             "PHI node operands are not the same type as the result!", &PN);
884
885   // All other PHI node constraints are checked in the visitBasicBlock method.
886
887   visitInstruction(PN);
888 }
889
890 void Verifier::VerifyCallSite(CallSite CS) {
891   Instruction *I = CS.getInstruction();
892
893   Assert1(isa<PointerType>(CS.getCalledValue()->getType()),
894           "Called function must be a pointer!", I);
895   const PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
896   Assert1(isa<FunctionType>(FPTy->getElementType()),
897           "Called function is not pointer to function type!", I);
898
899   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
900
901   // Verify that the correct number of arguments are being passed
902   if (FTy->isVarArg())
903     Assert1(CS.arg_size() >= FTy->getNumParams(),
904             "Called function requires more parameters than were provided!",I);
905   else
906     Assert1(CS.arg_size() == FTy->getNumParams(),
907             "Incorrect number of arguments passed to called function!", I);
908
909   // Verify that all arguments to the call match the function type...
910   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
911     Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
912             "Call parameter type does not match function signature!",
913             CS.getArgument(i), FTy->getParamType(i), I);
914
915   const PAListPtr &Attrs = CS.getParamAttrs();
916
917   Assert1(Attrs.isEmpty() ||
918           Attrs.getSlot(Attrs.getNumSlots()-1).Index <= CS.arg_size(),
919           "Attributes after last parameter!", I);
920
921   // Verify call attributes.
922   VerifyFunctionAttrs(FTy, Attrs, I);
923
924   if (FTy->isVarArg())
925     // Check attributes on the varargs part.
926     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
927       ParameterAttributes Attr = Attrs.getParamAttrs(Idx);
928
929       VerifyAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
930
931       ParameterAttributes VArgI = Attr & ParamAttr::VarArgsIncompatible;
932       Assert1(!VArgI, "Attribute " + ParamAttr::getAsString(VArgI) +
933               "cannot be used for vararg call arguments!", I);
934     }
935
936   visitInstruction(*I);
937 }
938
939 void Verifier::visitCallInst(CallInst &CI) {
940   VerifyCallSite(&CI);
941
942   if (Function *F = CI.getCalledFunction()) {
943     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
944       visitIntrinsicFunctionCall(ID, CI);
945   }
946 }
947
948 void Verifier::visitInvokeInst(InvokeInst &II) {
949   VerifyCallSite(&II);
950 }
951
952 /// visitBinaryOperator - Check that both arguments to the binary operator are
953 /// of the same type!
954 ///
955 void Verifier::visitBinaryOperator(BinaryOperator &B) {
956   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
957           "Both operands to a binary operator are not of the same type!", &B);
958
959   switch (B.getOpcode()) {
960   // Check that logical operators are only used with integral operands.
961   case Instruction::And:
962   case Instruction::Or:
963   case Instruction::Xor:
964     Assert1(B.getType()->isInteger() ||
965             (isa<VectorType>(B.getType()) && 
966              cast<VectorType>(B.getType())->getElementType()->isInteger()),
967             "Logical operators only work with integral types!", &B);
968     Assert1(B.getType() == B.getOperand(0)->getType(),
969             "Logical operators must have same type for operands and result!",
970             &B);
971     break;
972   case Instruction::Shl:
973   case Instruction::LShr:
974   case Instruction::AShr:
975     Assert1(B.getType()->isInteger(),
976             "Shift must return an integer result!", &B);
977     Assert1(B.getType() == B.getOperand(0)->getType(),
978             "Shift return type must be same as operands!", &B);
979     /* FALL THROUGH */
980   default:
981     // Arithmetic operators only work on integer or fp values
982     Assert1(B.getType() == B.getOperand(0)->getType(),
983             "Arithmetic operators must have same type for operands and result!",
984             &B);
985     Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
986             isa<VectorType>(B.getType()),
987             "Arithmetic operators must have integer, fp, or vector type!", &B);
988     break;
989   }
990
991   visitInstruction(B);
992 }
993
994 void Verifier::visitICmpInst(ICmpInst& IC) {
995   // Check that the operands are the same type
996   const Type* Op0Ty = IC.getOperand(0)->getType();
997   const Type* Op1Ty = IC.getOperand(1)->getType();
998   Assert1(Op0Ty == Op1Ty,
999           "Both operands to ICmp instruction are not of the same type!", &IC);
1000   // Check that the operands are the right type
1001   Assert1(Op0Ty->isInteger() || isa<PointerType>(Op0Ty),
1002           "Invalid operand types for ICmp instruction", &IC);
1003   visitInstruction(IC);
1004 }
1005
1006 void Verifier::visitFCmpInst(FCmpInst& FC) {
1007   // Check that the operands are the same type
1008   const Type* Op0Ty = FC.getOperand(0)->getType();
1009   const Type* Op1Ty = FC.getOperand(1)->getType();
1010   Assert1(Op0Ty == Op1Ty,
1011           "Both operands to FCmp instruction are not of the same type!", &FC);
1012   // Check that the operands are the right type
1013   Assert1(Op0Ty->isFloatingPoint(),
1014           "Invalid operand types for FCmp instruction", &FC);
1015   visitInstruction(FC);
1016 }
1017
1018 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1019   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1020                                               EI.getOperand(1)),
1021           "Invalid extractelement operands!", &EI);
1022   visitInstruction(EI);
1023 }
1024
1025 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1026   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1027                                              IE.getOperand(1),
1028                                              IE.getOperand(2)),
1029           "Invalid insertelement operands!", &IE);
1030   visitInstruction(IE);
1031 }
1032
1033 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1034   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1035                                              SV.getOperand(2)),
1036           "Invalid shufflevector operands!", &SV);
1037   Assert1(SV.getType() == SV.getOperand(0)->getType(),
1038           "Result of shufflevector must match first operand type!", &SV);
1039   
1040   // Check to see if Mask is valid.
1041   if (const ConstantVector *MV = dyn_cast<ConstantVector>(SV.getOperand(2))) {
1042     for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1043       Assert1(isa<ConstantInt>(MV->getOperand(i)) ||
1044               isa<UndefValue>(MV->getOperand(i)),
1045               "Invalid shufflevector shuffle mask!", &SV);
1046     }
1047   } else {
1048     Assert1(isa<UndefValue>(SV.getOperand(2)) || 
1049             isa<ConstantAggregateZero>(SV.getOperand(2)),
1050             "Invalid shufflevector shuffle mask!", &SV);
1051   }
1052   
1053   visitInstruction(SV);
1054 }
1055
1056 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1057   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1058   const Type *ElTy =
1059     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
1060                                       Idxs.begin(), Idxs.end());
1061   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1062   Assert2(isa<PointerType>(GEP.getType()) &&
1063           cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1064           "GEP is not of right type for indices!", &GEP, ElTy);
1065   visitInstruction(GEP);
1066 }
1067
1068 void Verifier::visitLoadInst(LoadInst &LI) {
1069   const Type *ElTy =
1070     cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
1071   Assert2(ElTy == LI.getType(),
1072           "Load result type does not match pointer operand type!", &LI, ElTy);
1073   visitInstruction(LI);
1074 }
1075
1076 void Verifier::visitStoreInst(StoreInst &SI) {
1077   const Type *ElTy =
1078     cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
1079   Assert2(ElTy == SI.getOperand(0)->getType(),
1080           "Stored value type does not match pointer operand type!", &SI, ElTy);
1081   visitInstruction(SI);
1082 }
1083
1084 void Verifier::visitAllocationInst(AllocationInst &AI) {
1085   const PointerType *PTy = AI.getType();
1086   Assert1(PTy->getAddressSpace() == 0, 
1087           "Allocation instruction pointer not in the generic address space!",
1088           &AI);
1089   Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1090           &AI);
1091   visitInstruction(AI);
1092 }
1093
1094 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1095   Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1096                                            EVI.idx_begin(), EVI.idx_end()) ==
1097           EVI.getType(),
1098           "Invalid ExtractValueInst operands!", &EVI);
1099   
1100   visitInstruction(EVI);
1101 }
1102
1103 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1104   Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1105                                            IVI.idx_begin(), IVI.idx_end()) ==
1106           IVI.getOperand(1)->getType(),
1107           "Invalid InsertValueInst operands!", &IVI);
1108   
1109   visitInstruction(IVI);
1110 }
1111
1112 /// verifyInstruction - Verify that an instruction is well formed.
1113 ///
1114 void Verifier::visitInstruction(Instruction &I) {
1115   BasicBlock *BB = I.getParent();
1116   Assert1(BB, "Instruction not embedded in basic block!", &I);
1117
1118   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
1119     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1120          UI != UE; ++UI)
1121       Assert1(*UI != (User*)&I ||
1122               !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
1123               "Only PHI nodes may reference their own value!", &I);
1124   }
1125   
1126   // Verify that if this is a terminator that it is at the end of the block.
1127   if (isa<TerminatorInst>(I))
1128     Assert1(BB->getTerminator() == &I, "Terminator not at end of block!", &I);
1129   
1130
1131   // Check that void typed values don't have names
1132   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
1133           "Instruction has a name, but provides a void value!", &I);
1134
1135   // Check that the return value of the instruction is either void or a legal
1136   // value type.
1137   Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType()
1138           || ((isa<CallInst>(I) || isa<InvokeInst>(I)) 
1139               && isa<StructType>(I.getType())),
1140           "Instruction returns a non-scalar type!", &I);
1141
1142   // Check that all uses of the instruction, if they are instructions
1143   // themselves, actually have parent basic blocks.  If the use is not an
1144   // instruction, it is an error!
1145   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1146        UI != UE; ++UI) {
1147     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
1148             *UI);
1149     Instruction *Used = cast<Instruction>(*UI);
1150     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1151             " embeded in a basic block!", &I, Used);
1152   }
1153
1154   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1155     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1156
1157     // Check to make sure that only first-class-values are operands to
1158     // instructions.
1159     if (!I.getOperand(i)->getType()->isFirstClassType()) {
1160       Assert1(0, "Instruction operands must be first-class values!", &I);
1161     }
1162     
1163     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1164       // Check to make sure that the "address of" an intrinsic function is never
1165       // taken.
1166       Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
1167               "Cannot take the address of an intrinsic!", &I);
1168       Assert1(F->getParent() == Mod, "Referencing function in another module!",
1169               &I);
1170     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1171       Assert1(OpBB->getParent() == BB->getParent(),
1172               "Referring to a basic block in another function!", &I);
1173     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1174       Assert1(OpArg->getParent() == BB->getParent(),
1175               "Referring to an argument in another function!", &I);
1176     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1177       Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1178               &I);
1179     } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1180       BasicBlock *OpBlock = Op->getParent();
1181
1182       // Check that a definition dominates all of its uses.
1183       if (!isa<PHINode>(I)) {
1184         // Invoke results are only usable in the normal destination, not in the
1185         // exceptional destination.
1186         if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1187           OpBlock = II->getNormalDest();
1188           
1189           Assert2(OpBlock != II->getUnwindDest(),
1190                   "No uses of invoke possible due to dominance structure!",
1191                   Op, II);
1192           
1193           // If the normal successor of an invoke instruction has multiple
1194           // predecessors, then the normal edge from the invoke is critical, so
1195           // the invoke value can only be live if the destination block
1196           // dominates all of it's predecessors (other than the invoke) or if
1197           // the invoke value is only used by a phi in the successor.
1198           if (!OpBlock->getSinglePredecessor() &&
1199               DT->dominates(&BB->getParent()->getEntryBlock(), BB)) {
1200             // The first case we allow is if the use is a PHI operand in the
1201             // normal block, and if that PHI operand corresponds to the invoke's
1202             // block.
1203             bool Bad = true;
1204             if (PHINode *PN = dyn_cast<PHINode>(&I))
1205               if (PN->getParent() == OpBlock &&
1206                   PN->getIncomingBlock(i/2) == Op->getParent())
1207                 Bad = false;
1208             
1209             // If it is used by something non-phi, then the other case is that
1210             // 'OpBlock' dominates all of its predecessors other than the
1211             // invoke.  In this case, the invoke value can still be used.
1212             if (Bad) {
1213               Bad = false;
1214               for (pred_iterator PI = pred_begin(OpBlock),
1215                    E = pred_end(OpBlock); PI != E; ++PI) {
1216                 if (*PI != II->getParent() && !DT->dominates(OpBlock, *PI)) {
1217                   Bad = true;
1218                   break;
1219                 }
1220               }
1221             }
1222             Assert2(!Bad,
1223                     "Invoke value defined on critical edge but not dead!", &I,
1224                     Op);
1225           }
1226         } else if (OpBlock == BB) {
1227           // If they are in the same basic block, make sure that the definition
1228           // comes before the use.
1229           Assert2(InstsInThisBlock.count(Op) ||
1230                   !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
1231                   "Instruction does not dominate all uses!", Op, &I);
1232         }
1233
1234         // Definition must dominate use unless use is unreachable!
1235         Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
1236                 !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
1237                 "Instruction does not dominate all uses!", Op, &I);
1238       } else {
1239         // PHI nodes are more difficult than other nodes because they actually
1240         // "use" the value in the predecessor basic blocks they correspond to.
1241         BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
1242         Assert2(DT->dominates(OpBlock, PredBB) ||
1243                 !DT->dominates(&BB->getParent()->getEntryBlock(), PredBB),
1244                 "Instruction does not dominate all uses!", Op, &I);
1245       }
1246     } else if (isa<InlineAsm>(I.getOperand(i))) {
1247       Assert1(i == 0 && (isa<CallInst>(I) || isa<InvokeInst>(I)),
1248               "Cannot take the address of an inline asm!", &I);
1249     }
1250   }
1251   InstsInThisBlock.insert(&I);
1252 }
1253
1254 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1255 ///
1256 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1257   Function *IF = CI.getCalledFunction();
1258   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1259           IF);
1260   
1261 #define GET_INTRINSIC_VERIFIER
1262 #include "llvm/Intrinsics.gen"
1263 #undef GET_INTRINSIC_VERIFIER
1264   
1265   switch (ID) {
1266   default:
1267     break;
1268   case Intrinsic::gcroot:
1269   case Intrinsic::gcwrite:
1270   case Intrinsic::gcread: {
1271       Type *PtrTy    = PointerType::getUnqual(Type::Int8Ty),
1272            *PtrPtrTy = PointerType::getUnqual(PtrTy);
1273       
1274       switch (ID) {
1275       default:
1276         break;
1277       case Intrinsic::gcroot:
1278         Assert1(CI.getOperand(1)->getType() == PtrPtrTy,
1279                 "Intrinsic parameter #1 is not i8**.", &CI);
1280         Assert1(CI.getOperand(2)->getType() == PtrTy,
1281                 "Intrinsic parameter #2 is not i8*.", &CI);
1282         Assert1(isa<AllocaInst>(CI.getOperand(1)->stripPointerCasts()),
1283                 "llvm.gcroot parameter #1 must be an alloca.", &CI);
1284         Assert1(isa<Constant>(CI.getOperand(2)),
1285                 "llvm.gcroot parameter #2 must be a constant.", &CI);
1286         break;
1287       case Intrinsic::gcwrite:
1288         Assert1(CI.getOperand(1)->getType() == PtrTy,
1289                 "Intrinsic parameter #1 is not a i8*.", &CI);
1290         Assert1(CI.getOperand(2)->getType() == PtrTy,
1291                 "Intrinsic parameter #2 is not a i8*.", &CI);
1292         Assert1(CI.getOperand(3)->getType() == PtrPtrTy,
1293                 "Intrinsic parameter #3 is not a i8**.", &CI);
1294         break;
1295       case Intrinsic::gcread:
1296         Assert1(CI.getOperand(1)->getType() == PtrTy,
1297                 "Intrinsic parameter #1 is not a i8*.", &CI);
1298         Assert1(CI.getOperand(2)->getType() == PtrPtrTy,
1299                 "Intrinsic parameter #2 is not a i8**.", &CI);
1300         break;
1301       }
1302       
1303       Assert1(CI.getParent()->getParent()->hasCollector(),
1304               "Enclosing function does not specify a collector algorithm.",
1305               &CI);
1306     } break;
1307   case Intrinsic::init_trampoline:
1308     Assert1(isa<Function>(CI.getOperand(2)->stripPointerCasts()),
1309             "llvm.init_trampoline parameter #2 must resolve to a function.",
1310             &CI);
1311     break;
1312   }
1313 }
1314
1315 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1316 /// Intrinsics.gen.  This implements a little state machine that verifies the
1317 /// prototype of intrinsics.
1318 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID,
1319                                         Function *F,
1320                                         unsigned Count, ...) {
1321   va_list VA;
1322   va_start(VA, Count);
1323   
1324   const FunctionType *FTy = F->getFunctionType();
1325   
1326   // For overloaded intrinsics, the Suffix of the function name must match the
1327   // types of the arguments. This variable keeps track of the expected
1328   // suffix, to be checked at the end.
1329   std::string Suffix;
1330
1331   if (FTy->getNumParams() + FTy->isVarArg() != Count - 1) {
1332     CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1333     return;
1334   }
1335
1336   // Note that "arg#0" is the return type.
1337   for (unsigned ArgNo = 0; ArgNo < Count; ++ArgNo) {
1338     int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
1339
1340     if (VT == MVT::isVoid && ArgNo > 0) {
1341       if (!FTy->isVarArg())
1342         CheckFailed("Intrinsic prototype has no '...'!", F);
1343       break;
1344     }
1345
1346     const Type *Ty;
1347     if (ArgNo == 0)
1348       Ty = FTy->getReturnType();
1349     else
1350       Ty = FTy->getParamType(ArgNo-1);
1351
1352     unsigned NumElts = 0;
1353     const Type *EltTy = Ty;
1354     if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1355       EltTy = VTy->getElementType();
1356       NumElts = VTy->getNumElements();
1357     }
1358
1359     if (VT < 0) {
1360       int Match = ~VT;
1361       if (Match == 0) {
1362         if (Ty != FTy->getReturnType()) {
1363           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " does not "
1364                       "match return type.", F);
1365           break;
1366         }
1367       } else {
1368         if (Ty != FTy->getParamType(Match-1)) {
1369           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " does not "
1370                       "match parameter %" + utostr(Match-1) + ".", F);
1371           break;
1372         }
1373       }
1374     } else if (VT == MVT::iAny) {
1375       if (!EltTy->isInteger()) {
1376         if (ArgNo == 0)
1377           CheckFailed("Intrinsic result type is not "
1378                       "an integer type.", F);
1379         else
1380           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is not "
1381                       "an integer type.", F);
1382         break;
1383       }
1384       unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1385       Suffix += ".";
1386       if (EltTy != Ty)
1387         Suffix += "v" + utostr(NumElts);
1388       Suffix += "i" + utostr(GotBits);;
1389       // Check some constraints on various intrinsics.
1390       switch (ID) {
1391         default: break; // Not everything needs to be checked.
1392         case Intrinsic::bswap:
1393           if (GotBits < 16 || GotBits % 16 != 0)
1394             CheckFailed("Intrinsic requires even byte width argument", F);
1395           break;
1396       }
1397     } else if (VT == MVT::fAny) {
1398       if (!EltTy->isFloatingPoint()) {
1399         if (ArgNo == 0)
1400           CheckFailed("Intrinsic result type is not "
1401                       "a floating-point type.", F);
1402         else
1403           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is not "
1404                       "a floating-point type.", F);
1405         break;
1406       }
1407       Suffix += ".";
1408       if (EltTy != Ty)
1409         Suffix += "v" + utostr(NumElts);
1410       Suffix += MVT::getMVT(EltTy).getMVTString();
1411     } else if (VT == MVT::iPTR) {
1412       if (!isa<PointerType>(Ty)) {
1413         if (ArgNo == 0)
1414           CheckFailed("Intrinsic result type is not a "
1415                       "pointer and a pointer is required.", F);
1416         else
1417           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is not a "
1418                       "pointer and a pointer is required.", F);
1419         break;
1420       }
1421     } else if (MVT((MVT::SimpleValueType)VT).isVector()) {
1422       MVT VVT = MVT((MVT::SimpleValueType)VT);
1423       // If this is a vector argument, verify the number and type of elements.
1424       if (VVT.getVectorElementType() != MVT::getMVT(EltTy)) {
1425         CheckFailed("Intrinsic prototype has incorrect vector element type!",
1426                     F);
1427         break;
1428       }
1429       if (VVT.getVectorNumElements() != NumElts) {
1430         CheckFailed("Intrinsic prototype has incorrect number of "
1431                     "vector elements!",F);
1432         break;
1433       }
1434     } else if (MVT((MVT::SimpleValueType)VT).getTypeForMVT() != EltTy) {
1435       if (ArgNo == 0)
1436         CheckFailed("Intrinsic prototype has incorrect result type!", F);
1437       else
1438         CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is wrong!",F);
1439       break;
1440     } else if (EltTy != Ty) {
1441       if (ArgNo == 0)
1442         CheckFailed("Intrinsic result type is vector "
1443                     "and a scalar is required.", F);
1444       else
1445         CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is vector "
1446                     "and a scalar is required.", F);
1447     }
1448   }
1449
1450   va_end(VA);
1451
1452   // If we computed a Suffix then the intrinsic is overloaded and we need to 
1453   // make sure that the name of the function is correct. We add the suffix to
1454   // the name of the intrinsic and compare against the given function name. If
1455   // they are not the same, the function name is invalid. This ensures that
1456   // overloading of intrinsics uses a sane and consistent naming convention.
1457   if (!Suffix.empty()) {
1458     std::string Name(Intrinsic::getName(ID));
1459     if (Name + Suffix != F->getName())
1460       CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1461                   F->getName().substr(Name.length()) + "'. It should be '" +
1462                   Suffix + "'", F);
1463   }
1464
1465   // Check parameter attributes.
1466   Assert1(F->getParamAttrs() == Intrinsic::getParamAttrs(ID),
1467           "Intrinsic has wrong parameter attributes!", F);
1468 }
1469
1470
1471 //===----------------------------------------------------------------------===//
1472 //  Implement the public interfaces to this file...
1473 //===----------------------------------------------------------------------===//
1474
1475 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1476   return new Verifier(action);
1477 }
1478
1479
1480 // verifyFunction - Create
1481 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1482   Function &F = const_cast<Function&>(f);
1483   assert(!F.isDeclaration() && "Cannot verify external functions");
1484
1485   FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
1486   Verifier *V = new Verifier(action);
1487   FPM.add(V);
1488   FPM.run(F);
1489   return V->Broken;
1490 }
1491
1492 /// verifyModule - Check a module for errors, printing messages on stderr.
1493 /// Return true if the module is corrupt.
1494 ///
1495 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1496                         std::string *ErrorInfo) {
1497   PassManager PM;
1498   Verifier *V = new Verifier(action);
1499   PM.add(V);
1500   PM.run(const_cast<Module&>(M));
1501   
1502   if (ErrorInfo && V->Broken)
1503     *ErrorInfo = V->msgs.str();
1504   return V->Broken;
1505 }
1506
1507 // vim: sw=2