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