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