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