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