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