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