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