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