Adding dllimport, dllexport and external weak linkage types.
[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/DerivedTypes.h"
50 #include "llvm/InlineAsm.h"
51 #include "llvm/Instructions.h"
52 #include "llvm/Intrinsics.h"
53 #include "llvm/PassManager.h"
54 #include "llvm/SymbolTable.h"
55 #include "llvm/Analysis/Dominators.h"
56 #include "llvm/Support/CFG.h"
57 #include "llvm/Support/InstVisitor.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include "llvm/Support/Compiler.h"
61 #include <algorithm>
62 #include <iostream>
63 #include <sstream>
64 #include <cstdarg>
65 using namespace llvm;
66
67 namespace {  // Anonymous namespace for class
68
69   struct VISIBILITY_HIDDEN
70      Verifier : public FunctionPass, InstVisitor<Verifier> {
71     bool Broken;          // Is this module found to be broken?
72     bool RealPass;        // Are we not being run by a PassManager?
73     VerifierFailureAction action;
74                           // What to do if verification fails.
75     Module *Mod;          // Module we are verifying right now
76     ETForest *EF;     // ET-Forest, caution can be null!
77     std::stringstream msgs;  // A stringstream to collect messages
78
79     /// InstInThisBlock - when verifying a basic block, keep track of all of the
80     /// instructions we have seen so far.  This allows us to do efficient
81     /// dominance checks for the case when an instruction has an operand that is
82     /// an instruction in the same block.
83     std::set<Instruction*> InstsInThisBlock;
84
85     Verifier()
86         : Broken(false), RealPass(true), action(AbortProcessAction),
87           EF(0), msgs( std::ios::app | std::ios::out ) {}
88     Verifier( VerifierFailureAction ctn )
89         : Broken(false), RealPass(true), action(ctn), EF(0),
90           msgs( std::ios::app | std::ios::out ) {}
91     Verifier(bool AB )
92         : Broken(false), RealPass(true),
93           action( AB ? AbortProcessAction : PrintMessageAction), EF(0),
94           msgs( std::ios::app | std::ios::out ) {}
95     Verifier(ETForest &ef)
96       : Broken(false), RealPass(false), action(PrintMessageAction),
97         EF(&ef), msgs( std::ios::app | std::ios::out ) {}
98
99
100     bool doInitialization(Module &M) {
101       Mod = &M;
102       verifySymbolTable(M.getSymbolTable());
103
104       // If this is a real pass, in a pass manager, we must abort before
105       // returning back to the pass manager, or else the pass manager may try to
106       // run other passes on the broken module.
107       if (RealPass)
108         return abortIfBroken();
109       return false;
110     }
111
112     bool runOnFunction(Function &F) {
113       // Get dominator information if we are being run by PassManager
114       if (RealPass) EF = &getAnalysis<ETForest>();
115       visit(F);
116       InstsInThisBlock.clear();
117
118       // If this is a real pass, in a pass manager, we must abort before
119       // returning back to the pass manager, or else the pass manager may try to
120       // run other passes on the broken module.
121       if (RealPass)
122         return abortIfBroken();
123
124       return false;
125     }
126
127     bool doFinalization(Module &M) {
128       // Scan through, checking all of the external function's linkage now...
129       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
130         visitGlobalValue(*I);
131
132         // Check to make sure function prototypes are okay.
133         if (I->isExternal()) visitFunction(*I);
134       }
135
136       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
137            I != E; ++I)
138         visitGlobalVariable(*I);
139
140       // If the module is broken, abort at this time.
141       return abortIfBroken();
142     }
143
144     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
145       AU.setPreservesAll();
146       if (RealPass)
147         AU.addRequired<ETForest>();
148     }
149
150     /// abortIfBroken - If the module is broken and we are supposed to abort on
151     /// this condition, do so.
152     ///
153     bool abortIfBroken() {
154       if (Broken) {
155         msgs << "Broken module found, ";
156         switch (action) {
157           case AbortProcessAction:
158             msgs << "compilation aborted!\n";
159             std::cerr << msgs.str();
160             abort();
161           case PrintMessageAction:
162             msgs << "verification continues.\n";
163             std::cerr << msgs.str();
164             return false;
165           case ReturnStatusAction:
166             msgs << "compilation terminated.\n";
167             return Broken;
168         }
169       }
170       return false;
171     }
172
173
174     // Verification methods...
175     void verifySymbolTable(SymbolTable &ST);
176     void visitGlobalValue(GlobalValue &GV);
177     void visitGlobalVariable(GlobalVariable &GV);
178     void visitFunction(Function &F);
179     void visitBasicBlock(BasicBlock &BB);
180     void visitPHINode(PHINode &PN);
181     void visitBinaryOperator(BinaryOperator &B);
182     void visitShiftInst(ShiftInst &SI);
183     void visitExtractElementInst(ExtractElementInst &EI);
184     void visitInsertElementInst(InsertElementInst &EI);
185     void visitShuffleVectorInst(ShuffleVectorInst &EI);
186     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
187     void visitCallInst(CallInst &CI);
188     void visitGetElementPtrInst(GetElementPtrInst &GEP);
189     void visitLoadInst(LoadInst &LI);
190     void visitStoreInst(StoreInst &SI);
191     void visitInstruction(Instruction &I);
192     void visitTerminatorInst(TerminatorInst &I);
193     void visitReturnInst(ReturnInst &RI);
194     void visitSwitchInst(SwitchInst &SI);
195     void visitSelectInst(SelectInst &SI);
196     void visitUserOp1(Instruction &I);
197     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
198     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
199
200     void VerifyIntrinsicPrototype(Function *F, ...);
201
202     void WriteValue(const Value *V) {
203       if (!V) return;
204       if (isa<Instruction>(V)) {
205         msgs << *V;
206       } else {
207         WriteAsOperand (msgs, V, true, true, Mod);
208         msgs << "\n";
209       }
210     }
211
212     void WriteType(const Type* T ) {
213       if ( !T ) return;
214       WriteTypeSymbolic(msgs, T, Mod );
215     }
216
217
218     // CheckFailed - A check failed, so print out the condition and the message
219     // that failed.  This provides a nice place to put a breakpoint if you want
220     // to see why something is not correct.
221     void CheckFailed(const std::string &Message,
222                      const Value *V1 = 0, const Value *V2 = 0,
223                      const Value *V3 = 0, const Value *V4 = 0) {
224       msgs << Message << "\n";
225       WriteValue(V1);
226       WriteValue(V2);
227       WriteValue(V3);
228       WriteValue(V4);
229       Broken = true;
230     }
231
232     void CheckFailed( const std::string& Message, const Value* V1,
233                       const Type* T2, const Value* V3 = 0 ) {
234       msgs << Message << "\n";
235       WriteValue(V1);
236       WriteType(T2);
237       WriteValue(V3);
238       Broken = true;
239     }
240   };
241
242   RegisterPass<Verifier> X("verify", "Module Verifier");
243 } // End anonymous namespace
244
245
246 // Assert - We know that cond should be true, if not print an error message.
247 #define Assert(C, M) \
248   do { if (!(C)) { CheckFailed(M); return; } } while (0)
249 #define Assert1(C, M, V1) \
250   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
251 #define Assert2(C, M, V1, V2) \
252   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
253 #define Assert3(C, M, V1, V2, V3) \
254   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
255 #define Assert4(C, M, V1, V2, V3, V4) \
256   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
257
258
259 void Verifier::visitGlobalValue(GlobalValue &GV) {
260   Assert1(!GV.isExternal() ||
261           GV.hasExternalLinkage() ||
262           GV.hasDLLImportLinkage() ||
263           GV.hasExternalWeakLinkage(),
264   "Global is external, but doesn't have external or dllimport or weak linkage!",
265           &GV);
266
267   Assert1(!GV.hasDLLImportLinkage() || GV.isExternal(),
268           "Global is marked as dllimport, but not external", &GV);
269   
270   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
271           "Only global variables can have appending linkage!", &GV);
272
273   if (GV.hasAppendingLinkage()) {
274     GlobalVariable &GVar = cast<GlobalVariable>(GV);
275     Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
276             "Only global arrays can have appending linkage!", &GV);
277   }
278 }
279
280 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
281   if (GV.hasInitializer())
282     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
283             "Global variable initializer type does not match global "
284             "variable type!", &GV);
285
286   visitGlobalValue(GV);
287 }
288
289
290 // verifySymbolTable - Verify that a function or module symbol table is ok
291 //
292 void Verifier::verifySymbolTable(SymbolTable &ST) {
293
294   // Loop over all of the values in all type planes in the symbol table.
295   for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
296        PE = ST.plane_end(); PI != PE; ++PI)
297     for (SymbolTable::value_const_iterator VI = PI->second.begin(),
298          VE = PI->second.end(); VI != VE; ++VI) {
299       Value *V = VI->second;
300       // Check that there are no void typed values in the symbol table.  Values
301       // with a void type cannot be put into symbol tables because they cannot
302       // have names!
303       Assert1(V->getType() != Type::VoidTy,
304         "Values with void type are not allowed to have names!", V);
305     }
306 }
307
308 // visitFunction - Verify that a function is ok.
309 //
310 void Verifier::visitFunction(Function &F) {
311   // Check function arguments.
312   const FunctionType *FT = F.getFunctionType();
313   unsigned NumArgs = F.getArgumentList().size();
314
315   Assert2(FT->getNumParams() == NumArgs,
316           "# formal arguments must match # of arguments for function type!",
317           &F, FT);
318   Assert1(F.getReturnType()->isFirstClassType() ||
319           F.getReturnType() == Type::VoidTy,
320           "Functions cannot return aggregate values!", &F);
321
322   // Check that this function meets the restrictions on this calling convention.
323   switch (F.getCallingConv()) {
324   default:
325     break;
326   case CallingConv::C:
327     break;
328   case CallingConv::CSRet:
329     Assert1(FT->getReturnType() == Type::VoidTy && 
330             FT->getNumParams() > 0 && isa<PointerType>(FT->getParamType(0)),
331             "Invalid struct-return function!", &F);
332     break;
333   case CallingConv::Fast:
334   case CallingConv::Cold:
335     Assert1(!F.isVarArg(),
336             "Varargs functions must have C calling conventions!", &F);
337     break;
338   }
339   
340   // Check that the argument values match the function type for this function...
341   unsigned i = 0;
342   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I, ++i) {
343     Assert2(I->getType() == FT->getParamType(i),
344             "Argument value does not match function argument type!",
345             I, FT->getParamType(i));
346     // Make sure no aggregates are passed by value.
347     Assert1(I->getType()->isFirstClassType(),
348             "Functions cannot take aggregates as arguments by value!", I);
349    }
350
351   if (!F.isExternal()) {
352     verifySymbolTable(F.getSymbolTable());
353
354     // Check the entry node
355     BasicBlock *Entry = &F.getEntryBlock();
356     Assert1(pred_begin(Entry) == pred_end(Entry),
357             "Entry block to function must not have predecessors!", Entry);
358   }
359 }
360
361
362 // verifyBasicBlock - Verify that a basic block is well formed...
363 //
364 void Verifier::visitBasicBlock(BasicBlock &BB) {
365   InstsInThisBlock.clear();
366
367   // Ensure that basic blocks have terminators!
368   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
369
370   // Check constraints that this basic block imposes on all of the PHI nodes in
371   // it.
372   if (isa<PHINode>(BB.front())) {
373     std::vector<BasicBlock*> Preds(pred_begin(&BB), pred_end(&BB));
374     std::sort(Preds.begin(), Preds.end());
375     PHINode *PN;
376     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
377
378       // Ensure that PHI nodes have at least one entry!
379       Assert1(PN->getNumIncomingValues() != 0,
380               "PHI nodes must have at least one entry.  If the block is dead, "
381               "the PHI should be removed!", PN);
382       Assert1(PN->getNumIncomingValues() == Preds.size(),
383               "PHINode should have one entry for each predecessor of its "
384               "parent basic block!", PN);
385
386       // Get and sort all incoming values in the PHI node...
387       std::vector<std::pair<BasicBlock*, Value*> > Values;
388       Values.reserve(PN->getNumIncomingValues());
389       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
390         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
391                                         PN->getIncomingValue(i)));
392       std::sort(Values.begin(), Values.end());
393
394       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
395         // Check to make sure that if there is more than one entry for a
396         // particular basic block in this PHI node, that the incoming values are
397         // all identical.
398         //
399         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
400                 Values[i].second == Values[i-1].second,
401                 "PHI node has multiple entries for the same basic block with "
402                 "different incoming values!", PN, Values[i].first,
403                 Values[i].second, Values[i-1].second);
404
405         // Check to make sure that the predecessors and PHI node entries are
406         // matched up.
407         Assert3(Values[i].first == Preds[i],
408                 "PHI node entries do not match predecessors!", PN,
409                 Values[i].first, Preds[i]);
410       }
411     }
412   }
413 }
414
415 void Verifier::visitTerminatorInst(TerminatorInst &I) {
416   // Ensure that terminators only exist at the end of the basic block.
417   Assert1(&I == I.getParent()->getTerminator(),
418           "Terminator found in the middle of a basic block!", I.getParent());
419   visitInstruction(I);
420 }
421
422 void Verifier::visitReturnInst(ReturnInst &RI) {
423   Function *F = RI.getParent()->getParent();
424   if (RI.getNumOperands() == 0)
425     Assert2(F->getReturnType() == Type::VoidTy,
426             "Found return instr that returns void in Function of non-void "
427             "return type!", &RI, F->getReturnType());
428   else
429     Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
430             "Function return type does not match operand "
431             "type of return inst!", &RI, F->getReturnType());
432
433   // Check to make sure that the return value has necessary properties for
434   // terminators...
435   visitTerminatorInst(RI);
436 }
437
438 void Verifier::visitSwitchInst(SwitchInst &SI) {
439   // Check to make sure that all of the constants in the switch instruction
440   // have the same type as the switched-on value.
441   const Type *SwitchTy = SI.getCondition()->getType();
442   for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
443     Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
444             "Switch constants must all be same type as switch value!", &SI);
445
446   visitTerminatorInst(SI);
447 }
448
449 void Verifier::visitSelectInst(SelectInst &SI) {
450   Assert1(SI.getCondition()->getType() == Type::BoolTy,
451           "Select condition type must be bool!", &SI);
452   Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
453           "Select values must have identical types!", &SI);
454   Assert1(SI.getTrueValue()->getType() == SI.getType(),
455           "Select values must have same type as select instruction!", &SI);
456   visitInstruction(SI);
457 }
458
459
460 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
461 /// a pass, if any exist, it's an error.
462 ///
463 void Verifier::visitUserOp1(Instruction &I) {
464   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
465 }
466
467 /// visitPHINode - Ensure that a PHI node is well formed.
468 ///
469 void Verifier::visitPHINode(PHINode &PN) {
470   // Ensure that the PHI nodes are all grouped together at the top of the block.
471   // This can be tested by checking whether the instruction before this is
472   // either nonexistent (because this is begin()) or is a PHI node.  If not,
473   // then there is some other instruction before a PHI.
474   Assert2(&PN.getParent()->front() == &PN || isa<PHINode>(PN.getPrev()),
475           "PHI nodes not grouped at top of basic block!",
476           &PN, PN.getParent());
477
478   // Check that all of the operands of the PHI node have the same type as the
479   // result.
480   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
481     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
482             "PHI node operands are not the same type as the result!", &PN);
483
484   // All other PHI node constraints are checked in the visitBasicBlock method.
485
486   visitInstruction(PN);
487 }
488
489 void Verifier::visitCallInst(CallInst &CI) {
490   Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
491           "Called function must be a pointer!", &CI);
492   const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
493   Assert1(isa<FunctionType>(FPTy->getElementType()),
494           "Called function is not pointer to function type!", &CI);
495
496   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
497
498   // Verify that the correct number of arguments are being passed
499   if (FTy->isVarArg())
500     Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
501             "Called function requires more parameters than were provided!",&CI);
502   else
503     Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
504             "Incorrect number of arguments passed to called function!", &CI);
505
506   // Verify that all arguments to the call match the function type...
507   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
508     Assert3(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
509             "Call parameter type does not match function signature!",
510             CI.getOperand(i+1), FTy->getParamType(i), &CI);
511
512   if (Function *F = CI.getCalledFunction())
513     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
514       visitIntrinsicFunctionCall(ID, CI);
515
516   visitInstruction(CI);
517 }
518
519 /// visitBinaryOperator - Check that both arguments to the binary operator are
520 /// of the same type!
521 ///
522 void Verifier::visitBinaryOperator(BinaryOperator &B) {
523   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
524           "Both operands to a binary operator are not of the same type!", &B);
525
526   // Check that logical operators are only used with integral operands.
527   if (B.getOpcode() == Instruction::And || B.getOpcode() == Instruction::Or ||
528       B.getOpcode() == Instruction::Xor) {
529     Assert1(B.getType()->isIntegral() ||
530             (isa<PackedType>(B.getType()) && 
531              cast<PackedType>(B.getType())->getElementType()->isIntegral()),
532             "Logical operators only work with integral types!", &B);
533     Assert1(B.getType() == B.getOperand(0)->getType(),
534             "Logical operators must have same type for operands and result!",
535             &B);
536   } else if (isa<SetCondInst>(B)) {
537     // Check that setcc instructions return bool
538     Assert1(B.getType() == Type::BoolTy,
539             "setcc instructions must return boolean values!", &B);
540   } else {
541     // Arithmetic operators only work on integer or fp values
542     Assert1(B.getType() == B.getOperand(0)->getType(),
543             "Arithmetic operators must have same type for operands and result!",
544             &B);
545     Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
546             isa<PackedType>(B.getType()),
547             "Arithmetic operators must have integer, fp, or packed type!", &B);
548   }
549
550   visitInstruction(B);
551 }
552
553 void Verifier::visitShiftInst(ShiftInst &SI) {
554   Assert1(SI.getType()->isInteger(),
555           "Shift must return an integer result!", &SI);
556   Assert1(SI.getType() == SI.getOperand(0)->getType(),
557           "Shift return type must be same as first operand!", &SI);
558   Assert1(SI.getOperand(1)->getType() == Type::UByteTy,
559           "Second operand to shift must be ubyte type!", &SI);
560   visitInstruction(SI);
561 }
562
563 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
564   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
565                                               EI.getOperand(1)),
566           "Invalid extractelement operands!", &EI);
567   visitInstruction(EI);
568 }
569
570 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
571   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
572                                              IE.getOperand(1),
573                                              IE.getOperand(2)),
574           "Invalid insertelement operands!", &IE);
575   visitInstruction(IE);
576 }
577
578 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
579   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
580                                              SV.getOperand(2)),
581           "Invalid shufflevector operands!", &SV);
582   Assert1(SV.getType() == SV.getOperand(0)->getType(),
583           "Result of shufflevector must match first operand type!", &SV);
584   
585   // Check to see if Mask is valid.
586   if (const ConstantPacked *MV = dyn_cast<ConstantPacked>(SV.getOperand(2))) {
587     for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
588       Assert1(isa<ConstantUInt>(MV->getOperand(i)) ||
589               isa<UndefValue>(MV->getOperand(i)),
590               "Invalid shufflevector shuffle mask!", &SV);
591     }
592   } else {
593     Assert1(isa<UndefValue>(SV.getOperand(2)) || 
594             isa<ConstantAggregateZero>(SV.getOperand(2)),
595             "Invalid shufflevector shuffle mask!", &SV);
596   }
597   
598   visitInstruction(SV);
599 }
600
601 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
602   const Type *ElTy =
603     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
604                    std::vector<Value*>(GEP.idx_begin(), GEP.idx_end()), true);
605   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
606   Assert2(PointerType::get(ElTy) == GEP.getType(),
607           "GEP is not of right type for indices!", &GEP, ElTy);
608   visitInstruction(GEP);
609 }
610
611 void Verifier::visitLoadInst(LoadInst &LI) {
612   const Type *ElTy =
613     cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
614   Assert2(ElTy == LI.getType(),
615           "Load result type does not match pointer operand type!", &LI, ElTy);
616   visitInstruction(LI);
617 }
618
619 void Verifier::visitStoreInst(StoreInst &SI) {
620   const Type *ElTy =
621     cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
622   Assert2(ElTy == SI.getOperand(0)->getType(),
623           "Stored value type does not match pointer operand type!", &SI, ElTy);
624   visitInstruction(SI);
625 }
626
627
628 /// verifyInstruction - Verify that an instruction is well formed.
629 ///
630 void Verifier::visitInstruction(Instruction &I) {
631   BasicBlock *BB = I.getParent();
632   Assert1(BB, "Instruction not embedded in basic block!", &I);
633
634   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
635     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
636          UI != UE; ++UI)
637       Assert1(*UI != (User*)&I ||
638               !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
639               "Only PHI nodes may reference their own value!", &I);
640   }
641
642   // Check that void typed values don't have names
643   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
644           "Instruction has a name, but provides a void value!", &I);
645
646   // Check that the return value of the instruction is either void or a legal
647   // value type.
648   Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType(),
649           "Instruction returns a non-scalar type!", &I);
650
651   // Check that all uses of the instruction, if they are instructions
652   // themselves, actually have parent basic blocks.  If the use is not an
653   // instruction, it is an error!
654   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
655        UI != UE; ++UI) {
656     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
657             *UI);
658     Instruction *Used = cast<Instruction>(*UI);
659     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
660             " embeded in a basic block!", &I, Used);
661   }
662
663   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
664     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
665
666     // Check to make sure that only first-class-values are operands to
667     // instructions.
668     Assert1(I.getOperand(i)->getType()->isFirstClassType(),
669             "Instruction operands must be first-class values!", &I);
670   
671     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
672       // Check to make sure that the "address of" an intrinsic function is never
673       // taken.
674       Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
675               "Cannot take the address of an intrinsic!", &I);
676     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
677       Assert1(OpBB->getParent() == BB->getParent(),
678               "Referring to a basic block in another function!", &I);
679     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
680       Assert1(OpArg->getParent() == BB->getParent(),
681               "Referring to an argument in another function!", &I);
682     } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
683       BasicBlock *OpBlock = Op->getParent();
684
685       // Check that a definition dominates all of its uses.
686       if (!isa<PHINode>(I)) {
687         // Invoke results are only usable in the normal destination, not in the
688         // exceptional destination.
689         if (InvokeInst *II = dyn_cast<InvokeInst>(Op))
690           OpBlock = II->getNormalDest();
691         else if (OpBlock == BB) {
692           // If they are in the same basic block, make sure that the definition
693           // comes before the use.
694           Assert2(InstsInThisBlock.count(Op) ||
695                   !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
696                   "Instruction does not dominate all uses!", Op, &I);
697         }
698
699         // Definition must dominate use unless use is unreachable!
700         Assert2(EF->dominates(OpBlock, BB) ||
701                 !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
702                 "Instruction does not dominate all uses!", Op, &I);
703       } else {
704         // PHI nodes are more difficult than other nodes because they actually
705         // "use" the value in the predecessor basic blocks they correspond to.
706         BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
707         Assert2(EF->dominates(OpBlock, PredBB) ||
708                 !EF->dominates(&BB->getParent()->getEntryBlock(), PredBB),
709                 "Instruction does not dominate all uses!", Op, &I);
710       }
711     } else if (isa<InlineAsm>(I.getOperand(i))) {
712       Assert1(i == 0 && isa<CallInst>(I),
713               "Cannot take the address of an inline asm!", &I);
714     }
715   }
716   InstsInThisBlock.insert(&I);
717 }
718
719 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
720 ///
721 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
722   Function *IF = CI.getCalledFunction();
723   Assert1(IF->isExternal(), "Intrinsic functions should never be defined!", IF);
724   
725 #define GET_INTRINSIC_VERIFIER
726 #include "llvm/Intrinsics.gen"
727 #undef GET_INTRINSIC_VERIFIER
728 }
729
730 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
731 /// Intrinsics.gen.  This implements a little state machine that verifies the
732 /// prototype of intrinsics.
733 void Verifier::VerifyIntrinsicPrototype(Function *F, ...) {
734   va_list VA;
735   va_start(VA, F);
736   
737   const FunctionType *FTy = F->getFunctionType();
738   
739   // Note that "arg#0" is the return type.
740   for (unsigned ArgNo = 0; 1; ++ArgNo) {
741     int TypeID = va_arg(VA, int);
742
743     if (TypeID == -1) {
744       if (ArgNo != FTy->getNumParams()+1)
745         CheckFailed("Intrinsic prototype has too many arguments!", F);
746       break;
747     }
748
749     if (ArgNo == FTy->getNumParams()+1) {
750       CheckFailed("Intrinsic prototype has too few arguments!", F);
751       break;
752     }
753     
754     const Type *Ty;
755     if (ArgNo == 0) 
756       Ty = FTy->getReturnType();
757     else
758       Ty = FTy->getParamType(ArgNo-1);
759     
760     if (Ty->getTypeID() != TypeID) {
761       if (ArgNo == 0)
762         CheckFailed("Intrinsic prototype has incorrect result type!", F);
763       else
764         CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is wrong!",F);
765       break;
766     }
767
768     // If this is a packed argument, verify the number and type of elements.
769     if (TypeID == Type::PackedTyID) {
770       const PackedType *PTy = cast<PackedType>(Ty);
771       if (va_arg(VA, int) != PTy->getElementType()->getTypeID()) {
772         CheckFailed("Intrinsic prototype has incorrect vector element type!",F);
773         break;
774       }
775
776       if ((unsigned)va_arg(VA, int) != PTy->getNumElements()) {
777         CheckFailed("Intrinsic prototype has incorrect number of "
778                     "vector elements!",F);
779         break;
780       }
781     }
782   }
783
784   va_end(VA);
785 }
786
787
788 //===----------------------------------------------------------------------===//
789 //  Implement the public interfaces to this file...
790 //===----------------------------------------------------------------------===//
791
792 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
793   return new Verifier(action);
794 }
795
796
797 // verifyFunction - Create
798 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
799   Function &F = const_cast<Function&>(f);
800   assert(!F.isExternal() && "Cannot verify external functions");
801
802   FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
803   Verifier *V = new Verifier(action);
804   FPM.add(V);
805   FPM.run(F);
806   return V->Broken;
807 }
808
809 /// verifyModule - Check a module for errors, printing messages on stderr.
810 /// Return true if the module is corrupt.
811 ///
812 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
813                         std::string *ErrorInfo) {
814   PassManager PM;
815   Verifier *V = new Verifier(action);
816   PM.add(V);
817   PM.run((Module&)M);
818   
819   if (ErrorInfo && V->Broken)
820     *ErrorInfo = V->msgs.str();
821   return V->Broken;
822 }
823
824 // vim: sw=2