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 is distributed under the University of Illinois Open Source
00006 // 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 i32 %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/CallingConv.h"
00044 #include "llvm/Constants.h"
00045 #include "llvm/DerivedTypes.h"
00046 #include "llvm/InlineAsm.h"
00047 #include "llvm/IntrinsicInst.h"
00048 #include "llvm/Module.h"
00049 #include "llvm/ModuleProvider.h"
00050 #include "llvm/Pass.h"
00051 #include "llvm/PassManager.h"
00052 #include "llvm/Analysis/Dominators.h"
00053 #include "llvm/Assembly/Writer.h"
00054 #include "llvm/CodeGen/ValueTypes.h"
00055 #include "llvm/Support/CallSite.h"
00056 #include "llvm/Support/CFG.h"
00057 #include "llvm/Support/InstVisitor.h"
00058 #include "llvm/Support/Streams.h"
00059 #include "llvm/ADT/SmallPtrSet.h"
00060 #include "llvm/ADT/SmallVector.h"
00061 #include "llvm/ADT/StringExtras.h"
00062 #include "llvm/ADT/STLExtras.h"
00063 #include "llvm/Support/Compiler.h"
00064 #include <algorithm>
00065 #include <sstream>
00066 #include <cstdarg>
00067 using namespace llvm;
00068 
00069 namespace {  // Anonymous namespace for class
00070   struct VISIBILITY_HIDDEN PreVerifier : public FunctionPass {
00071     static char ID; // Pass ID, replacement for typeid
00072 
00073     PreVerifier() : FunctionPass(&ID) { }
00074 
00075     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00076       AU.setPreservesAll();
00077     }
00078 
00079     // Check that the prerequisites for successful DominatorTree construction
00080     // are satisfied.
00081     bool runOnFunction(Function &F) {
00082       bool Broken = false;
00083 
00084       for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
00085         if (I->empty() || !I->back().isTerminator()) {
00086           cerr << "Basic Block does not have terminator!\n";
00087           WriteAsOperand(*cerr, I, true);
00088           cerr << "\n";
00089           Broken = true;
00090         }
00091       }
00092 
00093       if (Broken)
00094         abort();
00095 
00096       return false;
00097     }
00098   };
00099 }
00100 
00101 char PreVerifier::ID = 0;
00102 static RegisterPass<PreVerifier>
00103 PreVer("preverify", "Preliminary module verification");
00104 static const PassInfo *const PreVerifyID = &PreVer;
00105 
00106 namespace {
00107   struct VISIBILITY_HIDDEN
00108      Verifier : public FunctionPass, InstVisitor<Verifier> {
00109     static char ID; // Pass ID, replacement for typeid
00110     bool Broken;          // Is this module found to be broken?
00111     bool RealPass;        // Are we not being run by a PassManager?
00112     VerifierFailureAction action;
00113                           // What to do if verification fails.
00114     Module *Mod;          // Module we are verifying right now
00115     DominatorTree *DT; // Dominator Tree, caution can be null!
00116     std::stringstream msgs;  // A stringstream to collect messages
00117 
00118     /// InstInThisBlock - when verifying a basic block, keep track of all of the
00119     /// instructions we have seen so far.  This allows us to do efficient
00120     /// dominance checks for the case when an instruction has an operand that is
00121     /// an instruction in the same block.
00122     SmallPtrSet<Instruction*, 16> InstsInThisBlock;
00123 
00124     Verifier()
00125       : FunctionPass(&ID), 
00126       Broken(false), RealPass(true), action(AbortProcessAction),
00127       DT(0), msgs( std::ios::app | std::ios::out ) {}
00128     explicit Verifier(VerifierFailureAction ctn)
00129       : FunctionPass(&ID), 
00130       Broken(false), RealPass(true), action(ctn), DT(0),
00131       msgs( std::ios::app | std::ios::out ) {}
00132     explicit Verifier(bool AB)
00133       : FunctionPass(&ID), 
00134       Broken(false), RealPass(true),
00135       action( AB ? AbortProcessAction : PrintMessageAction), DT(0),
00136       msgs( std::ios::app | std::ios::out ) {}
00137     explicit Verifier(DominatorTree &dt)
00138       : FunctionPass(&ID), 
00139       Broken(false), RealPass(false), action(PrintMessageAction),
00140       DT(&dt), msgs( std::ios::app | std::ios::out ) {}
00141 
00142 
00143     bool doInitialization(Module &M) {
00144       Mod = &M;
00145       verifyTypeSymbolTable(M.getTypeSymbolTable());
00146 
00147       // If this is a real pass, in a pass manager, we must abort before
00148       // returning back to the pass manager, or else the pass manager may try to
00149       // run other passes on the broken module.
00150       if (RealPass)
00151         return abortIfBroken();
00152       return false;
00153     }
00154 
00155     bool runOnFunction(Function &F) {
00156       // Get dominator information if we are being run by PassManager
00157       if (RealPass) DT = &getAnalysis<DominatorTree>();
00158 
00159       Mod = F.getParent();
00160 
00161       visit(F);
00162       InstsInThisBlock.clear();
00163 
00164       // If this is a real pass, in a pass manager, we must abort before
00165       // returning back to the pass manager, or else the pass manager may try to
00166       // run other passes on the broken module.
00167       if (RealPass)
00168         return abortIfBroken();
00169 
00170       return false;
00171     }
00172 
00173     bool doFinalization(Module &M) {
00174       // Scan through, checking all of the external function's linkage now...
00175       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00176         visitGlobalValue(*I);
00177 
00178         // Check to make sure function prototypes are okay.
00179         if (I->isDeclaration()) visitFunction(*I);
00180       }
00181 
00182       for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
00183            I != E; ++I)
00184         visitGlobalVariable(*I);
00185 
00186       for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 
00187            I != E; ++I)
00188         visitGlobalAlias(*I);
00189 
00190       // If the module is broken, abort at this time.
00191       return abortIfBroken();
00192     }
00193 
00194     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00195       AU.setPreservesAll();
00196       AU.addRequiredID(PreVerifyID);
00197       if (RealPass)
00198         AU.addRequired<DominatorTree>();
00199     }
00200 
00201     /// abortIfBroken - If the module is broken and we are supposed to abort on
00202     /// this condition, do so.
00203     ///
00204     bool abortIfBroken() {
00205       if (!Broken) return false;
00206       msgs << "Broken module found, ";
00207       switch (action) {
00208       default: assert(0 && "Unknown action");
00209       case AbortProcessAction:
00210         msgs << "compilation aborted!\n";
00211         cerr << msgs.str();
00212         abort();
00213       case PrintMessageAction:
00214         msgs << "verification continues.\n";
00215         cerr << msgs.str();
00216         return false;
00217       case ReturnStatusAction:
00218         msgs << "compilation terminated.\n";
00219         return Broken;
00220       }
00221     }
00222 
00223 
00224     // Verification methods...
00225     void verifyTypeSymbolTable(TypeSymbolTable &ST);
00226     void visitGlobalValue(GlobalValue &GV);
00227     void visitGlobalVariable(GlobalVariable &GV);
00228     void visitGlobalAlias(GlobalAlias &GA);
00229     void visitFunction(Function &F);
00230     void visitBasicBlock(BasicBlock &BB);
00231     using InstVisitor<Verifier>::visit;
00232        
00233     void visit(Instruction &I);
00234        
00235     void visitTruncInst(TruncInst &I);
00236     void visitZExtInst(ZExtInst &I);
00237     void visitSExtInst(SExtInst &I);
00238     void visitFPTruncInst(FPTruncInst &I);
00239     void visitFPExtInst(FPExtInst &I);
00240     void visitFPToUIInst(FPToUIInst &I);
00241     void visitFPToSIInst(FPToSIInst &I);
00242     void visitUIToFPInst(UIToFPInst &I);
00243     void visitSIToFPInst(SIToFPInst &I);
00244     void visitIntToPtrInst(IntToPtrInst &I);
00245     void visitPtrToIntInst(PtrToIntInst &I);
00246     void visitBitCastInst(BitCastInst &I);
00247     void visitPHINode(PHINode &PN);
00248     void visitBinaryOperator(BinaryOperator &B);
00249     void visitICmpInst(ICmpInst &IC);
00250     void visitFCmpInst(FCmpInst &FC);
00251     void visitExtractElementInst(ExtractElementInst &EI);
00252     void visitInsertElementInst(InsertElementInst &EI);
00253     void visitShuffleVectorInst(ShuffleVectorInst &EI);
00254     void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
00255     void visitCallInst(CallInst &CI);
00256     void visitInvokeInst(InvokeInst &II);
00257     void visitGetElementPtrInst(GetElementPtrInst &GEP);
00258     void visitLoadInst(LoadInst &LI);
00259     void visitStoreInst(StoreInst &SI);
00260     void visitInstruction(Instruction &I);
00261     void visitTerminatorInst(TerminatorInst &I);
00262     void visitReturnInst(ReturnInst &RI);
00263     void visitSwitchInst(SwitchInst &SI);
00264     void visitSelectInst(SelectInst &SI);
00265     void visitUserOp1(Instruction &I);
00266     void visitUserOp2(Instruction &I) { visitUserOp1(I); }
00267     void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
00268     void visitAllocationInst(AllocationInst &AI);
00269     void visitExtractValueInst(ExtractValueInst &EVI);
00270     void visitInsertValueInst(InsertValueInst &IVI);
00271 
00272     void VerifyCallSite(CallSite CS);
00273     bool PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
00274                           int VT, unsigned ArgNo, std::string &Suffix);
00275     void VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
00276                                   unsigned RetNum, unsigned ParamNum, ...);
00277     void VerifyAttrs(Attributes Attrs, const Type *Ty,
00278                      bool isReturnValue, const Value *V);
00279     void VerifyFunctionAttrs(const FunctionType *FT, const AttrListPtr &Attrs,
00280                              const Value *V);
00281 
00282     void WriteValue(const Value *V) {
00283       if (!V) return;
00284       if (isa<Instruction>(V)) {
00285         msgs << *V;
00286       } else {
00287         WriteAsOperand(msgs, V, true, Mod);
00288         msgs << "\n";
00289       }
00290     }
00291 
00292     void WriteType(const Type *T) {
00293       if ( !T ) return;
00294       WriteTypeSymbolic(msgs, T, Mod );
00295     }
00296 
00297 
00298     // CheckFailed - A check failed, so print out the condition and the message
00299     // that failed.  This provides a nice place to put a breakpoint if you want
00300     // to see why something is not correct.
00301     void CheckFailed(const std::string &Message,
00302                      const Value *V1 = 0, const Value *V2 = 0,
00303                      const Value *V3 = 0, const Value *V4 = 0) {
00304       msgs << Message << "\n";
00305       WriteValue(V1);
00306       WriteValue(V2);
00307       WriteValue(V3);
00308       WriteValue(V4);
00309       Broken = true;
00310     }
00311 
00312     void CheckFailed( const std::string& Message, const Value* V1,
00313                       const Type* T2, const Value* V3 = 0 ) {
00314       msgs << Message << "\n";
00315       WriteValue(V1);
00316       WriteType(T2);
00317       WriteValue(V3);
00318       Broken = true;
00319     }
00320   };
00321 } // End anonymous namespace
00322 
00323 char Verifier::ID = 0;
00324 static RegisterPass<Verifier> X("verify", "Module Verifier");
00325 
00326 // Assert - We know that cond should be true, if not print an error message.
00327 #define Assert(C, M) \
00328   do { if (!(C)) { CheckFailed(M); return; } } while (0)
00329 #define Assert1(C, M, V1) \
00330   do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
00331 #define Assert2(C, M, V1, V2) \
00332   do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
00333 #define Assert3(C, M, V1, V2, V3) \
00334   do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
00335 #define Assert4(C, M, V1, V2, V3, V4) \
00336   do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
00337 
00338 
00339 void Verifier::visit(Instruction &I) {
00340   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
00341     Assert1(I.getOperand(i) != 0, "Operand is null", &I);
00342   InstVisitor<Verifier>::visit(I);
00343 }
00344 
00345 
00346 void Verifier::visitGlobalValue(GlobalValue &GV) {
00347   Assert1(!GV.isDeclaration() ||
00348           GV.hasExternalLinkage() ||
00349           GV.hasDLLImportLinkage() ||
00350           GV.hasExternalWeakLinkage() ||
00351           GV.hasGhostLinkage() ||
00352           (isa<GlobalAlias>(GV) &&
00353            (GV.hasLocalLinkage() || GV.hasWeakLinkage())),
00354   "Global is external, but doesn't have external or dllimport or weak linkage!",
00355           &GV);
00356 
00357   Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
00358           "Global is marked as dllimport, but not external", &GV);
00359   
00360   Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
00361           "Only global variables can have appending linkage!", &GV);
00362 
00363   if (GV.hasAppendingLinkage()) {
00364     GlobalVariable &GVar = cast<GlobalVariable>(GV);
00365     Assert1(isa<ArrayType>(GVar.getType()->getElementType()),
00366             "Only global arrays can have appending linkage!", &GV);
00367   }
00368 }
00369 
00370 void Verifier::visitGlobalVariable(GlobalVariable &GV) {
00371   if (GV.hasInitializer()) {
00372     Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
00373             "Global variable initializer type does not match global "
00374             "variable type!", &GV);
00375   } else {
00376     Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
00377             GV.hasExternalWeakLinkage(),
00378             "invalid linkage type for global declaration", &GV);
00379   }
00380 
00381   visitGlobalValue(GV);
00382 }
00383 
00384 void Verifier::visitGlobalAlias(GlobalAlias &GA) {
00385   Assert1(!GA.getName().empty(),
00386           "Alias name cannot be empty!", &GA);
00387   Assert1(GA.hasExternalLinkage() || GA.hasLocalLinkage() ||
00388           GA.hasWeakLinkage(),
00389           "Alias should have external or external weak linkage!", &GA);
00390   Assert1(GA.getAliasee(),
00391           "Aliasee cannot be NULL!", &GA);
00392   Assert1(GA.getType() == GA.getAliasee()->getType(),
00393           "Alias and aliasee types should match!", &GA);
00394 
00395   if (!isa<GlobalValue>(GA.getAliasee())) {
00396     const ConstantExpr *CE = dyn_cast<ConstantExpr>(GA.getAliasee());
00397     Assert1(CE && CE->getOpcode() == Instruction::BitCast &&
00398             isa<GlobalValue>(CE->getOperand(0)),
00399             "Aliasee should be either GlobalValue or bitcast of GlobalValue",
00400             &GA);
00401   }
00402 
00403   const GlobalValue* Aliasee = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
00404   Assert1(Aliasee,
00405           "Aliasing chain should end with function or global variable", &GA);
00406 
00407   visitGlobalValue(GA);
00408 }
00409 
00410 void Verifier::verifyTypeSymbolTable(TypeSymbolTable &ST) {
00411 }
00412 
00413 // VerifyAttrs - Check the given parameter attributes for an argument or return
00414 // value of the specified type.  The value V is printed in error messages.
00415 void Verifier::VerifyAttrs(Attributes Attrs, const Type *Ty, 
00416                            bool isReturnValue, const Value *V) {
00417   if (Attrs == Attribute::None)
00418     return;
00419 
00420   if (isReturnValue) {
00421     Attributes RetI = Attrs & Attribute::ParameterOnly;
00422     Assert1(!RetI, "Attribute " + Attribute::getAsString(RetI) +
00423             " does not apply to return values!", V);
00424   }
00425   Attributes FnCheckAttr = Attrs & Attribute::FunctionOnly;
00426   Assert1(!FnCheckAttr, "Attribute " + Attribute::getAsString(FnCheckAttr) +
00427           " only applies to functions!", V);
00428   
00429   for (unsigned i = 0;
00430        i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
00431     Attributes MutI = Attrs & Attribute::MutuallyIncompatible[i];
00432     Assert1(!(MutI & (MutI - 1)), "Attributes " +
00433             Attribute::getAsString(MutI) + " are incompatible!", V);
00434   }
00435 
00436   Attributes TypeI = Attrs & Attribute::typeIncompatible(Ty);
00437   Assert1(!TypeI, "Wrong type for attribute " +
00438           Attribute::getAsString(TypeI), V);
00439 
00440   Attributes ByValI = Attrs & Attribute::ByVal;
00441   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
00442     Assert1(!ByValI || PTy->getElementType()->isSized(),
00443             "Attribute " + Attribute::getAsString(ByValI) +
00444             " does not support unsized types!", V);
00445   } else {
00446     Assert1(!ByValI,
00447             "Attribute " + Attribute::getAsString(ByValI) +
00448             " only applies to parameters with pointer type!", V);
00449   }
00450 }
00451 
00452 // VerifyFunctionAttrs - Check parameter attributes against a function type.
00453 // The value V is printed in error messages.
00454 void Verifier::VerifyFunctionAttrs(const FunctionType *FT,
00455                                    const AttrListPtr &Attrs,
00456                                    const Value *V) {
00457   if (Attrs.isEmpty())
00458     return;
00459 
00460   bool SawNest = false;
00461 
00462   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
00463     const AttributeWithIndex &Attr = Attrs.getSlot(i);
00464 
00465     const Type *Ty;
00466     if (Attr.Index == 0)
00467       Ty = FT->getReturnType();
00468     else if (Attr.Index-1 < FT->getNumParams())
00469       Ty = FT->getParamType(Attr.Index-1);
00470     else
00471       break;  // VarArgs attributes, don't verify.
00472     
00473     VerifyAttrs(Attr.Attrs, Ty, Attr.Index == 0, V);
00474 
00475     if (Attr.Attrs & Attribute::Nest) {
00476       Assert1(!SawNest, "More than one parameter has attribute nest!", V);
00477       SawNest = true;
00478     }
00479 
00480     if (Attr.Attrs & Attribute::StructRet)
00481       Assert1(Attr.Index == 1, "Attribute sret not on first parameter!", V);
00482   }
00483 
00484   Attributes FAttrs = Attrs.getFnAttributes();
00485   Assert1(!(FAttrs & (~Attribute::FunctionOnly)),
00486           "Attribute " + Attribute::getAsString(FAttrs) +
00487           " does not apply to function!", V);
00488       
00489   for (unsigned i = 0;
00490        i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
00491     Attributes MutI = FAttrs & Attribute::MutuallyIncompatible[i];
00492     Assert1(!(MutI & (MutI - 1)), "Attributes " +
00493             Attribute::getAsString(MutI) + " are incompatible!", V);
00494   }
00495 }
00496 
00497 static bool VerifyAttributeCount(const AttrListPtr &Attrs, unsigned Params) {
00498   if (Attrs.isEmpty())
00499     return true;
00500     
00501   unsigned LastSlot = Attrs.getNumSlots() - 1;
00502   unsigned LastIndex = Attrs.getSlot(LastSlot).Index;
00503   if (LastIndex <= Params
00504       || (LastIndex == (unsigned)~0
00505           && (LastSlot == 0 || Attrs.getSlot(LastSlot - 1).Index <= Params)))  
00506     return true;
00507     
00508   return false;
00509 }
00510 // visitFunction - Verify that a function is ok.
00511 //
00512 void Verifier::visitFunction(Function &F) {
00513   // Check function arguments.
00514   const FunctionType *FT = F.getFunctionType();
00515   unsigned NumArgs = F.arg_size();
00516 
00517   Assert2(FT->getNumParams() == NumArgs,
00518           "# formal arguments must match # of arguments for function type!",
00519           &F, FT);
00520   Assert1(F.getReturnType()->isFirstClassType() ||
00521           F.getReturnType() == Type::VoidTy || 
00522           isa<StructType>(F.getReturnType()),
00523           "Functions cannot return aggregate values!", &F);
00524 
00525   Assert1(!F.hasStructRetAttr() || F.getReturnType() == Type::VoidTy,
00526           "Invalid struct return type!", &F);
00527 
00528   const AttrListPtr &Attrs = F.getAttributes();
00529 
00530   Assert1(VerifyAttributeCount(Attrs, FT->getNumParams()),
00531           "Attributes after last parameter!", &F);
00532 
00533   // Check function attributes.
00534   VerifyFunctionAttrs(FT, Attrs, &F);
00535 
00536   // Check that this function meets the restrictions on this calling convention.
00537   switch (F.getCallingConv()) {
00538   default:
00539     break;
00540   case CallingConv::C:
00541     break;
00542   case CallingConv::Fast:
00543   case CallingConv::Cold:
00544   case CallingConv::X86_FastCall:
00545     Assert1(!F.isVarArg(),
00546             "Varargs functions must have C calling conventions!", &F);
00547     break;
00548   }
00549   
00550   // Check that the argument values match the function type for this function...
00551   unsigned i = 0;
00552   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
00553        I != E; ++I, ++i) {
00554     Assert2(I->getType() == FT->getParamType(i),
00555             "Argument value does not match function argument type!",
00556             I, FT->getParamType(i));
00557     Assert1(I->getType()->isFirstClassType(),
00558             "Function arguments must have first-class types!", I);
00559   }
00560 
00561   if (F.isDeclaration()) {
00562     Assert1(F.hasExternalLinkage() || F.hasDLLImportLinkage() ||
00563             F.hasExternalWeakLinkage() || F.hasGhostLinkage(),
00564             "invalid linkage type for function declaration", &F);
00565   } else {
00566     // Verify that this function (which has a body) is not named "llvm.*".  It
00567     // is not legal to define intrinsics.
00568     if (F.getName().size() >= 5)
00569       Assert1(F.getName().substr(0, 5) != "llvm.",
00570               "llvm intrinsics cannot be defined!", &F);
00571     
00572     // Check the entry node
00573     BasicBlock *Entry = &F.getEntryBlock();
00574     Assert1(pred_begin(Entry) == pred_end(Entry),
00575             "Entry block to function must not have predecessors!", Entry);
00576   }
00577 }
00578 
00579 
00580 // verifyBasicBlock - Verify that a basic block is well formed...
00581 //
00582 void Verifier::visitBasicBlock(BasicBlock &BB) {
00583   InstsInThisBlock.clear();
00584 
00585   // Ensure that basic blocks have terminators!
00586   Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB);
00587 
00588   // Check constraints that this basic block imposes on all of the PHI nodes in
00589   // it.
00590   if (isa<PHINode>(BB.front())) {
00591     SmallVector<BasicBlock*, 8> Preds(pred_begin(&BB), pred_end(&BB));
00592     SmallVector<std::pair<BasicBlock*, Value*>, 8> Values;
00593     std::sort(Preds.begin(), Preds.end());
00594     PHINode *PN;
00595     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I));++I) {
00596 
00597       // Ensure that PHI nodes have at least one entry!
00598       Assert1(PN->getNumIncomingValues() != 0,
00599               "PHI nodes must have at least one entry.  If the block is dead, "
00600               "the PHI should be removed!", PN);
00601       Assert1(PN->getNumIncomingValues() == Preds.size(),
00602               "PHINode should have one entry for each predecessor of its "
00603               "parent basic block!", PN);
00604 
00605       // Get and sort all incoming values in the PHI node...
00606       Values.clear();
00607       Values.reserve(PN->getNumIncomingValues());
00608       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00609         Values.push_back(std::make_pair(PN->getIncomingBlock(i),
00610                                         PN->getIncomingValue(i)));
00611       std::sort(Values.begin(), Values.end());
00612 
00613       for (unsigned i = 0, e = Values.size(); i != e; ++i) {
00614         // Check to make sure that if there is more than one entry for a
00615         // particular basic block in this PHI node, that the incoming values are
00616         // all identical.
00617         //
00618         Assert4(i == 0 || Values[i].first  != Values[i-1].first ||
00619                 Values[i].second == Values[i-1].second,
00620                 "PHI node has multiple entries for the same basic block with "
00621                 "different incoming values!", PN, Values[i].first,
00622                 Values[i].second, Values[i-1].second);
00623 
00624         // Check to make sure that the predecessors and PHI node entries are
00625         // matched up.
00626         Assert3(Values[i].first == Preds[i],
00627                 "PHI node entries do not match predecessors!", PN,
00628                 Values[i].first, Preds[i]);
00629       }
00630     }
00631   }
00632 }
00633 
00634 void Verifier::visitTerminatorInst(TerminatorInst &I) {
00635   // Ensure that terminators only exist at the end of the basic block.
00636   Assert1(&I == I.getParent()->getTerminator(),
00637           "Terminator found in the middle of a basic block!", I.getParent());
00638   visitInstruction(I);
00639 }
00640 
00641 void Verifier::visitReturnInst(ReturnInst &RI) {
00642   Function *F = RI.getParent()->getParent();
00643   unsigned N = RI.getNumOperands();
00644   if (F->getReturnType() == Type::VoidTy) 
00645     Assert2(N == 0,
00646             "Found return instr that returns non-void in Function of void "
00647             "return type!", &RI, F->getReturnType());
00648   else if (N == 1 && F->getReturnType() == RI.getOperand(0)->getType()) {
00649     // Exactly one return value and it matches the return type. Good.
00650   } else if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
00651     // The return type is a struct; check for multiple return values.
00652     Assert2(STy->getNumElements() == N,
00653             "Incorrect number of return values in ret instruction!",
00654             &RI, F->getReturnType());
00655     for (unsigned i = 0; i != N; ++i)
00656       Assert2(STy->getElementType(i) == RI.getOperand(i)->getType(),
00657               "Function return type does not match operand "
00658               "type of return inst!", &RI, F->getReturnType());
00659   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(F->getReturnType())) {
00660     // The return type is an array; check for multiple return values.
00661     Assert2(ATy->getNumElements() == N,
00662             "Incorrect number of return values in ret instruction!",
00663             &RI, F->getReturnType());
00664     for (unsigned i = 0; i != N; ++i)
00665       Assert2(ATy->getElementType() == RI.getOperand(i)->getType(),
00666               "Function return type does not match operand "
00667               "type of return inst!", &RI, F->getReturnType());
00668   } else {
00669     CheckFailed("Function return type does not match operand "
00670                 "type of return inst!", &RI, F->getReturnType());
00671   }
00672   
00673   // Check to make sure that the return value has necessary properties for
00674   // terminators...
00675   visitTerminatorInst(RI);
00676 }
00677 
00678 void Verifier::visitSwitchInst(SwitchInst &SI) {
00679   // Check to make sure that all of the constants in the switch instruction
00680   // have the same type as the switched-on value.
00681   const Type *SwitchTy = SI.getCondition()->getType();
00682   for (unsigned i = 1, e = SI.getNumCases(); i != e; ++i)
00683     Assert1(SI.getCaseValue(i)->getType() == SwitchTy,
00684             "Switch constants must all be same type as switch value!", &SI);
00685 
00686   visitTerminatorInst(SI);
00687 }
00688 
00689 void Verifier::visitSelectInst(SelectInst &SI) {
00690   Assert1(!SelectInst::areInvalidOperands(SI.getOperand(0), SI.getOperand(1),
00691                                           SI.getOperand(2)),
00692           "Invalid operands for select instruction!", &SI);
00693 
00694   Assert1(SI.getTrueValue()->getType() == SI.getType(),
00695           "Select values must have same type as select instruction!", &SI);
00696   visitInstruction(SI);
00697 }
00698 
00699 
00700 /// visitUserOp1 - User defined operators shouldn't live beyond the lifetime of
00701 /// a pass, if any exist, it's an error.
00702 ///
00703 void Verifier::visitUserOp1(Instruction &I) {
00704   Assert1(0, "User-defined operators should not live outside of a pass!", &I);
00705 }
00706 
00707 void Verifier::visitTruncInst(TruncInst &I) {
00708   // Get the source and destination types
00709   const Type *SrcTy = I.getOperand(0)->getType();
00710   const Type *DestTy = I.getType();
00711 
00712   // Get the size of the types in bits, we'll need this later
00713   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
00714   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
00715 
00716   Assert1(SrcTy->isIntOrIntVector(), "Trunc only operates on integer", &I);
00717   Assert1(DestTy->isIntOrIntVector(), "Trunc only produces integer", &I);
00718   Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
00719           "trunc source and destination must both be a vector or neither", &I);
00720   Assert1(SrcBitSize > DestBitSize,"DestTy too big for Trunc", &I);
00721 
00722   visitInstruction(I);
00723 }
00724 
00725 void Verifier::visitZExtInst(ZExtInst &I) {
00726   // Get the source and destination types
00727   const Type *SrcTy = I.getOperand(0)->getType();
00728   const Type *DestTy = I.getType();
00729 
00730   // Get the size of the types in bits, we'll need this later
00731   Assert1(SrcTy->isIntOrIntVector(), "ZExt only operates on integer", &I);
00732   Assert1(DestTy->isIntOrIntVector(), "ZExt only produces an integer", &I);
00733   Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
00734           "zext source and destination must both be a vector or neither", &I);
00735   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
00736   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
00737 
00738   Assert1(SrcBitSize < DestBitSize,"Type too small for ZExt", &I);
00739 
00740   visitInstruction(I);
00741 }
00742 
00743 void Verifier::visitSExtInst(SExtInst &I) {
00744   // Get the source and destination types
00745   const Type *SrcTy = I.getOperand(0)->getType();
00746   const Type *DestTy = I.getType();
00747 
00748   // Get the size of the types in bits, we'll need this later
00749   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
00750   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
00751 
00752   Assert1(SrcTy->isIntOrIntVector(), "SExt only operates on integer", &I);
00753   Assert1(DestTy->isIntOrIntVector(), "SExt only produces an integer", &I);
00754   Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
00755           "sext source and destination must both be a vector or neither", &I);
00756   Assert1(SrcBitSize < DestBitSize,"Type too small for SExt", &I);
00757 
00758   visitInstruction(I);
00759 }
00760 
00761 void Verifier::visitFPTruncInst(FPTruncInst &I) {
00762   // Get the source and destination types
00763   const Type *SrcTy = I.getOperand(0)->getType();
00764   const Type *DestTy = I.getType();
00765   // Get the size of the types in bits, we'll need this later
00766   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
00767   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
00768 
00769   Assert1(SrcTy->isFPOrFPVector(),"FPTrunc only operates on FP", &I);
00770   Assert1(DestTy->isFPOrFPVector(),"FPTrunc only produces an FP", &I);
00771   Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
00772           "fptrunc source and destination must both be a vector or neither",&I);
00773   Assert1(SrcBitSize > DestBitSize,"DestTy too big for FPTrunc", &I);
00774 
00775   visitInstruction(I);
00776 }
00777 
00778 void Verifier::visitFPExtInst(FPExtInst &I) {
00779   // Get the source and destination types
00780   const Type *SrcTy = I.getOperand(0)->getType();
00781   const Type *DestTy = I.getType();
00782 
00783   // Get the size of the types in bits, we'll need this later
00784   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
00785   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
00786 
00787   Assert1(SrcTy->isFPOrFPVector(),"FPExt only operates on FP", &I);
00788   Assert1(DestTy->isFPOrFPVector(),"FPExt only produces an FP", &I);
00789   Assert1(isa<VectorType>(SrcTy) == isa<VectorType>(DestTy),
00790           "fpext source and destination must both be a vector or neither", &I);
00791   Assert1(SrcBitSize < DestBitSize,"DestTy too small for FPExt", &I);
00792 
00793   visitInstruction(I);
00794 }
00795 
00796 void Verifier::visitUIToFPInst(UIToFPInst &I) {
00797   // Get the source and destination types
00798   const Type *SrcTy = I.getOperand(0)->getType();
00799   const Type *DestTy = I.getType();
00800 
00801   bool SrcVec = isa<VectorType>(SrcTy);
00802   bool DstVec = isa<VectorType>(DestTy);
00803 
00804   Assert1(SrcVec == DstVec,
00805           "UIToFP source and dest must both be vector or scalar", &I);
00806   Assert1(SrcTy->isIntOrIntVector(),
00807           "UIToFP source must be integer or integer vector", &I);
00808   Assert1(DestTy->isFPOrFPVector(),
00809           "UIToFP result must be FP or FP vector", &I);
00810 
00811   if (SrcVec && DstVec)
00812     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
00813             cast<VectorType>(DestTy)->getNumElements(),
00814             "UIToFP source and dest vector length mismatch", &I);
00815 
00816   visitInstruction(I);
00817 }
00818 
00819 void Verifier::visitSIToFPInst(SIToFPInst &I) {
00820   // Get the source and destination types
00821   const Type *SrcTy = I.getOperand(0)->getType();
00822   const Type *DestTy = I.getType();
00823 
00824   bool SrcVec = SrcTy->getTypeID() == Type::VectorTyID;
00825   bool DstVec = DestTy->getTypeID() == Type::VectorTyID;
00826 
00827   Assert1(SrcVec == DstVec,
00828           "SIToFP source and dest must both be vector or scalar", &I);
00829   Assert1(SrcTy->isIntOrIntVector(),
00830           "SIToFP source must be integer or integer vector", &I);
00831   Assert1(DestTy->isFPOrFPVector(),
00832           "SIToFP result must be FP or FP vector", &I);
00833 
00834   if (SrcVec && DstVec)
00835     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
00836             cast<VectorType>(DestTy)->getNumElements(),
00837             "SIToFP source and dest vector length mismatch", &I);
00838 
00839   visitInstruction(I);
00840 }
00841 
00842 void Verifier::visitFPToUIInst(FPToUIInst &I) {
00843   // Get the source and destination types
00844   const Type *SrcTy = I.getOperand(0)->getType();
00845   const Type *DestTy = I.getType();
00846 
00847   bool SrcVec = isa<VectorType>(SrcTy);
00848   bool DstVec = isa<VectorType>(DestTy);
00849 
00850   Assert1(SrcVec == DstVec,
00851           "FPToUI source and dest must both be vector or scalar", &I);
00852   Assert1(SrcTy->isFPOrFPVector(), "FPToUI source must be FP or FP vector", &I);
00853   Assert1(DestTy->isIntOrIntVector(),
00854           "FPToUI result must be integer or integer vector", &I);
00855 
00856   if (SrcVec && DstVec)
00857     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
00858             cast<VectorType>(DestTy)->getNumElements(),
00859             "FPToUI source and dest vector length mismatch", &I);
00860 
00861   visitInstruction(I);
00862 }
00863 
00864 void Verifier::visitFPToSIInst(FPToSIInst &I) {
00865   // Get the source and destination types
00866   const Type *SrcTy = I.getOperand(0)->getType();
00867   const Type *DestTy = I.getType();
00868 
00869   bool SrcVec = isa<VectorType>(SrcTy);
00870   bool DstVec = isa<VectorType>(DestTy);
00871 
00872   Assert1(SrcVec == DstVec,
00873           "FPToSI source and dest must both be vector or scalar", &I);
00874   Assert1(SrcTy->isFPOrFPVector(),
00875           "FPToSI source must be FP or FP vector", &I);
00876   Assert1(DestTy->isIntOrIntVector(),
00877           "FPToSI result must be integer or integer vector", &I);
00878 
00879   if (SrcVec && DstVec)
00880     Assert1(cast<VectorType>(SrcTy)->getNumElements() ==
00881             cast<VectorType>(DestTy)->getNumElements(),
00882             "FPToSI source and dest vector length mismatch", &I);
00883 
00884   visitInstruction(I);
00885 }
00886 
00887 void Verifier::visitPtrToIntInst(PtrToIntInst &I) {
00888   // Get the source and destination types
00889   const Type *SrcTy = I.getOperand(0)->getType();
00890   const Type *DestTy = I.getType();
00891 
00892   Assert1(isa<PointerType>(SrcTy), "PtrToInt source must be pointer", &I);
00893   Assert1(DestTy->isInteger(), "PtrToInt result must be integral", &I);
00894 
00895   visitInstruction(I);
00896 }
00897 
00898 void Verifier::visitIntToPtrInst(IntToPtrInst &I) {
00899   // Get the source and destination types
00900   const Type *SrcTy = I.getOperand(0)->getType();
00901   const Type *DestTy = I.getType();
00902 
00903   Assert1(SrcTy->isInteger(), "IntToPtr source must be an integral", &I);
00904   Assert1(isa<PointerType>(DestTy), "IntToPtr result must be a pointer",&I);
00905 
00906   visitInstruction(I);
00907 }
00908 
00909 void Verifier::visitBitCastInst(BitCastInst &I) {
00910   // Get the source and destination types
00911   const Type *SrcTy = I.getOperand(0)->getType();
00912   const Type *DestTy = I.getType();
00913 
00914   // Get the size of the types in bits, we'll need this later
00915   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
00916   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
00917 
00918   // BitCast implies a no-op cast of type only. No bits change.
00919   // However, you can't cast pointers to anything but pointers.
00920   Assert1(isa<PointerType>(DestTy) == isa<PointerType>(DestTy),
00921           "Bitcast requires both operands to be pointer or neither", &I);
00922   Assert1(SrcBitSize == DestBitSize, "Bitcast requies types of same width", &I);
00923 
00924   // Disallow aggregates.
00925   Assert1(!SrcTy->isAggregateType(),
00926           "Bitcast operand must not be aggregate", &I);
00927   Assert1(!DestTy->isAggregateType(),
00928           "Bitcast type must not be aggregate", &I);
00929 
00930   visitInstruction(I);
00931 }
00932 
00933 /// visitPHINode - Ensure that a PHI node is well formed.
00934 ///
00935 void Verifier::visitPHINode(PHINode &PN) {
00936   // Ensure that the PHI nodes are all grouped together at the top of the block.
00937   // This can be tested by checking whether the instruction before this is
00938   // either nonexistent (because this is begin()) or is a PHI node.  If not,
00939   // then there is some other instruction before a PHI.
00940   Assert2(&PN == &PN.getParent()->front() || 
00941           isa<PHINode>(--BasicBlock::iterator(&PN)),
00942           "PHI nodes not grouped at top of basic block!",
00943           &PN, PN.getParent());
00944 
00945   // Check that all of the operands of the PHI node have the same type as the
00946   // result.
00947   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
00948     Assert1(PN.getType() == PN.getIncomingValue(i)->getType(),
00949             "PHI node operands are not the same type as the result!", &PN);
00950 
00951   // All other PHI node constraints are checked in the visitBasicBlock method.
00952 
00953   visitInstruction(PN);
00954 }
00955 
00956 void Verifier::VerifyCallSite(CallSite CS) {
00957   Instruction *I = CS.getInstruction();
00958 
00959   Assert1(isa<PointerType>(CS.getCalledValue()->getType()),
00960           "Called function must be a pointer!", I);
00961   const PointerType *FPTy = cast<PointerType>(CS.getCalledValue()->getType());
00962   Assert1(isa<FunctionType>(FPTy->getElementType()),
00963           "Called function is not pointer to function type!", I);
00964 
00965   const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType());
00966 
00967   // Verify that the correct number of arguments are being passed
00968   if (FTy->isVarArg())
00969     Assert1(CS.arg_size() >= FTy->getNumParams(),
00970             "Called function requires more parameters than were provided!",I);
00971   else
00972     Assert1(CS.arg_size() == FTy->getNumParams(),
00973             "Incorrect number of arguments passed to called function!", I);
00974 
00975   // Verify that all arguments to the call match the function type...
00976   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
00977     Assert3(CS.getArgument(i)->getType() == FTy->getParamType(i),
00978             "Call parameter type does not match function signature!",
00979             CS.getArgument(i), FTy->getParamType(i), I);
00980 
00981   const AttrListPtr &Attrs = CS.getAttributes();
00982 
00983   Assert1(VerifyAttributeCount(Attrs, CS.arg_size()),
00984           "Attributes after last parameter!", I);
00985 
00986   // Verify call attributes.
00987   VerifyFunctionAttrs(FTy, Attrs, I);
00988 
00989   if (FTy->isVarArg())
00990     // Check attributes on the varargs part.
00991     for (unsigned Idx = 1 + FTy->getNumParams(); Idx <= CS.arg_size(); ++Idx) {
00992       Attributes Attr = Attrs.getParamAttributes(Idx);
00993 
00994       VerifyAttrs(Attr, CS.getArgument(Idx-1)->getType(), false, I);
00995 
00996       Attributes VArgI = Attr & Attribute::VarArgsIncompatible;
00997       Assert1(!VArgI, "Attribute " + Attribute::getAsString(VArgI) +
00998               " cannot be used for vararg call arguments!", I);
00999     }
01000 
01001   visitInstruction(*I);
01002 }
01003 
01004 void Verifier::visitCallInst(CallInst &CI) {
01005   VerifyCallSite(&CI);
01006 
01007   if (Function *F = CI.getCalledFunction()) {
01008     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
01009       visitIntrinsicFunctionCall(ID, CI);
01010   }
01011 }
01012 
01013 void Verifier::visitInvokeInst(InvokeInst &II) {
01014   VerifyCallSite(&II);
01015 }
01016 
01017 /// visitBinaryOperator - Check that both arguments to the binary operator are
01018 /// of the same type!
01019 ///
01020 void Verifier::visitBinaryOperator(BinaryOperator &B) {
01021   Assert1(B.getOperand(0)->getType() == B.getOperand(1)->getType(),
01022           "Both operands to a binary operator are not of the same type!", &B);
01023 
01024   switch (B.getOpcode()) {
01025   // Check that logical operators are only used with integral operands.
01026   case Instruction::And:
01027   case Instruction::Or:
01028   case Instruction::Xor:
01029     Assert1(B.getType()->isInteger() ||
01030             (isa<VectorType>(B.getType()) && 
01031              cast<VectorType>(B.getType())->getElementType()->isInteger()),
01032             "Logical operators only work with integral types!", &B);
01033     Assert1(B.getType() == B.getOperand(0)->getType(),
01034             "Logical operators must have same type for operands and result!",
01035             &B);
01036     break;
01037   case Instruction::Shl:
01038   case Instruction::LShr:
01039   case Instruction::AShr:
01040     Assert1(B.getType()->isInteger() ||
01041             (isa<VectorType>(B.getType()) && 
01042              cast<VectorType>(B.getType())->getElementType()->isInteger()),
01043             "Shifts only work with integral types!", &B);
01044     Assert1(B.getType() == B.getOperand(0)->getType(),
01045             "Shift return type must be same as operands!", &B);
01046     /* FALL THROUGH */
01047   default:
01048     // Arithmetic operators only work on integer or fp values
01049     Assert1(B.getType() == B.getOperand(0)->getType(),
01050             "Arithmetic operators must have same type for operands and result!",
01051             &B);
01052     Assert1(B.getType()->isInteger() || B.getType()->isFloatingPoint() ||
01053             isa<VectorType>(B.getType()),
01054             "Arithmetic operators must have integer, fp, or vector type!", &B);
01055     break;
01056   }
01057 
01058   visitInstruction(B);
01059 }
01060 
01061 void Verifier::visitICmpInst(ICmpInst& IC) {
01062   // Check that the operands are the same type
01063   const Type* Op0Ty = IC.getOperand(0)->getType();
01064   const Type* Op1Ty = IC.getOperand(1)->getType();
01065   Assert1(Op0Ty == Op1Ty,
01066           "Both operands to ICmp instruction are not of the same type!", &IC);
01067   // Check that the operands are the right type
01068   Assert1(Op0Ty->isIntOrIntVector() || isa<PointerType>(Op0Ty),
01069           "Invalid operand types for ICmp instruction", &IC);
01070   visitInstruction(IC);
01071 }
01072 
01073 void Verifier::visitFCmpInst(FCmpInst& FC) {
01074   // Check that the operands are the same type
01075   const Type* Op0Ty = FC.getOperand(0)->getType();
01076   const Type* Op1Ty = FC.getOperand(1)->getType();
01077   Assert1(Op0Ty == Op1Ty,
01078           "Both operands to FCmp instruction are not of the same type!", &FC);
01079   // Check that the operands are the right type
01080   Assert1(Op0Ty->isFPOrFPVector(),
01081           "Invalid operand types for FCmp instruction", &FC);
01082   visitInstruction(FC);
01083 }
01084 
01085 void Verifier::visitExtractElementInst(ExtractElementInst &EI) {
01086   Assert1(ExtractElementInst::isValidOperands(EI.getOperand(0),
01087                                               EI.getOperand(1)),
01088           "Invalid extractelement operands!", &EI);
01089   visitInstruction(EI);
01090 }
01091 
01092 void Verifier::visitInsertElementInst(InsertElementInst &IE) {
01093   Assert1(InsertElementInst::isValidOperands(IE.getOperand(0),
01094                                              IE.getOperand(1),
01095                                              IE.getOperand(2)),
01096           "Invalid insertelement operands!", &IE);
01097   visitInstruction(IE);
01098 }
01099 
01100 void Verifier::visitShuffleVectorInst(ShuffleVectorInst &SV) {
01101   Assert1(ShuffleVectorInst::isValidOperands(SV.getOperand(0), SV.getOperand(1),
01102                                              SV.getOperand(2)),
01103           "Invalid shufflevector operands!", &SV);
01104 
01105   const VectorType *VTy = dyn_cast<VectorType>(SV.getOperand(0)->getType());
01106   Assert1(VTy, "Operands are not a vector type", &SV);
01107 
01108   // Check to see if Mask is valid.
01109   if (const ConstantVector *MV = dyn_cast<ConstantVector>(SV.getOperand(2))) {
01110     for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
01111       if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
01112         Assert1(!CI->uge(VTy->getNumElements()*2),
01113                 "Invalid shufflevector shuffle mask!", &SV);
01114       } else {
01115         Assert1(isa<UndefValue>(MV->getOperand(i)),
01116                 "Invalid shufflevector shuffle mask!", &SV);
01117       }
01118     }
01119   } else {
01120     Assert1(isa<UndefValue>(SV.getOperand(2)) || 
01121             isa<ConstantAggregateZero>(SV.getOperand(2)),
01122             "Invalid shufflevector shuffle mask!", &SV);
01123   }
01124 
01125   visitInstruction(SV);
01126 }
01127 
01128 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
01129   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
01130   const Type *ElTy =
01131     GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(),
01132                                       Idxs.begin(), Idxs.end());
01133   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
01134   Assert2(isa<PointerType>(GEP.getType()) &&
01135           cast<PointerType>(GEP.getType())->getElementType() == ElTy,
01136           "GEP is not of right type for indices!", &GEP, ElTy);
01137   visitInstruction(GEP);
01138 }
01139 
01140 void Verifier::visitLoadInst(LoadInst &LI) {
01141   const Type *ElTy =
01142     cast<PointerType>(LI.getOperand(0)->getType())->getElementType();
01143   Assert2(ElTy == LI.getType(),
01144           "Load result type does not match pointer operand type!", &LI, ElTy);
01145   visitInstruction(LI);
01146 }
01147 
01148 void Verifier::visitStoreInst(StoreInst &SI) {
01149   const Type *ElTy =
01150     cast<PointerType>(SI.getOperand(1)->getType())->getElementType();
01151   Assert2(ElTy == SI.getOperand(0)->getType(),
01152           "Stored value type does not match pointer operand type!", &SI, ElTy);
01153   visitInstruction(SI);
01154 }
01155 
01156 void Verifier::visitAllocationInst(AllocationInst &AI) {
01157   const PointerType *PTy = AI.getType();
01158   Assert1(PTy->getAddressSpace() == 0, 
01159           "Allocation instruction pointer not in the generic address space!",
01160           &AI);
01161   Assert1(PTy->getElementType()->isSized(), "Cannot allocate unsized type",
01162           &AI);
01163   visitInstruction(AI);
01164 }
01165 
01166 void Verifier::visitExtractValueInst(ExtractValueInst &EVI) {
01167   Assert1(ExtractValueInst::getIndexedType(EVI.getAggregateOperand()->getType(),
01168                                            EVI.idx_begin(), EVI.idx_end()) ==
01169           EVI.getType(),
01170           "Invalid ExtractValueInst operands!", &EVI);
01171   
01172   visitInstruction(EVI);
01173 }
01174 
01175 void Verifier::visitInsertValueInst(InsertValueInst &IVI) {
01176   Assert1(ExtractValueInst::getIndexedType(IVI.getAggregateOperand()->getType(),
01177                                            IVI.idx_begin(), IVI.idx_end()) ==
01178           IVI.getOperand(1)->getType(),
01179           "Invalid InsertValueInst operands!", &IVI);
01180   
01181   visitInstruction(IVI);
01182 }
01183 
01184 /// verifyInstruction - Verify that an instruction is well formed.
01185 ///
01186 void Verifier::visitInstruction(Instruction &I) {
01187   BasicBlock *BB = I.getParent();
01188   Assert1(BB, "Instruction not embedded in basic block!", &I);
01189 
01190   if (!isa<PHINode>(I)) {   // Check that non-phi nodes are not self referential
01191     for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
01192          UI != UE; ++UI)
01193       Assert1(*UI != (User*)&I ||
01194               !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
01195               "Only PHI nodes may reference their own value!", &I);
01196   }
01197   
01198   // Verify that if this is a terminator that it is at the end of the block.
01199   if (isa<TerminatorInst>(I))
01200     Assert1(BB->getTerminator() == &I, "Terminator not at end of block!", &I);
01201   
01202 
01203   // Check that void typed values don't have names
01204   Assert1(I.getType() != Type::VoidTy || !I.hasName(),
01205           "Instruction has a name, but provides a void value!", &I);
01206 
01207   // Check that the return value of the instruction is either void or a legal
01208   // value type.
01209   Assert1(I.getType() == Type::VoidTy || I.getType()->isFirstClassType()
01210           || ((isa<CallInst>(I) || isa<InvokeInst>(I)) 
01211               && isa<StructType>(I.getType())),
01212           "Instruction returns a non-scalar type!", &I);
01213 
01214   // Check that all uses of the instruction, if they are instructions
01215   // themselves, actually have parent basic blocks.  If the use is not an
01216   // instruction, it is an error!
01217   for (User::use_iterator UI = I.use_begin(), UE = I.use_end();
01218        UI != UE; ++UI) {
01219     Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!",
01220             *UI);
01221     Instruction *Used = cast<Instruction>(*UI);
01222     Assert2(Used->getParent() != 0, "Instruction referencing instruction not"
01223             " embeded in a basic block!", &I, Used);
01224   }
01225 
01226   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
01227     Assert1(I.getOperand(i) != 0, "Instruction has null operand!", &I);
01228 
01229     // Check to make sure that only first-class-values are operands to
01230     // instructions.
01231     if (!I.getOperand(i)->getType()->isFirstClassType()) {
01232       Assert1(0, "Instruction operands must be first-class values!", &I);
01233     }
01234     
01235     if (Function *F = dyn_cast<Function>(I.getOperand(i))) {
01236       // Check to make sure that the "address of" an intrinsic function is never
01237       // taken.
01238       Assert1(!F->isIntrinsic() || (i == 0 && isa<CallInst>(I)),
01239               "Cannot take the address of an intrinsic!", &I);
01240       Assert1(F->getParent() == Mod, "Referencing function in another module!",
01241               &I);
01242     } else if (BasicBlock *OpBB = dyn_cast<BasicBlock>(I.getOperand(i))) {
01243       Assert1(OpBB->getParent() == BB->getParent(),
01244               "Referring to a basic block in another function!", &I);
01245     } else if (Argument *OpArg = dyn_cast<Argument>(I.getOperand(i))) {
01246       Assert1(OpArg->getParent() == BB->getParent(),
01247               "Referring to an argument in another function!", &I);
01248     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(i))) {
01249       Assert1(GV->getParent() == Mod, "Referencing global in another module!",
01250               &I);
01251     } else if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
01252       BasicBlock *OpBlock = Op->getParent();
01253 
01254       // Check that a definition dominates all of its uses.
01255       if (!isa<PHINode>(I)) {
01256         // Invoke results are only usable in the normal destination, not in the
01257         // exceptional destination.
01258         if (InvokeInst *II = dyn_cast<InvokeInst>(Op)) {
01259           OpBlock = II->getNormalDest();
01260           
01261           Assert2(OpBlock != II->getUnwindDest(),
01262                   "No uses of invoke possible due to dominance structure!",
01263                   Op, II);
01264           
01265           // If the normal successor of an invoke instruction has multiple
01266           // predecessors, then the normal edge from the invoke is critical, so
01267           // the invoke value can only be live if the destination block
01268           // dominates all of it's predecessors (other than the invoke) or if
01269           // the invoke value is only used by a phi in the successor.
01270           if (!OpBlock->getSinglePredecessor() &&
01271               DT->dominates(&BB->getParent()->getEntryBlock(), BB)) {
01272             // The first case we allow is if the use is a PHI operand in the
01273             // normal block, and if that PHI operand corresponds to the invoke's
01274             // block.
01275             bool Bad = true;
01276             if (PHINode *PN = dyn_cast<PHINode>(&I))
01277               if (PN->getParent() == OpBlock &&
01278                   PN->getIncomingBlock(i/2) == Op->getParent())
01279                 Bad = false;
01280             
01281             // If it is used by something non-phi, then the other case is that
01282             // 'OpBlock' dominates all of its predecessors other than the
01283             // invoke.  In this case, the invoke value can still be used.
01284             if (Bad) {
01285               Bad = false;
01286               for (pred_iterator PI = pred_begin(OpBlock),
01287                    E = pred_end(OpBlock); PI != E; ++PI) {
01288                 if (*PI != II->getParent() && !DT->dominates(OpBlock, *PI)) {
01289                   Bad = true;
01290                   break;
01291                 }
01292               }
01293             }
01294             Assert2(!Bad,
01295                     "Invoke value defined on critical edge but not dead!", &I,
01296                     Op);
01297           }
01298         } else if (OpBlock == BB) {
01299           // If they are in the same basic block, make sure that the definition
01300           // comes before the use.
01301           Assert2(InstsInThisBlock.count(Op) ||
01302                   !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
01303                   "Instruction does not dominate all uses!", Op, &I);
01304         }
01305 
01306         // Definition must dominate use unless use is unreachable!
01307         Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
01308                 !DT->dominates(&BB->getParent()->getEntryBlock(), BB),
01309                 "Instruction does not dominate all uses!", Op, &I);
01310       } else {
01311         // PHI nodes are more difficult than other nodes because they actually
01312         // "use" the value in the predecessor basic blocks they correspond to.
01313         BasicBlock *PredBB = cast<BasicBlock>(I.getOperand(i+1));
01314         Assert2(DT->dominates(OpBlock, PredBB) ||
01315                 !DT->dominates(&BB->getParent()->getEntryBlock(), PredBB),
01316                 "Instruction does not dominate all uses!", Op, &I);
01317       }
01318     } else if (isa<InlineAsm>(I.getOperand(i))) {
01319       Assert1(i == 0 && (isa<CallInst>(I) || isa<InvokeInst>(I)),
01320               "Cannot take the address of an inline asm!", &I);
01321     }
01322   }
01323   InstsInThisBlock.insert(&I);
01324 }
01325 
01326 // Flags used by TableGen to mark intrinsic parameters with the
01327 // LLVMExtendedElementVectorType and LLVMTruncatedElementVectorType classes.
01328 static const unsigned ExtendedElementVectorType = 0x40000000;
01329 static const unsigned TruncatedElementVectorType = 0x20000000;
01330 
01331 /// visitIntrinsicFunction - Allow intrinsics to be verified in different ways.
01332 ///
01333 void Verifier::visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI) {
01334   Function *IF = CI.getCalledFunction();
01335   Assert1(IF->isDeclaration(), "Intrinsic functions should never be defined!",
01336           IF);
01337   
01338 #define GET_INTRINSIC_VERIFIER
01339 #include "llvm/Intrinsics.gen"
01340 #undef GET_INTRINSIC_VERIFIER
01341   
01342   switch (ID) {
01343   default:
01344     break;
01345   case Intrinsic::dbg_declare:    // llvm.dbg.declare
01346     if (Constant *C = dyn_cast<Constant>(CI.getOperand(1)))
01347       Assert1(C && !isa<ConstantPointerNull>(C),
01348               "invalid llvm.dbg.declare intrinsic call", &CI);
01349     break;
01350   case Intrinsic::memcpy:
01351   case Intrinsic::memmove:
01352   case Intrinsic::memset:
01353     Assert1(isa<ConstantInt>(CI.getOperand(4)),
01354             "alignment argument of memory intrinsics must be a constant int",
01355             &CI);
01356     break;
01357   case Intrinsic::gcroot:
01358   case Intrinsic::gcwrite:
01359   case Intrinsic::gcread:
01360     if (ID == Intrinsic::gcroot) {
01361       AllocaInst *AI =
01362         dyn_cast<AllocaInst>(CI.getOperand(1)->stripPointerCasts());
01363       Assert1(AI && isa<PointerType>(AI->getType()->getElementType()),
01364               "llvm.gcroot parameter #1 must be a pointer alloca.", &CI);
01365       Assert1(isa<Constant>(CI.getOperand(2)),
01366               "llvm.gcroot parameter #2 must be a constant.", &CI);
01367     }
01368       
01369     Assert1(CI.getParent()->getParent()->hasGC(),
01370             "Enclosing function does not use GC.", &CI);
01371     break;
01372   case Intrinsic::init_trampoline:
01373     Assert1(isa<Function>(CI.getOperand(2)->stripPointerCasts()),
01374             "llvm.init_trampoline parameter #2 must resolve to a function.",
01375             &CI);
01376     break;
01377   case Intrinsic::prefetch:
01378     Assert1(isa<ConstantInt>(CI.getOperand(2)) &&
01379             isa<ConstantInt>(CI.getOperand(3)) &&
01380             cast<ConstantInt>(CI.getOperand(2))->getZExtValue() < 2 &&
01381             cast<ConstantInt>(CI.getOperand(3))->getZExtValue() < 4,
01382             "invalid arguments to llvm.prefetch",
01383             &CI);
01384     break;
01385   case Intrinsic::stackprotector:
01386     Assert1(isa<AllocaInst>(CI.getOperand(2)->stripPointerCasts()),
01387             "llvm.stackprotector parameter #2 must resolve to an alloca.",
01388             &CI);
01389     break;
01390   }
01391 }
01392 
01393 /// Produce a string to identify an intrinsic parameter or return value.
01394 /// The ArgNo value numbers the return values from 0 to NumRets-1 and the
01395 /// parameters beginning with NumRets.
01396 ///
01397 static std::string IntrinsicParam(unsigned ArgNo, unsigned NumRets) {
01398   if (ArgNo < NumRets) {
01399     if (NumRets == 1)
01400       return "Intrinsic result type";
01401     else
01402       return "Intrinsic result type #" + utostr(ArgNo);
01403   } else
01404     return "Intrinsic parameter #" + utostr(ArgNo - NumRets);
01405 }
01406 
01407 bool Verifier::PerformTypeCheck(Intrinsic::ID ID, Function *F, const Type *Ty,
01408                                 int VT, unsigned ArgNo, std::string &Suffix) {
01409   const FunctionType *FTy = F->getFunctionType();
01410 
01411   unsigned NumElts = 0;
01412   const Type *EltTy = Ty;
01413   const VectorType *VTy = dyn_cast<VectorType>(Ty);
01414   if (VTy) {
01415     EltTy = VTy->getElementType();
01416     NumElts = VTy->getNumElements();
01417   }
01418 
01419   const Type *RetTy = FTy->getReturnType();
01420   const StructType *ST = dyn_cast<StructType>(RetTy);
01421   unsigned NumRets = 1;
01422   if (ST)
01423     NumRets = ST->getNumElements();
01424 
01425   if (VT < 0) {
01426     int Match = ~VT;
01427 
01428     // Check flags that indicate a type that is an integral vector type with
01429     // elements that are larger or smaller than the elements of the matched
01430     // type.
01431     if ((Match & (ExtendedElementVectorType |
01432                   TruncatedElementVectorType)) != 0) {
01433       const IntegerType *IEltTy = dyn_cast<IntegerType>(EltTy);
01434       if (!VTy || !IEltTy) {
01435         CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
01436                     "an integral vector type.", F);
01437         return false;
01438       }
01439       // Adjust the current Ty (in the opposite direction) rather than
01440       // the type being matched against.
01441       if ((Match & ExtendedElementVectorType) != 0) {
01442         if ((IEltTy->getBitWidth() & 1) != 0) {
01443           CheckFailed(IntrinsicParam(ArgNo, NumRets) + " vector "
01444                       "element bit-width is odd.", F);
01445           return false;
01446         }
01447         Ty = VectorType::getTruncatedElementVectorType(VTy);
01448       } else
01449         Ty = VectorType::getExtendedElementVectorType(VTy);
01450       Match &= ~(ExtendedElementVectorType | TruncatedElementVectorType);
01451     }
01452 
01453     if (Match <= static_cast<int>(NumRets - 1)) {
01454       if (ST)
01455         RetTy = ST->getElementType(Match);
01456 
01457       if (Ty != RetTy) {
01458         CheckFailed(IntrinsicParam(ArgNo, NumRets) + " does not "
01459                     "match return type.", F);
01460         return false;
01461       }
01462     } else {
01463       if (Ty != FTy->getParamType(Match - 1)) {
01464         CheckFailed(IntrinsicParam(ArgNo, NumRets) + " does not "
01465                     "match parameter %" + utostr(Match - 1) + ".", F);
01466         return false;
01467       }
01468     }
01469   } else if (VT == MVT::iAny) {
01470     if (!EltTy->isInteger()) {
01471       CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
01472                   "an integer type.", F);
01473       return false;
01474     }
01475 
01476     unsigned GotBits = cast<IntegerType>(EltTy)->getBitWidth();
01477     Suffix += ".";
01478 
01479     if (EltTy != Ty)
01480       Suffix += "v" + utostr(NumElts);
01481 
01482     Suffix += "i" + utostr(GotBits);;
01483 
01484     // Check some constraints on various intrinsics.
01485     switch (ID) {
01486     default: break; // Not everything needs to be checked.
01487     case Intrinsic::bswap:
01488       if (GotBits < 16 || GotBits % 16 != 0) {
01489         CheckFailed("Intrinsic requires even byte width argument", F);
01490         return false;
01491       }
01492       break;
01493     }
01494   } else if (VT == MVT::fAny) {
01495     if (!EltTy->isFloatingPoint()) {
01496       CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not "
01497                   "a floating-point type.", F);
01498       return false;
01499     }
01500 
01501     Suffix += ".";
01502 
01503     if (EltTy != Ty)
01504       Suffix += "v" + utostr(NumElts);
01505 
01506     Suffix += MVT::getMVT(EltTy).getMVTString();
01507   } else if (VT == MVT::iPTR) {
01508     if (!isa<PointerType>(Ty)) {
01509       CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not a "
01510                   "pointer and a pointer is required.", F);
01511       return false;
01512     }
01513   } else if (VT == MVT::iPTRAny) {
01514     // Outside of TableGen, we don't distinguish iPTRAny (to any address space)
01515     // and iPTR. In the verifier, we can not distinguish which case we have so
01516     // allow either case to be legal.
01517     if (const PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
01518       Suffix += ".p" + utostr(PTyp->getAddressSpace()) + 
01519         MVT::getMVT(PTyp->getElementType()).getMVTString();
01520     } else {
01521       CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is not a "
01522                   "pointer and a pointer is required.", F);
01523       return false;
01524     }
01525   } else if (MVT((MVT::SimpleValueType)VT).isVector()) {
01526     MVT VVT = MVT((MVT::SimpleValueType)VT);
01527 
01528     // If this is a vector argument, verify the number and type of elements.
01529     if (VVT.getVectorElementType() != MVT::getMVT(EltTy)) {
01530       CheckFailed("Intrinsic prototype has incorrect vector element type!", F);
01531       return false;
01532     }
01533 
01534     if (VVT.getVectorNumElements() != NumElts) {
01535       CheckFailed("Intrinsic prototype has incorrect number of "
01536                   "vector elements!", F);
01537       return false;
01538     }
01539   } else if (MVT((MVT::SimpleValueType)VT).getTypeForMVT() != EltTy) {
01540     CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is wrong!", F);
01541     return false;
01542   } else if (EltTy != Ty) {
01543     CheckFailed(IntrinsicParam(ArgNo, NumRets) + " is a vector "
01544                 "and a scalar is required.", F);
01545     return false;
01546   }
01547 
01548   return true;
01549 }
01550 
01551 /// VerifyIntrinsicPrototype - TableGen emits calls to this function into
01552 /// Intrinsics.gen.  This implements a little state machine that verifies the
01553 /// prototype of intrinsics.
01554 void Verifier::VerifyIntrinsicPrototype(Intrinsic::ID ID, Function *F,
01555                                         unsigned RetNum,
01556                                         unsigned ParamNum, ...) {
01557   va_list VA;
01558   va_start(VA, ParamNum);
01559   const FunctionType *FTy = F->getFunctionType();
01560   
01561   // For overloaded intrinsics, the Suffix of the function name must match the
01562   // types of the arguments. This variable keeps track of the expected
01563   // suffix, to be checked at the end.
01564   std::string Suffix;
01565 
01566   if (FTy->getNumParams() + FTy->isVarArg() != ParamNum) {
01567     CheckFailed("Intrinsic prototype has incorrect number of arguments!", F);
01568     return;
01569   }
01570 
01571   const Type *Ty = FTy->getReturnType();
01572   const StructType *ST = dyn_cast<StructType>(Ty);
01573 
01574   // Verify the return types.
01575   if (ST && ST->getNumElements() != RetNum) {
01576     CheckFailed("Intrinsic prototype has incorrect number of return types!", F);
01577     return;
01578   }
01579 
01580   for (unsigned ArgNo = 0; ArgNo < RetNum; ++ArgNo) {
01581     int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
01582 
01583     if (ST) Ty = ST->getElementType(ArgNo);
01584 
01585     if (!PerformTypeCheck(ID, F, Ty, VT, ArgNo, Suffix))
01586       break;
01587   }
01588 
01589   // Verify the parameter types.
01590   for (unsigned ArgNo = 0; ArgNo < ParamNum; ++ArgNo) {
01591     int VT = va_arg(VA, int); // An MVT::SimpleValueType when non-negative.
01592 
01593     if (VT == MVT::isVoid && ArgNo > 0) {
01594       if (!FTy->isVarArg())
01595         CheckFailed("Intrinsic prototype has no '...'!", F);
01596       break;
01597     }
01598 
01599     if (!PerformTypeCheck(ID, F, FTy->getParamType(ArgNo), VT, ArgNo + RetNum,
01600                           Suffix))
01601       break;
01602   }
01603 
01604   va_end(VA);
01605 
01606   // For intrinsics without pointer arguments, if we computed a Suffix then the
01607   // intrinsic is overloaded and we need to make sure that the name of the
01608   // function is correct. We add the suffix to the name of the intrinsic and
01609   // compare against the given function name. If they are not the same, the
01610   // function name is invalid. This ensures that overloading of intrinsics
01611   // uses a sane and consistent naming convention.  Note that intrinsics with
01612   // pointer argument may or may not be overloaded so we will check assuming it
01613   // has a suffix and not.
01614   if (!Suffix.empty()) {
01615     std::string Name(Intrinsic::getName(ID));
01616     if (Name + Suffix != F->getName()) {
01617       CheckFailed("Overloaded intrinsic has incorrect suffix: '" +
01618                   F->getName().substr(Name.length()) + "'. It should be '" +
01619                   Suffix + "'", F);
01620     }
01621   }
01622 
01623   // Check parameter attributes.
01624   Assert1(F->getAttributes() == Intrinsic::getAttributes(ID),
01625           "Intrinsic has wrong parameter attributes!", F);
01626 }
01627 
01628 
01629 //===----------------------------------------------------------------------===//
01630 //  Implement the public interfaces to this file...
01631 //===----------------------------------------------------------------------===//
01632 
01633 FunctionPass *llvm::createVerifierPass(VerifierFailureAction action) {
01634   return new Verifier(action);
01635 }
01636 
01637 
01638 // verifyFunction - Create
01639 bool llvm::verifyFunction(const Function &f, VerifierFailureAction action) {
01640   Function &F = const_cast<Function&>(f);
01641   assert(!F.isDeclaration() && "Cannot verify external functions");
01642 
01643   ExistingModuleProvider MP(F.getParent());
01644   FunctionPassManager FPM(&MP);
01645   Verifier *V = new Verifier(action);
01646   FPM.add(V);
01647   FPM.run(F);
01648   MP.releaseModule();
01649   return V->Broken;
01650 }
01651 
01652 /// verifyModule - Check a module for errors, printing messages on stderr.
01653 /// Return true if the module is corrupt.
01654 ///
01655 bool llvm::verifyModule(const Module &M, VerifierFailureAction action,
01656                         std::string *ErrorInfo) {
01657   PassManager PM;
01658   Verifier *V = new Verifier(action);
01659   PM.add(V);
01660   PM.run(const_cast<Module&>(M));
01661   
01662   if (ErrorInfo && V->Broken)
01663     *ErrorInfo = V->msgs.str();
01664   return V->Broken;
01665 }
01666 
01667 // vim: sw=2