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