LLVM API Documentation

Verifier.cpp

Go to the documentation of this file.
00001 //===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the function verifier interface, that can be used for some
00011 // sanity checking of input to the system.
00012 //
00013 // Note that this does not provide full `Java style' security and verifications,
00014 // instead it just tries to ensure that code is well-formed.
00015 //
00016 //  * Both of a binary operator's parameters are of the same type
00017 //  * Verify that the indices of mem access instructions match other operands
00018 //  * Verify that arithmetic and other things are only performed on first-class
00019 //    types.  Verify that shifts & logicals only happen on integrals f.e.
00020 //  * All of the constants in a switch statement are of the correct type
00021 //  * The code is in valid SSA form
00022 //  * It should be illegal to put a label into any other type (like a structure)
00023 //    or to return one. [except constant arrays!]
00024 //  * Only phi nodes can be self referential: 'add int %0, %0 ; <int>:0' is bad
00025 //  * PHI nodes must have an entry for each predecessor, with no extras.
00026 //  * PHI nodes must be the first thing in a basic block, all grouped together
00027 //  * PHI nodes must have at least one entry
00028 //  * All basic blocks should only end with terminator insts, not contain them
00029 //  * The entry node to a function must not have predecessors
00030 //  * All Instructions must be embedded into a basic block
00031 //  * Functions cannot take a void-typed parameter
00032 //  * Verify that a function's argument list agrees with it's declared type.
00033 //  * It is illegal to specify a name for a void value.
00034 //  * It is illegal to have a internal global value with no initializer
00035 //  * It is illegal to have a ret instruction that returns a value that does not
00036 //    agree with the function return value type.
00037 //  * Function call argument types match the function prototype
00038 //  * All other things that are tested by asserts spread about the code...
00039 //
00040 //===----------------------------------------------------------------------===//
00041 
00042 #include "llvm/Analysis/Verifier.h"
00043 #include "llvm/Assembly/Writer.h"
00044 #include "llvm/CallingConv.h"
00045 #include "llvm/Constants.h"
00046 #include "llvm/Pass.h"
00047 #include "llvm/Module.h"
00048 #include "llvm/ModuleProvider.h"
00049 #include "llvm/DerivedTypes.h"
00050 #include "llvm/InlineAsm.h"
00051 #include "llvm/Instructions.h"
00052 #include "llvm/Intrinsics.h"
00053 #include "llvm/PassManager.h"
00054 #include "llvm/SymbolTable.h"
00055 #include "llvm/Analysis/Dominators.h"
00056 #include "llvm/Support/CFG.h"
00057 #include "llvm/Support/InstVisitor.h"
00058 #include "llvm/ADT/StringExtras.h"
00059 #include "llvm/ADT/STLExtras.h"
00060 #include "llvm/Support/Visibility.h"
00061 #include <algorithm>
00062 #include <iostream>
00063 #include <sstream>
00064 #include <cstdarg>
00065 using namespace llvm;
00066 
00067 namespace {  // Anonymous namespace for class
00068 
00069   struct VISIBILITY_HIDDEN
00070      Verifier : public FunctionPass, InstVisitor<Verifier> {
00071     bool Broken;          // Is this module found to be broken?
00072     bool RealPass;        // Are we not being run by a PassManager?
00073     VerifierFailureAction action;
00074                           // What to do if verification fails.
00075     Module *Mod;          // Module we are verifying right now
00076     ETForest *EF;     // ET-Forest, caution can be null!
00077     std::stringstream msgs;  // A stringstream to collect messages
00078 
00079     /// InstInThisBlock - when verifying a basic block, keep track of all of the
00080     /// instructions we have seen so far.  This allows us to do efficient
00081     /// dominance checks for the case when an instruction has an operand that is
00082     /// an instruction in the same block.
00083     std::set<Instruction*> InstsInThisBlock;
00084 
00085     Verifier()
00086         : Broken(false), RealPass(true), action(AbortProcessAction),
00087           EF(0), msgs( std::ios::app | std::ios::out ) {}
00088     Verifier( VerifierFailureAction ctn )
00089         : Broken(false), RealPass(true), action(ctn), EF(0),
00090           msgs( std::ios::app | std::ios::out ) {}
00091     Verifier(bool AB )
00092         : Broken(false), RealPass(true),
00093           action( AB ? AbortProcessAction : PrintMessageAction), EF(0),
00094           msgs( std::ios::app | std::ios::out ) {}
00095     Verifier(ETForest &ef)
00096       : Broken(false), RealPass(false), action(PrintMessageAction),
00097         EF(&ef), msgs( std::ios::app | std::ios::out ) {}
00098 
00099 
00100     bool doInitialization(Module &M) {
00101       Mod = &M;
00102       verifySymbolTable(M.getSymbolTable());
00103 
00104       // If this is a real pass, in a pass manager, we must abort before
00105       // returning back to the pass manager, or else the pass manager may try to
00106       // run other passes on the broken module.
00107       if (RealPass)
00108         return abortIfBroken();
00109       return false;
00110     }
00111 
00112     bool runOnFunction(Function &F) {
00113       // Get dominator information if we are being run by PassManager
00114       if (RealPass) EF = &getAnalysis<ETForest>();
00115       visit(F);
00116       InstsInThisBlock.clear();
00117 
00118       // If this is a real pass, in a pass manager, we must abort before
00119       // returning back to the pass manager, or else the pass manager may try to
00120       // run other passes on the broken module.
00121       if (RealPass)
00122         return abortIfBroken();
00123 
00124       return false;
00125     }
00126 
00127     bool doFinalization(Module &M) {
00128       // Scan through, checking all of the external function's linkage now...
00129       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00130         visitGlobalValue(*I);
00131 
00132         // Check to make sure function prototypes are okay.
00133         if (I->isExternal()) visitFunction(*I);
00134       }
00135 
00136       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
00137            I != E; ++I)
00138         visitGlobalVariable(*I);
00139 
00140       // If the module is broken, abort at this time.
00141       return abortIfBroken();
00142     }
00143 
00144     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00145       AU.setPreservesAll();
00146       if (RealPass)
00147         AU.addRequired<ETForest>();
00148     }
00149 
00150     /// abortIfBroken - If the module is broken and we are supposed to abort on
00151     /// this condition, do so.
00152     ///
00153     bool abortIfBroken() {
00154       if (Broken) {
00155         msgs << "Broken module found, ";
00156         switch (action) {
00157           case AbortProcessAction:
00158             msgs << "compilation aborted!\n";
00159             std::cerr << msgs.str();
00160             abort();
00161           case PrintMessageAction:
00162             msgs << "verification continues.\n";
00163             std::cerr << msgs.str();
00164             return false;
00165           case ReturnStatusAction:
00166             msgs << "compilation terminated.\n";
00167             return Broken;
00168         }
00169       }
00170       return false;
00171     }
00172 
00173 
00174     // Verification methods...
00175     void verifySymbolTable(SymbolTable &ST);
00176     void visitGlobalValue(GlobalValue &GV);
00177     void visitGlobalVariable(GlobalVariable &GV);
00178     void visitFunction(Function &F);
00179     void visitBasicBlock(BasicBlock &BB);
00180     void visitPHINode(PHINode &PN);
00181     void visitBinaryOperator(BinaryOperator &B);
00182     void visitShiftInst(ShiftInst &SI);
00183     void visitExtractElementInst(ExtractElementInst &EI);
00184     void visitInsertElementInst(InsertElementInst &EI);
00185     void visitShuffleVectorInst(ShuffleVectorInst &EI);
00186     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
00187     void visitCallInst(CallInst &CI);
00188     void visitGetElementPtrInst(GetElementPtrInst &GEP);
00189     void visitLoadInst(LoadInst &LI);
00190     void visitStoreInst(StoreInst &SI);
00191     void visitInstruction(Instruction &I);
00192     void visitTerminatorInst(TerminatorInst &I);
00193     void visitReturnInst(ReturnInst &RI);
00194     void visitSwitchInst(SwitchInst &SI);
00195     void visitSelectInst(SelectInst &SI);
00196     void visitUserOp1(Instruction &I);
00197     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
00198     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
00199 
00200     void VerifyIntrinsicPrototype(Function *F, ...);
00201 
00202     void WriteValue(const Value *V) {
00203       if (!V) return;
00204       if (isa<Instruction>(V)) {
00205         msgs << *V;
00206       } else {
00207         WriteAsOperand (msgs, V, true, true, Mod);
00208         msgs << "\n";
00209       }
00210     }
00211 
00212     void WriteType(const Type* T ) {
00213       if ( !T ) return;
00214       WriteTypeSymbolic(msgs, T, Mod );
00215     }
00216 
00217 
00218     // CheckFailed - A check failed, so print out the condition and the message
00219     // that failed.  This provides a nice place to put a breakpoint if you want
00220     // to see why something is not correct.
00221     void CheckFailed(const std::string &Message,
00222                      const Value *V1 = 0, const Value *V2 = 0,
00223                      const Value *V3 = 0, const Value *V4 = 0) {
00224       msgs << Message << "\n";
00225       WriteValue(V1);
00226       WriteValue(V2);
00227       WriteValue(V3);
00228       WriteValue(V4);
00229       Broken = true;
00230     }
00231 
00232     void CheckFailed( const std::string& Message, const Value* V1,
00233                       const Type* T2, const Value* V3 = 0 ) {
00234       msgs << Message << "\n";
00235       WriteValue(V1);
00236       WriteType(T2);
00237       WriteValue(V3);
00238       Broken = true;
00239     }
00240   };
00241 
00242   RegisterOpt<Verifier> X("verify", "Module Verifier");
00243 } // End anonymous namespace
00244 
00245 
00246 // Assert - We know that cond should be true, if not print an error message.
00247 #define Assert(C, M) \
00248   do { if (!(C)) { CheckFailed(M); return; } } while (0)
00249 #define Assert1(C, M, V1) \
00250   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
00251 #define Assert2(C, M, V1, V2) \
00252   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
00253 #define Assert3(C, M, V1, V2, V3) \
00254   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
00255 #define Assert4(C, M, V1, V2, V3, V4) \
00256   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
00257 
00258 
00259 void Verifier::visitGlobalValue(GlobalValue &GV) {
00260   Assert1(!GV.isExternal() || GV.hasExternalLinkage(),
00261           "Global is external, but doesn't have external linkage!", &GV);
00262   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
00263           "Only global variables can have appending linkage!", &GV);
00264 
00265   if (GV.hasAppendingLinkage()) {
00266     GlobalVariable &GVar = cast<GlobalVariable>(GV);
00267     Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
00268             "Only global arrays can have appending linkage!", &GV);
00269   }
00270 }
00271 
00272 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
00273   if (GV.hasInitializer())
00274     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
00275             "Global variable initializer type does not match global "
00276             "variable type!", &GV);
00277 
00278   visitGlobalValue(GV);
00279 }
00280 
00281 
00282 // verifySymbolTable - Verify that a function or module symbol table is ok
00283 //
00284 void Verifier::verifySymbolTable(SymbolTable &ST) {
00285 
00286   // Loop over all of the values in all type planes in the symbol table.
00287   for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
00288        PE = ST.plane_end(); PI != PE; ++PI)
00289     for (SymbolTable::value_const_iterator VI = PI->second.begin(),
00290          VE = PI->second.end(); VI != VE; ++VI) {
00291       Value *V = VI->second;
00292       // Check that there are no void typed values in the symbol table.  Values
00293       // with a void type cannot be put into symbol tables because they cannot
00294       // have names!
00295       Assert1(V->getType() != Type::VoidTy,
00296         "Values with void type are not allowed to have names!", V);
00297     }
00298 }
00299 
00300 // visitFunction - Verify that a function is ok.
00301 //
00302 void Verifier::visitFunction(Function &F) {
00303   // Check function arguments.
00304   const FunctionType *FT = F.getFunctionType();
00305   unsigned NumArgs = F.getArgumentList().size();
00306 
00307   Assert2(FT->getNumParams() == NumArgs,
00308           "# formal arguments must match # of arguments for function type!",
00309           &F, FT);
00310   Assert1(F.getReturnType()->isFirstClassType() ||
00311           F.getReturnType() == Type::VoidTy,
00312           "Functions cannot return aggregate values!", &F);
00313 
00314   // Check that this function meets the restrictions on this calling convention.
00315   switch (F.getCallingConv()) {
00316   default:
00317     break;
00318   case CallingConv::C:
00319     break;
00320   case CallingConv::CSRet:
00321     Assert1(FT->getReturnType() == Type::VoidTy && 
00322             FT->getNumParams() > 0 && isa<PointerType>(FT->getParamType(0)),
00323             "Invalid struct-return function!", &F);
00324     break;
00325   case CallingConv::Fast:
00326   case CallingConv::Cold:
00327     Assert1(!F.isVarArg(),
00328             "Varargs functions must have C calling conventions!", &F);
00329     break;
00330   }
00331   
00332   // Check that the argument values match the function type for this function...
00333   unsigned i = 0;
00334   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I, ++i) {
00335     Assert2(I->getType() == FT->getParamType(i),
00336             "Argument value does not match function argument type!",
00337             I, FT->getParamType(i));
00338     // Make sure no aggregates are passed by value.
00339     Assert1(I->getType()->isFirstClassType(),
00340             "Functions cannot take aggregates as arguments by value!", I);
00341    }
00342 
00343   if (!F.isExternal()) {
00344     verifySymbolTable(F.getSymbolTable());
00345 
00346     // Check the entry node
00347     BasicBlock *Entry = &F.getEntryBlock();
00348     Assert1(pred_begin(Entry) == pred_end(Entry),
00349             "Entry block to function must not have predecessors!", Entry);
00350   }
00351 }
00352 
00353 
00354 // verifyBasicBlock - Verify that a basic block is well formed...
00355 //
00356 void Verifier::visitBasicBlock(BasicBlock &BB) {
00357   InstsInThisBlock.clear();
00358 
00359   // Ensure that basic blocks have terminators!
00360   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
00361 
00362   // Check constraints that this basic block imposes on all of the PHI nodes in
00363   // it.
00364   if (isa<PHINode>(BB.front())) {
00365     std::vector<BasicBlock*> Preds(pred_begin(&BB), pred_end(&BB));
00366     std::sort(Preds.begin(), Preds.end());
00367     PHINode *PN;
00368     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
00369 
00370       // Ensure that PHI nodes have at least one entry!
00371       Assert1(PN->getNumIncomingValues() != 0,
00372               "PHI nodes must have at least one entry.  If the block is dead, "
00373               "the PHI should be removed!", PN);
00374       Assert1(PN->getNumIncomingValues() == Preds.size(),
00375               "PHINode should have one entry for each predecessor of its "
00376               "parent basic block!", PN);
00377 
00378       // Get and sort all incoming values in the PHI node...
00379       std::vector<std::pair<BasicBlock*, Value*> > Values;
00380       Values.reserve(PN->getNumIncomingValues());
00381       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00382         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
00383                                         PN->getIncomingValue(i)));
00384       std::sort(Values.begin(), Values.end());
00385 
00386       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
00387         // Check to make sure that if there is more than one entry for a
00388         // particular basic block in this PHI node, that the incoming values are
00389         // all identical.
00390         //
00391         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
00392                 Values[i].second == Values[i-1].second,
00393                 "PHI node has multiple entries for the same basic block with "
00394                 "different incoming values!", PN, Values[i].first,
00395                 Values[i].second, Values[i-1].second);
00396 
00397         // Check to make sure that the predecessors and PHI node entries are
00398         // matched up.
00399         Assert3(Values[i].first == Preds[i],
00400                 "PHI node entries do not match predecessors!", PN,
00401                 Values[i].first, Preds[i]);
00402       }
00403     }
00404   }
00405 }
00406 
00407 void Verifier::visitTerminatorInst(TerminatorInst &I) {
00408   // Ensure that terminators only exist at the end of the basic block.
00409   Assert1(&I == I.getParent()->getTerminator(),
00410           "Terminator found in the middle of a basic block!", I.getParent());
00411   visitInstruction(I);
00412 }
00413 
00414 void Verifier::visitReturnInst(ReturnInst &RI) {
00415   Function *F = RI.getParent()->getParent();
00416   if (RI.getNumOperands() == 0)
00417     Assert2(F->getReturnType() == Type::VoidTy,
00418             "Found return instr that returns void in Function of non-void "
00419             "return type!", &RI, F->getReturnType());
00420   else
00421     Assert2(F->getReturnType() == RI.getOperand(0)->getType(),
00422             "Function return type does not match operand "
00423             "type of return inst!", &RI, F->getReturnType());
00424 
00425   // Check to make sure that the return value has necessary properties for
00426   // terminators...
00427   visitTerminatorInst(RI);
00428 }
00429 
00430 void Verifier::visitSwitchInst(SwitchInst &SI) {
00431   // Check to make sure that all of the constants in the switch instruction
00432   // have the same type as the switched-on value.
00433   const Type *SwitchTy = SI.getCondition()->getType();
00434   for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
00435     Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
00436             "Switch constants must all be same type as switch value!", &SI);
00437 
00438   visitTerminatorInst(SI);
00439 }
00440 
00441 void Verifier::visitSelectInst(SelectInst &SI) {
00442   Assert1(SI.getCondition()->getType() == Type::BoolTy,
00443           "Select condition type must be bool!", &SI);
00444   Assert1(SI.getTrueValue()->getType() == SI.getFalseValue()->getType(),
00445           "Select values must have identical types!", &SI);
00446   Assert1(SI.getTrueValue()->getType() == SI.getType(),
00447           "Select values must have same type as select instruction!", &SI);
00448   visitInstruction(SI);
00449 }
00450 
00451 
00452 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
00453 /// a pass, if any exist, it's an error.
00454 ///
00455 void Verifier::visitUserOp1(Instruction &I) {
00456   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
00457 }
00458 
00459 /// visitPHINode - Ensure that a PHI node is well formed.
00460 ///
00461 void Verifier::visitPHINode(PHINode &PN) {
00462   // Ensure that the PHI nodes are all grouped together at the top of the block.
00463   // This can be tested by checking whether the instruction before this is
00464   // either nonexistent (because this is begin()) or is a PHI node.  If not,
00465   // then there is some other instruction before a PHI.
00466   Assert2(&PN.getParent()->front() == &PN || isa<PHINode>(PN.getPrev()),
00467           "PHI nodes not grouped at top of basic block!",
00468           &PN, PN.getParent());
00469 
00470   // Check that all of the operands of the PHI node have the same type as the
00471   // result.
00472   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
00473     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
00474             "PHI node operands are not the same type as the result!", &PN);
00475 
00476   // All other PHI node constraints are checked in the visitBasicBlock method.
00477 
00478   visitInstruction(PN);
00479 }
00480 
00481 void Verifier::visitCallInst(CallInst &CI) {
00482   Assert1(isa<PointerType>(CI.getOperand(0)->getType()),
00483           "Called function must be a pointer!", &CI);
00484   const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType());
00485   Assert1(isa<FunctionType>(FPTy->getElementType()),
00486           "Called function is not pointer to function type!", &CI);
00487 
00488   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
00489 
00490   // Verify that the correct number of arguments are being passed
00491   if (FTy->isVarArg())
00492     Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(),
00493             "Called function requires more parameters than were provided!",&CI);
00494   else
00495     Assert1(CI.getNumOperands()-1 == FTy->getNumParams(),
00496             "Incorrect number of arguments passed to called function!", &CI);
00497 
00498   // Verify that all arguments to the call match the function type...
00499   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
00500     Assert3(CI.getOperand(i+1)->getType() == FTy->getParamType(i),
00501             "Call parameter type does not match function signature!",
00502             CI.getOperand(i+1), FTy->getParamType(i), &CI);
00503 
00504   if (Function *F = CI.getCalledFunction())
00505     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
00506       visitIntrinsicFunctionCall(ID, CI);
00507 
00508   visitInstruction(CI);
00509 }
00510 
00511 /// visitBinaryOperator - Check that both arguments to the binary operator are
00512 /// of the same type!
00513 ///
00514 void Verifier::visitBinaryOperator(BinaryOperator &B) {
00515   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
00516           "Both operands to a binary operator are not of the same type!", &B);
00517 
00518   // Check that logical operators are only used with integral operands.
00519   if (B.getOpcode() == Instruction::And || B.getOpcode() == Instruction::Or ||
00520       B.getOpcode() == Instruction::Xor) {
00521     Assert1(B.getType()->isIntegral() ||
00522             (isa<PackedType>(B.getType()) && 
00523              cast<PackedType>(B.getType())->getElementType()->isIntegral()),
00524             "Logical operators only work with integral types!", &B);
00525     Assert1(B.getType() == B.getOperand(0)->getType(),
00526             "Logical operators must have same type for operands and result!",
00527             &B);
00528   } else if (isa<SetCondInst>(B)) {
00529     // Check that setcc instructions return bool
00530     Assert1(B.getType() == Type::BoolTy,
00531             "setcc instructions must return boolean values!", &B);
00532   } else {
00533     // Arithmetic operators only work on integer or fp values
00534     Assert1(B.getType() == B.getOperand(0)->getType(),
00535             "Arithmetic operators must have same type for operands and result!",
00536             &B);
00537     Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
00538             isa<PackedType>(B.getType()),
00539             "Arithmetic operators must have integer, fp, or packed type!", &B);
00540   }
00541 
00542   visitInstruction(B);
00543 }
00544 
00545 void Verifier::visitShiftInst(ShiftInst &SI) {
00546   Assert1(SI.getType()->isInteger(),
00547           "Shift must return an integer result!", &SI);
00548   Assert1(SI.getType() == SI.getOperand(0)->getType(),
00549           "Shift return type must be same as first operand!", &SI);
00550   Assert1(SI.getOperand(1)->getType() == Type::UByteTy,
00551           "Second operand to shift must be ubyte type!", &SI);
00552   visitInstruction(SI);
00553 }
00554 
00555 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
00556   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
00557                                               EI.getOperand(1)),
00558           "Invalid extractelement operands!", &EI);
00559   visitInstruction(EI);
00560 }
00561 
00562 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
00563   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
00564                                              IE.getOperand(1),
00565                                              IE.getOperand(2)),
00566           "Invalid insertelement operands!", &IE);
00567   visitInstruction(IE);
00568 }
00569 
00570 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
00571   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
00572                                              SV.getOperand(2)),
00573           "Invalid shufflevector operands!", &SV);
00574   Assert1(SV.getType() == SV.getOperand(0)->getType(),
00575           "Result of shufflevector must match first operand type!", &SV);
00576   
00577   // Check to see if Mask is valid.
00578   if (const ConstantPacked *MV = dyn_cast<ConstantPacked>(SV.getOperand(2))) {
00579     for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
00580       Assert1(isa<ConstantUInt>(MV->getOperand(i)) ||
00581               isa<UndefValue>(MV->getOperand(i)),
00582               "Invalid shufflevector shuffle mask!", &SV);
00583     }
00584   } else {
00585     Assert1(isa<UndefValue>(SV.getOperand(2)) || 
00586             isa<ConstantAggregateZero>(SV.getOperand(2)),
00587             "Invalid shufflevector shuffle mask!", &SV);
00588   }
00589   
00590   visitInstruction(SV);
00591 }
00592 
00593 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
00594   const Type *ElTy =
00595     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
00596                    std::vector<Value*>(GEP.idx_begin(), GEP.idx_end()), true);
00597   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
00598   Assert2(PointerType::get(ElTy) == GEP.getType(),
00599           "GEP is not of right type for indices!", &GEP, ElTy);
00600   visitInstruction(GEP);
00601 }
00602 
00603 void Verifier::visitLoadInst(LoadInst &LI) {
00604   const Type *ElTy =
00605     cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
00606   Assert2(ElTy == LI.getType(),
00607           "Load result type does not match pointer operand type!", &LI, ElTy);
00608   visitInstruction(LI);
00609 }
00610 
00611 void Verifier::visitStoreInst(StoreInst &SI) {
00612   const Type *ElTy =
00613     cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
00614   Assert2(ElTy == SI.getOperand(0)->getType(),
00615           "Stored value type does not match pointer operand type!", &SI, ElTy);
00616   visitInstruction(SI);
00617 }
00618 
00619 
00620 /// verifyInstruction - Verify that an instruction is well formed.
00621 ///
00622 void Verifier::visitInstruction(Instruction &I) {
00623   BasicBlock *BB = I.getParent();
00624   Assert1(BB, "Instruction not embedded in basic block!", &I);
00625 
00626   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
00627     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
00628          UI != UE; ++UI)
00629       Assert1(*UI != (User*)&I ||
00630               !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
00631               "Only PHI nodes may reference their own value!", &I);
00632   }
00633 
00634   // Check that void typed values don't have names
00635   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
00636           "Instruction has a name, but provides a void value!", &I);
00637 
00638   // Check that the return value of the instruction is either void or a legal
00639   // value type.
00640   Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType(),
00641           "Instruction returns a non-scalar type!", &I);
00642 
00643   // Check that all uses of the instruction, if they are instructions
00644   // themselves, actually have parent basic blocks.  If the use is not an
00645   // instruction, it is an error!
00646   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
00647        UI != UE; ++UI) {
00648     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
00649             *UI);
00650     Instruction *Used = cast<Instruction>(*UI);
00651     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
00652             " embeded in a basic block!", &I, Used);
00653   }
00654 
00655   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
00656     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
00657 
00658     // Check to make sure that only first-class-values are operands to
00659     // instructions.
00660     Assert1(I.getOperand(i)->getType()->isFirstClassType(),
00661             "Instruction operands must be first-class values!", &I);
00662   
00663     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
00664       // Check to make sure that the "address of" an intrinsic function is never
00665       // taken.
00666       Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
00667               "Cannot take the address of an intrinsic!", &I);
00668     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
00669       Assert1(OpBB->getParent() == BB->getParent(),
00670               "Referring to a basic block in another function!", &I);
00671     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
00672       Assert1(OpArg->getParent() == BB->getParent(),
00673               "Referring to an argument in another function!", &I);
00674     } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
00675       BasicBlock *OpBlock = Op->getParent();
00676 
00677       // Check that a definition dominates all of its uses.
00678       if (!isa<PHINode>(I)) {
00679         // Invoke results are only usable in the normal destination, not in the
00680         // exceptional destination.
00681         if (InvokeInst *II = dyn_cast<InvokeInst>(Op))
00682           OpBlock = II->getNormalDest();
00683         else if (OpBlock == BB) {
00684           // If they are in the same basic block, make sure that the definition
00685           // comes before the use.
00686           Assert2(InstsInThisBlock.count(Op) ||
00687                   !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
00688                   "Instruction does not dominate all uses!", Op, &I);
00689         }
00690 
00691         // Definition must dominate use unless use is unreachable!
00692         Assert2(EF->dominates(OpBlock, BB) ||
00693                 !EF->dominates(&BB->getParent()->getEntryBlock(), BB),
00694                 "Instruction does not dominate all uses!", Op, &I);
00695       } else {
00696         // PHI nodes are more difficult than other nodes because they actually
00697         // "use" the value in the predecessor basic blocks they correspond to.
00698         BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
00699         Assert2(EF->dominates(OpBlock, PredBB) ||
00700                 !EF->dominates(&BB->getParent()->getEntryBlock(), PredBB),
00701                 "Instruction does not dominate all uses!", Op, &I);
00702       }
00703     } else if (isa<InlineAsm>(I.getOperand(i))) {
00704       Assert1(i == 0 && isa<CallInst>(I),
00705               "Cannot take the address of an inline asm!", &I);
00706     }
00707   }
00708   InstsInThisBlock.insert(&I);
00709 }
00710 
00711 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
00712 ///
00713 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
00714   Function *IF = CI.getCalledFunction();
00715   Assert1(IF->isExternal(), "Intrinsic functions should never be defined!", IF);
00716   
00717 #define GET_INTRINSIC_VERIFIER
00718 #include "llvm/Intrinsics.gen"
00719 #undef GET_INTRINSIC_VERIFIER
00720 }
00721 
00722 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
00723 /// Intrinsics.gen.  This implements a little state machine that verifies the
00724 /// prototype of intrinsics.
00725 void Verifier::VerifyIntrinsicPrototype(Function *F, ...) {
00726   va_list VA;
00727   va_start(VA, F);
00728   
00729   const FunctionType *FTy = F->getFunctionType();
00730   
00731   // Note that "arg#0" is the return type.
00732   for (unsigned ArgNo = 0; 1; ++ArgNo) {
00733     int TypeID = va_arg(VA, int);
00734 
00735     if (TypeID == -1) {
00736       if (ArgNo != FTy->getNumParams()+1)
00737         CheckFailed("Intrinsic prototype has too many arguments!", F);
00738       break;
00739     }
00740 
00741     if (ArgNo == FTy->getNumParams()+1) {
00742       CheckFailed("Intrinsic prototype has too few arguments!", F);
00743       break;
00744     }
00745     
00746     const Type *Ty;
00747     if (ArgNo == 0) 
00748       Ty = FTy->getReturnType();
00749     else
00750       Ty = FTy->getParamType(ArgNo-1);
00751     
00752     if (Ty->getTypeID() != TypeID) {
00753       if (ArgNo == 0)
00754         CheckFailed("Intrinsic prototype has incorrect result type!", F);
00755       else
00756         CheckFailed("Intrinsic parameter #" + utostr(ArgNo-1) + " is wrong!",F);
00757       break;
00758     }
00759 
00760     // If this is a packed argument, verify the number and type of elements.
00761     if (TypeID == Type::PackedTyID) {
00762       const PackedType *PTy = cast<PackedType>(Ty);
00763       if (va_arg(VA, int) != PTy->getElementType()->getTypeID()) {
00764         CheckFailed("Intrinsic prototype has incorrect vector element type!",F);
00765         break;
00766       }
00767 
00768       if ((unsigned)va_arg(VA, int) != PTy->getNumElements()) {
00769         CheckFailed("Intrinsic prototype has incorrect number of "
00770                     "vector elements!",F);
00771         break;
00772       }
00773     }
00774   }
00775 
00776   va_end(VA);
00777 }
00778 
00779 
00780 //===----------------------------------------------------------------------===//
00781 //  Implement the public interfaces to this file...
00782 //===----------------------------------------------------------------------===//
00783 
00784 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
00785   return new Verifier(action);
00786 }
00787 
00788 
00789 // verifyFunction - Create
00790 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
00791   Function &F = const_cast<Function&>(f);
00792   assert(!F.isExternal() && "Cannot verify external functions");
00793 
00794   FunctionPassManager FPM(new ExistingModuleProvider(F.getParent()));
00795   Verifier *V = new Verifier(action);
00796   FPM.add(V);
00797   FPM.run(F);
00798   return V->Broken;
00799 }
00800 
00801 /// verifyModule - Check a module for errors, printing messages on stderr.
00802 /// Return true if the module is corrupt.
00803 ///
00804 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
00805                         std::string *ErrorInfo) {
00806   PassManager PM;
00807   Verifier *V = new Verifier(action);
00808   PM.add(V);
00809   PM.run((Module&)M);
00810   
00811   if (ErrorInfo && V->Broken)
00812     *ErrorInfo = V->msgs.str();
00813   return V->Broken;
00814 }
00815 
00816 // vim: sw=2