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