Delete a directory that wasn't supposed to be checked in yet.
[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)
438           ->getPointerTo(GV.getType());
439       Assert1(STy && STy->getNumElements() == 2 &&
440               STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
441               STy->getTypeAtIndex(1) == FuncPtrTy,
442               "wrong type for intrinsic global variable", &GV);
443     }
444   }
445
446   visitGlobalValue(GV);
447 }
448
449 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
450   Assert1(!GA.getName().empty(),
451           "Alias name cannot be empty!", &GA);
452   Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
453           GA.hasWeakLinkage(),
454           "Alias should have external or external weak linkage!", &GA);
455   Assert1(GA.getAliasee(),
456           "Aliasee cannot be NULL!", &GA);
457   Assert1(GA.getType() == GA.getAliasee()->getType(),
458           "Alias and aliasee types should match!", &GA);
459   Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
460
461   if (!isa<GlobalValue>(GA.getAliasee())) {
462     const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
463     Assert1(CE && 
464             (CE->getOpcode() == Instruction::BitCast ||
465              CE->getOpcode() == Instruction::GetElementPtr) &&
466             isa<GlobalValue>(CE->getOperand(0)),
467             "Aliasee should be either GlobalValue or bitcast of GlobalValue",
468             &GA);
469   }
470
471   const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
472   Assert1(Aliasee,
473           "Aliasing chain should end with function or global variable", &GA);
474
475   visitGlobalValue(GA);
476 }
477
478 void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
479   for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
480     MDNode *MD = NMD.getOperand(i);
481     if (!MD)
482       continue;
483
484     Assert1(!MD->isFunctionLocal(),
485             "Named metadata operand cannot be function local!", MD);
486     visitMDNode(*MD, 0);
487   }
488 }
489
490 void Verifier::visitMDNode(MDNode &MD, Function *F) {
491   // Only visit each node once.  Metadata can be mutually recursive, so this
492   // avoids infinite recursion here, as well as being an optimization.
493   if (!MDNodes.insert(&MD))
494     return;
495
496   for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
497     Value *Op = MD.getOperand(i);
498     if (!Op)
499       continue;
500     if (isa<Constant>(Op) || isa<MDString>(Op))
501       continue;
502     if (MDNode *N = dyn_cast<MDNode>(Op)) {
503       Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
504               "Global metadata operand cannot be function local!", &MD, N);
505       visitMDNode(*N, F);
506       continue;
507     }
508     Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
509
510     // If this was an instruction, bb, or argument, verify that it is in the
511     // function that we expect.
512     Function *ActualF = 0;
513     if (Instruction *I = dyn_cast<Instruction>(Op))
514       ActualF = I->getParent()->getParent();
515     else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
516       ActualF = BB->getParent();
517     else if (Argument *A = dyn_cast<Argument>(Op))
518       ActualF = A->getParent();
519     assert(ActualF && "Unimplemented function local metadata case!");
520
521     Assert2(ActualF == F, "function-local metadata used in wrong function",
522             &MD, Op);
523   }
524 }
525
526 // VerifyParameterAttrs - Check the given attributes for an argument or return
527 // value of the specified type.  The value V is printed in error messages.
528 void Verifier::VerifyParameterAttrs(Attributes Attrs, Type *Ty,
529                                     bool isReturnValue, const Value *V) {
530   if (!Attrs.hasAttributes())
531     return;
532
533   Assert1(!Attrs.hasFunctionOnlyAttrs(),
534           "Some attributes in '" + Attrs.getAsString() +
535           "' only apply to functions!", V);
536
537   if (isReturnValue)
538     Assert1(!Attrs.hasParameterOnlyAttrs(),
539             "Attributes 'byval', 'nest', 'sret', and 'nocapture' "
540             "do not apply to return values!", V);
541
542   // Check for mutually incompatible attributes.
543   Assert1(!((Attrs.hasAttribute(Attributes::ByVal) &&
544              Attrs.hasAttribute(Attributes::Nest)) ||
545             (Attrs.hasAttribute(Attributes::ByVal) &&
546              Attrs.hasAttribute(Attributes::StructRet)) ||
547             (Attrs.hasAttribute(Attributes::Nest) &&
548              Attrs.hasAttribute(Attributes::StructRet))), "Attributes "
549           "'byval, nest, and sret' are incompatible!", V);
550
551   Assert1(!((Attrs.hasAttribute(Attributes::ByVal) &&
552              Attrs.hasAttribute(Attributes::Nest)) ||
553             (Attrs.hasAttribute(Attributes::ByVal) &&
554              Attrs.hasAttribute(Attributes::InReg)) ||
555             (Attrs.hasAttribute(Attributes::Nest) &&
556              Attrs.hasAttribute(Attributes::InReg))), "Attributes "
557           "'byval, nest, and inreg' are incompatible!", V);
558
559   Assert1(!(Attrs.hasAttribute(Attributes::ZExt) &&
560             Attrs.hasAttribute(Attributes::SExt)), "Attributes "
561           "'zeroext and signext' are incompatible!", V);
562
563   Assert1(!(Attrs.hasAttribute(Attributes::ReadNone) &&
564             Attrs.hasAttribute(Attributes::ReadOnly)), "Attributes "
565           "'readnone and readonly' are incompatible!", V);
566
567   Assert1(!(Attrs.hasAttribute(Attributes::NoInline) &&
568             Attrs.hasAttribute(Attributes::AlwaysInline)), "Attributes "
569           "'noinline and alwaysinline' are incompatible!", V);
570
571   Assert1(!AttrBuilder(Attrs).
572             hasAttributes(Attributes::typeIncompatible(Ty)),
573           "Wrong types for attribute: " +
574           Attributes::typeIncompatible(Ty).getAsString(), V);
575
576   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
577     Assert1(!Attrs.hasAttribute(Attributes::ByVal) ||
578             PTy->getElementType()->isSized(),
579             "Attribute 'byval' does not support unsized types!", V);
580   else
581     Assert1(!Attrs.hasAttribute(Attributes::ByVal),
582             "Attribute 'byval' only applies to parameters with pointer type!",
583             V);
584 }
585
586 // VerifyFunctionAttrs - Check parameter attributes against a function type.
587 // The value V is printed in error messages.
588 void Verifier::VerifyFunctionAttrs(FunctionType *FT,
589                                    const AttrListPtr &Attrs,
590                                    const Value *V) {
591   if (Attrs.isEmpty())
592     return;
593
594   bool SawNest = false;
595
596   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
597     const AttributeWithIndex &Attr = Attrs.getSlot(i);
598
599     Type *Ty;
600     if (Attr.Index == 0)
601       Ty = FT->getReturnType();
602     else if (Attr.Index-1 < FT->getNumParams())
603       Ty = FT->getParamType(Attr.Index-1);
604     else
605       break;  // VarArgs attributes, verified elsewhere.
606
607     VerifyParameterAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
608
609     if (Attr.Attrs.hasAttribute(Attributes::Nest)) {
610       Assert1(!SawNest, "More than one parameter has attribute nest!", V);
611       SawNest = true;
612     }
613
614     if (Attr.Attrs.hasAttribute(Attributes::StructRet))
615       Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
616   }
617
618   Attributes FAttrs = Attrs.getFnAttributes();
619   AttrBuilder NotFn(FAttrs);
620   NotFn.removeFunctionOnlyAttrs();
621   Assert1(!NotFn.hasAttributes(), "Attributes '" +
622           Attributes::get(V->getContext(), NotFn).getAsString() +
623           "' do not apply to the function!", V);
624
625   // Check for mutually incompatible attributes.
626   Assert1(!((FAttrs.hasAttribute(Attributes::ByVal) &&
627              FAttrs.hasAttribute(Attributes::Nest)) ||
628             (FAttrs.hasAttribute(Attributes::ByVal) &&
629              FAttrs.hasAttribute(Attributes::StructRet)) ||
630             (FAttrs.hasAttribute(Attributes::Nest) &&
631              FAttrs.hasAttribute(Attributes::StructRet))), "Attributes "
632           "'byval, nest, and sret' are incompatible!", V);
633
634   Assert1(!((FAttrs.hasAttribute(Attributes::ByVal) &&
635              FAttrs.hasAttribute(Attributes::Nest)) ||
636             (FAttrs.hasAttribute(Attributes::ByVal) &&
637              FAttrs.hasAttribute(Attributes::InReg)) ||
638             (FAttrs.hasAttribute(Attributes::Nest) &&
639              FAttrs.hasAttribute(Attributes::InReg))), "Attributes "
640           "'byval, nest, and inreg' are incompatible!", V);
641
642   Assert1(!(FAttrs.hasAttribute(Attributes::ZExt) &&
643             FAttrs.hasAttribute(Attributes::SExt)), "Attributes "
644           "'zeroext and signext' are incompatible!", V);
645
646   Assert1(!(FAttrs.hasAttribute(Attributes::ReadNone) &&
647             FAttrs.hasAttribute(Attributes::ReadOnly)), "Attributes "
648           "'readnone and readonly' are incompatible!", V);
649
650   Assert1(!(FAttrs.hasAttribute(Attributes::NoInline) &&
651             FAttrs.hasAttribute(Attributes::AlwaysInline)), "Attributes "
652           "'noinline and alwaysinline' are incompatible!", V);
653 }
654
655 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
656   if (Attrs.isEmpty())
657     return true;
658
659   unsigned LastSlot = Attrs.getNumSlots() - 1;
660   unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
661   if (LastIndex <= Params
662       || (LastIndex == (unsigned)~0
663           && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))  
664     return true;
665
666   return false;
667 }
668
669 // visitFunction - Verify that a function is ok.
670 //
671 void Verifier::visitFunction(Function &F) {
672   // Check function arguments.
673   FunctionType *FT = F.getFunctionType();
674   unsigned NumArgs = F.arg_size();
675
676   Assert1(Context == &F.getContext(),
677           "Function context does not match Module context!", &F);
678
679   Assert1(!F.hasCommonLinkage(), "Functions may not have common linkage", &F);
680   Assert2(FT->getNumParams() == NumArgs,
681           "# formal arguments must match # of arguments for function type!",
682           &F, FT);
683   Assert1(F.getReturnType()->isFirstClassType() ||
684           F.getReturnType()->isVoidTy() || 
685           F.getReturnType()->isStructTy(),
686           "Functions cannot return aggregate values!", &F);
687
688   Assert1(!F.hasStructRetAttr() || F.getReturnType()->isVoidTy(),
689           "Invalid struct return type!", &F);
690
691   const AttrListPtr &Attrs = F.getAttributes();
692
693   Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
694           "Attributes after last parameter!", &F);
695
696   // Check function attributes.
697   VerifyFunctionAttrs(FT, Attrs, &F);
698
699   // Check that this function meets the restrictions on this calling convention.
700   switch (F.getCallingConv()) {
701   default:
702     break;
703   case CallingConv::C:
704     break;
705   case CallingConv::Fast:
706   case CallingConv::Cold:
707   case CallingConv::X86_FastCall:
708   case CallingConv::X86_ThisCall:
709   case CallingConv::Intel_OCL_BI:
710   case CallingConv::PTX_Kernel:
711   case CallingConv::PTX_Device:
712     Assert1(!F.isVarArg(),
713             "Varargs functions must have C calling conventions!", &F);
714     break;
715   }
716
717   bool isLLVMdotName = F.getName().size() >= 5 &&
718                        F.getName().substr(0, 5) == "llvm.";
719
720   // Check that the argument values match the function type for this function...
721   unsigned i = 0;
722   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
723        I != E; ++I, ++i) {
724     Assert2(I->getType() == FT->getParamType(i),
725             "Argument value does not match function argument type!",
726             I, FT->getParamType(i));
727     Assert1(I->getType()->isFirstClassType(),
728             "Function arguments must have first-class types!", I);
729     if (!isLLVMdotName)
730       Assert2(!I->getType()->isMetadataTy(),
731               "Function takes metadata but isn't an intrinsic", I, &F);
732   }
733
734   if (F.isMaterializable()) {
735     // Function has a body somewhere we can't see.
736   } else if (F.isDeclaration()) {
737     Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
738             F.hasExternalWeakLinkage(),
739             "invalid linkage type for function declaration", &F);
740   } else {
741     // Verify that this function (which has a body) is not named "llvm.*".  It
742     // is not legal to define intrinsics.
743     Assert1(!isLLVMdotName, "llvm intrinsics cannot be defined!", &F);
744     
745     // Check the entry node
746     BasicBlock *Entry = &F.getEntryBlock();
747     Assert1(pred_begin(Entry) == pred_end(Entry),
748             "Entry block to function must not have predecessors!", Entry);
749     
750     // The address of the entry block cannot be taken, unless it is dead.
751     if (Entry->hasAddressTaken()) {
752       Assert1(!BlockAddress::get(Entry)->isConstantUsed(),
753               "blockaddress may not be used with the entry block!", Entry);
754     }
755   }
756  
757   // If this function is actually an intrinsic, verify that it is only used in
758   // direct call/invokes, never having its "address taken".
759   if (F.getIntrinsicID()) {
760     const User *U;
761     if (F.hasAddressTaken(&U))
762       Assert1(0, "Invalid user of intrinsic instruction!", U); 
763   }
764 }
765
766 // verifyBasicBlock - Verify that a basic block is well formed...
767 //
768 void Verifier::visitBasicBlock(BasicBlock &BB) {
769   InstsInThisBlock.clear();
770
771   // Ensure that basic blocks have terminators!
772   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
773
774   // Check constraints that this basic block imposes on all of the PHI nodes in
775   // it.
776   if (isa<PHINode>(BB.front())) {
777     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
778     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
779     std::sort(Preds.begin(), Preds.end());
780     PHINode *PN;
781     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
782       // Ensure that PHI nodes have at least one entry!
783       Assert1(PN->getNumIncomingValues() != 0,
784               "PHI nodes must have at least one entry.  If the block is dead, "
785               "the PHI should be removed!", PN);
786       Assert1(PN->getNumIncomingValues() == Preds.size(),
787               "PHINode should have one entry for each predecessor of its "
788               "parent basic block!", PN);
789
790       // Get and sort all incoming values in the PHI node...
791       Values.clear();
792       Values.reserve(PN->getNumIncomingValues());
793       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
794         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
795                                         PN->getIncomingValue(i)));
796       std::sort(Values.begin(), Values.end());
797
798       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
799         // Check to make sure that if there is more than one entry for a
800         // particular basic block in this PHI node, that the incoming values are
801         // all identical.
802         //
803         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
804                 Values[i].second == Values[i-1].second,
805                 "PHI node has multiple entries for the same basic block with "
806                 "different incoming values!", PN, Values[i].first,
807                 Values[i].second, Values[i-1].second);
808
809         // Check to make sure that the predecessors and PHI node entries are
810         // matched up.
811         Assert3(Values[i].first == Preds[i],
812                 "PHI node entries do not match predecessors!", PN,
813                 Values[i].first, Preds[i]);
814       }
815     }
816   }
817 }
818
819 void Verifier::visitTerminatorInst(TerminatorInst &I) {
820   // Ensure that terminators only exist at the end of the basic block.
821   Assert1(&I == I.getParent()->getTerminator(),
822           "Terminator found in the middle of a basic block!", I.getParent());
823   visitInstruction(I);
824 }
825
826 void Verifier::visitBranchInst(BranchInst &BI) {
827   if (BI.isConditional()) {
828     Assert2(BI.getCondition()->getType()->isIntegerTy(1),
829             "Branch condition is not 'i1' type!", &BI, BI.getCondition());
830   }
831   visitTerminatorInst(BI);
832 }
833
834 void Verifier::visitReturnInst(ReturnInst &RI) {
835   Function *F = RI.getParent()->getParent();
836   unsigned N = RI.getNumOperands();
837   if (F->getReturnType()->isVoidTy()) 
838     Assert2(N == 0,
839             "Found return instr that returns non-void in Function of void "
840             "return type!", &RI, F->getReturnType());
841   else
842     Assert2(N == 1 && F->getReturnType() == RI.getOperand(0)->getType(),
843             "Function return type does not match operand "
844             "type of return inst!", &RI, F->getReturnType());
845
846   // Check to make sure that the return value has necessary properties for
847   // terminators...
848   visitTerminatorInst(RI);
849 }
850
851 void Verifier::visitSwitchInst(SwitchInst &SI) {
852   // Check to make sure that all of the constants in the switch instruction
853   // have the same type as the switched-on value.
854   Type *SwitchTy = SI.getCondition()->getType();
855   IntegerType *IntTy = cast<IntegerType>(SwitchTy);
856   IntegersSubsetToBB Mapping;
857   std::map<IntegersSubset::Range, unsigned> RangeSetMap;
858   for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); i != e; ++i) {
859     IntegersSubset CaseRanges = i.getCaseValueEx();
860     for (unsigned ri = 0, rie = CaseRanges.getNumItems(); ri < rie; ++ri) {
861       IntegersSubset::Range r = CaseRanges.getItem(ri);
862       Assert1(((const APInt&)r.getLow()).getBitWidth() == IntTy->getBitWidth(),
863               "Switch constants must all be same type as switch value!", &SI);
864       Assert1(((const APInt&)r.getHigh()).getBitWidth() == IntTy->getBitWidth(),
865               "Switch constants must all be same type as switch value!", &SI);
866       Mapping.add(r);
867       RangeSetMap[r] = i.getCaseIndex();
868     }
869   }
870   
871   IntegersSubsetToBB::RangeIterator errItem;
872   if (!Mapping.verify(errItem)) {
873     unsigned CaseIndex = RangeSetMap[errItem->first];
874     SwitchInst::CaseIt i(&SI, CaseIndex);
875     Assert2(false, "Duplicate integer as switch case", &SI, i.getCaseValueEx());
876   }
877   
878   visitTerminatorInst(SI);
879 }
880
881 void Verifier::visitIndirectBrInst(IndirectBrInst &BI) {
882   Assert1(BI.getAddress()->getType()->isPointerTy(),
883           "Indirectbr operand must have pointer type!", &BI);
884   for (unsigned i = 0, e = BI.getNumDestinations(); i != e; ++i)
885     Assert1(BI.getDestination(i)->getType()->isLabelTy(),
886             "Indirectbr destinations must all have pointer type!", &BI);
887
888   visitTerminatorInst(BI);
889 }
890
891 void Verifier::visitSelectInst(SelectInst &SI) {
892   Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
893                                           SI.getOperand(2)),
894           "Invalid operands for select instruction!", &SI);
895
896   Assert1(SI.getTrueValue()->getType() == SI.getType(),
897           "Select values must have same type as select instruction!", &SI);
898   visitInstruction(SI);
899 }
900
901 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
902 /// a pass, if any exist, it's an error.
903 ///
904 void Verifier::visitUserOp1(Instruction &I) {
905   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
906 }
907
908 void Verifier::visitTruncInst(TruncInst &I) {
909   // Get the source and destination types
910   Type *SrcTy = I.getOperand(0)->getType();
911   Type *DestTy = I.getType();
912
913   // Get the size of the types in bits, we'll need this later
914   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
915   unsigned DestBitSize = DestTy->getScalarSizeInBits();
916
917   Assert1(SrcTy->isIntOrIntVectorTy(), "Trunc only operates on integer", &I);
918   Assert1(DestTy->isIntOrIntVectorTy(), "Trunc only produces integer", &I);
919   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
920           "trunc source and destination must both be a vector or neither", &I);
921   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
922
923   visitInstruction(I);
924 }
925
926 void Verifier::visitZExtInst(ZExtInst &I) {
927   // Get the source and destination types
928   Type *SrcTy = I.getOperand(0)->getType();
929   Type *DestTy = I.getType();
930
931   // Get the size of the types in bits, we'll need this later
932   Assert1(SrcTy->isIntOrIntVectorTy(), "ZExt only operates on integer", &I);
933   Assert1(DestTy->isIntOrIntVectorTy(), "ZExt only produces an integer", &I);
934   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
935           "zext source and destination must both be a vector or neither", &I);
936   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
937   unsigned DestBitSize = DestTy->getScalarSizeInBits();
938
939   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
940
941   visitInstruction(I);
942 }
943
944 void Verifier::visitSExtInst(SExtInst &I) {
945   // Get the source and destination types
946   Type *SrcTy = I.getOperand(0)->getType();
947   Type *DestTy = I.getType();
948
949   // Get the size of the types in bits, we'll need this later
950   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
951   unsigned DestBitSize = DestTy->getScalarSizeInBits();
952
953   Assert1(SrcTy->isIntOrIntVectorTy(), "SExt only operates on integer", &I);
954   Assert1(DestTy->isIntOrIntVectorTy(), "SExt only produces an integer", &I);
955   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
956           "sext source and destination must both be a vector or neither", &I);
957   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
958
959   visitInstruction(I);
960 }
961
962 void Verifier::visitFPTruncInst(FPTruncInst &I) {
963   // Get the source and destination types
964   Type *SrcTy = I.getOperand(0)->getType();
965   Type *DestTy = I.getType();
966   // Get the size of the types in bits, we'll need this later
967   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
968   unsigned DestBitSize = DestTy->getScalarSizeInBits();
969
970   Assert1(SrcTy->isFPOrFPVectorTy(),"FPTrunc only operates on FP", &I);
971   Assert1(DestTy->isFPOrFPVectorTy(),"FPTrunc only produces an FP", &I);
972   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
973           "fptrunc source and destination must both be a vector or neither",&I);
974   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
975
976   visitInstruction(I);
977 }
978
979 void Verifier::visitFPExtInst(FPExtInst &I) {
980   // Get the source and destination types
981   Type *SrcTy = I.getOperand(0)->getType();
982   Type *DestTy = I.getType();
983
984   // Get the size of the types in bits, we'll need this later
985   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
986   unsigned DestBitSize = DestTy->getScalarSizeInBits();
987
988   Assert1(SrcTy->isFPOrFPVectorTy(),"FPExt only operates on FP", &I);
989   Assert1(DestTy->isFPOrFPVectorTy(),"FPExt only produces an FP", &I);
990   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
991           "fpext source and destination must both be a vector or neither", &I);
992   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
993
994   visitInstruction(I);
995 }
996
997 void Verifier::visitUIToFPInst(UIToFPInst &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           "UIToFP source and dest must both be vector or scalar", &I);
1007   Assert1(SrcTy->isIntOrIntVectorTy(),
1008           "UIToFP source must be integer or integer vector", &I);
1009   Assert1(DestTy->isFPOrFPVectorTy(),
1010           "UIToFP result must be FP or FP vector", &I);
1011
1012   if (SrcVec && DstVec)
1013     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1014             cast<VectorType>(DestTy)->getNumElements(),
1015             "UIToFP source and dest vector length mismatch", &I);
1016
1017   visitInstruction(I);
1018 }
1019
1020 void Verifier::visitSIToFPInst(SIToFPInst &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           "SIToFP source and dest must both be vector or scalar", &I);
1030   Assert1(SrcTy->isIntOrIntVectorTy(),
1031           "SIToFP source must be integer or integer vector", &I);
1032   Assert1(DestTy->isFPOrFPVectorTy(),
1033           "SIToFP result must be FP or FP vector", &I);
1034
1035   if (SrcVec && DstVec)
1036     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1037             cast<VectorType>(DestTy)->getNumElements(),
1038             "SIToFP source and dest vector length mismatch", &I);
1039
1040   visitInstruction(I);
1041 }
1042
1043 void Verifier::visitFPToUIInst(FPToUIInst &I) {
1044   // Get the source and destination types
1045   Type *SrcTy = I.getOperand(0)->getType();
1046   Type *DestTy = I.getType();
1047
1048   bool SrcVec = SrcTy->isVectorTy();
1049   bool DstVec = DestTy->isVectorTy();
1050
1051   Assert1(SrcVec == DstVec,
1052           "FPToUI source and dest must both be vector or scalar", &I);
1053   Assert1(SrcTy->isFPOrFPVectorTy(), "FPToUI source must be FP or FP vector",
1054           &I);
1055   Assert1(DestTy->isIntOrIntVectorTy(),
1056           "FPToUI result must be integer or integer vector", &I);
1057
1058   if (SrcVec && DstVec)
1059     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1060             cast<VectorType>(DestTy)->getNumElements(),
1061             "FPToUI source and dest vector length mismatch", &I);
1062
1063   visitInstruction(I);
1064 }
1065
1066 void Verifier::visitFPToSIInst(FPToSIInst &I) {
1067   // Get the source and destination types
1068   Type *SrcTy = I.getOperand(0)->getType();
1069   Type *DestTy = I.getType();
1070
1071   bool SrcVec = SrcTy->isVectorTy();
1072   bool DstVec = DestTy->isVectorTy();
1073
1074   Assert1(SrcVec == DstVec,
1075           "FPToSI source and dest must both be vector or scalar", &I);
1076   Assert1(SrcTy->isFPOrFPVectorTy(),
1077           "FPToSI source must be FP or FP vector", &I);
1078   Assert1(DestTy->isIntOrIntVectorTy(),
1079           "FPToSI result must be integer or integer vector", &I);
1080
1081   if (SrcVec && DstVec)
1082     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
1083             cast<VectorType>(DestTy)->getNumElements(),
1084             "FPToSI source and dest vector length mismatch", &I);
1085
1086   visitInstruction(I);
1087 }
1088
1089 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
1090   // Get the source and destination types
1091   Type *SrcTy = I.getOperand(0)->getType();
1092   Type *DestTy = I.getType();
1093
1094   Assert1(SrcTy->getScalarType()->isPointerTy(),
1095           "PtrToInt source must be pointer", &I);
1096   Assert1(DestTy->getScalarType()->isIntegerTy(),
1097           "PtrToInt result must be integral", &I);
1098   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1099           "PtrToInt type mismatch", &I);
1100
1101   if (SrcTy->isVectorTy()) {
1102     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1103     VectorType *VDest = dyn_cast<VectorType>(DestTy);
1104     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1105           "PtrToInt Vector width mismatch", &I);
1106   }
1107
1108   visitInstruction(I);
1109 }
1110
1111 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
1112   // Get the source and destination types
1113   Type *SrcTy = I.getOperand(0)->getType();
1114   Type *DestTy = I.getType();
1115
1116   Assert1(SrcTy->getScalarType()->isIntegerTy(),
1117           "IntToPtr source must be an integral", &I);
1118   Assert1(DestTy->getScalarType()->isPointerTy(),
1119           "IntToPtr result must be a pointer",&I);
1120   Assert1(SrcTy->isVectorTy() == DestTy->isVectorTy(),
1121           "IntToPtr type mismatch", &I);
1122   if (SrcTy->isVectorTy()) {
1123     VectorType *VSrc = dyn_cast<VectorType>(SrcTy);
1124     VectorType *VDest = dyn_cast<VectorType>(DestTy);
1125     Assert1(VSrc->getNumElements() == VDest->getNumElements(),
1126           "IntToPtr Vector width mismatch", &I);
1127   }
1128   visitInstruction(I);
1129 }
1130
1131 void Verifier::visitBitCastInst(BitCastInst &I) {
1132   // Get the source and destination types
1133   Type *SrcTy = I.getOperand(0)->getType();
1134   Type *DestTy = I.getType();
1135
1136   // Get the size of the types in bits, we'll need this later
1137   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1138   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
1139
1140   // BitCast implies a no-op cast of type only. No bits change.
1141   // However, you can't cast pointers to anything but pointers.
1142   Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
1143           "Bitcast requires both operands to be pointer or neither", &I);
1144   Assert1(SrcBitSize == DestBitSize, "Bitcast requires types of same width",&I);
1145
1146   // Disallow aggregates.
1147   Assert1(!SrcTy->isAggregateType(),
1148           "Bitcast operand must not be aggregate", &I);
1149   Assert1(!DestTy->isAggregateType(),
1150           "Bitcast type must not be aggregate", &I);
1151
1152   visitInstruction(I);
1153 }
1154
1155 /// visitPHINode - Ensure that a PHI node is well formed.
1156 ///
1157 void Verifier::visitPHINode(PHINode &PN) {
1158   // Ensure that the PHI nodes are all grouped together at the top of the block.
1159   // This can be tested by checking whether the instruction before this is
1160   // either nonexistent (because this is begin()) or is a PHI node.  If not,
1161   // then there is some other instruction before a PHI.
1162   Assert2(&PN == &PN.getParent()->front() || 
1163           isa<PHINode>(--BasicBlock::iterator(&PN)),
1164           "PHI nodes not grouped at top of basic block!",
1165           &PN, PN.getParent());
1166
1167   // Check that all of the values of the PHI node have the same type as the
1168   // result, and that the incoming blocks are really basic blocks.
1169   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1170     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
1171             "PHI node operands are not the same type as the result!", &PN);
1172   }
1173
1174   // All other PHI node constraints are checked in the visitBasicBlock method.
1175
1176   visitInstruction(PN);
1177 }
1178
1179 void Verifier::VerifyCallSite(CallSite CS) {
1180   Instruction *I = CS.getInstruction();
1181
1182   Assert1(CS.getCalledValue()->getType()->isPointerTy(),
1183           "Called function must be a pointer!", I);
1184   PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
1185
1186   Assert1(FPTy->getElementType()->isFunctionTy(),
1187           "Called function is not pointer to function type!", I);
1188   FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
1189
1190   // Verify that the correct number of arguments are being passed
1191   if (FTy->isVarArg())
1192     Assert1(CS.arg_size() >= FTy->getNumParams(),
1193             "Called function requires more parameters than were provided!",I);
1194   else
1195     Assert1(CS.arg_size() == FTy->getNumParams(),
1196             "Incorrect number of arguments passed to called function!", I);
1197
1198   // Verify that all arguments to the call match the function type.
1199   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1200     Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
1201             "Call parameter type does not match function signature!",
1202             CS.getArgument(i), FTy->getParamType(i), I);
1203
1204   const AttrListPtr &Attrs = CS.getAttributes();
1205
1206   Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
1207           "Attributes after last parameter!", I);
1208
1209   // Verify call attributes.
1210   VerifyFunctionAttrs(FTy, Attrs, I);
1211
1212   if (FTy->isVarArg())
1213     // Check attributes on the varargs part.
1214     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
1215       Attributes Attr = Attrs.getParamAttributes(Idx);
1216
1217       VerifyParameterAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
1218
1219       Assert1(!Attr.hasIncompatibleWithVarArgsAttrs(),
1220               "Attribute 'sret' cannot be used for vararg call arguments!", I);
1221     }
1222
1223   // Verify that there's no metadata unless it's a direct call to an intrinsic.
1224   if (CS.getCalledFunction() == 0 ||
1225       !CS.getCalledFunction()->getName().startswith("llvm.")) {
1226     for (FunctionType::param_iterator PI = FTy->param_begin(),
1227            PE = FTy->param_end(); PI != PE; ++PI)
1228       Assert1(!(*PI)->isMetadataTy(),
1229               "Function has metadata parameter but isn't an intrinsic", I);
1230   }
1231
1232   visitInstruction(*I);
1233 }
1234
1235 void Verifier::visitCallInst(CallInst &CI) {
1236   VerifyCallSite(&CI);
1237
1238   if (Function *F = CI.getCalledFunction())
1239     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
1240       visitIntrinsicFunctionCall(ID, CI);
1241 }
1242
1243 void Verifier::visitInvokeInst(InvokeInst &II) {
1244   VerifyCallSite(&II);
1245
1246   // Verify that there is a landingpad instruction as the first non-PHI
1247   // instruction of the 'unwind' destination.
1248   Assert1(II.getUnwindDest()->isLandingPad(),
1249           "The unwind destination does not have a landingpad instruction!",&II);
1250
1251   visitTerminatorInst(II);
1252 }
1253
1254 /// visitBinaryOperator - Check that both arguments to the binary operator are
1255 /// of the same type!
1256 ///
1257 void Verifier::visitBinaryOperator(BinaryOperator &B) {
1258   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
1259           "Both operands to a binary operator are not of the same type!", &B);
1260
1261   switch (B.getOpcode()) {
1262   // Check that integer arithmetic operators are only used with
1263   // integral operands.
1264   case Instruction::Add:
1265   case Instruction::Sub:
1266   case Instruction::Mul:
1267   case Instruction::SDiv:
1268   case Instruction::UDiv:
1269   case Instruction::SRem:
1270   case Instruction::URem:
1271     Assert1(B.getType()->isIntOrIntVectorTy(),
1272             "Integer arithmetic operators only work with integral types!", &B);
1273     Assert1(B.getType() == B.getOperand(0)->getType(),
1274             "Integer arithmetic operators must have same type "
1275             "for operands and result!", &B);
1276     break;
1277   // Check that floating-point arithmetic operators are only used with
1278   // floating-point operands.
1279   case Instruction::FAdd:
1280   case Instruction::FSub:
1281   case Instruction::FMul:
1282   case Instruction::FDiv:
1283   case Instruction::FRem:
1284     Assert1(B.getType()->isFPOrFPVectorTy(),
1285             "Floating-point arithmetic operators only work with "
1286             "floating-point types!", &B);
1287     Assert1(B.getType() == B.getOperand(0)->getType(),
1288             "Floating-point arithmetic operators must have same type "
1289             "for operands and result!", &B);
1290     break;
1291   // Check that logical operators are only used with integral operands.
1292   case Instruction::And:
1293   case Instruction::Or:
1294   case Instruction::Xor:
1295     Assert1(B.getType()->isIntOrIntVectorTy(),
1296             "Logical operators only work with integral types!", &B);
1297     Assert1(B.getType() == B.getOperand(0)->getType(),
1298             "Logical operators must have same type for operands and result!",
1299             &B);
1300     break;
1301   case Instruction::Shl:
1302   case Instruction::LShr:
1303   case Instruction::AShr:
1304     Assert1(B.getType()->isIntOrIntVectorTy(),
1305             "Shifts only work with integral types!", &B);
1306     Assert1(B.getType() == B.getOperand(0)->getType(),
1307             "Shift return type must be same as operands!", &B);
1308     break;
1309   default:
1310     llvm_unreachable("Unknown BinaryOperator opcode!");
1311   }
1312
1313   visitInstruction(B);
1314 }
1315
1316 void Verifier::visitICmpInst(ICmpInst &IC) {
1317   // Check that the operands are the same type
1318   Type *Op0Ty = IC.getOperand(0)->getType();
1319   Type *Op1Ty = IC.getOperand(1)->getType();
1320   Assert1(Op0Ty == Op1Ty,
1321           "Both operands to ICmp instruction are not of the same type!", &IC);
1322   // Check that the operands are the right type
1323   Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointerTy(),
1324           "Invalid operand types for ICmp instruction", &IC);
1325   // Check that the predicate is valid.
1326   Assert1(IC.getPredicate() >= CmpInst::FIRST_ICMP_PREDICATE &&
1327           IC.getPredicate() <= CmpInst::LAST_ICMP_PREDICATE,
1328           "Invalid predicate in ICmp instruction!", &IC);
1329
1330   visitInstruction(IC);
1331 }
1332
1333 void Verifier::visitFCmpInst(FCmpInst &FC) {
1334   // Check that the operands are the same type
1335   Type *Op0Ty = FC.getOperand(0)->getType();
1336   Type *Op1Ty = FC.getOperand(1)->getType();
1337   Assert1(Op0Ty == Op1Ty,
1338           "Both operands to FCmp instruction are not of the same type!", &FC);
1339   // Check that the operands are the right type
1340   Assert1(Op0Ty->isFPOrFPVectorTy(),
1341           "Invalid operand types for FCmp instruction", &FC);
1342   // Check that the predicate is valid.
1343   Assert1(FC.getPredicate() >= CmpInst::FIRST_FCMP_PREDICATE &&
1344           FC.getPredicate() <= CmpInst::LAST_FCMP_PREDICATE,
1345           "Invalid predicate in FCmp instruction!", &FC);
1346
1347   visitInstruction(FC);
1348 }
1349
1350 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
1351   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
1352                                               EI.getOperand(1)),
1353           "Invalid extractelement operands!", &EI);
1354   visitInstruction(EI);
1355 }
1356
1357 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
1358   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
1359                                              IE.getOperand(1),
1360                                              IE.getOperand(2)),
1361           "Invalid insertelement operands!", &IE);
1362   visitInstruction(IE);
1363 }
1364
1365 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
1366   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
1367                                              SV.getOperand(2)),
1368           "Invalid shufflevector operands!", &SV);
1369   visitInstruction(SV);
1370 }
1371
1372 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1373   Type *TargetTy = GEP.getPointerOperandType()->getScalarType();
1374
1375   Assert1(isa<PointerType>(TargetTy),
1376     "GEP base pointer is not a vector or a vector of pointers", &GEP);
1377   Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
1378           "GEP into unsized type!", &GEP);
1379
1380   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
1381   Type *ElTy =
1382     GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
1383   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
1384
1385   if (GEP.getPointerOperandType()->isPointerTy()) {
1386     // Validate GEPs with scalar indices.
1387     Assert2(GEP.getType()->isPointerTy() &&
1388            cast<PointerType>(GEP.getType())->getElementType() == ElTy,
1389            "GEP is not of right type for indices!", &GEP, ElTy);
1390   } else {
1391     // Validate GEPs with a vector index.
1392     Assert1(Idxs.size() == 1, "Invalid number of indices!", &GEP);
1393     Value *Index = Idxs[0];
1394     Type  *IndexTy = Index->getType();
1395     Assert1(IndexTy->isVectorTy(),
1396       "Vector GEP must have vector indices!", &GEP);
1397     Assert1(GEP.getType()->isVectorTy(),
1398       "Vector GEP must return a vector value", &GEP);
1399     Type *ElemPtr = cast<VectorType>(GEP.getType())->getElementType();
1400     Assert1(ElemPtr->isPointerTy(),
1401       "Vector GEP pointer operand is not a pointer!", &GEP);
1402     unsigned IndexWidth = cast<VectorType>(IndexTy)->getNumElements();
1403     unsigned GepWidth = cast<VectorType>(GEP.getType())->getNumElements();
1404     Assert1(IndexWidth == GepWidth, "Invalid GEP index vector width", &GEP);
1405     Assert1(ElTy == cast<PointerType>(ElemPtr)->getElementType(),
1406       "Vector GEP type does not match pointer type!", &GEP);
1407   }
1408   visitInstruction(GEP);
1409 }
1410
1411 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1412   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1413 }
1414
1415 void Verifier::visitLoadInst(LoadInst &LI) {
1416   PointerType *PTy = dyn_cast<PointerType>(LI.getOperand(0)->getType());
1417   Assert1(PTy, "Load operand must be a pointer.", &LI);
1418   Type *ElTy = PTy->getElementType();
1419   Assert2(ElTy == LI.getType(),
1420           "Load result type does not match pointer operand type!", &LI, ElTy);
1421   if (LI.isAtomic()) {
1422     Assert1(LI.getOrdering() != Release && LI.getOrdering() != AcquireRelease,
1423             "Load cannot have Release ordering", &LI);
1424     Assert1(LI.getAlignment() != 0,
1425             "Atomic load must specify explicit alignment", &LI);
1426     if (!ElTy->isPointerTy()) {
1427       Assert2(ElTy->isIntegerTy(),
1428               "atomic store operand must have integer type!",
1429               &LI, ElTy);
1430       unsigned Size = ElTy->getPrimitiveSizeInBits();
1431       Assert2(Size >= 8 && !(Size & (Size - 1)),
1432               "atomic store operand must be power-of-two byte-sized integer",
1433               &LI, ElTy);
1434     }
1435   } else {
1436     Assert1(LI.getSynchScope() == CrossThread,
1437             "Non-atomic load cannot have SynchronizationScope specified", &LI);
1438   }
1439
1440   if (MDNode *Range = LI.getMetadata(LLVMContext::MD_range)) {
1441     unsigned NumOperands = Range->getNumOperands();
1442     Assert1(NumOperands % 2 == 0, "Unfinished range!", Range);
1443     unsigned NumRanges = NumOperands / 2;
1444     Assert1(NumRanges >= 1, "It should have at least one range!", Range);
1445
1446     ConstantRange LastRange(1); // Dummy initial value
1447     for (unsigned i = 0; i < NumRanges; ++i) {
1448       ConstantInt *Low = dyn_cast<ConstantInt>(Range->getOperand(2*i));
1449       Assert1(Low, "The lower limit must be an integer!", Low);
1450       ConstantInt *High = dyn_cast<ConstantInt>(Range->getOperand(2*i + 1));
1451       Assert1(High, "The upper limit must be an integer!", High);
1452       Assert1(High->getType() == Low->getType() &&
1453               High->getType() == ElTy, "Range types must match load type!",
1454               &LI);
1455
1456       APInt HighV = High->getValue();
1457       APInt LowV = Low->getValue();
1458       ConstantRange CurRange(LowV, HighV);
1459       Assert1(!CurRange.isEmptySet() && !CurRange.isFullSet(),
1460               "Range must not be empty!", Range);
1461       if (i != 0) {
1462         Assert1(CurRange.intersectWith(LastRange).isEmptySet(),
1463                 "Intervals are overlapping", Range);
1464         Assert1(LowV.sgt(LastRange.getLower()), "Intervals are not in order",
1465                 Range);
1466         Assert1(!isContiguous(CurRange, LastRange), "Intervals are contiguous",
1467                 Range);
1468       }
1469       LastRange = ConstantRange(LowV, HighV);
1470     }
1471     if (NumRanges > 2) {
1472       APInt FirstLow =
1473         dyn_cast<ConstantInt>(Range->getOperand(0))->getValue();
1474       APInt FirstHigh =
1475         dyn_cast<ConstantInt>(Range->getOperand(1))->getValue();
1476       ConstantRange FirstRange(FirstLow, FirstHigh);
1477       Assert1(FirstRange.intersectWith(LastRange).isEmptySet(),
1478               "Intervals are overlapping", Range);
1479       Assert1(!isContiguous(FirstRange, LastRange), "Intervals are contiguous",
1480               Range);
1481     }
1482
1483
1484   }
1485
1486   visitInstruction(LI);
1487 }
1488
1489 void Verifier::visitStoreInst(StoreInst &SI) {
1490   PointerType *PTy = dyn_cast<PointerType>(SI.getOperand(1)->getType());
1491   Assert1(PTy, "Store operand must be a pointer.", &SI);
1492   Type *ElTy = PTy->getElementType();
1493   Assert2(ElTy == SI.getOperand(0)->getType(),
1494           "Stored value type does not match pointer operand type!",
1495           &SI, ElTy);
1496   if (SI.isAtomic()) {
1497     Assert1(SI.getOrdering() != Acquire && SI.getOrdering() != AcquireRelease,
1498             "Store cannot have Acquire ordering", &SI);
1499     Assert1(SI.getAlignment() != 0,
1500             "Atomic store must specify explicit alignment", &SI);
1501     if (!ElTy->isPointerTy()) {
1502       Assert2(ElTy->isIntegerTy(),
1503               "atomic store operand must have integer type!",
1504               &SI, ElTy);
1505       unsigned Size = ElTy->getPrimitiveSizeInBits();
1506       Assert2(Size >= 8 && !(Size & (Size - 1)),
1507               "atomic store operand must be power-of-two byte-sized integer",
1508               &SI, ElTy);
1509     }
1510   } else {
1511     Assert1(SI.getSynchScope() == CrossThread,
1512             "Non-atomic store cannot have SynchronizationScope specified", &SI);
1513   }
1514   visitInstruction(SI);
1515 }
1516
1517 void Verifier::visitAllocaInst(AllocaInst &AI) {
1518   PointerType *PTy = AI.getType();
1519   Assert1(PTy->getAddressSpace() == 0, 
1520           "Allocation instruction pointer not in the generic address space!",
1521           &AI);
1522   Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
1523           &AI);
1524   Assert1(AI.getArraySize()->getType()->isIntegerTy(),
1525           "Alloca array size must have integer type", &AI);
1526   visitInstruction(AI);
1527 }
1528
1529 void Verifier::visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI) {
1530   Assert1(CXI.getOrdering() != NotAtomic,
1531           "cmpxchg instructions must be atomic.", &CXI);
1532   Assert1(CXI.getOrdering() != Unordered,
1533           "cmpxchg instructions cannot be unordered.", &CXI);
1534   PointerType *PTy = dyn_cast<PointerType>(CXI.getOperand(0)->getType());
1535   Assert1(PTy, "First cmpxchg operand must be a pointer.", &CXI);
1536   Type *ElTy = PTy->getElementType();
1537   Assert2(ElTy->isIntegerTy(),
1538           "cmpxchg operand must have integer type!",
1539           &CXI, ElTy);
1540   unsigned Size = ElTy->getPrimitiveSizeInBits();
1541   Assert2(Size >= 8 && !(Size & (Size - 1)),
1542           "cmpxchg operand must be power-of-two byte-sized integer",
1543           &CXI, ElTy);
1544   Assert2(ElTy == CXI.getOperand(1)->getType(),
1545           "Expected value type does not match pointer operand type!",
1546           &CXI, ElTy);
1547   Assert2(ElTy == CXI.getOperand(2)->getType(),
1548           "Stored value type does not match pointer operand type!",
1549           &CXI, ElTy);
1550   visitInstruction(CXI);
1551 }
1552
1553 void Verifier::visitAtomicRMWInst(AtomicRMWInst &RMWI) {
1554   Assert1(RMWI.getOrdering() != NotAtomic,
1555           "atomicrmw instructions must be atomic.", &RMWI);
1556   Assert1(RMWI.getOrdering() != Unordered,
1557           "atomicrmw instructions cannot be unordered.", &RMWI);
1558   PointerType *PTy = dyn_cast<PointerType>(RMWI.getOperand(0)->getType());
1559   Assert1(PTy, "First atomicrmw operand must be a pointer.", &RMWI);
1560   Type *ElTy = PTy->getElementType();
1561   Assert2(ElTy->isIntegerTy(),
1562           "atomicrmw operand must have integer type!",
1563           &RMWI, ElTy);
1564   unsigned Size = ElTy->getPrimitiveSizeInBits();
1565   Assert2(Size >= 8 && !(Size & (Size - 1)),
1566           "atomicrmw operand must be power-of-two byte-sized integer",
1567           &RMWI, ElTy);
1568   Assert2(ElTy == RMWI.getOperand(1)->getType(),
1569           "Argument value type does not match pointer operand type!",
1570           &RMWI, ElTy);
1571   Assert1(AtomicRMWInst::FIRST_BINOP <= RMWI.getOperation() &&
1572           RMWI.getOperation() <= AtomicRMWInst::LAST_BINOP,
1573           "Invalid binary operation!", &RMWI);
1574   visitInstruction(RMWI);
1575 }
1576
1577 void Verifier::visitFenceInst(FenceInst &FI) {
1578   const AtomicOrdering Ordering = FI.getOrdering();
1579   Assert1(Ordering == Acquire || Ordering == Release ||
1580           Ordering == AcquireRelease || Ordering == SequentiallyConsistent,
1581           "fence instructions may only have "
1582           "acquire, release, acq_rel, or seq_cst ordering.", &FI);
1583   visitInstruction(FI);
1584 }
1585
1586 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
1587   Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
1588                                            EVI.getIndices()) ==
1589           EVI.getType(),
1590           "Invalid ExtractValueInst operands!", &EVI);
1591   
1592   visitInstruction(EVI);
1593 }
1594
1595 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
1596   Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
1597                                            IVI.getIndices()) ==
1598           IVI.getOperand(1)->getType(),
1599           "Invalid InsertValueInst operands!", &IVI);
1600   
1601   visitInstruction(IVI);
1602 }
1603
1604 void Verifier::visitLandingPadInst(LandingPadInst &LPI) {
1605   BasicBlock *BB = LPI.getParent();
1606
1607   // The landingpad instruction is ill-formed if it doesn't have any clauses and
1608   // isn't a cleanup.
1609   Assert1(LPI.getNumClauses() > 0 || LPI.isCleanup(),
1610           "LandingPadInst needs at least one clause or to be a cleanup.", &LPI);
1611
1612   // The landingpad instruction defines its parent as a landing pad block. The
1613   // landing pad block may be branched to only by the unwind edge of an invoke.
1614   for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
1615     const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator());
1616     Assert1(II && II->getUnwindDest() == BB && II->getNormalDest() != BB,
1617             "Block containing LandingPadInst must be jumped to "
1618             "only by the unwind edge of an invoke.", &LPI);
1619   }
1620
1621   // The landingpad instruction must be the first non-PHI instruction in the
1622   // block.
1623   Assert1(LPI.getParent()->getLandingPadInst() == &LPI,
1624           "LandingPadInst not the first non-PHI instruction in the block.",
1625           &LPI);
1626
1627   // The personality functions for all landingpad instructions within the same
1628   // function should match.
1629   if (PersonalityFn)
1630     Assert1(LPI.getPersonalityFn() == PersonalityFn,
1631             "Personality function doesn't match others in function", &LPI);
1632   PersonalityFn = LPI.getPersonalityFn();
1633
1634   // All operands must be constants.
1635   Assert1(isa<Constant>(PersonalityFn), "Personality function is not constant!",
1636           &LPI);
1637   for (unsigned i = 0, e = LPI.getNumClauses(); i < e; ++i) {
1638     Value *Clause = LPI.getClause(i);
1639     Assert1(isa<Constant>(Clause), "Clause is not constant!", &LPI);
1640     if (LPI.isCatch(i)) {
1641       Assert1(isa<PointerType>(Clause->getType()),
1642               "Catch operand does not have pointer type!", &LPI);
1643     } else {
1644       Assert1(LPI.isFilter(i), "Clause is neither catch nor filter!", &LPI);
1645       Assert1(isa<ConstantArray>(Clause) || isa<ConstantAggregateZero>(Clause),
1646               "Filter operand is not an array of constants!", &LPI);
1647     }
1648   }
1649
1650   visitInstruction(LPI);
1651 }
1652
1653 void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
1654   Instruction *Op = cast<Instruction>(I.getOperand(i));
1655   // If the we have an invalid invoke, don't try to compute the dominance.
1656   // We already reject it in the invoke specific checks and the dominance
1657   // computation doesn't handle multiple edges.
1658   if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1659     if (II->getNormalDest() == II->getUnwindDest())
1660       return;
1661   }
1662
1663   const Use &U = I.getOperandUse(i);
1664   Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, U),
1665           "Instruction does not dominate all uses!", Op, &I);
1666 }
1667
1668 /// verifyInstruction - Verify that an instruction is well formed.
1669 ///
1670 void Verifier::visitInstruction(Instruction &I) {
1671   BasicBlock *BB = I.getParent();
1672   Assert1(BB, "Instruction not embedded in basic block!", &I);
1673
1674   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
1675     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
1676          UI != UE; ++UI)
1677       Assert1(*UI != (User*)&I || !DT->isReachableFromEntry(BB),
1678               "Only PHI nodes may reference their own value!", &I);
1679   }
1680
1681   // Check that void typed values don't have names
1682   Assert1(!I.getType()->isVoidTy() || !I.hasName(),
1683           "Instruction has a name, but provides a void value!", &I);
1684
1685   // Check that the return value of the instruction is either void or a legal
1686   // value type.
1687   Assert1(I.getType()->isVoidTy() || 
1688           I.getType()->isFirstClassType(),
1689           "Instruction returns a non-scalar type!", &I);
1690
1691   // Check that the instruction doesn't produce metadata. Calls are already
1692   // checked against the callee type.
1693   Assert1(!I.getType()->isMetadataTy() ||
1694           isa<CallInst>(I) || isa<InvokeInst>(I),
1695           "Invalid use of metadata!", &I);
1696
1697   // Check that all uses of the instruction, if they are instructions
1698   // themselves, actually have parent basic blocks.  If the use is not an
1699   // instruction, it is an error!
1700   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
1701        UI != UE; ++UI) {
1702     if (Instruction *Used = dyn_cast<Instruction>(*UI))
1703       Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
1704               " embedded in a basic block!", &I, Used);
1705     else {
1706       CheckFailed("Use of instruction is not an instruction!", *UI);
1707       return;
1708     }
1709   }
1710
1711   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1712     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
1713
1714     // Check to make sure that only first-class-values are operands to
1715     // instructions.
1716     if (!I.getOperand(i)->getType()->isFirstClassType()) {
1717       Assert1(0, "Instruction operands must be first-class values!", &I);
1718     }
1719
1720     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1721       // Check to make sure that the "address of" an intrinsic function is never
1722       // taken.
1723       Assert1(!F->isIntrinsic() || i == (isa<CallInst>(I) ? e-1 : 0),
1724               "Cannot take the address of an intrinsic!", &I);
1725       Assert1(!F->isIntrinsic() || isa<CallInst>(I) ||
1726               F->getIntrinsicID() == Intrinsic::donothing,
1727               "Cannot invoke an intrinsinc other than donothing", &I);
1728       Assert1(F->getParent() == Mod, "Referencing function in another module!",
1729               &I);
1730     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1731       Assert1(OpBB->getParent() == BB->getParent(),
1732               "Referring to a basic block in another function!", &I);
1733     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1734       Assert1(OpArg->getParent() == BB->getParent(),
1735               "Referring to an argument in another function!", &I);
1736     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1737       Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1738               &I);
1739     } else if (isa<Instruction>(I.getOperand(i))) {
1740       verifyDominatesUse(I, i);
1741     } else if (isa<InlineAsm>(I.getOperand(i))) {
1742       Assert1((i + 1 == e && isa<CallInst>(I)) ||
1743               (i + 3 == e && isa<InvokeInst>(I)),
1744               "Cannot take the address of an inline asm!", &I);
1745     }
1746   }
1747
1748   if (MDNode *MD = I.getMetadata(LLVMContext::MD_fpmath)) {
1749     Assert1(I.getType()->isFPOrFPVectorTy(),
1750             "fpmath requires a floating point result!", &I);
1751     Assert1(MD->getNumOperands() == 1, "fpmath takes one operand!", &I);
1752     Value *Op0 = MD->getOperand(0);
1753     if (ConstantFP *CFP0 = dyn_cast_or_null<ConstantFP>(Op0)) {
1754       APFloat Accuracy = CFP0->getValueAPF();
1755       Assert1(Accuracy.isNormal() && !Accuracy.isNegative(),
1756               "fpmath accuracy not a positive number!", &I);
1757     } else {
1758       Assert1(false, "invalid fpmath accuracy!", &I);
1759     }
1760   }
1761
1762   MDNode *MD = I.getMetadata(LLVMContext::MD_range);
1763   Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
1764
1765   InstsInThisBlock.insert(&I);
1766 }
1767
1768 /// VerifyIntrinsicType - Verify that the specified type (which comes from an
1769 /// intrinsic argument or return value) matches the type constraints specified
1770 /// by the .td file (e.g. an "any integer" argument really is an integer).
1771 ///
1772 /// This return true on error but does not print a message.
1773 bool Verifier::VerifyIntrinsicType(Type *Ty,
1774                                    ArrayRef<Intrinsic::IITDescriptor> &Infos,
1775                                    SmallVectorImpl<Type*> &ArgTys) {
1776   using namespace Intrinsic;
1777
1778   // If we ran out of descriptors, there are too many arguments.
1779   if (Infos.empty()) return true; 
1780   IITDescriptor D = Infos.front();
1781   Infos = Infos.slice(1);
1782   
1783   switch (D.Kind) {
1784   case IITDescriptor::Void: return !Ty->isVoidTy();
1785   case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
1786   case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1787   case IITDescriptor::Float: return !Ty->isFloatTy();
1788   case IITDescriptor::Double: return !Ty->isDoubleTy();
1789   case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1790   case IITDescriptor::Vector: {
1791     VectorType *VT = dyn_cast<VectorType>(Ty);
1792     return VT == 0 || VT->getNumElements() != D.Vector_Width ||
1793            VerifyIntrinsicType(VT->getElementType(), Infos, ArgTys);
1794   }
1795   case IITDescriptor::Pointer: {
1796     PointerType *PT = dyn_cast<PointerType>(Ty);
1797     return PT == 0 || PT->getAddressSpace() != D.Pointer_AddressSpace ||
1798            VerifyIntrinsicType(PT->getElementType(), Infos, ArgTys);
1799   }
1800       
1801   case IITDescriptor::Struct: {
1802     StructType *ST = dyn_cast<StructType>(Ty);
1803     if (ST == 0 || ST->getNumElements() != D.Struct_NumElements)
1804       return true;
1805     
1806     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1807       if (VerifyIntrinsicType(ST->getElementType(i), Infos, ArgTys))
1808         return true;
1809     return false;
1810   }
1811       
1812   case IITDescriptor::Argument:
1813     // Two cases here - If this is the second occurrence of an argument, verify
1814     // that the later instance matches the previous instance. 
1815     if (D.getArgumentNumber() < ArgTys.size())
1816       return Ty != ArgTys[D.getArgumentNumber()];  
1817       
1818     // Otherwise, if this is the first instance of an argument, record it and
1819     // verify the "Any" kind.
1820     assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
1821     ArgTys.push_back(Ty);
1822       
1823     switch (D.getArgumentKind()) {
1824     case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1825     case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
1826     case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
1827     case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1828     }
1829     llvm_unreachable("all argument kinds not covered");
1830       
1831   case IITDescriptor::ExtendVecArgument:
1832     // This may only be used when referring to a previous vector argument.
1833     return D.getArgumentNumber() >= ArgTys.size() ||
1834            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1835            VectorType::getExtendedElementVectorType(
1836                        cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1837
1838   case IITDescriptor::TruncVecArgument:
1839     // This may only be used when referring to a previous vector argument.
1840     return D.getArgumentNumber() >= ArgTys.size() ||
1841            !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1842            VectorType::getTruncatedElementVectorType(
1843                          cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1844   }
1845   llvm_unreachable("unhandled");
1846 }
1847
1848 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1849 ///
1850 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1851   Function *IF = CI.getCalledFunction();
1852   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1853           IF);
1854
1855   // Verify that the intrinsic prototype lines up with what the .td files
1856   // describe.
1857   FunctionType *IFTy = IF->getFunctionType();
1858   Assert1(!IFTy->isVarArg(), "Intrinsic prototypes are not varargs", IF);
1859   
1860   SmallVector<Intrinsic::IITDescriptor, 8> Table;
1861   getIntrinsicInfoTableEntries(ID, Table);
1862   ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1863
1864   SmallVector<Type *, 4> ArgTys;
1865   Assert1(!VerifyIntrinsicType(IFTy->getReturnType(), TableRef, ArgTys),
1866           "Intrinsic has incorrect return type!", IF);
1867   for (unsigned i = 0, e = IFTy->getNumParams(); i != e; ++i)
1868     Assert1(!VerifyIntrinsicType(IFTy->getParamType(i), TableRef, ArgTys),
1869             "Intrinsic has incorrect argument type!", IF);
1870   Assert1(TableRef.empty(), "Intrinsic has too few arguments!", IF);
1871
1872   // Now that we have the intrinsic ID and the actual argument types (and we
1873   // know they are legal for the intrinsic!) get the intrinsic name through the
1874   // usual means.  This allows us to verify the mangling of argument types into
1875   // the name.
1876   Assert1(Intrinsic::getName(ID, ArgTys) == IF->getName(),
1877           "Intrinsic name not mangled correctly for type arguments!", IF);
1878   
1879   // If the intrinsic takes MDNode arguments, verify that they are either global
1880   // or are local to *this* function.
1881   for (unsigned i = 0, e = CI.getNumArgOperands(); i != e; ++i)
1882     if (MDNode *MD = dyn_cast<MDNode>(CI.getArgOperand(i)))
1883       visitMDNode(*MD, CI.getParent()->getParent());
1884
1885   switch (ID) {
1886   default:
1887     break;
1888   case Intrinsic::ctlz:  // llvm.ctlz
1889   case Intrinsic::cttz:  // llvm.cttz
1890     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1891             "is_zero_undef argument of bit counting intrinsics must be a "
1892             "constant int", &CI);
1893     break;
1894   case Intrinsic::dbg_declare: {  // llvm.dbg.declare
1895     Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
1896                 "invalid llvm.dbg.declare intrinsic call 1", &CI);
1897     MDNode *MD = cast<MDNode>(CI.getArgOperand(0));
1898     Assert1(MD->getNumOperands() == 1,
1899                 "invalid llvm.dbg.declare intrinsic call 2", &CI);
1900   } break;
1901   case Intrinsic::memcpy:
1902   case Intrinsic::memmove:
1903   case Intrinsic::memset:
1904     Assert1(isa<ConstantInt>(CI.getArgOperand(3)),
1905             "alignment argument of memory intrinsics must be a constant int",
1906             &CI);
1907     Assert1(isa<ConstantInt>(CI.getArgOperand(4)),
1908             "isvolatile argument of memory intrinsics must be a constant int",
1909             &CI);
1910     break;
1911   case Intrinsic::gcroot:
1912   case Intrinsic::gcwrite:
1913   case Intrinsic::gcread:
1914     if (ID == Intrinsic::gcroot) {
1915       AllocaInst *AI =
1916         dyn_cast<AllocaInst>(CI.getArgOperand(0)->stripPointerCasts());
1917       Assert1(AI, "llvm.gcroot parameter #1 must be an alloca.", &CI);
1918       Assert1(isa<Constant>(CI.getArgOperand(1)),
1919               "llvm.gcroot parameter #2 must be a constant.", &CI);
1920       if (!AI->getType()->getElementType()->isPointerTy()) {
1921         Assert1(!isa<ConstantPointerNull>(CI.getArgOperand(1)),
1922                 "llvm.gcroot parameter #1 must either be a pointer alloca, "
1923                 "or argument #2 must be a non-null constant.", &CI);
1924       }
1925     }
1926
1927     Assert1(CI.getParent()->getParent()->hasGC(),
1928             "Enclosing function does not use GC.", &CI);
1929     break;
1930   case Intrinsic::init_trampoline:
1931     Assert1(isa<Function>(CI.getArgOperand(1)->stripPointerCasts()),
1932             "llvm.init_trampoline parameter #2 must resolve to a function.",
1933             &CI);
1934     break;
1935   case Intrinsic::prefetch:
1936     Assert1(isa<ConstantInt>(CI.getArgOperand(1)) &&
1937             isa<ConstantInt>(CI.getArgOperand(2)) &&
1938             cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue() < 2 &&
1939             cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue() < 4,
1940             "invalid arguments to llvm.prefetch",
1941             &CI);
1942     break;
1943   case Intrinsic::stackprotector:
1944     Assert1(isa<AllocaInst>(CI.getArgOperand(1)->stripPointerCasts()),
1945             "llvm.stackprotector parameter #2 must resolve to an alloca.",
1946             &CI);
1947     break;
1948   case Intrinsic::lifetime_start:
1949   case Intrinsic::lifetime_end:
1950   case Intrinsic::invariant_start:
1951     Assert1(isa<ConstantInt>(CI.getArgOperand(0)),
1952             "size argument of memory use markers must be a constant integer",
1953             &CI);
1954     break;
1955   case Intrinsic::invariant_end:
1956     Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
1957             "llvm.invariant.end parameter #2 must be a constant integer", &CI);
1958     break;
1959   }
1960 }
1961
1962 //===----------------------------------------------------------------------===//
1963 //  Implement the public interfaces to this file...
1964 //===----------------------------------------------------------------------===//
1965
1966 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1967   return new Verifier(action);
1968 }
1969
1970
1971 /// verifyFunction - Check a function for errors, printing messages on stderr.
1972 /// Return true if the function is corrupt.
1973 ///
1974 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1975   Function &F = const_cast<Function&>(f);
1976   assert(!F.isDeclaration() && "Cannot verify external functions");
1977
1978   FunctionPassManager FPM(F.getParent());
1979   Verifier *V = new Verifier(action);
1980   FPM.add(V);
1981   FPM.run(F);
1982   return V->Broken;
1983 }
1984
1985 /// verifyModule - Check a module for errors, printing messages on stderr.
1986 /// Return true if the module is corrupt.
1987 ///
1988 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1989                         std::string *ErrorInfo) {
1990   PassManager PM;
1991   Verifier *V = new Verifier(action);
1992   PM.add(V);
1993   PM.run(const_cast<Module&>(M));
1994
1995   if (ErrorInfo && V->Broken)
1996     *ErrorInfo = V->MessagesStr.str();
1997   return V->Broken;
1998 }