LLVM API Documentation

Execution.cpp

Go to the documentation of this file.
00001 //===-- Execution.cpp - Implement code to simulate the program ------------===//
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 contains the actual instruction interpreter.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "interpreter"
00015 #include "Interpreter.h"
00016 #include "llvm/Constants.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/Instructions.h"
00019 #include "llvm/CodeGen/IntrinsicLowering.h"
00020 #include "llvm/Support/GetElementPtrTypeIterator.h"
00021 #include "llvm/ADT/APInt.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/Support/CommandLine.h"
00024 #include "llvm/Support/Debug.h"
00025 #include "llvm/Support/MathExtras.h"
00026 #include <algorithm>
00027 #include <cmath>
00028 #include <cstring>
00029 using namespace llvm;
00030 
00031 STATISTIC(NumDynamicInsts, "Number of dynamic instructions executed");
00032 static Interpreter *TheEE = 0;
00033 
00034 static cl::opt<bool> PrintVolatile("interpreter-print-volatile", cl::Hidden,
00035           cl::desc("make the interpreter print every volatile load and store"));
00036 
00037 //===----------------------------------------------------------------------===//
00038 //                     Various Helper Functions
00039 //===----------------------------------------------------------------------===//
00040 
00041 static inline uint64_t doSignExtension(uint64_t Val, const IntegerType* ITy) {
00042   // Determine if the value is signed or not
00043   bool isSigned = (Val & (1 << (ITy->getBitWidth()-1))) != 0;
00044   // If its signed, extend the sign bits
00045   if (isSigned)
00046     Val |= ~ITy->getBitMask();
00047   return Val;
00048 }
00049 
00050 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
00051   SF.Values[V] = Val;
00052 }
00053 
00054 void Interpreter::initializeExecutionEngine() {
00055   TheEE = this;
00056 }
00057 
00058 //===----------------------------------------------------------------------===//
00059 //                    Binary Instruction Implementations
00060 //===----------------------------------------------------------------------===//
00061 
00062 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
00063    case Type::TY##TyID: \
00064      Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; \
00065      break
00066 
00067 #define IMPLEMENT_INTEGER_BINOP1(OP, TY) \
00068    case Type::IntegerTyID: { \
00069      Dest.IntVal = Src1.IntVal OP Src2.IntVal; \
00070      break; \
00071    }
00072 
00073 
00074 static void executeAddInst(GenericValue &Dest, GenericValue Src1, 
00075                            GenericValue Src2, const Type *Ty) {
00076   switch (Ty->getTypeID()) {
00077     IMPLEMENT_INTEGER_BINOP1(+, Ty);
00078     IMPLEMENT_BINARY_OPERATOR(+, Float);
00079     IMPLEMENT_BINARY_OPERATOR(+, Double);
00080   default:
00081     cerr << "Unhandled type for Add instruction: " << *Ty << "\n";
00082     abort();
00083   }
00084 }
00085 
00086 static void executeSubInst(GenericValue &Dest, GenericValue Src1, 
00087                            GenericValue Src2, const Type *Ty) {
00088   switch (Ty->getTypeID()) {
00089     IMPLEMENT_INTEGER_BINOP1(-, Ty);
00090     IMPLEMENT_BINARY_OPERATOR(-, Float);
00091     IMPLEMENT_BINARY_OPERATOR(-, Double);
00092   default:
00093     cerr << "Unhandled type for Sub instruction: " << *Ty << "\n";
00094     abort();
00095   }
00096 }
00097 
00098 static void executeMulInst(GenericValue &Dest, GenericValue Src1, 
00099                            GenericValue Src2, const Type *Ty) {
00100   switch (Ty->getTypeID()) {
00101     IMPLEMENT_INTEGER_BINOP1(*, Ty);
00102     IMPLEMENT_BINARY_OPERATOR(*, Float);
00103     IMPLEMENT_BINARY_OPERATOR(*, Double);
00104   default:
00105     cerr << "Unhandled type for Mul instruction: " << *Ty << "\n";
00106     abort();
00107   }
00108 }
00109 
00110 static void executeFDivInst(GenericValue &Dest, GenericValue Src1, 
00111                             GenericValue Src2, const Type *Ty) {
00112   switch (Ty->getTypeID()) {
00113     IMPLEMENT_BINARY_OPERATOR(/, Float);
00114     IMPLEMENT_BINARY_OPERATOR(/, Double);
00115   default:
00116     cerr << "Unhandled type for FDiv instruction: " << *Ty << "\n";
00117     abort();
00118   }
00119 }
00120 
00121 static void executeFRemInst(GenericValue &Dest, GenericValue Src1, 
00122                             GenericValue Src2, const Type *Ty) {
00123   switch (Ty->getTypeID()) {
00124   case Type::FloatTyID:
00125     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
00126     break;
00127   case Type::DoubleTyID:
00128     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
00129     break;
00130   default:
00131     cerr << "Unhandled type for Rem instruction: " << *Ty << "\n";
00132     abort();
00133   }
00134 }
00135 
00136 #define IMPLEMENT_INTEGER_ICMP(OP, TY) \
00137    case Type::IntegerTyID:  \
00138       Dest.IntVal = APInt(1,Src1.IntVal.OP(Src2.IntVal)); \
00139       break;
00140 
00141 // Handle pointers specially because they must be compared with only as much
00142 // width as the host has.  We _do not_ want to be comparing 64 bit values when
00143 // running on a 32-bit target, otherwise the upper 32 bits might mess up
00144 // comparisons if they contain garbage.
00145 #define IMPLEMENT_POINTER_ICMP(OP) \
00146    case Type::PointerTyID: \
00147       Dest.IntVal = APInt(1,(void*)(intptr_t)Src1.PointerVal OP \
00148                             (void*)(intptr_t)Src2.PointerVal); \
00149       break;
00150 
00151 static GenericValue executeICMP_EQ(GenericValue Src1, GenericValue Src2,
00152                                    const Type *Ty) {
00153   GenericValue Dest;
00154   switch (Ty->getTypeID()) {
00155     IMPLEMENT_INTEGER_ICMP(eq,Ty);
00156     IMPLEMENT_POINTER_ICMP(==);
00157   default:
00158     cerr << "Unhandled type for ICMP_EQ predicate: " << *Ty << "\n";
00159     abort();
00160   }
00161   return Dest;
00162 }
00163 
00164 static GenericValue executeICMP_NE(GenericValue Src1, GenericValue Src2,
00165                                    const Type *Ty) {
00166   GenericValue Dest;
00167   switch (Ty->getTypeID()) {
00168     IMPLEMENT_INTEGER_ICMP(ne,Ty);
00169     IMPLEMENT_POINTER_ICMP(!=);
00170   default:
00171     cerr << "Unhandled type for ICMP_NE predicate: " << *Ty << "\n";
00172     abort();
00173   }
00174   return Dest;
00175 }
00176 
00177 static GenericValue executeICMP_ULT(GenericValue Src1, GenericValue Src2,
00178                                     const Type *Ty) {
00179   GenericValue Dest;
00180   switch (Ty->getTypeID()) {
00181     IMPLEMENT_INTEGER_ICMP(ult,Ty);
00182     IMPLEMENT_POINTER_ICMP(<);
00183   default:
00184     cerr << "Unhandled type for ICMP_ULT predicate: " << *Ty << "\n";
00185     abort();
00186   }
00187   return Dest;
00188 }
00189 
00190 static GenericValue executeICMP_SLT(GenericValue Src1, GenericValue Src2,
00191                                     const Type *Ty) {
00192   GenericValue Dest;
00193   switch (Ty->getTypeID()) {
00194     IMPLEMENT_INTEGER_ICMP(slt,Ty);
00195     IMPLEMENT_POINTER_ICMP(<);
00196   default:
00197     cerr << "Unhandled type for ICMP_SLT predicate: " << *Ty << "\n";
00198     abort();
00199   }
00200   return Dest;
00201 }
00202 
00203 static GenericValue executeICMP_UGT(GenericValue Src1, GenericValue Src2,
00204                                     const Type *Ty) {
00205   GenericValue Dest;
00206   switch (Ty->getTypeID()) {
00207     IMPLEMENT_INTEGER_ICMP(ugt,Ty);
00208     IMPLEMENT_POINTER_ICMP(>);
00209   default:
00210     cerr << "Unhandled type for ICMP_UGT predicate: " << *Ty << "\n";
00211     abort();
00212   }
00213   return Dest;
00214 }
00215 
00216 static GenericValue executeICMP_SGT(GenericValue Src1, GenericValue Src2,
00217                                     const Type *Ty) {
00218   GenericValue Dest;
00219   switch (Ty->getTypeID()) {
00220     IMPLEMENT_INTEGER_ICMP(sgt,Ty);
00221     IMPLEMENT_POINTER_ICMP(>);
00222   default:
00223     cerr << "Unhandled type for ICMP_SGT predicate: " << *Ty << "\n";
00224     abort();
00225   }
00226   return Dest;
00227 }
00228 
00229 static GenericValue executeICMP_ULE(GenericValue Src1, GenericValue Src2,
00230                                     const Type *Ty) {
00231   GenericValue Dest;
00232   switch (Ty->getTypeID()) {
00233     IMPLEMENT_INTEGER_ICMP(ule,Ty);
00234     IMPLEMENT_POINTER_ICMP(<=);
00235   default:
00236     cerr << "Unhandled type for ICMP_ULE predicate: " << *Ty << "\n";
00237     abort();
00238   }
00239   return Dest;
00240 }
00241 
00242 static GenericValue executeICMP_SLE(GenericValue Src1, GenericValue Src2,
00243                                     const Type *Ty) {
00244   GenericValue Dest;
00245   switch (Ty->getTypeID()) {
00246     IMPLEMENT_INTEGER_ICMP(sle,Ty);
00247     IMPLEMENT_POINTER_ICMP(<=);
00248   default:
00249     cerr << "Unhandled type for ICMP_SLE predicate: " << *Ty << "\n";
00250     abort();
00251   }
00252   return Dest;
00253 }
00254 
00255 static GenericValue executeICMP_UGE(GenericValue Src1, GenericValue Src2,
00256                                     const Type *Ty) {
00257   GenericValue Dest;
00258   switch (Ty->getTypeID()) {
00259     IMPLEMENT_INTEGER_ICMP(uge,Ty);
00260     IMPLEMENT_POINTER_ICMP(>=);
00261   default:
00262     cerr << "Unhandled type for ICMP_UGE predicate: " << *Ty << "\n";
00263     abort();
00264   }
00265   return Dest;
00266 }
00267 
00268 static GenericValue executeICMP_SGE(GenericValue Src1, GenericValue Src2,
00269                                     const Type *Ty) {
00270   GenericValue Dest;
00271   switch (Ty->getTypeID()) {
00272     IMPLEMENT_INTEGER_ICMP(sge,Ty);
00273     IMPLEMENT_POINTER_ICMP(>=);
00274   default:
00275     cerr << "Unhandled type for ICMP_SGE predicate: " << *Ty << "\n";
00276     abort();
00277   }
00278   return Dest;
00279 }
00280 
00281 void Interpreter::visitICmpInst(ICmpInst &I) {
00282   ExecutionContext &SF = ECStack.back();
00283   const Type *Ty    = I.getOperand(0)->getType();
00284   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
00285   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
00286   GenericValue R;   // Result
00287   
00288   switch (I.getPredicate()) {
00289   case ICmpInst::ICMP_EQ:  R = executeICMP_EQ(Src1,  Src2, Ty); break;
00290   case ICmpInst::ICMP_NE:  R = executeICMP_NE(Src1,  Src2, Ty); break;
00291   case ICmpInst::ICMP_ULT: R = executeICMP_ULT(Src1, Src2, Ty); break;
00292   case ICmpInst::ICMP_SLT: R = executeICMP_SLT(Src1, Src2, Ty); break;
00293   case ICmpInst::ICMP_UGT: R = executeICMP_UGT(Src1, Src2, Ty); break;
00294   case ICmpInst::ICMP_SGT: R = executeICMP_SGT(Src1, Src2, Ty); break;
00295   case ICmpInst::ICMP_ULE: R = executeICMP_ULE(Src1, Src2, Ty); break;
00296   case ICmpInst::ICMP_SLE: R = executeICMP_SLE(Src1, Src2, Ty); break;
00297   case ICmpInst::ICMP_UGE: R = executeICMP_UGE(Src1, Src2, Ty); break;
00298   case ICmpInst::ICMP_SGE: R = executeICMP_SGE(Src1, Src2, Ty); break;
00299   default:
00300     cerr << "Don't know how to handle this ICmp predicate!\n-->" << I;
00301     abort();
00302   }
00303  
00304   SetValue(&I, R, SF);
00305 }
00306 
00307 #define IMPLEMENT_FCMP(OP, TY) \
00308    case Type::TY##TyID: \
00309      Dest.IntVal = APInt(1,Src1.TY##Val OP Src2.TY##Val); \
00310      break
00311 
00312 static GenericValue executeFCMP_OEQ(GenericValue Src1, GenericValue Src2,
00313                                    const Type *Ty) {
00314   GenericValue Dest;
00315   switch (Ty->getTypeID()) {
00316     IMPLEMENT_FCMP(==, Float);
00317     IMPLEMENT_FCMP(==, Double);
00318   default:
00319     cerr << "Unhandled type for FCmp EQ instruction: " << *Ty << "\n";
00320     abort();
00321   }
00322   return Dest;
00323 }
00324 
00325 static GenericValue executeFCMP_ONE(GenericValue Src1, GenericValue Src2,
00326                                    const Type *Ty) {
00327   GenericValue Dest;
00328   switch (Ty->getTypeID()) {
00329     IMPLEMENT_FCMP(!=, Float);
00330     IMPLEMENT_FCMP(!=, Double);
00331 
00332   default:
00333     cerr << "Unhandled type for FCmp NE instruction: " << *Ty << "\n";
00334     abort();
00335   }
00336   return Dest;
00337 }
00338 
00339 static GenericValue executeFCMP_OLE(GenericValue Src1, GenericValue Src2,
00340                                    const Type *Ty) {
00341   GenericValue Dest;
00342   switch (Ty->getTypeID()) {
00343     IMPLEMENT_FCMP(<=, Float);
00344     IMPLEMENT_FCMP(<=, Double);
00345   default:
00346     cerr << "Unhandled type for FCmp LE instruction: " << *Ty << "\n";
00347     abort();
00348   }
00349   return Dest;
00350 }
00351 
00352 static GenericValue executeFCMP_OGE(GenericValue Src1, GenericValue Src2,
00353                                    const Type *Ty) {
00354   GenericValue Dest;
00355   switch (Ty->getTypeID()) {
00356     IMPLEMENT_FCMP(>=, Float);
00357     IMPLEMENT_FCMP(>=, Double);
00358   default:
00359     cerr << "Unhandled type for FCmp GE instruction: " << *Ty << "\n";
00360     abort();
00361   }
00362   return Dest;
00363 }
00364 
00365 static GenericValue executeFCMP_OLT(GenericValue Src1, GenericValue Src2,
00366                                    const Type *Ty) {
00367   GenericValue Dest;
00368   switch (Ty->getTypeID()) {
00369     IMPLEMENT_FCMP(<, Float);
00370     IMPLEMENT_FCMP(<, Double);
00371   default:
00372     cerr << "Unhandled type for FCmp LT instruction: " << *Ty << "\n";
00373     abort();
00374   }
00375   return Dest;
00376 }
00377 
00378 static GenericValue executeFCMP_OGT(GenericValue Src1, GenericValue Src2,
00379                                      const Type *Ty) {
00380   GenericValue Dest;
00381   switch (Ty->getTypeID()) {
00382     IMPLEMENT_FCMP(>, Float);
00383     IMPLEMENT_FCMP(>, Double);
00384   default:
00385     cerr << "Unhandled type for FCmp GT instruction: " << *Ty << "\n";
00386     abort();
00387   }
00388   return Dest;
00389 }
00390 
00391 #define IMPLEMENT_UNORDERED(TY, X,Y)                                     \
00392   if (TY == Type::FloatTy) {                                             \
00393     if (X.FloatVal != X.FloatVal || Y.FloatVal != Y.FloatVal) {          \
00394       Dest.IntVal = APInt(1,true);                                       \
00395       return Dest;                                                       \
00396     }                                                                    \
00397   } else if (X.DoubleVal != X.DoubleVal || Y.DoubleVal != Y.DoubleVal) { \
00398     Dest.IntVal = APInt(1,true);                                         \
00399     return Dest;                                                         \
00400   }
00401 
00402 
00403 static GenericValue executeFCMP_UEQ(GenericValue Src1, GenericValue Src2,
00404                                    const Type *Ty) {
00405   GenericValue Dest;
00406   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00407   return executeFCMP_OEQ(Src1, Src2, Ty);
00408 }
00409 
00410 static GenericValue executeFCMP_UNE(GenericValue Src1, GenericValue Src2,
00411                                    const Type *Ty) {
00412   GenericValue Dest;
00413   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00414   return executeFCMP_ONE(Src1, Src2, Ty);
00415 }
00416 
00417 static GenericValue executeFCMP_ULE(GenericValue Src1, GenericValue Src2,
00418                                    const Type *Ty) {
00419   GenericValue Dest;
00420   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00421   return executeFCMP_OLE(Src1, Src2, Ty);
00422 }
00423 
00424 static GenericValue executeFCMP_UGE(GenericValue Src1, GenericValue Src2,
00425                                    const Type *Ty) {
00426   GenericValue Dest;
00427   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00428   return executeFCMP_OGE(Src1, Src2, Ty);
00429 }
00430 
00431 static GenericValue executeFCMP_ULT(GenericValue Src1, GenericValue Src2,
00432                                    const Type *Ty) {
00433   GenericValue Dest;
00434   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00435   return executeFCMP_OLT(Src1, Src2, Ty);
00436 }
00437 
00438 static GenericValue executeFCMP_UGT(GenericValue Src1, GenericValue Src2,
00439                                      const Type *Ty) {
00440   GenericValue Dest;
00441   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00442   return executeFCMP_OGT(Src1, Src2, Ty);
00443 }
00444 
00445 static GenericValue executeFCMP_ORD(GenericValue Src1, GenericValue Src2,
00446                                      const Type *Ty) {
00447   GenericValue Dest;
00448   if (Ty == Type::FloatTy)
00449     Dest.IntVal = APInt(1,(Src1.FloatVal == Src1.FloatVal && 
00450                            Src2.FloatVal == Src2.FloatVal));
00451   else
00452     Dest.IntVal = APInt(1,(Src1.DoubleVal == Src1.DoubleVal && 
00453                            Src2.DoubleVal == Src2.DoubleVal));
00454   return Dest;
00455 }
00456 
00457 static GenericValue executeFCMP_UNO(GenericValue Src1, GenericValue Src2,
00458                                      const Type *Ty) {
00459   GenericValue Dest;
00460   if (Ty == Type::FloatTy)
00461     Dest.IntVal = APInt(1,(Src1.FloatVal != Src1.FloatVal || 
00462                            Src2.FloatVal != Src2.FloatVal));
00463   else
00464     Dest.IntVal = APInt(1,(Src1.DoubleVal != Src1.DoubleVal || 
00465                            Src2.DoubleVal != Src2.DoubleVal));
00466   return Dest;
00467 }
00468 
00469 void Interpreter::visitFCmpInst(FCmpInst &I) {
00470   ExecutionContext &SF = ECStack.back();
00471   const Type *Ty    = I.getOperand(0)->getType();
00472   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
00473   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
00474   GenericValue R;   // Result
00475   
00476   switch (I.getPredicate()) {
00477   case FCmpInst::FCMP_FALSE: R.IntVal = APInt(1,false); break;
00478   case FCmpInst::FCMP_TRUE:  R.IntVal = APInt(1,true); break;
00479   case FCmpInst::FCMP_ORD:   R = executeFCMP_ORD(Src1, Src2, Ty); break;
00480   case FCmpInst::FCMP_UNO:   R = executeFCMP_UNO(Src1, Src2, Ty); break;
00481   case FCmpInst::FCMP_UEQ:   R = executeFCMP_UEQ(Src1, Src2, Ty); break;
00482   case FCmpInst::FCMP_OEQ:   R = executeFCMP_OEQ(Src1, Src2, Ty); break;
00483   case FCmpInst::FCMP_UNE:   R = executeFCMP_UNE(Src1, Src2, Ty); break;
00484   case FCmpInst::FCMP_ONE:   R = executeFCMP_ONE(Src1, Src2, Ty); break;
00485   case FCmpInst::FCMP_ULT:   R = executeFCMP_ULT(Src1, Src2, Ty); break;
00486   case FCmpInst::FCMP_OLT:   R = executeFCMP_OLT(Src1, Src2, Ty); break;
00487   case FCmpInst::FCMP_UGT:   R = executeFCMP_UGT(Src1, Src2, Ty); break;
00488   case FCmpInst::FCMP_OGT:   R = executeFCMP_OGT(Src1, Src2, Ty); break;
00489   case FCmpInst::FCMP_ULE:   R = executeFCMP_ULE(Src1, Src2, Ty); break;
00490   case FCmpInst::FCMP_OLE:   R = executeFCMP_OLE(Src1, Src2, Ty); break;
00491   case FCmpInst::FCMP_UGE:   R = executeFCMP_UGE(Src1, Src2, Ty); break;
00492   case FCmpInst::FCMP_OGE:   R = executeFCMP_OGE(Src1, Src2, Ty); break;
00493   default:
00494     cerr << "Don't know how to handle this FCmp predicate!\n-->" << I;
00495     abort();
00496   }
00497  
00498   SetValue(&I, R, SF);
00499 }
00500 
00501 static GenericValue executeCmpInst(unsigned predicate, GenericValue Src1, 
00502                                    GenericValue Src2, const Type *Ty) {
00503   GenericValue Result;
00504   switch (predicate) {
00505   case ICmpInst::ICMP_EQ:    return executeICMP_EQ(Src1, Src2, Ty);
00506   case ICmpInst::ICMP_NE:    return executeICMP_NE(Src1, Src2, Ty);
00507   case ICmpInst::ICMP_UGT:   return executeICMP_UGT(Src1, Src2, Ty);
00508   case ICmpInst::ICMP_SGT:   return executeICMP_SGT(Src1, Src2, Ty);
00509   case ICmpInst::ICMP_ULT:   return executeICMP_ULT(Src1, Src2, Ty);
00510   case ICmpInst::ICMP_SLT:   return executeICMP_SLT(Src1, Src2, Ty);
00511   case ICmpInst::ICMP_UGE:   return executeICMP_UGE(Src1, Src2, Ty);
00512   case ICmpInst::ICMP_SGE:   return executeICMP_SGE(Src1, Src2, Ty);
00513   case ICmpInst::ICMP_ULE:   return executeICMP_ULE(Src1, Src2, Ty);
00514   case ICmpInst::ICMP_SLE:   return executeICMP_SLE(Src1, Src2, Ty);
00515   case FCmpInst::FCMP_ORD:   return executeFCMP_ORD(Src1, Src2, Ty);
00516   case FCmpInst::FCMP_UNO:   return executeFCMP_UNO(Src1, Src2, Ty);
00517   case FCmpInst::FCMP_OEQ:   return executeFCMP_OEQ(Src1, Src2, Ty);
00518   case FCmpInst::FCMP_UEQ:   return executeFCMP_UEQ(Src1, Src2, Ty);
00519   case FCmpInst::FCMP_ONE:   return executeFCMP_ONE(Src1, Src2, Ty);
00520   case FCmpInst::FCMP_UNE:   return executeFCMP_UNE(Src1, Src2, Ty);
00521   case FCmpInst::FCMP_OLT:   return executeFCMP_OLT(Src1, Src2, Ty);
00522   case FCmpInst::FCMP_ULT:   return executeFCMP_ULT(Src1, Src2, Ty);
00523   case FCmpInst::FCMP_OGT:   return executeFCMP_OGT(Src1, Src2, Ty);
00524   case FCmpInst::FCMP_UGT:   return executeFCMP_UGT(Src1, Src2, Ty);
00525   case FCmpInst::FCMP_OLE:   return executeFCMP_OLE(Src1, Src2, Ty);
00526   case FCmpInst::FCMP_ULE:   return executeFCMP_ULE(Src1, Src2, Ty);
00527   case FCmpInst::FCMP_OGE:   return executeFCMP_OGE(Src1, Src2, Ty);
00528   case FCmpInst::FCMP_UGE:   return executeFCMP_UGE(Src1, Src2, Ty);
00529   case FCmpInst::FCMP_FALSE: { 
00530     GenericValue Result;
00531     Result.IntVal = APInt(1, false);
00532     return Result;
00533   }
00534   case FCmpInst::FCMP_TRUE: {
00535     GenericValue Result;
00536     Result.IntVal = APInt(1, true);
00537     return Result;
00538   }
00539   default:
00540     cerr << "Unhandled Cmp predicate\n";
00541     abort();
00542   }
00543 }
00544 
00545 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
00546   ExecutionContext &SF = ECStack.back();
00547   const Type *Ty    = I.getOperand(0)->getType();
00548   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
00549   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
00550   GenericValue R;   // Result
00551 
00552   switch (I.getOpcode()) {
00553   case Instruction::Add:   executeAddInst  (R, Src1, Src2, Ty); break;
00554   case Instruction::Sub:   executeSubInst  (R, Src1, Src2, Ty); break;
00555   case Instruction::Mul:   executeMulInst  (R, Src1, Src2, Ty); break;
00556   case Instruction::FDiv:  executeFDivInst (R, Src1, Src2, Ty); break;
00557   case Instruction::FRem:  executeFRemInst (R, Src1, Src2, Ty); break;
00558   case Instruction::UDiv:  R.IntVal = Src1.IntVal.udiv(Src2.IntVal); break;
00559   case Instruction::SDiv:  R.IntVal = Src1.IntVal.sdiv(Src2.IntVal); break;
00560   case Instruction::URem:  R.IntVal = Src1.IntVal.urem(Src2.IntVal); break;
00561   case Instruction::SRem:  R.IntVal = Src1.IntVal.srem(Src2.IntVal); break;
00562   case Instruction::And:   R.IntVal = Src1.IntVal & Src2.IntVal; break;
00563   case Instruction::Or:    R.IntVal = Src1.IntVal | Src2.IntVal; break;
00564   case Instruction::Xor:   R.IntVal = Src1.IntVal ^ Src2.IntVal; break;
00565   default:
00566     cerr << "Don't know how to handle this binary operator!\n-->" << I;
00567     abort();
00568   }
00569 
00570   SetValue(&I, R, SF);
00571 }
00572 
00573 static GenericValue executeSelectInst(GenericValue Src1, GenericValue Src2,
00574                                       GenericValue Src3) {
00575   return Src1.IntVal == 0 ? Src3 : Src2;
00576 }
00577 
00578 void Interpreter::visitSelectInst(SelectInst &I) {
00579   ExecutionContext &SF = ECStack.back();
00580   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
00581   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
00582   GenericValue Src3 = getOperandValue(I.getOperand(2), SF);
00583   GenericValue R = executeSelectInst(Src1, Src2, Src3);
00584   SetValue(&I, R, SF);
00585 }
00586 
00587 
00588 //===----------------------------------------------------------------------===//
00589 //                     Terminator Instruction Implementations
00590 //===----------------------------------------------------------------------===//
00591 
00592 void Interpreter::exitCalled(GenericValue GV) {
00593   // runAtExitHandlers() assumes there are no stack frames, but
00594   // if exit() was called, then it had a stack frame. Blow away
00595   // the stack before interpreting atexit handlers.
00596   ECStack.clear ();
00597   runAtExitHandlers ();
00598   exit (GV.IntVal.zextOrTrunc(32).getZExtValue());
00599 }
00600 
00601 /// Pop the last stack frame off of ECStack and then copy the result
00602 /// back into the result variable if we are not returning void. The
00603 /// result variable may be the ExitValue, or the Value of the calling
00604 /// CallInst if there was a previous stack frame. This method may
00605 /// invalidate any ECStack iterators you have. This method also takes
00606 /// care of switching to the normal destination BB, if we are returning
00607 /// from an invoke.
00608 ///
00609 void Interpreter::popStackAndReturnValueToCaller (const Type *RetTy,
00610                                                   GenericValue Result) {
00611   // Pop the current stack frame.
00612   ECStack.pop_back();
00613 
00614   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
00615     if (RetTy && RetTy->isInteger()) {          // Nonvoid return type?
00616       ExitValue = Result;   // Capture the exit value of the program
00617     } else {
00618       memset(&ExitValue.Untyped, 0, sizeof(ExitValue.Untyped));
00619     }
00620   } else {
00621     // If we have a previous stack frame, and we have a previous call,
00622     // fill in the return value...
00623     ExecutionContext &CallingSF = ECStack.back();
00624     if (Instruction *I = CallingSF.Caller.getInstruction()) {
00625       if (CallingSF.Caller.getType() != Type::VoidTy)      // Save result...
00626         SetValue(I, Result, CallingSF);
00627       if (InvokeInst *II = dyn_cast<InvokeInst> (I))
00628         SwitchToNewBasicBlock (II->getNormalDest (), CallingSF);
00629       CallingSF.Caller = CallSite();          // We returned from the call...
00630     }
00631   }
00632 }
00633 
00634 void Interpreter::visitReturnInst(ReturnInst &I) {
00635   ExecutionContext &SF = ECStack.back();
00636   const Type *RetTy = Type::VoidTy;
00637   GenericValue Result;
00638 
00639   // Save away the return value... (if we are not 'ret void')
00640   if (I.getNumOperands()) {
00641     RetTy  = I.getReturnValue()->getType();
00642     Result = getOperandValue(I.getReturnValue(), SF);
00643   }
00644 
00645   popStackAndReturnValueToCaller(RetTy, Result);
00646 }
00647 
00648 void Interpreter::visitUnwindInst(UnwindInst &I) {
00649   // Unwind stack
00650   Instruction *Inst;
00651   do {
00652     ECStack.pop_back ();
00653     if (ECStack.empty ())
00654       abort ();
00655     Inst = ECStack.back ().Caller.getInstruction ();
00656   } while (!(Inst && isa<InvokeInst> (Inst)));
00657 
00658   // Return from invoke
00659   ExecutionContext &InvokingSF = ECStack.back ();
00660   InvokingSF.Caller = CallSite ();
00661 
00662   // Go to exceptional destination BB of invoke instruction
00663   SwitchToNewBasicBlock(cast<InvokeInst>(Inst)->getUnwindDest(), InvokingSF);
00664 }
00665 
00666 void Interpreter::visitUnreachableInst(UnreachableInst &I) {
00667   cerr << "ERROR: Program executed an 'unreachable' instruction!\n";
00668   abort();
00669 }
00670 
00671 void Interpreter::visitBranchInst(BranchInst &I) {
00672   ExecutionContext &SF = ECStack.back();
00673   BasicBlock *Dest;
00674 
00675   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
00676   if (!I.isUnconditional()) {
00677     Value *Cond = I.getCondition();
00678     if (getOperandValue(Cond, SF).IntVal == 0) // If false cond...
00679       Dest = I.getSuccessor(1);
00680   }
00681   SwitchToNewBasicBlock(Dest, SF);
00682 }
00683 
00684 void Interpreter::visitSwitchInst(SwitchInst &I) {
00685   ExecutionContext &SF = ECStack.back();
00686   GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
00687   const Type *ElTy = I.getOperand(0)->getType();
00688 
00689   // Check to see if any of the cases match...
00690   BasicBlock *Dest = 0;
00691   for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
00692     if (executeICMP_EQ(CondVal, getOperandValue(I.getOperand(i), SF), ElTy)
00693         .IntVal != 0) {
00694       Dest = cast<BasicBlock>(I.getOperand(i+1));
00695       break;
00696     }
00697 
00698   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
00699   SwitchToNewBasicBlock(Dest, SF);
00700 }
00701 
00702 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
00703 // This function handles the actual updating of block and instruction iterators
00704 // as well as execution of all of the PHI nodes in the destination block.
00705 //
00706 // This method does this because all of the PHI nodes must be executed
00707 // atomically, reading their inputs before any of the results are updated.  Not
00708 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
00709 // their inputs.  If the input PHI node is updated before it is read, incorrect
00710 // results can happen.  Thus we use a two phase approach.
00711 //
00712 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
00713   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
00714   SF.CurBB   = Dest;                  // Update CurBB to branch destination
00715   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
00716 
00717   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
00718 
00719   // Loop over all of the PHI nodes in the current block, reading their inputs.
00720   std::vector<GenericValue> ResultValues;
00721 
00722   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
00723     // Search for the value corresponding to this previous bb...
00724     int i = PN->getBasicBlockIndex(PrevBB);
00725     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
00726     Value *IncomingValue = PN->getIncomingValue(i);
00727 
00728     // Save the incoming value for this PHI node...
00729     ResultValues.push_back(getOperandValue(IncomingValue, SF));
00730   }
00731 
00732   // Now loop over all of the PHI nodes setting their values...
00733   SF.CurInst = SF.CurBB->begin();
00734   for (unsigned i = 0; isa<PHINode>(SF.CurInst); ++SF.CurInst, ++i) {
00735     PHINode *PN = cast<PHINode>(SF.CurInst);
00736     SetValue(PN, ResultValues[i], SF);
00737   }
00738 }
00739 
00740 //===----------------------------------------------------------------------===//
00741 //                     Memory Instruction Implementations
00742 //===----------------------------------------------------------------------===//
00743 
00744 void Interpreter::visitAllocationInst(AllocationInst &I) {
00745   ExecutionContext &SF = ECStack.back();
00746 
00747   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
00748 
00749   // Get the number of elements being allocated by the array...
00750   unsigned NumElements = 
00751     getOperandValue(I.getOperand(0), SF).IntVal.getZExtValue();
00752 
00753   unsigned TypeSize = (size_t)TD.getTypePaddedSize(Ty);
00754 
00755   // Avoid malloc-ing zero bytes, use max()...
00756   unsigned MemToAlloc = std::max(1U, NumElements * TypeSize);
00757 
00758   // Allocate enough memory to hold the type...
00759   void *Memory = malloc(MemToAlloc);
00760 
00761   DOUT << "Allocated Type: " << *Ty << " (" << TypeSize << " bytes) x " 
00762        << NumElements << " (Total: " << MemToAlloc << ") at "
00763        << uintptr_t(Memory) << '\n';
00764 
00765   GenericValue Result = PTOGV(Memory);
00766   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
00767   SetValue(&I, Result, SF);
00768 
00769   if (I.getOpcode() == Instruction::Alloca)
00770     ECStack.back().Allocas.add(Memory);
00771 }
00772 
00773 void Interpreter::visitFreeInst(FreeInst &I) {
00774   ExecutionContext &SF = ECStack.back();
00775   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
00776   GenericValue Value = getOperandValue(I.getOperand(0), SF);
00777   // TODO: Check to make sure memory is allocated
00778   free(GVTOP(Value));   // Free memory
00779 }
00780 
00781 // getElementOffset - The workhorse for getelementptr.
00782 //
00783 GenericValue Interpreter::executeGEPOperation(Value *Ptr, gep_type_iterator I,
00784                                               gep_type_iterator E,
00785                                               ExecutionContext &SF) {
00786   assert(isa<PointerType>(Ptr->getType()) &&
00787          "Cannot getElementOffset of a nonpointer type!");
00788 
00789   uint64_t Total = 0;
00790 
00791   for (; I != E; ++I) {
00792     if (const StructType *STy = dyn_cast<StructType>(*I)) {
00793       const StructLayout *SLO = TD.getStructLayout(STy);
00794 
00795       const ConstantInt *CPU = cast<ConstantInt>(I.getOperand());
00796       unsigned Index = unsigned(CPU->getZExtValue());
00797 
00798       Total += SLO->getElementOffset(Index);
00799     } else {
00800       const SequentialType *ST = cast<SequentialType>(*I);
00801       // Get the index number for the array... which must be long type...
00802       GenericValue IdxGV = getOperandValue(I.getOperand(), SF);
00803 
00804       int64_t Idx;
00805       unsigned BitWidth = 
00806         cast<IntegerType>(I.getOperand()->getType())->getBitWidth();
00807       if (BitWidth == 32)
00808         Idx = (int64_t)(int32_t)IdxGV.IntVal.getZExtValue();
00809       else {
00810         assert(BitWidth == 64 && "Invalid index type for getelementptr");
00811         Idx = (int64_t)IdxGV.IntVal.getZExtValue();
00812       }
00813       Total += TD.getTypePaddedSize(ST->getElementType())*Idx;
00814     }
00815   }
00816 
00817   GenericValue Result;
00818   Result.PointerVal = ((char*)getOperandValue(Ptr, SF).PointerVal) + Total;
00819   DOUT << "GEP Index " << Total << " bytes.\n";
00820   return Result;
00821 }
00822 
00823 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
00824   ExecutionContext &SF = ECStack.back();
00825   SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
00826                                    gep_type_begin(I), gep_type_end(I), SF), SF);
00827 }
00828 
00829 void Interpreter::visitLoadInst(LoadInst &I) {
00830   ExecutionContext &SF = ECStack.back();
00831   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
00832   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
00833   GenericValue Result;
00834   LoadValueFromMemory(Result, Ptr, I.getType());
00835   SetValue(&I, Result, SF);
00836   if (I.isVolatile() && PrintVolatile)
00837     cerr << "Volatile load " << I;
00838 }
00839 
00840 void Interpreter::visitStoreInst(StoreInst &I) {
00841   ExecutionContext &SF = ECStack.back();
00842   GenericValue Val = getOperandValue(I.getOperand(0), SF);
00843   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
00844   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
00845                      I.getOperand(0)->getType());
00846   if (I.isVolatile() && PrintVolatile)
00847     cerr << "Volatile store: " << I;
00848 }
00849 
00850 //===----------------------------------------------------------------------===//
00851 //                 Miscellaneous Instruction Implementations
00852 //===----------------------------------------------------------------------===//
00853 
00854 void Interpreter::visitCallSite(CallSite CS) {
00855   ExecutionContext &SF = ECStack.back();
00856 
00857   // Check to see if this is an intrinsic function call...
00858   Function *F = CS.getCalledFunction();
00859   if (F && F->isDeclaration ())
00860     switch (F->getIntrinsicID()) {
00861     case Intrinsic::not_intrinsic:
00862       break;
00863     case Intrinsic::vastart: { // va_start
00864       GenericValue ArgIndex;
00865       ArgIndex.UIntPairVal.first = ECStack.size() - 1;
00866       ArgIndex.UIntPairVal.second = 0;
00867       SetValue(CS.getInstruction(), ArgIndex, SF);
00868       return;
00869     }
00870     case Intrinsic::vaend:    // va_end is a noop for the interpreter
00871       return;
00872     case Intrinsic::vacopy:   // va_copy: dest = src
00873       SetValue(CS.getInstruction(), getOperandValue(*CS.arg_begin(), SF), SF);
00874       return;
00875     default:
00876       // If it is an unknown intrinsic function, use the intrinsic lowering
00877       // class to transform it into hopefully tasty LLVM code.
00878       //
00879       BasicBlock::iterator me(CS.getInstruction());
00880       BasicBlock *Parent = CS.getInstruction()->getParent();
00881       bool atBegin(Parent->begin() == me);
00882       if (!atBegin)
00883         --me;
00884       IL->LowerIntrinsicCall(cast<CallInst>(CS.getInstruction()));
00885 
00886       // Restore the CurInst pointer to the first instruction newly inserted, if
00887       // any.
00888       if (atBegin) {
00889         SF.CurInst = Parent->begin();
00890       } else {
00891         SF.CurInst = me;
00892         ++SF.CurInst;
00893       }
00894       return;
00895     }
00896 
00897 
00898   SF.Caller = CS;
00899   std::vector<GenericValue> ArgVals;
00900   const unsigned NumArgs = SF.Caller.arg_size();
00901   ArgVals.reserve(NumArgs);
00902   uint16_t pNum = 1;
00903   for (CallSite::arg_iterator i = SF.Caller.arg_begin(),
00904          e = SF.Caller.arg_end(); i != e; ++i, ++pNum) {
00905     Value *V = *i;
00906     ArgVals.push_back(getOperandValue(V, SF));
00907     // Promote all integral types whose size is < sizeof(i32) into i32.
00908     // We do this by zero or sign extending the value as appropriate
00909     // according to the parameter attributes
00910     const Type *Ty = V->getType();
00911     if (Ty->isInteger() && (ArgVals.back().IntVal.getBitWidth() < 32)) {
00912       if (CS.paramHasAttr(pNum, Attribute::ZExt))
00913         ArgVals.back().IntVal = ArgVals.back().IntVal.zext(32);
00914       else if (CS.paramHasAttr(pNum, Attribute::SExt))
00915         ArgVals.back().IntVal = ArgVals.back().IntVal.sext(32);
00916     }
00917   }
00918 
00919   // To handle indirect calls, we must get the pointer value from the argument
00920   // and treat it as a function pointer.
00921   GenericValue SRC = getOperandValue(SF.Caller.getCalledValue(), SF);
00922   callFunction((Function*)GVTOP(SRC), ArgVals);
00923 }
00924 
00925 void Interpreter::visitShl(BinaryOperator &I) {
00926   ExecutionContext &SF = ECStack.back();
00927   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
00928   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
00929   GenericValue Dest;
00930   if (Src2.IntVal.getZExtValue() < Src1.IntVal.getBitWidth())
00931     Dest.IntVal = Src1.IntVal.shl(Src2.IntVal.getZExtValue());
00932   else
00933     Dest.IntVal = Src1.IntVal;
00934   
00935   SetValue(&I, Dest, SF);
00936 }
00937 
00938 void Interpreter::visitLShr(BinaryOperator &I) {
00939   ExecutionContext &SF = ECStack.back();
00940   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
00941   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
00942   GenericValue Dest;
00943   if (Src2.IntVal.getZExtValue() < Src1.IntVal.getBitWidth())
00944     Dest.IntVal = Src1.IntVal.lshr(Src2.IntVal.getZExtValue());
00945   else
00946     Dest.IntVal = Src1.IntVal;
00947   
00948   SetValue(&I, Dest, SF);
00949 }
00950 
00951 void Interpreter::visitAShr(BinaryOperator &I) {
00952   ExecutionContext &SF = ECStack.back();
00953   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
00954   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
00955   GenericValue Dest;
00956   if (Src2.IntVal.getZExtValue() < Src1.IntVal.getBitWidth())
00957     Dest.IntVal = Src1.IntVal.ashr(Src2.IntVal.getZExtValue());
00958   else
00959     Dest.IntVal = Src1.IntVal;
00960   
00961   SetValue(&I, Dest, SF);
00962 }
00963 
00964 GenericValue Interpreter::executeTruncInst(Value *SrcVal, const Type *DstTy,
00965                                            ExecutionContext &SF) {
00966   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
00967   const IntegerType *DITy = cast<IntegerType>(DstTy);
00968   unsigned DBitWidth = DITy->getBitWidth();
00969   Dest.IntVal = Src.IntVal.trunc(DBitWidth);
00970   return Dest;
00971 }
00972 
00973 GenericValue Interpreter::executeSExtInst(Value *SrcVal, const Type *DstTy,
00974                                           ExecutionContext &SF) {
00975   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
00976   const IntegerType *DITy = cast<IntegerType>(DstTy);
00977   unsigned DBitWidth = DITy->getBitWidth();
00978   Dest.IntVal = Src.IntVal.sext(DBitWidth);
00979   return Dest;
00980 }
00981 
00982 GenericValue Interpreter::executeZExtInst(Value *SrcVal, const Type *DstTy,
00983                                           ExecutionContext &SF) {
00984   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
00985   const IntegerType *DITy = cast<IntegerType>(DstTy);
00986   unsigned DBitWidth = DITy->getBitWidth();
00987   Dest.IntVal = Src.IntVal.zext(DBitWidth);
00988   return Dest;
00989 }
00990 
00991 GenericValue Interpreter::executeFPTruncInst(Value *SrcVal, const Type *DstTy,
00992                                              ExecutionContext &SF) {
00993   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
00994   assert(SrcVal->getType() == Type::DoubleTy && DstTy == Type::FloatTy &&
00995          "Invalid FPTrunc instruction");
00996   Dest.FloatVal = (float) Src.DoubleVal;
00997   return Dest;
00998 }
00999 
01000 GenericValue Interpreter::executeFPExtInst(Value *SrcVal, const Type *DstTy,
01001                                            ExecutionContext &SF) {
01002   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01003   assert(SrcVal->getType() == Type::FloatTy && DstTy == Type::DoubleTy &&
01004          "Invalid FPTrunc instruction");
01005   Dest.DoubleVal = (double) Src.FloatVal;
01006   return Dest;
01007 }
01008 
01009 GenericValue Interpreter::executeFPToUIInst(Value *SrcVal, const Type *DstTy,
01010                                             ExecutionContext &SF) {
01011   const Type *SrcTy = SrcVal->getType();
01012   uint32_t DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
01013   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01014   assert(SrcTy->isFloatingPoint() && "Invalid FPToUI instruction");
01015 
01016   if (SrcTy->getTypeID() == Type::FloatTyID)
01017     Dest.IntVal = APIntOps::RoundFloatToAPInt(Src.FloatVal, DBitWidth);
01018   else
01019     Dest.IntVal = APIntOps::RoundDoubleToAPInt(Src.DoubleVal, DBitWidth);
01020   return Dest;
01021 }
01022 
01023 GenericValue Interpreter::executeFPToSIInst(Value *SrcVal, const Type *DstTy,
01024                                             ExecutionContext &SF) {
01025   const Type *SrcTy = SrcVal->getType();
01026   uint32_t DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
01027   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01028   assert(SrcTy->isFloatingPoint() && "Invalid FPToSI instruction");
01029 
01030   if (SrcTy->getTypeID() == Type::FloatTyID)
01031     Dest.IntVal = APIntOps::RoundFloatToAPInt(Src.FloatVal, DBitWidth);
01032   else
01033     Dest.IntVal = APIntOps::RoundDoubleToAPInt(Src.DoubleVal, DBitWidth);
01034   return Dest;
01035 }
01036 
01037 GenericValue Interpreter::executeUIToFPInst(Value *SrcVal, const Type *DstTy,
01038                                             ExecutionContext &SF) {
01039   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01040   assert(DstTy->isFloatingPoint() && "Invalid UIToFP instruction");
01041 
01042   if (DstTy->getTypeID() == Type::FloatTyID)
01043     Dest.FloatVal = APIntOps::RoundAPIntToFloat(Src.IntVal);
01044   else
01045     Dest.DoubleVal = APIntOps::RoundAPIntToDouble(Src.IntVal);
01046   return Dest;
01047 }
01048 
01049 GenericValue Interpreter::executeSIToFPInst(Value *SrcVal, const Type *DstTy,
01050                                             ExecutionContext &SF) {
01051   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01052   assert(DstTy->isFloatingPoint() && "Invalid SIToFP instruction");
01053 
01054   if (DstTy->getTypeID() == Type::FloatTyID)
01055     Dest.FloatVal = APIntOps::RoundSignedAPIntToFloat(Src.IntVal);
01056   else
01057     Dest.DoubleVal = APIntOps::RoundSignedAPIntToDouble(Src.IntVal);
01058   return Dest;
01059 
01060 }
01061 
01062 GenericValue Interpreter::executePtrToIntInst(Value *SrcVal, const Type *DstTy,
01063                                               ExecutionContext &SF) {
01064   uint32_t DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
01065   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01066   assert(isa<PointerType>(SrcVal->getType()) && "Invalid PtrToInt instruction");
01067 
01068   Dest.IntVal = APInt(DBitWidth, (intptr_t) Src.PointerVal);
01069   return Dest;
01070 }
01071 
01072 GenericValue Interpreter::executeIntToPtrInst(Value *SrcVal, const Type *DstTy,
01073                                               ExecutionContext &SF) {
01074   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01075   assert(isa<PointerType>(DstTy) && "Invalid PtrToInt instruction");
01076 
01077   uint32_t PtrSize = TD.getPointerSizeInBits();
01078   if (PtrSize != Src.IntVal.getBitWidth())
01079     Src.IntVal = Src.IntVal.zextOrTrunc(PtrSize);
01080 
01081   Dest.PointerVal = PointerTy(intptr_t(Src.IntVal.getZExtValue()));
01082   return Dest;
01083 }
01084 
01085 GenericValue Interpreter::executeBitCastInst(Value *SrcVal, const Type *DstTy,
01086                                              ExecutionContext &SF) {
01087   
01088   const Type *SrcTy = SrcVal->getType();
01089   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01090   if (isa<PointerType>(DstTy)) {
01091     assert(isa<PointerType>(SrcTy) && "Invalid BitCast");
01092     Dest.PointerVal = Src.PointerVal;
01093   } else if (DstTy->isInteger()) {
01094     if (SrcTy == Type::FloatTy) {
01095       Dest.IntVal.zext(sizeof(Src.FloatVal) * 8);
01096       Dest.IntVal.floatToBits(Src.FloatVal);
01097     } else if (SrcTy == Type::DoubleTy) {
01098       Dest.IntVal.zext(sizeof(Src.DoubleVal) * 8);
01099       Dest.IntVal.doubleToBits(Src.DoubleVal);
01100     } else if (SrcTy->isInteger()) {
01101       Dest.IntVal = Src.IntVal;
01102     } else 
01103       assert(0 && "Invalid BitCast");
01104   } else if (DstTy == Type::FloatTy) {
01105     if (SrcTy->isInteger())
01106       Dest.FloatVal = Src.IntVal.bitsToFloat();
01107     else
01108       Dest.FloatVal = Src.FloatVal;
01109   } else if (DstTy == Type::DoubleTy) {
01110     if (SrcTy->isInteger())
01111       Dest.DoubleVal = Src.IntVal.bitsToDouble();
01112     else
01113       Dest.DoubleVal = Src.DoubleVal;
01114   } else
01115     assert(0 && "Invalid Bitcast");
01116 
01117   return Dest;
01118 }
01119 
01120 void Interpreter::visitTruncInst(TruncInst &I) {
01121   ExecutionContext &SF = ECStack.back();
01122   SetValue(&I, executeTruncInst(I.getOperand(0), I.getType(), SF), SF);
01123 }
01124 
01125 void Interpreter::visitSExtInst(SExtInst &I) {
01126   ExecutionContext &SF = ECStack.back();
01127   SetValue(&I, executeSExtInst(I.getOperand(0), I.getType(), SF), SF);
01128 }
01129 
01130 void Interpreter::visitZExtInst(ZExtInst &I) {
01131   ExecutionContext &SF = ECStack.back();
01132   SetValue(&I, executeZExtInst(I.getOperand(0), I.getType(), SF), SF);
01133 }
01134 
01135 void Interpreter::visitFPTruncInst(FPTruncInst &I) {
01136   ExecutionContext &SF = ECStack.back();
01137   SetValue(&I, executeFPTruncInst(I.getOperand(0), I.getType(), SF), SF);
01138 }
01139 
01140 void Interpreter::visitFPExtInst(FPExtInst &I) {
01141   ExecutionContext &SF = ECStack.back();
01142   SetValue(&I, executeFPExtInst(I.getOperand(0), I.getType(), SF), SF);
01143 }
01144 
01145 void Interpreter::visitUIToFPInst(UIToFPInst &I) {
01146   ExecutionContext &SF = ECStack.back();
01147   SetValue(&I, executeUIToFPInst(I.getOperand(0), I.getType(), SF), SF);
01148 }
01149 
01150 void Interpreter::visitSIToFPInst(SIToFPInst &I) {
01151   ExecutionContext &SF = ECStack.back();
01152   SetValue(&I, executeSIToFPInst(I.getOperand(0), I.getType(), SF), SF);
01153 }
01154 
01155 void Interpreter::visitFPToUIInst(FPToUIInst &I) {
01156   ExecutionContext &SF = ECStack.back();
01157   SetValue(&I, executeFPToUIInst(I.getOperand(0), I.getType(), SF), SF);
01158 }
01159 
01160 void Interpreter::visitFPToSIInst(FPToSIInst &I) {
01161   ExecutionContext &SF = ECStack.back();
01162   SetValue(&I, executeFPToSIInst(I.getOperand(0), I.getType(), SF), SF);
01163 }
01164 
01165 void Interpreter::visitPtrToIntInst(PtrToIntInst &I) {
01166   ExecutionContext &SF = ECStack.back();
01167   SetValue(&I, executePtrToIntInst(I.getOperand(0), I.getType(), SF), SF);
01168 }
01169 
01170 void Interpreter::visitIntToPtrInst(IntToPtrInst &I) {
01171   ExecutionContext &SF = ECStack.back();
01172   SetValue(&I, executeIntToPtrInst(I.getOperand(0), I.getType(), SF), SF);
01173 }
01174 
01175 void Interpreter::visitBitCastInst(BitCastInst &I) {
01176   ExecutionContext &SF = ECStack.back();
01177   SetValue(&I, executeBitCastInst(I.getOperand(0), I.getType(), SF), SF);
01178 }
01179 
01180 #define IMPLEMENT_VAARG(TY) \
01181    case Type::TY##TyID: Dest.TY##Val = Src.TY##Val; break
01182 
01183 void Interpreter::visitVAArgInst(VAArgInst &I) {
01184   ExecutionContext &SF = ECStack.back();
01185 
01186   // Get the incoming valist parameter.  LLI treats the valist as a
01187   // (ec-stack-depth var-arg-index) pair.
01188   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
01189   GenericValue Dest;
01190   GenericValue Src = ECStack[VAList.UIntPairVal.first]
01191                       .VarArgs[VAList.UIntPairVal.second];
01192   const Type *Ty = I.getType();
01193   switch (Ty->getTypeID()) {
01194     case Type::IntegerTyID: Dest.IntVal = Src.IntVal;
01195     IMPLEMENT_VAARG(Pointer);
01196     IMPLEMENT_VAARG(Float);
01197     IMPLEMENT_VAARG(Double);
01198   default:
01199     cerr << "Unhandled dest type for vaarg instruction: " << *Ty << "\n";
01200     abort();
01201   }
01202 
01203   // Set the Value of this Instruction.
01204   SetValue(&I, Dest, SF);
01205 
01206   // Move the pointer to the next vararg.
01207   ++VAList.UIntPairVal.second;
01208 }
01209 
01210 GenericValue Interpreter::getConstantExprValue (ConstantExpr *CE,
01211                                                 ExecutionContext &SF) {
01212   switch (CE->getOpcode()) {
01213   case Instruction::Trunc:   
01214       return executeTruncInst(CE->getOperand(0), CE->getType(), SF);
01215   case Instruction::ZExt:
01216       return executeZExtInst(CE->getOperand(0), CE->getType(), SF);
01217   case Instruction::SExt:
01218       return executeSExtInst(CE->getOperand(0), CE->getType(), SF);
01219   case Instruction::FPTrunc:
01220       return executeFPTruncInst(CE->getOperand(0), CE->getType(), SF);
01221   case Instruction::FPExt:
01222       return executeFPExtInst(CE->getOperand(0), CE->getType(), SF);
01223   case Instruction::UIToFP:
01224       return executeUIToFPInst(CE->getOperand(0), CE->getType(), SF);
01225   case Instruction::SIToFP:
01226       return executeSIToFPInst(CE->getOperand(0), CE->getType(), SF);
01227   case Instruction::FPToUI:
01228       return executeFPToUIInst(CE->getOperand(0), CE->getType(), SF);
01229   case Instruction::FPToSI:
01230       return executeFPToSIInst(CE->getOperand(0), CE->getType(), SF);
01231   case Instruction::PtrToInt:
01232       return executePtrToIntInst(CE->getOperand(0), CE->getType(), SF);
01233   case Instruction::IntToPtr:
01234       return executeIntToPtrInst(CE->getOperand(0), CE->getType(), SF);
01235   case Instruction::BitCast:
01236       return executeBitCastInst(CE->getOperand(0), CE->getType(), SF);
01237   case Instruction::GetElementPtr:
01238     return executeGEPOperation(CE->getOperand(0), gep_type_begin(CE),
01239                                gep_type_end(CE), SF);
01240   case Instruction::FCmp:
01241   case Instruction::ICmp:
01242     return executeCmpInst(CE->getPredicate(),
01243                           getOperandValue(CE->getOperand(0), SF),
01244                           getOperandValue(CE->getOperand(1), SF),
01245                           CE->getOperand(0)->getType());
01246   case Instruction::Select:
01247     return executeSelectInst(getOperandValue(CE->getOperand(0), SF),
01248                              getOperandValue(CE->getOperand(1), SF),
01249                              getOperandValue(CE->getOperand(2), SF));
01250   default :
01251     break;
01252   }
01253 
01254   // The cases below here require a GenericValue parameter for the result
01255   // so we initialize one, compute it and then return it.
01256   GenericValue Op0 = getOperandValue(CE->getOperand(0), SF);
01257   GenericValue Op1 = getOperandValue(CE->getOperand(1), SF);
01258   GenericValue Dest;
01259   const Type * Ty = CE->getOperand(0)->getType();
01260   switch (CE->getOpcode()) {
01261   case Instruction::Add:  executeAddInst (Dest, Op0, Op1, Ty); break;
01262   case Instruction::Sub:  executeSubInst (Dest, Op0, Op1, Ty); break;
01263   case Instruction::Mul:  executeMulInst (Dest, Op0, Op1, Ty); break;
01264   case Instruction::FDiv: executeFDivInst(Dest, Op0, Op1, Ty); break;
01265   case Instruction::FRem: executeFRemInst(Dest, Op0, Op1, Ty); break;
01266   case Instruction::SDiv: Dest.IntVal = Op0.IntVal.sdiv(Op1.IntVal); break;
01267   case Instruction::UDiv: Dest.IntVal = Op0.IntVal.udiv(Op1.IntVal); break;
01268   case Instruction::URem: Dest.IntVal = Op0.IntVal.urem(Op1.IntVal); break;
01269   case Instruction::SRem: Dest.IntVal = Op0.IntVal.srem(Op1.IntVal); break;
01270   case Instruction::And:  Dest.IntVal = Op0.IntVal.And(Op1.IntVal); break;
01271   case Instruction::Or:   Dest.IntVal = Op0.IntVal.Or(Op1.IntVal); break;
01272   case Instruction::Xor:  Dest.IntVal = Op0.IntVal.Xor(Op1.IntVal); break;
01273   case Instruction::Shl:  
01274     Dest.IntVal = Op0.IntVal.shl(Op1.IntVal.getZExtValue());
01275     break;
01276   case Instruction::LShr: 
01277     Dest.IntVal = Op0.IntVal.lshr(Op1.IntVal.getZExtValue());
01278     break;
01279   case Instruction::AShr: 
01280     Dest.IntVal = Op0.IntVal.ashr(Op1.IntVal.getZExtValue());
01281     break;
01282   default:
01283     cerr << "Unhandled ConstantExpr: " << *CE << "\n";
01284     abort();
01285     return GenericValue();
01286   }
01287   return Dest;
01288 }
01289 
01290 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
01291   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
01292     return getConstantExprValue(CE, SF);
01293   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
01294     return getConstantValue(CPV);
01295   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
01296     return PTOGV(getPointerToGlobal(GV));
01297   } else {
01298     return SF.Values[V];
01299   }
01300 }
01301 
01302 //===----------------------------------------------------------------------===//
01303 //                        Dispatch and Execution Code
01304 //===----------------------------------------------------------------------===//
01305 
01306 //===----------------------------------------------------------------------===//
01307 // callFunction - Execute the specified function...
01308 //
01309 void Interpreter::callFunction(Function *F,
01310                                const std::vector<GenericValue> &ArgVals) {
01311   assert((ECStack.empty() || ECStack.back().Caller.getInstruction() == 0 ||
01312           ECStack.back().Caller.arg_size() == ArgVals.size()) &&
01313          "Incorrect number of arguments passed into function call!");
01314   // Make a new stack frame... and fill it in.
01315   ECStack.push_back(ExecutionContext());
01316   ExecutionContext &StackFrame = ECStack.back();
01317   StackFrame.CurFunction = F;
01318 
01319   // Special handling for external functions.
01320   if (F->isDeclaration()) {
01321     GenericValue Result = callExternalFunction (F, ArgVals);
01322     // Simulate a 'ret' instruction of the appropriate type.
01323     popStackAndReturnValueToCaller (F->getReturnType (), Result);
01324     return;
01325   }
01326 
01327   // Get pointers to first LLVM BB & Instruction in function.
01328   StackFrame.CurBB     = F->begin();
01329   StackFrame.CurInst   = StackFrame.CurBB->begin();
01330 
01331   // Run through the function arguments and initialize their values...
01332   assert((ArgVals.size() == F->arg_size() ||
01333          (ArgVals.size() > F->arg_size() && F->getFunctionType()->isVarArg()))&&
01334          "Invalid number of values passed to function invocation!");
01335 
01336   // Handle non-varargs arguments...
01337   unsigned i = 0;
01338   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 
01339        AI != E; ++AI, ++i)
01340     SetValue(AI, ArgVals[i], StackFrame);
01341 
01342   // Handle varargs arguments...
01343   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
01344 }
01345 
01346 
01347 void Interpreter::run() {
01348   while (!ECStack.empty()) {
01349     // Interpret a single instruction & increment the "PC".
01350     ExecutionContext &SF = ECStack.back();  // Current stack frame
01351     Instruction &I = *SF.CurInst++;         // Increment before execute
01352 
01353     // Track the number of dynamic instructions executed.
01354     ++NumDynamicInsts;
01355 
01356     DOUT << "About to interpret: " << I;
01357     visit(I);   // Dispatch to one of the visit* methods...
01358 #if 0
01359     // This is not safe, as visiting the instruction could lower it and free I.
01360 #ifndef NDEBUG
01361     if (!isa<CallInst>(I) && !isa<InvokeInst>(I) && 
01362         I.getType() != Type::VoidTy) {
01363       DOUT << "  --> ";
01364       const GenericValue &Val = SF.Values[&I];
01365       switch (I.getType()->getTypeID()) {
01366       default: assert(0 && "Invalid GenericValue Type");
01367       case Type::VoidTyID:    DOUT << "void"; break;
01368       case Type::FloatTyID:   DOUT << "float " << Val.FloatVal; break;
01369       case Type::DoubleTyID:  DOUT << "double " << Val.DoubleVal; break;
01370       case Type::PointerTyID: DOUT << "void* " << intptr_t(Val.PointerVal);
01371         break;
01372       case Type::IntegerTyID: 
01373         DOUT << "i" << Val.IntVal.getBitWidth() << " "
01374         << Val.IntVal.toStringUnsigned(10)
01375         << " (0x" << Val.IntVal.toStringUnsigned(16) << ")\n";
01376         break;
01377       }
01378     }
01379 #endif
01380 #endif
01381   }
01382 }