I am not sure this is a good idea to be an option, but rename the option for
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 int %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/Assembly/Writer.h"
44 #include "llvm/CallingConv.h"
45 #include "llvm/Constants.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Module.h"
48 #include "llvm/ModuleProvider.h"
49 #include "llvm/ParameterAttributes.h"
50 #include "llvm/DerivedTypes.h"
51 #include "llvm/InlineAsm.h"
52 #include "llvm/IntrinsicInst.h"
53 #include "llvm/PassManager.h"
54 #include "llvm/Analysis/Dominators.h"
55 #include "llvm/CodeGen/ValueTypes.h"
56 #include "llvm/Support/CFG.h"
57 #include "llvm/Support/InstVisitor.h"
58 #include "llvm/Support/Streams.h"
59 #include "llvm/ADT/SmallPtrSet.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/StringExtras.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Compiler.h"
65 #include <algorithm>
66 #include <sstream>
67 #include <cstdarg>
68 using namespace llvm;
69
70 namespace {  // Anonymous namespace for class
71   cl::opt<bool>
72   Pedantic("verify-pedantic",
73            cl::desc("Reject code with undefined behaviour"));
74     
75   struct VISIBILITY_HIDDEN
76      Verifier : public FunctionPass, InstVisitor<Verifier> {
77     static char ID; // Pass ID, replacement for typeid
78     bool Broken;          // Is this module found to be broken?
79     bool RealPass;        // Are we not being run by a PassManager?
80     VerifierFailureAction action;
81                           // What to do if verification fails.
82     Module *Mod;          // Module we are verifying right now
83     DominatorTree *DT; // Dominator Tree, caution can be null!
84     std::stringstream msgs;  // A stringstream to collect messages
85
86     /// InstInThisBlock - when verifying a basic block, keep track of all of the
87     /// instructions we have seen so far.  This allows us to do efficient
88     /// dominance checks for the case when an instruction has an operand that is
89     /// an instruction in the same block.
90     SmallPtrSet<Instruction*, 16> InstsInThisBlock;
91
92     Verifier()
93       : FunctionPass((intptr_t)&ID), 
94       Broken(false), RealPass(true), action(AbortProcessAction),
95       DT(0), msgs( std::ios::app | std::ios::out ) {}
96     Verifier( VerifierFailureAction ctn )
97       : FunctionPass((intptr_t)&ID), 
98       Broken(false), RealPass(true), action(ctn), DT(0),
99       msgs( std::ios::app | std::ios::out ) {}
100     Verifier(bool AB )
101       : FunctionPass((intptr_t)&ID), 
102       Broken(false), RealPass(true),
103       action( AB ? AbortProcessAction : PrintMessageAction), DT(0),
104       msgs( std::ios::app | std::ios::out ) {}
105     Verifier(DominatorTree &dt)
106       : FunctionPass((intptr_t)&ID), 
107       Broken(false), RealPass(false), action(PrintMessageAction),
108       DT(&dt), msgs( std::ios::app | std::ios::out ) {}
109
110
111     bool doInitialization(Module &M) {
112       Mod = &M;
113       verifyTypeSymbolTable(M.getTypeSymbolTable());
114
115       // If this is a real pass, in a pass manager, we must abort before
116       // returning back to the pass manager, or else the pass manager may try to
117       // run other passes on the broken module.
118       if (RealPass)
119         return abortIfBroken();
120       return false;
121     }
122
123     bool runOnFunction(Function &F) {
124       // Get dominator information if we are being run by PassManager
125       if (RealPass) DT = &getAnalysis<DominatorTree>();
126
127       Mod = F.getParent();
128
129       visit(F);
130       InstsInThisBlock.clear();
131
132       // If this is a real pass, in a pass manager, we must abort before
133       // returning back to the pass manager, or else the pass manager may try to
134       // run other passes on the broken module.
135       if (RealPass)
136         return abortIfBroken();
137
138       return false;
139     }
140
141     bool doFinalization(Module &M) {
142       // Scan through, checking all of the external function's linkage now...
143       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
144         visitGlobalValue(*I);
145
146         // Check to make sure function prototypes are okay.
147         if (I->isDeclaration()) visitFunction(*I);
148       }
149
150       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
151            I != E; ++I)
152         visitGlobalVariable(*I);
153
154       for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 
155            I != E; ++I)
156         visitGlobalAlias(*I);
157
158       // If the module is broken, abort at this time.
159       return abortIfBroken();
160     }
161
162     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
163       AU.setPreservesAll();
164       if (RealPass)
165         AU.addRequired<DominatorTree>();
166     }
167
168     /// abortIfBroken - If the module is broken and we are supposed to abort on
169     /// this condition, do so.
170     ///
171     bool abortIfBroken() {
172       if (Broken) {
173         msgs << "Broken module found, ";
174         switch (action) {
175           case AbortProcessAction:
176             msgs << "compilation aborted!\n";
177             cerr << msgs.str();
178             abort();
179           case PrintMessageAction:
180             msgs << "verification continues.\n";
181             cerr << msgs.str();
182             return false;
183           case ReturnStatusAction:
184             msgs << "compilation terminated.\n";
185             return Broken;
186         }
187       }
188       return false;
189     }
190
191
192     // Verification methods...
193     void verifyTypeSymbolTable(TypeSymbolTable &ST);
194     void visitGlobalValue(GlobalValue &GV);
195     void visitGlobalVariable(GlobalVariable &GV);
196     void visitGlobalAlias(GlobalAlias &GA);
197     void visitFunction(Function &F);
198     void visitBasicBlock(BasicBlock &BB);
199     void visitTruncInst(TruncInst &I);
200     void visitZExtInst(ZExtInst &I);
201     void visitSExtInst(SExtInst &I);
202     void visitFPTruncInst(FPTruncInst &I);
203     void visitFPExtInst(FPExtInst &I);
204     void visitFPToUIInst(FPToUIInst &I);
205     void visitFPToSIInst(FPToSIInst &I);
206     void visitUIToFPInst(UIToFPInst &I);
207     void visitSIToFPInst(SIToFPInst &I);
208     void visitIntToPtrInst(IntToPtrInst &I);
209     void visitPtrToIntInst(PtrToIntInst &I);
210     void visitBitCastInst(BitCastInst &I);
211     void visitPHINode(PHINode &PN);
212     void visitBinaryOperator(BinaryOperator &B);
213     void visitICmpInst(ICmpInst &IC);
214     void visitFCmpInst(FCmpInst &FC);
215     void visitExtractElementInst(ExtractElementInst &EI);
216     void visitInsertElementInst(InsertElementInst &EI);
217     void visitShuffleVectorInst(ShuffleVectorInst &EI);
218     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
219     void visitCallInst(CallInst &CI);
220     void visitGetElementPtrInst(GetElementPtrInst &GEP);
221     void visitLoadInst(LoadInst &LI);
222     void visitStoreInst(StoreInst &SI);
223     void visitInstruction(Instruction &I);
224     void visitTerminatorInst(TerminatorInst &I);
225     void visitReturnInst(ReturnInst &RI);
226     void visitSwitchInst(SwitchInst &SI);
227     void visitSelectInst(SelectInst &SI);
228     void visitUserOp1(Instruction &I);
229     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
230     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
231
232     void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
233                                   unsigned Count, ...);
234
235     void WriteValue(const Value *V) {
236       if (!V) return;
237       if (isa<Instruction>(V)) {
238         msgs << *V;
239       } else {
240         WriteAsOperand(msgs, V, true, Mod);
241         msgs << "\n";
242       }
243     }
244
245     void WriteType(const Type* T ) {
246       if ( !T ) return;
247       WriteTypeSymbolic(msgs, T, Mod );
248     }
249
250
251     // CheckFailed - A check failed, so print out the condition and the message
252     // that failed.  This provides a nice place to put a breakpoint if you want
253     // to see why something is not correct.
254     void CheckFailed(const std::string &Message,
255                      const Value *V1 = 0, const Value *V2 = 0,
256                      const Value *V3 = 0, const Value *V4 = 0) {
257       msgs << Message << "\n";
258       WriteValue(V1);
259       WriteValue(V2);
260       WriteValue(V3);
261       WriteValue(V4);
262       Broken = true;
263     }
264
265     void CheckFailed( const std::string& Message, const Value* V1,
266                       const Type* T2, const Value* V3 = 0 ) {
267       msgs << Message << "\n";
268       WriteValue(V1);
269       WriteType(T2);
270       WriteValue(V3);
271       Broken = true;
272     }
273   };
274
275   char Verifier::ID = 0;
276   RegisterPass<Verifier> X("verify", "Module Verifier");
277 } // End anonymous namespace
278
279
280 // Assert - We know that cond should be true, if not print an error message.
281 #define Assert(C, M) \
282   do { if (!(C)) { CheckFailed(M); return; } } while (0)
283 #define Assert1(C, M, V1) \
284   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
285 #define Assert2(C, M, V1, V2) \
286   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
287 #define Assert3(C, M, V1, V2, V3) \
288   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
289 #define Assert4(C, M, V1, V2, V3, V4) \
290   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
291
292
293 void Verifier::visitGlobalValue(GlobalValue &GV) {
294   Assert1(!GV.isDeclaration() ||
295           GV.hasExternalLinkage() ||
296           GV.hasDLLImportLinkage() ||
297           GV.hasExternalWeakLinkage() ||
298           (isa<GlobalAlias>(GV) &&
299            (GV.hasInternalLinkage() || GV.hasWeakLinkage())),
300   "Global is external, but doesn't have external or dllimport or weak linkage!",
301           &GV);
302
303   Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
304           "Global is marked as dllimport, but not external", &GV);
305   
306   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
307           "Only global variables can have appending linkage!", &GV);
308
309   if (GV.hasAppendingLinkage()) {
310     GlobalVariable &GVar = cast<GlobalVariable>(GV);
311     Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
312             "Only global arrays can have appending linkage!", &GV);
313   }
314 }
315
316 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
317   if (GV.hasInitializer()) {
318     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
319             "Global variable initializer type does not match global "
320             "variable type!", &GV);
321   } else {
322     Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
323             GV.hasExternalWeakLinkage(),
324             "invalid linkage type for global declaration", &GV);
325   }
326
327   visitGlobalValue(GV);
328 }
329
330 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
331   Assert1(!GA.getName().empty(),
332           "Alias name cannot be empty!", &GA);
333   Assert1(GA.hasExternalLinkage() || GA.hasInternalLinkage() ||
334           GA.hasWeakLinkage(),
335           "Alias should have external or external weak linkage!", &GA);
336   Assert1(GA.getType() == GA.getAliasee()->getType(),
337           "Alias and aliasee types should match!", &GA);
338   
339   if (!isa<GlobalValue>(GA.getAliasee())) {
340     const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
341     Assert1(CE && CE->getOpcode() == Instruction::BitCast &&
342             isa<GlobalValue>(CE->getOperand(0)),
343             "Aliasee should be either GlobalValue or bitcast of GlobalValue",
344             &GA);
345   }
346   
347   visitGlobalValue(GA);
348 }
349
350 void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
351 }
352
353 // visitFunction - Verify that a function is ok.
354 //
355 void Verifier::visitFunction(Function &F) {
356   // Check function arguments.
357   const FunctionType *FT = F.getFunctionType();
358   unsigned NumArgs = F.arg_size();
359
360   Assert2(FT->getNumParams() == NumArgs,
361           "# formal arguments must match # of arguments for function type!",
362           &F, FT);
363   Assert1(F.getReturnType()->isFirstClassType() ||
364           F.getReturnType() == Type::VoidTy,
365           "Functions cannot return aggregate values!", &F);
366
367   Assert1(!FT->isStructReturn() || FT->getReturnType() == Type::VoidTy,
368           "Invalid struct-return function!", &F);
369
370   const uint16_t ReturnIncompatible =
371     ParamAttr::ByVal | ParamAttr::InReg |
372     ParamAttr::Nest  | ParamAttr::StructRet;
373
374   const uint16_t ParameterIncompatible =
375     ParamAttr::NoReturn | ParamAttr::NoUnwind;
376
377   const uint16_t MutuallyIncompatible =
378     ParamAttr::ByVal | ParamAttr::InReg |
379     ParamAttr::Nest  | ParamAttr::StructRet;
380
381   const uint16_t MutuallyIncompatible2 =
382     ParamAttr::ZExt | ParamAttr::SExt;
383
384   const uint16_t IntegerTypeOnly =
385     ParamAttr::SExt | ParamAttr::ZExt;
386
387   const uint16_t PointerTypeOnly =
388     ParamAttr::ByVal   | ParamAttr::Nest |
389     ParamAttr::NoAlias | ParamAttr::StructRet;
390
391   bool SawSRet = false;
392
393   if (const ParamAttrsList *Attrs = FT->getParamAttrs()) {
394     unsigned Idx = 1;
395     bool SawNest = false;
396
397     uint16_t RetI = Attrs->getParamAttrs(0) & ReturnIncompatible;
398     Assert1(!RetI, "Attribute " + Attrs->getParamAttrsText(RetI) +
399             "should not apply to functions!", &F);
400     uint16_t MutI = Attrs->getParamAttrs(0) & MutuallyIncompatible2;
401     Assert1(MutI != MutuallyIncompatible2, "Attributes" + 
402             Attrs->getParamAttrsText(MutI) + "are incompatible!", &F);
403
404     for (FunctionType::param_iterator I = FT->param_begin(), 
405          E = FT->param_end(); I != E; ++I, ++Idx) {
406
407       uint16_t Attr = Attrs->getParamAttrs(Idx);
408
409       uint16_t ParmI = Attr & ParameterIncompatible;
410       Assert1(!ParmI, "Attribute " + Attrs->getParamAttrsText(ParmI) +
411               "should only be applied to function!", &F);
412
413       uint16_t MutI = Attr & MutuallyIncompatible;
414       Assert1(!(MutI & (MutI - 1)), "Attributes " +
415               Attrs->getParamAttrsText(MutI) + "are incompatible!", &F);
416
417       uint16_t MutI2 = Attr & MutuallyIncompatible2;
418       Assert1(MutI2 != MutuallyIncompatible2, "Attributes" + 
419               Attrs->getParamAttrsText(MutI2) + "are incompatible!", &F);
420
421       uint16_t IType = Attr & IntegerTypeOnly;
422       Assert1(!IType || FT->getParamType(Idx-1)->isInteger(),
423               "Attribute " + Attrs->getParamAttrsText(IType) +
424               "should only apply to Integer type!", &F);
425
426       uint16_t PType = Attr & PointerTypeOnly;
427       Assert1(!PType || isa<PointerType>(FT->getParamType(Idx-1)),
428               "Attribute " + Attrs->getParamAttrsText(PType) +
429               "should only apply to Pointer type!", &F);
430
431       if (Attrs->paramHasAttr(Idx, ParamAttr::ByVal)) {
432         const PointerType *Ty =
433             dyn_cast<PointerType>(FT->getParamType(Idx-1));
434         Assert1(!Ty || isa<StructType>(Ty->getElementType()),
435                 "Attribute byval should only apply to pointer to structs!", &F);
436       }
437
438       if (Attrs->paramHasAttr(Idx, ParamAttr::Nest)) {
439         Assert1(!SawNest, "More than one parameter has attribute nest!", &F);
440         SawNest = true;
441       }
442
443       if (Attrs->paramHasAttr(Idx, ParamAttr::StructRet)) {
444         SawSRet = true;
445         Assert1(Idx == 1, "Attribute sret not on first parameter!", &F);
446       }
447     }
448   }
449
450   Assert1(SawSRet == FT->isStructReturn(),
451           "StructReturn function with no sret attribute!", &F);
452
453   // Check that this function meets the restrictions on this calling convention.
454   switch (F.getCallingConv()) {
455   default:
456     break;
457   case CallingConv::C:
458     break;
459   case CallingConv::Fast:
460   case CallingConv::Cold:
461   case CallingConv::X86_FastCall:
462     Assert1(!F.isVarArg(),
463             "Varargs functions must have C calling conventions!", &F);
464     break;
465   }
466   
467   // Check that the argument values match the function type for this function...
468   unsigned i = 0;
469   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
470        I != E; ++I, ++i) {
471     Assert2(I->getType() == FT->getParamType(i),
472             "Argument value does not match function argument type!",
473             I, FT->getParamType(i));
474     // Make sure no aggregates are passed by value.
475     Assert1(I->getType()->isFirstClassType(),
476             "Functions cannot take aggregates as arguments by value!", I);
477    }
478
479   if (F.isDeclaration()) {
480     Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
481             F.hasExternalWeakLinkage(),
482             "invalid linkage type for function declaration", &F);
483   } else {
484     // Verify that this function (which has a body) is not named "llvm.*".  It
485     // is not legal to define intrinsics.
486     if (F.getName().size() >= 5)
487       Assert1(F.getName().substr(0, 5) != "llvm.",
488               "llvm intrinsics cannot be defined!", &F);
489     
490     // Check the entry node
491     BasicBlock *Entry = &F.getEntryBlock();
492     Assert1(pred_begin(Entry) == pred_end(Entry),
493             "Entry block to function must not have predecessors!", Entry);
494   }
495 }
496
497
498 // verifyBasicBlock - Verify that a basic block is well formed...
499 //
500 void Verifier::visitBasicBlock(BasicBlock &BB) {
501   InstsInThisBlock.clear();
502
503   // Ensure that basic blocks have terminators!
504   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
505
506   // Check constraints that this basic block imposes on all of the PHI nodes in
507   // it.
508   if (isa<PHINode>(BB.front())) {
509     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
510     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
511     std::sort(Preds.begin(), Preds.end());
512     PHINode *PN;
513     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
514
515       // Ensure that PHI nodes have at least one entry!
516       Assert1(PN->getNumIncomingValues() != 0,
517               "PHI nodes must have at least one entry.  If the block is dead, "
518               "the PHI should be removed!", PN);
519       Assert1(PN->getNumIncomingValues() == Preds.size(),
520               "PHINode should have one entry for each predecessor of its "
521               "parent basic block!", PN);
522
523       // Get and sort all incoming values in the PHI node...
524       Values.clear();
525       Values.reserve(PN->getNumIncomingValues());
526       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
527         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
528                                         PN->getIncomingValue(i)));
529       std::sort(Values.begin(), Values.end());
530
531       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
532         // Check to make sure that if there is more than one entry for a
533         // particular basic block in this PHI node, that the incoming values are
534         // all identical.
535         //
536         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
537                 Values[i].second == Values[i-1].second,
538                 "PHI node has multiple entries for the same basic block with "
539                 "different incoming values!", PN, Values[i].first,
540                 Values[i].second, Values[i-1].second);
541
542         // Check to make sure that the predecessors and PHI node entries are
543         // matched up.
544         Assert3(Values[i].first == Preds[i],
545                 "PHI node entries do not match predecessors!", PN,
546                 Values[i].first, Preds[i]);
547       }
548     }
549   }
550 }
551
552 void Verifier::visitTerminatorInst(TerminatorInst &I) {
553   // Ensure that terminators only exist at the end of the basic block.
554   Assert1(&I == I.getParent()->getTerminator(),
555           "Terminator found in the middle of a basic block!", I.getParent());
556   visitInstruction(I);
557 }
558
559 void Verifier::visitReturnInst(ReturnInst &RI) {
560   Function *F = RI.getParent()->getParent();
561   if (RI.getNumOperands() == 0)
562     Assert2(F->getReturnType() == Type::VoidTy,
563             "Found return instr that returns void in Function of non-void "
564             "return type!", &RI, F->getReturnType());
565   else
566     Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
567             "Function return type does not match operand "
568             "type of return inst!", &RI, F->getReturnType());
569
570   // Check to make sure that the return value has necessary properties for
571   // terminators...
572   visitTerminatorInst(RI);
573 }
574
575 void Verifier::visitSwitchInst(SwitchInst &SI) {
576   // Check to make sure that all of the constants in the switch instruction
577   // have the same type as the switched-on value.
578   const Type *SwitchTy = SI.getCondition()->getType();
579   for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
580     Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
581             "Switch constants must all be same type as switch value!", &SI);
582
583   visitTerminatorInst(SI);
584 }
585
586 void Verifier::visitSelectInst(SelectInst &SI) {
587   Assert1(SI.getCondition()->getType() == Type::Int1Ty,
588           "Select condition type must be bool!", &SI);
589   Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
590           "Select values must have identical types!", &SI);
591   Assert1(SI.getTrueValue()->getType() == SI.getType(),
592           "Select values must have same type as select instruction!", &SI);
593   visitInstruction(SI);
594 }
595
596
597 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
598 /// a pass, if any exist, it's an error.
599 ///
600 void Verifier::visitUserOp1(Instruction &I) {
601   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
602 }
603
604 void Verifier::visitTruncInst(TruncInst &I) {
605   // Get the source and destination types
606   const Type *SrcTy = I.getOperand(0)->getType();
607   const Type *DestTy = I.getType();
608
609   // Get the size of the types in bits, we'll need this later
610   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
611   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
612
613   Assert1(SrcTy->isInteger(), "Trunc only operates on integer", &I);
614   Assert1(DestTy->isInteger(), "Trunc only produces integer", &I);
615   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
616
617   visitInstruction(I);
618 }
619
620 void Verifier::visitZExtInst(ZExtInst &I) {
621   // Get the source and destination types
622   const Type *SrcTy = I.getOperand(0)->getType();
623   const Type *DestTy = I.getType();
624
625   // Get the size of the types in bits, we'll need this later
626   Assert1(SrcTy->isInteger(), "ZExt only operates on integer", &I);
627   Assert1(DestTy->isInteger(), "ZExt only produces an integer", &I);
628   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
629   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
630
631   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
632
633   visitInstruction(I);
634 }
635
636 void Verifier::visitSExtInst(SExtInst &I) {
637   // Get the source and destination types
638   const Type *SrcTy = I.getOperand(0)->getType();
639   const Type *DestTy = I.getType();
640
641   // Get the size of the types in bits, we'll need this later
642   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
643   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
644
645   Assert1(SrcTy->isInteger(), "SExt only operates on integer", &I);
646   Assert1(DestTy->isInteger(), "SExt only produces an integer", &I);
647   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
648
649   visitInstruction(I);
650 }
651
652 void Verifier::visitFPTruncInst(FPTruncInst &I) {
653   // Get the source and destination types
654   const Type *SrcTy = I.getOperand(0)->getType();
655   const Type *DestTy = I.getType();
656   // Get the size of the types in bits, we'll need this later
657   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
658   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
659
660   Assert1(SrcTy->isFloatingPoint(),"FPTrunc only operates on FP", &I);
661   Assert1(DestTy->isFloatingPoint(),"FPTrunc only produces an FP", &I);
662   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
663
664   visitInstruction(I);
665 }
666
667 void Verifier::visitFPExtInst(FPExtInst &I) {
668   // Get the source and destination types
669   const Type *SrcTy = I.getOperand(0)->getType();
670   const Type *DestTy = I.getType();
671
672   // Get the size of the types in bits, we'll need this later
673   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
674   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
675
676   Assert1(SrcTy->isFloatingPoint(),"FPExt only operates on FP", &I);
677   Assert1(DestTy->isFloatingPoint(),"FPExt only produces an FP", &I);
678   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
679
680   visitInstruction(I);
681 }
682
683 void Verifier::visitUIToFPInst(UIToFPInst &I) {
684   // Get the source and destination types
685   const Type *SrcTy = I.getOperand(0)->getType();
686   const Type *DestTy = I.getType();
687
688   Assert1(SrcTy->isInteger(),"UInt2FP source must be integral", &I);
689   Assert1(DestTy->isFloatingPoint(),"UInt2FP result must be FP", &I);
690
691   visitInstruction(I);
692 }
693
694 void Verifier::visitSIToFPInst(SIToFPInst &I) {
695   // Get the source and destination types
696   const Type *SrcTy = I.getOperand(0)->getType();
697   const Type *DestTy = I.getType();
698
699   Assert1(SrcTy->isInteger(),"SInt2FP source must be integral", &I);
700   Assert1(DestTy->isFloatingPoint(),"SInt2FP result must be FP", &I);
701
702   visitInstruction(I);
703 }
704
705 void Verifier::visitFPToUIInst(FPToUIInst &I) {
706   // Get the source and destination types
707   const Type *SrcTy = I.getOperand(0)->getType();
708   const Type *DestTy = I.getType();
709
710   Assert1(SrcTy->isFloatingPoint(),"FP2UInt source must be FP", &I);
711   Assert1(DestTy->isInteger(),"FP2UInt result must be integral", &I);
712
713   visitInstruction(I);
714 }
715
716 void Verifier::visitFPToSIInst(FPToSIInst &I) {
717   // Get the source and destination types
718   const Type *SrcTy = I.getOperand(0)->getType();
719   const Type *DestTy = I.getType();
720
721   Assert1(SrcTy->isFloatingPoint(),"FPToSI source must be FP", &I);
722   Assert1(DestTy->isInteger(),"FP2ToI result must be integral", &I);
723
724   visitInstruction(I);
725 }
726
727 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
728   // Get the source and destination types
729   const Type *SrcTy = I.getOperand(0)->getType();
730   const Type *DestTy = I.getType();
731
732   Assert1(isa<PointerType>(SrcTy), "PtrToInt source must be pointer", &I);
733   Assert1(DestTy->isInteger(), "PtrToInt result must be integral", &I);
734
735   visitInstruction(I);
736 }
737
738 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
739   // Get the source and destination types
740   const Type *SrcTy = I.getOperand(0)->getType();
741   const Type *DestTy = I.getType();
742
743   Assert1(SrcTy->isInteger(), "IntToPtr source must be an integral", &I);
744   Assert1(isa<PointerType>(DestTy), "IntToPtr result must be a pointer",&I);
745
746   visitInstruction(I);
747 }
748
749 void Verifier::visitBitCastInst(BitCastInst &I) {
750   // Get the source and destination types
751   const Type *SrcTy = I.getOperand(0)->getType();
752   const Type *DestTy = I.getType();
753
754   // Get the size of the types in bits, we'll need this later
755   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
756   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
757
758   // BitCast implies a no-op cast of type only. No bits change.
759   // However, you can't cast pointers to anything but pointers.
760   Assert1(isa<PointerType>(DestTy) == isa<PointerType>(DestTy),
761           "Bitcast requires both operands to be pointer or neither", &I);
762   Assert1(SrcBitSize == DestBitSize, "Bitcast requies types of same width", &I);
763
764   visitInstruction(I);
765 }
766
767 /// visitPHINode - Ensure that a PHI node is well formed.
768 ///
769 void Verifier::visitPHINode(PHINode &PN) {
770   // Ensure that the PHI nodes are all grouped together at the top of the block.
771   // This can be tested by checking whether the instruction before this is
772   // either nonexistent (because this is begin()) or is a PHI node.  If not,
773   // then there is some other instruction before a PHI.
774   Assert2(&PN == &PN.getParent()->front() || 
775           isa<PHINode>(--BasicBlock::iterator(&PN)),
776           "PHI nodes not grouped at top of basic block!",
777           &PN, PN.getParent());
778
779   // Check that all of the operands of the PHI node have the same type as the
780   // result.
781   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
782     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
783             "PHI node operands are not the same type as the result!", &PN);
784
785   // All other PHI node constraints are checked in the visitBasicBlock method.
786
787   visitInstruction(PN);
788 }
789
790 void Verifier::visitCallInst(CallInst &CI) {
791   Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
792           "Called function must be a pointer!", &CI);
793   const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
794   Assert1(isa<FunctionType>(FPTy->getElementType()),
795           "Called function is not pointer to function type!", &CI);
796
797   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
798
799   // Verify that the correct number of arguments are being passed
800   if (FTy->isVarArg())
801     Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
802             "Called function requires more parameters than were provided!",&CI);
803   else
804     Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
805             "Incorrect number of arguments passed to called function!", &CI);
806
807   // Verify that all arguments to the call match the function type...
808   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
809     Assert3(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
810             "Call parameter type does not match function signature!",
811             CI.getOperand(i+1), FTy->getParamType(i), &CI);
812
813   if (Function *F = CI.getCalledFunction()) {
814     if (Pedantic) {
815       // Verify that calling convention of Function and CallInst match
816       Assert1(F->getCallingConv() == CI.getCallingConv(),
817               "Call uses different calling convention than function", &CI);
818     }
819     
820     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
821       visitIntrinsicFunctionCall(ID, CI);
822   }
823   
824   visitInstruction(CI);
825 }
826
827 /// visitBinaryOperator - Check that both arguments to the binary operator are
828 /// of the same type!
829 ///
830 void Verifier::visitBinaryOperator(BinaryOperator &B) {
831   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
832           "Both operands to a binary operator are not of the same type!", &B);
833
834   switch (B.getOpcode()) {
835   // Check that logical operators are only used with integral operands.
836   case Instruction::And:
837   case Instruction::Or:
838   case Instruction::Xor:
839     Assert1(B.getType()->isInteger() ||
840             (isa<VectorType>(B.getType()) && 
841              cast<VectorType>(B.getType())->getElementType()->isInteger()),
842             "Logical operators only work with integral types!", &B);
843     Assert1(B.getType() == B.getOperand(0)->getType(),
844             "Logical operators must have same type for operands and result!",
845             &B);
846     break;
847   case Instruction::Shl:
848   case Instruction::LShr:
849   case Instruction::AShr:
850     Assert1(B.getType()->isInteger(),
851             "Shift must return an integer result!", &B);
852     Assert1(B.getType() == B.getOperand(0)->getType(),
853             "Shift return type must be same as operands!", &B);
854     /* FALL THROUGH */
855   default:
856     // Arithmetic operators only work on integer or fp values
857     Assert1(B.getType() == B.getOperand(0)->getType(),
858             "Arithmetic operators must have same type for operands and result!",
859             &B);
860     Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
861             isa<VectorType>(B.getType()),
862             "Arithmetic operators must have integer, fp, or vector type!", &B);
863     break;
864   }
865
866   visitInstruction(B);
867 }
868
869 void Verifier::visitICmpInst(ICmpInst& IC) {
870   // Check that the operands are the same type
871   const Type* Op0Ty = IC.getOperand(0)->getType();
872   const Type* Op1Ty = IC.getOperand(1)->getType();
873   Assert1(Op0Ty == Op1Ty,
874           "Both operands to ICmp instruction are not of the same type!", &IC);
875   // Check that the operands are the right type
876   Assert1(Op0Ty->isInteger() || isa<PointerType>(Op0Ty),
877           "Invalid operand types for ICmp instruction", &IC);
878   visitInstruction(IC);
879 }
880
881 void Verifier::visitFCmpInst(FCmpInst& FC) {
882   // Check that the operands are the same type
883   const Type* Op0Ty = FC.getOperand(0)->getType();
884   const Type* Op1Ty = FC.getOperand(1)->getType();
885   Assert1(Op0Ty == Op1Ty,
886           "Both operands to FCmp instruction are not of the same type!", &FC);
887   // Check that the operands are the right type
888   Assert1(Op0Ty->isFloatingPoint(),
889           "Invalid operand types for FCmp instruction", &FC);
890   visitInstruction(FC);
891 }
892
893 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
894   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
895                                               EI.getOperand(1)),
896           "Invalid extractelement operands!", &EI);
897   visitInstruction(EI);
898 }
899
900 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
901   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
902                                              IE.getOperand(1),
903                                              IE.getOperand(2)),
904           "Invalid insertelement operands!", &IE);
905   visitInstruction(IE);
906 }
907
908 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
909   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
910                                              SV.getOperand(2)),
911           "Invalid shufflevector operands!", &SV);
912   Assert1(SV.getType() == SV.getOperand(0)->getType(),
913           "Result of shufflevector must match first operand type!", &SV);
914   
915   // Check to see if Mask is valid.
916   if (const ConstantVector *MV = dyn_cast<ConstantVector>(SV.getOperand(2))) {
917     for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
918       Assert1(isa<ConstantInt>(MV->getOperand(i)) ||
919               isa<UndefValue>(MV->getOperand(i)),
920               "Invalid shufflevector shuffle mask!", &SV);
921     }
922   } else {
923     Assert1(isa<UndefValue>(SV.getOperand(2)) || 
924             isa<ConstantAggregateZero>(SV.getOperand(2)),
925             "Invalid shufflevector shuffle mask!", &SV);
926   }
927   
928   visitInstruction(SV);
929 }
930
931 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
932   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
933   const Type *ElTy =
934     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
935                                       Idxs.begin(), Idxs.end(), true);
936   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
937   Assert2(isa<PointerType>(GEP.getType()) &&
938           cast<PointerType>(GEP.getType())->getElementType() == ElTy,
939           "GEP is not of right type for indices!", &GEP, ElTy);
940   visitInstruction(GEP);
941 }
942
943 void Verifier::visitLoadInst(LoadInst &LI) {
944   const Type *ElTy =
945     cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
946   Assert2(ElTy == LI.getType(),
947           "Load result type does not match pointer operand type!", &LI, ElTy);
948   visitInstruction(LI);
949 }
950
951 void Verifier::visitStoreInst(StoreInst &SI) {
952   const Type *ElTy =
953     cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
954   Assert2(ElTy == SI.getOperand(0)->getType(),
955           "Stored value type does not match pointer operand type!", &SI, ElTy);
956   visitInstruction(SI);
957 }
958
959
960 /// verifyInstruction - Verify that an instruction is well formed.
961 ///
962 void Verifier::visitInstruction(Instruction &I) {
963   BasicBlock *BB = I.getParent();
964   Assert1(BB, "Instruction not embedded in basic block!", &I);
965
966   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
967     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
968          UI != UE; ++UI)
969       Assert1(*UI != (User*)&I ||
970               !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
971               "Only PHI nodes may reference their own value!", &I);
972   }
973
974   // Check that void typed values don't have names
975   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
976           "Instruction has a name, but provides a void value!", &I);
977
978   // Check that the return value of the instruction is either void or a legal
979   // value type.
980   Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType(),
981           "Instruction returns a non-scalar type!", &I);
982
983   // Check that all uses of the instruction, if they are instructions
984   // themselves, actually have parent basic blocks.  If the use is not an
985   // instruction, it is an error!
986   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
987        UI != UE; ++UI) {
988     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
989             *UI);
990     Instruction *Used = cast<Instruction>(*UI);
991     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
992             " embeded in a basic block!", &I, Used);
993   }
994
995   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
996     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
997
998     // Check to make sure that only first-class-values are operands to
999     // instructions.
1000     Assert1(I.getOperand(i)->getType()->isFirstClassType(),
1001             "Instruction operands must be first-class values!", &I);
1002   
1003     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
1004       // Check to make sure that the "address of" an intrinsic function is never
1005       // taken.
1006       Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
1007               "Cannot take the address of an intrinsic!", &I);
1008       Assert1(F->getParent() == Mod, "Referencing function in another module!",
1009               &I);
1010     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
1011       Assert1(OpBB->getParent() == BB->getParent(),
1012               "Referring to a basic block in another function!", &I);
1013     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
1014       Assert1(OpArg->getParent() == BB->getParent(),
1015               "Referring to an argument in another function!", &I);
1016     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
1017       Assert1(GV->getParent() == Mod, "Referencing global in another module!",
1018               &I);
1019     } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
1020       BasicBlock *OpBlock = Op->getParent();
1021
1022       // Check that a definition dominates all of its uses.
1023       if (!isa<PHINode>(I)) {
1024         // Invoke results are only usable in the normal destination, not in the
1025         // exceptional destination.
1026         if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
1027           OpBlock = II->getNormalDest();
1028           
1029           Assert2(OpBlock != II->getUnwindDest(),
1030                   "No uses of invoke possible due to dominance structure!",
1031                   Op, II);
1032           
1033           // If the normal successor of an invoke instruction has multiple
1034           // predecessors, then the normal edge from the invoke is critical, so
1035           // the invoke value can only be live if the destination block
1036           // dominates all of it's predecessors (other than the invoke) or if
1037           // the invoke value is only used by a phi in the successor.
1038           if (!OpBlock->getSinglePredecessor() &&
1039               DT->dominates(&BB->getParent()->getEntryBlock(), BB)) {
1040             // The first case we allow is if the use is a PHI operand in the
1041             // normal block, and if that PHI operand corresponds to the invoke's
1042             // block.
1043             bool Bad = true;
1044             if (PHINode *PN = dyn_cast<PHINode>(&I))
1045               if (PN->getParent() == OpBlock &&
1046                   PN->getIncomingBlock(i/2) == Op->getParent())
1047                 Bad = false;
1048             
1049             // If it is used by something non-phi, then the other case is that
1050             // 'OpBlock' dominates all of its predecessors other than the
1051             // invoke.  In this case, the invoke value can still be used.
1052             if (Bad) {
1053               Bad = false;
1054               for (pred_iterator PI = pred_begin(OpBlock),
1055                    E = pred_end(OpBlock); PI != E; ++PI) {
1056                 if (*PI != II->getParent() && !DT->dominates(OpBlock, *PI)) {
1057                   Bad = true;
1058                   break;
1059                 }
1060               }
1061             }
1062             Assert2(!Bad,
1063                     "Invoke value defined on critical edge but not dead!", &I,
1064                     Op);
1065           }
1066         } else if (OpBlock == BB) {
1067           // If they are in the same basic block, make sure that the definition
1068           // comes before the use.
1069           Assert2(InstsInThisBlock.count(Op) ||
1070                   !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
1071                   "Instruction does not dominate all uses!", Op, &I);
1072         }
1073
1074         // Definition must dominate use unless use is unreachable!
1075         Assert2(DT->dominates(OpBlock, BB) ||
1076                 !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
1077                 "Instruction does not dominate all uses!", Op, &I);
1078       } else {
1079         // PHI nodes are more difficult than other nodes because they actually
1080         // "use" the value in the predecessor basic blocks they correspond to.
1081         BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
1082         Assert2(DT->dominates(OpBlock, PredBB) ||
1083                 !DT->dominates(&BB->getParent()->getEntryBlock(), PredBB),
1084                 "Instruction does not dominate all uses!", Op, &I);
1085       }
1086     } else if (isa<InlineAsm>(I.getOperand(i))) {
1087       Assert1(i == 0 && isa<CallInst>(I),
1088               "Cannot take the address of an inline asm!", &I);
1089     }
1090   }
1091   InstsInThisBlock.insert(&I);
1092 }
1093
1094 static bool HasPtrPtrType(Value *Val) {
1095   if (const PointerType *PtrTy = dyn_cast<PointerType>(Val->getType()))
1096     return isa<PointerType>(PtrTy->getElementType());
1097   return false;
1098 }
1099
1100 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
1101 ///
1102 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
1103   Function *IF = CI.getCalledFunction();
1104   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
1105           IF);
1106   
1107 #define GET_INTRINSIC_VERIFIER
1108 #include "llvm/Intrinsics.gen"
1109 #undef GET_INTRINSIC_VERIFIER
1110   
1111   switch (ID) {
1112   default:
1113     break;
1114   case Intrinsic::gcroot:
1115     Assert1(HasPtrPtrType(CI.getOperand(1)),
1116             "llvm.gcroot parameter #1 must be a pointer to a pointer.", &CI);
1117     Assert1(isa<AllocaInst>(IntrinsicInst::StripPointerCasts(CI.getOperand(1))),
1118             "llvm.gcroot parameter #1 must be an alloca (or a bitcast of one).",
1119             &CI);
1120     Assert1(isa<Constant>(CI.getOperand(2)),
1121             "llvm.gcroot parameter #2 must be a constant.", &CI);
1122     break;
1123   case Intrinsic::gcwrite:
1124     Assert1(CI.getOperand(3)->getType()
1125             == PointerType::get(CI.getOperand(1)->getType()),
1126             "Call to llvm.gcwrite must be with type 'void (%ty*, %ty2*, %ty**)'.",
1127             &CI);
1128     break;
1129   case Intrinsic::gcread:
1130     Assert1(CI.getOperand(2)->getType() == PointerType::get(CI.getType()),
1131             "Call to llvm.gcread must be with type '%ty* (%ty2*, %ty**).'",
1132             &CI);
1133     break;
1134   case Intrinsic::init_trampoline:
1135     Assert1(isa<Function>(IntrinsicInst::StripPointerCasts(CI.getOperand(2))),
1136             "llvm.init_trampoline parameter #2 must resolve to a function.",
1137             &CI);
1138   }
1139 }
1140
1141 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
1142 /// Intrinsics.gen.  This implements a little state machine that verifies the
1143 /// prototype of intrinsics.
1144 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID,
1145                                         Function *F,
1146                                         unsigned Count, ...) {
1147   va_list VA;
1148   va_start(VA, Count);
1149   
1150   const FunctionType *FTy = F->getFunctionType();
1151   
1152   // For overloaded intrinsics, the Suffix of the function name must match the
1153   // types of the arguments. This variable keeps track of the expected
1154   // suffix, to be checked at the end.
1155   std::string Suffix;
1156
1157   if (FTy->getNumParams() + FTy->isVarArg() != Count - 1) {
1158     CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
1159     return;
1160   }
1161
1162   // Note that "arg#0" is the return type.
1163   for (unsigned ArgNo = 0; ArgNo < Count; ++ArgNo) {
1164     MVT::ValueType VT = va_arg(VA, MVT::ValueType);
1165
1166     if (VT == MVT::isVoid && ArgNo > 0) {
1167       if (!FTy->isVarArg())
1168         CheckFailed("Intrinsic prototype has no '...'!", F);
1169       break;
1170     }
1171
1172     const Type *Ty;
1173     if (ArgNo == 0)
1174       Ty = FTy->getReturnType();
1175     else
1176       Ty = FTy->getParamType(ArgNo-1);
1177
1178     unsigned NumElts = 0;
1179     const Type *EltTy = Ty;
1180     if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1181       EltTy = VTy->getElementType();
1182       NumElts = VTy->getNumElements();
1183     }
1184     
1185     if ((int)VT < 0) {
1186       int Match = ~VT;
1187       if (Match == 0) {
1188         if (Ty != FTy->getReturnType()) {
1189           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " does not "
1190                       "match return type.", F);
1191           break;
1192         }
1193       } else {
1194         if (Ty != FTy->getParamType(Match-1)) {
1195           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " does not "
1196                       "match parameter %" + utostr(Match-1) + ".", F);
1197           break;
1198         }
1199       }
1200     } else if (VT == MVT::iAny) {
1201       if (!EltTy->isInteger()) {
1202         if (ArgNo == 0)
1203           CheckFailed("Intrinsic result type is not "
1204                       "an integer type.", F);
1205         else
1206           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is not "
1207                       "an integer type.", F);
1208         break;
1209       }
1210       unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
1211       Suffix += ".";
1212       if (EltTy != Ty)
1213         Suffix += "v" + utostr(NumElts);
1214       Suffix += "i" + utostr(GotBits);;
1215       // Check some constraints on various intrinsics.
1216       switch (ID) {
1217         default: break; // Not everything needs to be checked.
1218         case Intrinsic::bswap:
1219           if (GotBits < 16 || GotBits % 16 != 0)
1220             CheckFailed("Intrinsic requires even byte width argument", F);
1221           break;
1222       }
1223     } else if (VT == MVT::fAny) {
1224       if (!EltTy->isFloatingPoint()) {
1225         if (ArgNo == 0)
1226           CheckFailed("Intrinsic result type is not "
1227                       "a floating-point type.", F);
1228         else
1229           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is not "
1230                       "a floating-point type.", F);
1231         break;
1232       }
1233       Suffix += ".";
1234       if (EltTy != Ty)
1235         Suffix += "v" + utostr(NumElts);
1236       Suffix += MVT::getValueTypeString(MVT::getValueType(EltTy));
1237     } else if (VT == MVT::iPTR) {
1238       if (!isa<PointerType>(Ty)) {
1239         if (ArgNo == 0)
1240           CheckFailed("Intrinsic result type is not a "
1241                       "pointer and a pointer is required.", F);
1242         else
1243           CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is not a "
1244                       "pointer and a pointer is required.", F);
1245         break;
1246       }
1247     } else if (MVT::isVector(VT)) {
1248       // If this is a vector argument, verify the number and type of elements.
1249       if (MVT::getVectorElementType(VT) != MVT::getValueType(EltTy)) {
1250         CheckFailed("Intrinsic prototype has incorrect vector element type!",
1251                     F);
1252         break;
1253       }
1254       if (MVT::getVectorNumElements(VT) != NumElts) {
1255         CheckFailed("Intrinsic prototype has incorrect number of "
1256                     "vector elements!",F);
1257         break;
1258       }
1259     } else if (MVT::getTypeForValueType(VT) != EltTy) {
1260       if (ArgNo == 0)
1261         CheckFailed("Intrinsic prototype has incorrect result type!", F);
1262       else
1263         CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is wrong!",F);
1264       break;
1265     } else if (EltTy != Ty) {
1266       if (ArgNo == 0)
1267         CheckFailed("Intrinsic result type is vector "
1268                     "and a scalar is required.", F);
1269       else
1270         CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is vector "
1271                     "and a scalar is required.", F);
1272     }
1273   }
1274
1275   va_end(VA);
1276
1277   // If we computed a Suffix then the intrinsic is overloaded and we need to 
1278   // make sure that the name of the function is correct. We add the suffix to
1279   // the name of the intrinsic and compare against the given function name. If
1280   // they are not the same, the function name is invalid. This ensures that
1281   // overloading of intrinsics uses a sane and consistent naming convention.
1282   if (!Suffix.empty()) {
1283     std::string Name(Intrinsic::getName(ID));
1284     if (Name + Suffix != F->getName())
1285       CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
1286                   F->getName().substr(Name.length()) + "'. It should be '" +
1287                   Suffix + "'", F);
1288   }
1289 }
1290
1291
1292 //===----------------------------------------------------------------------===//
1293 //  Implement the public interfaces to this file...
1294 //===----------------------------------------------------------------------===//
1295
1296 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
1297   return new Verifier(action);
1298 }
1299
1300
1301 // verifyFunction - Create
1302 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
1303   Function &F = const_cast<Function&>(f);
1304   assert(!F.isDeclaration() && "Cannot verify external functions");
1305
1306   FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
1307   Verifier *V = new Verifier(action);
1308   FPM.add(V);
1309   FPM.run(F);
1310   return V->Broken;
1311 }
1312
1313 /// verifyModule - Check a module for errors, printing messages on stderr.
1314 /// Return true if the module is corrupt.
1315 ///
1316 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
1317                         std::string *ErrorInfo) {
1318   PassManager PM;
1319   Verifier *V = new Verifier(action);
1320   PM.add(V);
1321   PM.run((Module&)M);
1322   
1323   if (ErrorInfo && V->Broken)
1324     *ErrorInfo = V->msgs.str();
1325   return V->Broken;
1326 }
1327
1328 // vim: sw=2