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