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