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