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