LLVM  mainline
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 #include "Interpreter.h"
00015 #include "llvm/ADT/APInt.h"
00016 #include "llvm/ADT/Statistic.h"
00017 #include "llvm/CodeGen/IntrinsicLowering.h"
00018 #include "llvm/IR/Constants.h"
00019 #include "llvm/IR/DerivedTypes.h"
00020 #include "llvm/IR/GetElementPtrTypeIterator.h"
00021 #include "llvm/IR/Instructions.h"
00022 #include "llvm/Support/CommandLine.h"
00023 #include "llvm/Support/Debug.h"
00024 #include "llvm/Support/ErrorHandling.h"
00025 #include "llvm/Support/MathExtras.h"
00026 #include "llvm/Support/raw_ostream.h"
00027 #include <algorithm>
00028 #include <cmath>
00029 using namespace llvm;
00030 
00031 #define DEBUG_TYPE "interpreter"
00032 
00033 STATISTIC(NumDynamicInsts, "Number of dynamic instructions executed");
00034 
00035 static cl::opt<bool> PrintVolatile("interpreter-print-volatile", cl::Hidden,
00036           cl::desc("make the interpreter print every volatile load and store"));
00037 
00038 //===----------------------------------------------------------------------===//
00039 //                     Various Helper Functions
00040 //===----------------------------------------------------------------------===//
00041 
00042 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
00043   SF.Values[V] = Val;
00044 }
00045 
00046 //===----------------------------------------------------------------------===//
00047 //                    Binary Instruction Implementations
00048 //===----------------------------------------------------------------------===//
00049 
00050 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
00051    case Type::TY##TyID: \
00052      Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; \
00053      break
00054 
00055 static void executeFAddInst(GenericValue &Dest, GenericValue Src1,
00056                             GenericValue Src2, Type *Ty) {
00057   switch (Ty->getTypeID()) {
00058     IMPLEMENT_BINARY_OPERATOR(+, Float);
00059     IMPLEMENT_BINARY_OPERATOR(+, Double);
00060   default:
00061     dbgs() << "Unhandled type for FAdd instruction: " << *Ty << "\n";
00062     llvm_unreachable(nullptr);
00063   }
00064 }
00065 
00066 static void executeFSubInst(GenericValue &Dest, GenericValue Src1,
00067                             GenericValue Src2, Type *Ty) {
00068   switch (Ty->getTypeID()) {
00069     IMPLEMENT_BINARY_OPERATOR(-, Float);
00070     IMPLEMENT_BINARY_OPERATOR(-, Double);
00071   default:
00072     dbgs() << "Unhandled type for FSub instruction: " << *Ty << "\n";
00073     llvm_unreachable(nullptr);
00074   }
00075 }
00076 
00077 static void executeFMulInst(GenericValue &Dest, GenericValue Src1,
00078                             GenericValue Src2, Type *Ty) {
00079   switch (Ty->getTypeID()) {
00080     IMPLEMENT_BINARY_OPERATOR(*, Float);
00081     IMPLEMENT_BINARY_OPERATOR(*, Double);
00082   default:
00083     dbgs() << "Unhandled type for FMul instruction: " << *Ty << "\n";
00084     llvm_unreachable(nullptr);
00085   }
00086 }
00087 
00088 static void executeFDivInst(GenericValue &Dest, GenericValue Src1, 
00089                             GenericValue Src2, Type *Ty) {
00090   switch (Ty->getTypeID()) {
00091     IMPLEMENT_BINARY_OPERATOR(/, Float);
00092     IMPLEMENT_BINARY_OPERATOR(/, Double);
00093   default:
00094     dbgs() << "Unhandled type for FDiv instruction: " << *Ty << "\n";
00095     llvm_unreachable(nullptr);
00096   }
00097 }
00098 
00099 static void executeFRemInst(GenericValue &Dest, GenericValue Src1, 
00100                             GenericValue Src2, Type *Ty) {
00101   switch (Ty->getTypeID()) {
00102   case Type::FloatTyID:
00103     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
00104     break;
00105   case Type::DoubleTyID:
00106     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
00107     break;
00108   default:
00109     dbgs() << "Unhandled type for Rem instruction: " << *Ty << "\n";
00110     llvm_unreachable(nullptr);
00111   }
00112 }
00113 
00114 #define IMPLEMENT_INTEGER_ICMP(OP, TY) \
00115    case Type::IntegerTyID:  \
00116       Dest.IntVal = APInt(1,Src1.IntVal.OP(Src2.IntVal)); \
00117       break;
00118 
00119 #define IMPLEMENT_VECTOR_INTEGER_ICMP(OP, TY)                        \
00120   case Type::VectorTyID: {                                           \
00121     assert(Src1.AggregateVal.size() == Src2.AggregateVal.size());    \
00122     Dest.AggregateVal.resize( Src1.AggregateVal.size() );            \
00123     for( uint32_t _i=0;_i<Src1.AggregateVal.size();_i++)             \
00124       Dest.AggregateVal[_i].IntVal = APInt(1,                        \
00125       Src1.AggregateVal[_i].IntVal.OP(Src2.AggregateVal[_i].IntVal));\
00126   } break;
00127 
00128 // Handle pointers specially because they must be compared with only as much
00129 // width as the host has.  We _do not_ want to be comparing 64 bit values when
00130 // running on a 32-bit target, otherwise the upper 32 bits might mess up
00131 // comparisons if they contain garbage.
00132 #define IMPLEMENT_POINTER_ICMP(OP) \
00133    case Type::PointerTyID: \
00134       Dest.IntVal = APInt(1,(void*)(intptr_t)Src1.PointerVal OP \
00135                             (void*)(intptr_t)Src2.PointerVal); \
00136       break;
00137 
00138 static GenericValue executeICMP_EQ(GenericValue Src1, GenericValue Src2,
00139                                    Type *Ty) {
00140   GenericValue Dest;
00141   switch (Ty->getTypeID()) {
00142     IMPLEMENT_INTEGER_ICMP(eq,Ty);
00143     IMPLEMENT_VECTOR_INTEGER_ICMP(eq,Ty);
00144     IMPLEMENT_POINTER_ICMP(==);
00145   default:
00146     dbgs() << "Unhandled type for ICMP_EQ predicate: " << *Ty << "\n";
00147     llvm_unreachable(nullptr);
00148   }
00149   return Dest;
00150 }
00151 
00152 static GenericValue executeICMP_NE(GenericValue Src1, GenericValue Src2,
00153                                    Type *Ty) {
00154   GenericValue Dest;
00155   switch (Ty->getTypeID()) {
00156     IMPLEMENT_INTEGER_ICMP(ne,Ty);
00157     IMPLEMENT_VECTOR_INTEGER_ICMP(ne,Ty);
00158     IMPLEMENT_POINTER_ICMP(!=);
00159   default:
00160     dbgs() << "Unhandled type for ICMP_NE predicate: " << *Ty << "\n";
00161     llvm_unreachable(nullptr);
00162   }
00163   return Dest;
00164 }
00165 
00166 static GenericValue executeICMP_ULT(GenericValue Src1, GenericValue Src2,
00167                                     Type *Ty) {
00168   GenericValue Dest;
00169   switch (Ty->getTypeID()) {
00170     IMPLEMENT_INTEGER_ICMP(ult,Ty);
00171     IMPLEMENT_VECTOR_INTEGER_ICMP(ult,Ty);
00172     IMPLEMENT_POINTER_ICMP(<);
00173   default:
00174     dbgs() << "Unhandled type for ICMP_ULT predicate: " << *Ty << "\n";
00175     llvm_unreachable(nullptr);
00176   }
00177   return Dest;
00178 }
00179 
00180 static GenericValue executeICMP_SLT(GenericValue Src1, GenericValue Src2,
00181                                     Type *Ty) {
00182   GenericValue Dest;
00183   switch (Ty->getTypeID()) {
00184     IMPLEMENT_INTEGER_ICMP(slt,Ty);
00185     IMPLEMENT_VECTOR_INTEGER_ICMP(slt,Ty);
00186     IMPLEMENT_POINTER_ICMP(<);
00187   default:
00188     dbgs() << "Unhandled type for ICMP_SLT predicate: " << *Ty << "\n";
00189     llvm_unreachable(nullptr);
00190   }
00191   return Dest;
00192 }
00193 
00194 static GenericValue executeICMP_UGT(GenericValue Src1, GenericValue Src2,
00195                                     Type *Ty) {
00196   GenericValue Dest;
00197   switch (Ty->getTypeID()) {
00198     IMPLEMENT_INTEGER_ICMP(ugt,Ty);
00199     IMPLEMENT_VECTOR_INTEGER_ICMP(ugt,Ty);
00200     IMPLEMENT_POINTER_ICMP(>);
00201   default:
00202     dbgs() << "Unhandled type for ICMP_UGT predicate: " << *Ty << "\n";
00203     llvm_unreachable(nullptr);
00204   }
00205   return Dest;
00206 }
00207 
00208 static GenericValue executeICMP_SGT(GenericValue Src1, GenericValue Src2,
00209                                     Type *Ty) {
00210   GenericValue Dest;
00211   switch (Ty->getTypeID()) {
00212     IMPLEMENT_INTEGER_ICMP(sgt,Ty);
00213     IMPLEMENT_VECTOR_INTEGER_ICMP(sgt,Ty);
00214     IMPLEMENT_POINTER_ICMP(>);
00215   default:
00216     dbgs() << "Unhandled type for ICMP_SGT predicate: " << *Ty << "\n";
00217     llvm_unreachable(nullptr);
00218   }
00219   return Dest;
00220 }
00221 
00222 static GenericValue executeICMP_ULE(GenericValue Src1, GenericValue Src2,
00223                                     Type *Ty) {
00224   GenericValue Dest;
00225   switch (Ty->getTypeID()) {
00226     IMPLEMENT_INTEGER_ICMP(ule,Ty);
00227     IMPLEMENT_VECTOR_INTEGER_ICMP(ule,Ty);
00228     IMPLEMENT_POINTER_ICMP(<=);
00229   default:
00230     dbgs() << "Unhandled type for ICMP_ULE predicate: " << *Ty << "\n";
00231     llvm_unreachable(nullptr);
00232   }
00233   return Dest;
00234 }
00235 
00236 static GenericValue executeICMP_SLE(GenericValue Src1, GenericValue Src2,
00237                                     Type *Ty) {
00238   GenericValue Dest;
00239   switch (Ty->getTypeID()) {
00240     IMPLEMENT_INTEGER_ICMP(sle,Ty);
00241     IMPLEMENT_VECTOR_INTEGER_ICMP(sle,Ty);
00242     IMPLEMENT_POINTER_ICMP(<=);
00243   default:
00244     dbgs() << "Unhandled type for ICMP_SLE predicate: " << *Ty << "\n";
00245     llvm_unreachable(nullptr);
00246   }
00247   return Dest;
00248 }
00249 
00250 static GenericValue executeICMP_UGE(GenericValue Src1, GenericValue Src2,
00251                                     Type *Ty) {
00252   GenericValue Dest;
00253   switch (Ty->getTypeID()) {
00254     IMPLEMENT_INTEGER_ICMP(uge,Ty);
00255     IMPLEMENT_VECTOR_INTEGER_ICMP(uge,Ty);
00256     IMPLEMENT_POINTER_ICMP(>=);
00257   default:
00258     dbgs() << "Unhandled type for ICMP_UGE predicate: " << *Ty << "\n";
00259     llvm_unreachable(nullptr);
00260   }
00261   return Dest;
00262 }
00263 
00264 static GenericValue executeICMP_SGE(GenericValue Src1, GenericValue Src2,
00265                                     Type *Ty) {
00266   GenericValue Dest;
00267   switch (Ty->getTypeID()) {
00268     IMPLEMENT_INTEGER_ICMP(sge,Ty);
00269     IMPLEMENT_VECTOR_INTEGER_ICMP(sge,Ty);
00270     IMPLEMENT_POINTER_ICMP(>=);
00271   default:
00272     dbgs() << "Unhandled type for ICMP_SGE predicate: " << *Ty << "\n";
00273     llvm_unreachable(nullptr);
00274   }
00275   return Dest;
00276 }
00277 
00278 void Interpreter::visitICmpInst(ICmpInst &I) {
00279   ExecutionContext &SF = ECStack.back();
00280   Type *Ty    = I.getOperand(0)->getType();
00281   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
00282   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
00283   GenericValue R;   // Result
00284   
00285   switch (I.getPredicate()) {
00286   case ICmpInst::ICMP_EQ:  R = executeICMP_EQ(Src1,  Src2, Ty); break;
00287   case ICmpInst::ICMP_NE:  R = executeICMP_NE(Src1,  Src2, Ty); break;
00288   case ICmpInst::ICMP_ULT: R = executeICMP_ULT(Src1, Src2, Ty); break;
00289   case ICmpInst::ICMP_SLT: R = executeICMP_SLT(Src1, Src2, Ty); break;
00290   case ICmpInst::ICMP_UGT: R = executeICMP_UGT(Src1, Src2, Ty); break;
00291   case ICmpInst::ICMP_SGT: R = executeICMP_SGT(Src1, Src2, Ty); break;
00292   case ICmpInst::ICMP_ULE: R = executeICMP_ULE(Src1, Src2, Ty); break;
00293   case ICmpInst::ICMP_SLE: R = executeICMP_SLE(Src1, Src2, Ty); break;
00294   case ICmpInst::ICMP_UGE: R = executeICMP_UGE(Src1, Src2, Ty); break;
00295   case ICmpInst::ICMP_SGE: R = executeICMP_SGE(Src1, Src2, Ty); break;
00296   default:
00297     dbgs() << "Don't know how to handle this ICmp predicate!\n-->" << I;
00298     llvm_unreachable(nullptr);
00299   }
00300  
00301   SetValue(&I, R, SF);
00302 }
00303 
00304 #define IMPLEMENT_FCMP(OP, TY) \
00305    case Type::TY##TyID: \
00306      Dest.IntVal = APInt(1,Src1.TY##Val OP Src2.TY##Val); \
00307      break
00308 
00309 #define IMPLEMENT_VECTOR_FCMP_T(OP, TY)                             \
00310   assert(Src1.AggregateVal.size() == Src2.AggregateVal.size());     \
00311   Dest.AggregateVal.resize( Src1.AggregateVal.size() );             \
00312   for( uint32_t _i=0;_i<Src1.AggregateVal.size();_i++)              \
00313     Dest.AggregateVal[_i].IntVal = APInt(1,                         \
00314     Src1.AggregateVal[_i].TY##Val OP Src2.AggregateVal[_i].TY##Val);\
00315   break;
00316 
00317 #define IMPLEMENT_VECTOR_FCMP(OP)                                   \
00318   case Type::VectorTyID:                                            \
00319     if (cast<VectorType>(Ty)->getElementType()->isFloatTy()) {      \
00320       IMPLEMENT_VECTOR_FCMP_T(OP, Float);                           \
00321     } else {                                                        \
00322         IMPLEMENT_VECTOR_FCMP_T(OP, Double);                        \
00323     }
00324 
00325 static GenericValue executeFCMP_OEQ(GenericValue Src1, GenericValue Src2,
00326                                    Type *Ty) {
00327   GenericValue Dest;
00328   switch (Ty->getTypeID()) {
00329     IMPLEMENT_FCMP(==, Float);
00330     IMPLEMENT_FCMP(==, Double);
00331     IMPLEMENT_VECTOR_FCMP(==);
00332   default:
00333     dbgs() << "Unhandled type for FCmp EQ instruction: " << *Ty << "\n";
00334     llvm_unreachable(nullptr);
00335   }
00336   return Dest;
00337 }
00338 
00339 #define IMPLEMENT_SCALAR_NANS(TY, X,Y)                                      \
00340   if (TY->isFloatTy()) {                                                    \
00341     if (X.FloatVal != X.FloatVal || Y.FloatVal != Y.FloatVal) {             \
00342       Dest.IntVal = APInt(1,false);                                         \
00343       return Dest;                                                          \
00344     }                                                                       \
00345   } else {                                                                  \
00346     if (X.DoubleVal != X.DoubleVal || Y.DoubleVal != Y.DoubleVal) {         \
00347       Dest.IntVal = APInt(1,false);                                         \
00348       return Dest;                                                          \
00349     }                                                                       \
00350   }
00351 
00352 #define MASK_VECTOR_NANS_T(X,Y, TZ, FLAG)                                   \
00353   assert(X.AggregateVal.size() == Y.AggregateVal.size());                   \
00354   Dest.AggregateVal.resize( X.AggregateVal.size() );                        \
00355   for( uint32_t _i=0;_i<X.AggregateVal.size();_i++) {                       \
00356     if (X.AggregateVal[_i].TZ##Val != X.AggregateVal[_i].TZ##Val ||         \
00357         Y.AggregateVal[_i].TZ##Val != Y.AggregateVal[_i].TZ##Val)           \
00358       Dest.AggregateVal[_i].IntVal = APInt(1,FLAG);                         \
00359     else  {                                                                 \
00360       Dest.AggregateVal[_i].IntVal = APInt(1,!FLAG);                        \
00361     }                                                                       \
00362   }
00363 
00364 #define MASK_VECTOR_NANS(TY, X,Y, FLAG)                                     \
00365   if (TY->isVectorTy()) {                                                   \
00366     if (cast<VectorType>(TY)->getElementType()->isFloatTy()) {              \
00367       MASK_VECTOR_NANS_T(X, Y, Float, FLAG)                                 \
00368     } else {                                                                \
00369       MASK_VECTOR_NANS_T(X, Y, Double, FLAG)                                \
00370     }                                                                       \
00371   }                                                                         \
00372 
00373 
00374 
00375 static GenericValue executeFCMP_ONE(GenericValue Src1, GenericValue Src2,
00376                                     Type *Ty)
00377 {
00378   GenericValue Dest;
00379   // if input is scalar value and Src1 or Src2 is NaN return false
00380   IMPLEMENT_SCALAR_NANS(Ty, Src1, Src2)
00381   // if vector input detect NaNs and fill mask
00382   MASK_VECTOR_NANS(Ty, Src1, Src2, false)
00383   GenericValue DestMask = Dest;
00384   switch (Ty->getTypeID()) {
00385     IMPLEMENT_FCMP(!=, Float);
00386     IMPLEMENT_FCMP(!=, Double);
00387     IMPLEMENT_VECTOR_FCMP(!=);
00388     default:
00389       dbgs() << "Unhandled type for FCmp NE instruction: " << *Ty << "\n";
00390       llvm_unreachable(nullptr);
00391   }
00392   // in vector case mask out NaN elements
00393   if (Ty->isVectorTy())
00394     for( size_t _i=0; _i<Src1.AggregateVal.size(); _i++)
00395       if (DestMask.AggregateVal[_i].IntVal == false)
00396         Dest.AggregateVal[_i].IntVal = APInt(1,false);
00397 
00398   return Dest;
00399 }
00400 
00401 static GenericValue executeFCMP_OLE(GenericValue Src1, GenericValue Src2,
00402                                    Type *Ty) {
00403   GenericValue Dest;
00404   switch (Ty->getTypeID()) {
00405     IMPLEMENT_FCMP(<=, Float);
00406     IMPLEMENT_FCMP(<=, Double);
00407     IMPLEMENT_VECTOR_FCMP(<=);
00408   default:
00409     dbgs() << "Unhandled type for FCmp LE instruction: " << *Ty << "\n";
00410     llvm_unreachable(nullptr);
00411   }
00412   return Dest;
00413 }
00414 
00415 static GenericValue executeFCMP_OGE(GenericValue Src1, GenericValue Src2,
00416                                    Type *Ty) {
00417   GenericValue Dest;
00418   switch (Ty->getTypeID()) {
00419     IMPLEMENT_FCMP(>=, Float);
00420     IMPLEMENT_FCMP(>=, Double);
00421     IMPLEMENT_VECTOR_FCMP(>=);
00422   default:
00423     dbgs() << "Unhandled type for FCmp GE instruction: " << *Ty << "\n";
00424     llvm_unreachable(nullptr);
00425   }
00426   return Dest;
00427 }
00428 
00429 static GenericValue executeFCMP_OLT(GenericValue Src1, GenericValue Src2,
00430                                    Type *Ty) {
00431   GenericValue Dest;
00432   switch (Ty->getTypeID()) {
00433     IMPLEMENT_FCMP(<, Float);
00434     IMPLEMENT_FCMP(<, Double);
00435     IMPLEMENT_VECTOR_FCMP(<);
00436   default:
00437     dbgs() << "Unhandled type for FCmp LT instruction: " << *Ty << "\n";
00438     llvm_unreachable(nullptr);
00439   }
00440   return Dest;
00441 }
00442 
00443 static GenericValue executeFCMP_OGT(GenericValue Src1, GenericValue Src2,
00444                                      Type *Ty) {
00445   GenericValue Dest;
00446   switch (Ty->getTypeID()) {
00447     IMPLEMENT_FCMP(>, Float);
00448     IMPLEMENT_FCMP(>, Double);
00449     IMPLEMENT_VECTOR_FCMP(>);
00450   default:
00451     dbgs() << "Unhandled type for FCmp GT instruction: " << *Ty << "\n";
00452     llvm_unreachable(nullptr);
00453   }
00454   return Dest;
00455 }
00456 
00457 #define IMPLEMENT_UNORDERED(TY, X,Y)                                     \
00458   if (TY->isFloatTy()) {                                                 \
00459     if (X.FloatVal != X.FloatVal || Y.FloatVal != Y.FloatVal) {          \
00460       Dest.IntVal = APInt(1,true);                                       \
00461       return Dest;                                                       \
00462     }                                                                    \
00463   } else if (X.DoubleVal != X.DoubleVal || Y.DoubleVal != Y.DoubleVal) { \
00464     Dest.IntVal = APInt(1,true);                                         \
00465     return Dest;                                                         \
00466   }
00467 
00468 #define IMPLEMENT_VECTOR_UNORDERED(TY, X, Y, FUNC)                             \
00469   if (TY->isVectorTy()) {                                                      \
00470     GenericValue DestMask = Dest;                                              \
00471     Dest = FUNC(Src1, Src2, Ty);                                               \
00472     for (size_t _i = 0; _i < Src1.AggregateVal.size(); _i++)                   \
00473       if (DestMask.AggregateVal[_i].IntVal == true)                            \
00474         Dest.AggregateVal[_i].IntVal = APInt(1, true);                         \
00475     return Dest;                                                               \
00476   }
00477 
00478 static GenericValue executeFCMP_UEQ(GenericValue Src1, GenericValue Src2,
00479                                    Type *Ty) {
00480   GenericValue Dest;
00481   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00482   MASK_VECTOR_NANS(Ty, Src1, Src2, true)
00483   IMPLEMENT_VECTOR_UNORDERED(Ty, Src1, Src2, executeFCMP_OEQ)
00484   return executeFCMP_OEQ(Src1, Src2, Ty);
00485 
00486 }
00487 
00488 static GenericValue executeFCMP_UNE(GenericValue Src1, GenericValue Src2,
00489                                    Type *Ty) {
00490   GenericValue Dest;
00491   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00492   MASK_VECTOR_NANS(Ty, Src1, Src2, true)
00493   IMPLEMENT_VECTOR_UNORDERED(Ty, Src1, Src2, executeFCMP_ONE)
00494   return executeFCMP_ONE(Src1, Src2, Ty);
00495 }
00496 
00497 static GenericValue executeFCMP_ULE(GenericValue Src1, GenericValue Src2,
00498                                    Type *Ty) {
00499   GenericValue Dest;
00500   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00501   MASK_VECTOR_NANS(Ty, Src1, Src2, true)
00502   IMPLEMENT_VECTOR_UNORDERED(Ty, Src1, Src2, executeFCMP_OLE)
00503   return executeFCMP_OLE(Src1, Src2, Ty);
00504 }
00505 
00506 static GenericValue executeFCMP_UGE(GenericValue Src1, GenericValue Src2,
00507                                    Type *Ty) {
00508   GenericValue Dest;
00509   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00510   MASK_VECTOR_NANS(Ty, Src1, Src2, true)
00511   IMPLEMENT_VECTOR_UNORDERED(Ty, Src1, Src2, executeFCMP_OGE)
00512   return executeFCMP_OGE(Src1, Src2, Ty);
00513 }
00514 
00515 static GenericValue executeFCMP_ULT(GenericValue Src1, GenericValue Src2,
00516                                    Type *Ty) {
00517   GenericValue Dest;
00518   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00519   MASK_VECTOR_NANS(Ty, Src1, Src2, true)
00520   IMPLEMENT_VECTOR_UNORDERED(Ty, Src1, Src2, executeFCMP_OLT)
00521   return executeFCMP_OLT(Src1, Src2, Ty);
00522 }
00523 
00524 static GenericValue executeFCMP_UGT(GenericValue Src1, GenericValue Src2,
00525                                      Type *Ty) {
00526   GenericValue Dest;
00527   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
00528   MASK_VECTOR_NANS(Ty, Src1, Src2, true)
00529   IMPLEMENT_VECTOR_UNORDERED(Ty, Src1, Src2, executeFCMP_OGT)
00530   return executeFCMP_OGT(Src1, Src2, Ty);
00531 }
00532 
00533 static GenericValue executeFCMP_ORD(GenericValue Src1, GenericValue Src2,
00534                                      Type *Ty) {
00535   GenericValue Dest;
00536   if(Ty->isVectorTy()) {
00537     assert(Src1.AggregateVal.size() == Src2.AggregateVal.size());
00538     Dest.AggregateVal.resize( Src1.AggregateVal.size() );
00539     if (cast<VectorType>(Ty)->getElementType()->isFloatTy()) {
00540       for( size_t _i=0;_i<Src1.AggregateVal.size();_i++)
00541         Dest.AggregateVal[_i].IntVal = APInt(1,
00542         ( (Src1.AggregateVal[_i].FloatVal ==
00543         Src1.AggregateVal[_i].FloatVal) &&
00544         (Src2.AggregateVal[_i].FloatVal ==
00545         Src2.AggregateVal[_i].FloatVal)));
00546     } else {
00547       for( size_t _i=0;_i<Src1.AggregateVal.size();_i++)
00548         Dest.AggregateVal[_i].IntVal = APInt(1,
00549         ( (Src1.AggregateVal[_i].DoubleVal ==
00550         Src1.AggregateVal[_i].DoubleVal) &&
00551         (Src2.AggregateVal[_i].DoubleVal ==
00552         Src2.AggregateVal[_i].DoubleVal)));
00553     }
00554   } else if (Ty->isFloatTy())
00555     Dest.IntVal = APInt(1,(Src1.FloatVal == Src1.FloatVal && 
00556                            Src2.FloatVal == Src2.FloatVal));
00557   else {
00558     Dest.IntVal = APInt(1,(Src1.DoubleVal == Src1.DoubleVal && 
00559                            Src2.DoubleVal == Src2.DoubleVal));
00560   }
00561   return Dest;
00562 }
00563 
00564 static GenericValue executeFCMP_UNO(GenericValue Src1, GenericValue Src2,
00565                                      Type *Ty) {
00566   GenericValue Dest;
00567   if(Ty->isVectorTy()) {
00568     assert(Src1.AggregateVal.size() == Src2.AggregateVal.size());
00569     Dest.AggregateVal.resize( Src1.AggregateVal.size() );
00570     if (cast<VectorType>(Ty)->getElementType()->isFloatTy()) {
00571       for( size_t _i=0;_i<Src1.AggregateVal.size();_i++)
00572         Dest.AggregateVal[_i].IntVal = APInt(1,
00573         ( (Src1.AggregateVal[_i].FloatVal !=
00574            Src1.AggregateVal[_i].FloatVal) ||
00575           (Src2.AggregateVal[_i].FloatVal !=
00576            Src2.AggregateVal[_i].FloatVal)));
00577       } else {
00578         for( size_t _i=0;_i<Src1.AggregateVal.size();_i++)
00579           Dest.AggregateVal[_i].IntVal = APInt(1,
00580           ( (Src1.AggregateVal[_i].DoubleVal !=
00581              Src1.AggregateVal[_i].DoubleVal) ||
00582             (Src2.AggregateVal[_i].DoubleVal !=
00583              Src2.AggregateVal[_i].DoubleVal)));
00584       }
00585   } else if (Ty->isFloatTy())
00586     Dest.IntVal = APInt(1,(Src1.FloatVal != Src1.FloatVal || 
00587                            Src2.FloatVal != Src2.FloatVal));
00588   else {
00589     Dest.IntVal = APInt(1,(Src1.DoubleVal != Src1.DoubleVal || 
00590                            Src2.DoubleVal != Src2.DoubleVal));
00591   }
00592   return Dest;
00593 }
00594 
00595 static GenericValue executeFCMP_BOOL(GenericValue Src1, GenericValue Src2,
00596                                     const Type *Ty, const bool val) {
00597   GenericValue Dest;
00598     if(Ty->isVectorTy()) {
00599       assert(Src1.AggregateVal.size() == Src2.AggregateVal.size());
00600       Dest.AggregateVal.resize( Src1.AggregateVal.size() );
00601       for( size_t _i=0; _i<Src1.AggregateVal.size(); _i++)
00602         Dest.AggregateVal[_i].IntVal = APInt(1,val);
00603     } else {
00604       Dest.IntVal = APInt(1, val);
00605     }
00606 
00607     return Dest;
00608 }
00609 
00610 void Interpreter::visitFCmpInst(FCmpInst &I) {
00611   ExecutionContext &SF = ECStack.back();
00612   Type *Ty    = I.getOperand(0)->getType();
00613   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
00614   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
00615   GenericValue R;   // Result
00616   
00617   switch (I.getPredicate()) {
00618   default:
00619     dbgs() << "Don't know how to handle this FCmp predicate!\n-->" << I;
00620     llvm_unreachable(nullptr);
00621   break;
00622   case FCmpInst::FCMP_FALSE: R = executeFCMP_BOOL(Src1, Src2, Ty, false); 
00623   break;
00624   case FCmpInst::FCMP_TRUE:  R = executeFCMP_BOOL(Src1, Src2, Ty, true); 
00625   break;
00626   case FCmpInst::FCMP_ORD:   R = executeFCMP_ORD(Src1, Src2, Ty); break;
00627   case FCmpInst::FCMP_UNO:   R = executeFCMP_UNO(Src1, Src2, Ty); break;
00628   case FCmpInst::FCMP_UEQ:   R = executeFCMP_UEQ(Src1, Src2, Ty); break;
00629   case FCmpInst::FCMP_OEQ:   R = executeFCMP_OEQ(Src1, Src2, Ty); break;
00630   case FCmpInst::FCMP_UNE:   R = executeFCMP_UNE(Src1, Src2, Ty); break;
00631   case FCmpInst::FCMP_ONE:   R = executeFCMP_ONE(Src1, Src2, Ty); break;
00632   case FCmpInst::FCMP_ULT:   R = executeFCMP_ULT(Src1, Src2, Ty); break;
00633   case FCmpInst::FCMP_OLT:   R = executeFCMP_OLT(Src1, Src2, Ty); break;
00634   case FCmpInst::FCMP_UGT:   R = executeFCMP_UGT(Src1, Src2, Ty); break;
00635   case FCmpInst::FCMP_OGT:   R = executeFCMP_OGT(Src1, Src2, Ty); break;
00636   case FCmpInst::FCMP_ULE:   R = executeFCMP_ULE(Src1, Src2, Ty); break;
00637   case FCmpInst::FCMP_OLE:   R = executeFCMP_OLE(Src1, Src2, Ty); break;
00638   case FCmpInst::FCMP_UGE:   R = executeFCMP_UGE(Src1, Src2, Ty); break;
00639   case FCmpInst::FCMP_OGE:   R = executeFCMP_OGE(Src1, Src2, Ty); break;
00640   }
00641  
00642   SetValue(&I, R, SF);
00643 }
00644 
00645 static GenericValue executeCmpInst(unsigned predicate, GenericValue Src1, 
00646                                    GenericValue Src2, Type *Ty) {
00647   GenericValue Result;
00648   switch (predicate) {
00649   case ICmpInst::ICMP_EQ:    return executeICMP_EQ(Src1, Src2, Ty);
00650   case ICmpInst::ICMP_NE:    return executeICMP_NE(Src1, Src2, Ty);
00651   case ICmpInst::ICMP_UGT:   return executeICMP_UGT(Src1, Src2, Ty);
00652   case ICmpInst::ICMP_SGT:   return executeICMP_SGT(Src1, Src2, Ty);
00653   case ICmpInst::ICMP_ULT:   return executeICMP_ULT(Src1, Src2, Ty);
00654   case ICmpInst::ICMP_SLT:   return executeICMP_SLT(Src1, Src2, Ty);
00655   case ICmpInst::ICMP_UGE:   return executeICMP_UGE(Src1, Src2, Ty);
00656   case ICmpInst::ICMP_SGE:   return executeICMP_SGE(Src1, Src2, Ty);
00657   case ICmpInst::ICMP_ULE:   return executeICMP_ULE(Src1, Src2, Ty);
00658   case ICmpInst::ICMP_SLE:   return executeICMP_SLE(Src1, Src2, Ty);
00659   case FCmpInst::FCMP_ORD:   return executeFCMP_ORD(Src1, Src2, Ty);
00660   case FCmpInst::FCMP_UNO:   return executeFCMP_UNO(Src1, Src2, Ty);
00661   case FCmpInst::FCMP_OEQ:   return executeFCMP_OEQ(Src1, Src2, Ty);
00662   case FCmpInst::FCMP_UEQ:   return executeFCMP_UEQ(Src1, Src2, Ty);
00663   case FCmpInst::FCMP_ONE:   return executeFCMP_ONE(Src1, Src2, Ty);
00664   case FCmpInst::FCMP_UNE:   return executeFCMP_UNE(Src1, Src2, Ty);
00665   case FCmpInst::FCMP_OLT:   return executeFCMP_OLT(Src1, Src2, Ty);
00666   case FCmpInst::FCMP_ULT:   return executeFCMP_ULT(Src1, Src2, Ty);
00667   case FCmpInst::FCMP_OGT:   return executeFCMP_OGT(Src1, Src2, Ty);
00668   case FCmpInst::FCMP_UGT:   return executeFCMP_UGT(Src1, Src2, Ty);
00669   case FCmpInst::FCMP_OLE:   return executeFCMP_OLE(Src1, Src2, Ty);
00670   case FCmpInst::FCMP_ULE:   return executeFCMP_ULE(Src1, Src2, Ty);
00671   case FCmpInst::FCMP_OGE:   return executeFCMP_OGE(Src1, Src2, Ty);
00672   case FCmpInst::FCMP_UGE:   return executeFCMP_UGE(Src1, Src2, Ty);
00673   case FCmpInst::FCMP_FALSE: return executeFCMP_BOOL(Src1, Src2, Ty, false);
00674   case FCmpInst::FCMP_TRUE:  return executeFCMP_BOOL(Src1, Src2, Ty, true);
00675   default:
00676     dbgs() << "Unhandled Cmp predicate\n";
00677     llvm_unreachable(nullptr);
00678   }
00679 }
00680 
00681 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
00682   ExecutionContext &SF = ECStack.back();
00683   Type *Ty    = I.getOperand(0)->getType();
00684   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
00685   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
00686   GenericValue R;   // Result
00687 
00688   // First process vector operation
00689   if (Ty->isVectorTy()) {
00690     assert(Src1.AggregateVal.size() == Src2.AggregateVal.size());
00691     R.AggregateVal.resize(Src1.AggregateVal.size());
00692 
00693     // Macros to execute binary operation 'OP' over integer vectors
00694 #define INTEGER_VECTOR_OPERATION(OP)                               \
00695     for (unsigned i = 0; i < R.AggregateVal.size(); ++i)           \
00696       R.AggregateVal[i].IntVal =                                   \
00697       Src1.AggregateVal[i].IntVal OP Src2.AggregateVal[i].IntVal;
00698 
00699     // Additional macros to execute binary operations udiv/sdiv/urem/srem since
00700     // they have different notation.
00701 #define INTEGER_VECTOR_FUNCTION(OP)                                \
00702     for (unsigned i = 0; i < R.AggregateVal.size(); ++i)           \
00703       R.AggregateVal[i].IntVal =                                   \
00704       Src1.AggregateVal[i].IntVal.OP(Src2.AggregateVal[i].IntVal);
00705 
00706     // Macros to execute binary operation 'OP' over floating point type TY
00707     // (float or double) vectors
00708 #define FLOAT_VECTOR_FUNCTION(OP, TY)                               \
00709       for (unsigned i = 0; i < R.AggregateVal.size(); ++i)          \
00710         R.AggregateVal[i].TY =                                      \
00711         Src1.AggregateVal[i].TY OP Src2.AggregateVal[i].TY;
00712 
00713     // Macros to choose appropriate TY: float or double and run operation
00714     // execution
00715 #define FLOAT_VECTOR_OP(OP) {                                         \
00716   if (cast<VectorType>(Ty)->getElementType()->isFloatTy())            \
00717     FLOAT_VECTOR_FUNCTION(OP, FloatVal)                               \
00718   else {                                                              \
00719     if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())         \
00720       FLOAT_VECTOR_FUNCTION(OP, DoubleVal)                            \
00721     else {                                                            \
00722       dbgs() << "Unhandled type for OP instruction: " << *Ty << "\n"; \
00723       llvm_unreachable(0);                                            \
00724     }                                                                 \
00725   }                                                                   \
00726 }
00727 
00728     switch(I.getOpcode()){
00729     default:
00730       dbgs() << "Don't know how to handle this binary operator!\n-->" << I;
00731       llvm_unreachable(nullptr);
00732       break;
00733     case Instruction::Add:   INTEGER_VECTOR_OPERATION(+) break;
00734     case Instruction::Sub:   INTEGER_VECTOR_OPERATION(-) break;
00735     case Instruction::Mul:   INTEGER_VECTOR_OPERATION(*) break;
00736     case Instruction::UDiv:  INTEGER_VECTOR_FUNCTION(udiv) break;
00737     case Instruction::SDiv:  INTEGER_VECTOR_FUNCTION(sdiv) break;
00738     case Instruction::URem:  INTEGER_VECTOR_FUNCTION(urem) break;
00739     case Instruction::SRem:  INTEGER_VECTOR_FUNCTION(srem) break;
00740     case Instruction::And:   INTEGER_VECTOR_OPERATION(&) break;
00741     case Instruction::Or:    INTEGER_VECTOR_OPERATION(|) break;
00742     case Instruction::Xor:   INTEGER_VECTOR_OPERATION(^) break;
00743     case Instruction::FAdd:  FLOAT_VECTOR_OP(+) break;
00744     case Instruction::FSub:  FLOAT_VECTOR_OP(-) break;
00745     case Instruction::FMul:  FLOAT_VECTOR_OP(*) break;
00746     case Instruction::FDiv:  FLOAT_VECTOR_OP(/) break;
00747     case Instruction::FRem:
00748       if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
00749         for (unsigned i = 0; i < R.AggregateVal.size(); ++i)
00750           R.AggregateVal[i].FloatVal = 
00751           fmod(Src1.AggregateVal[i].FloatVal, Src2.AggregateVal[i].FloatVal);
00752       else {
00753         if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
00754           for (unsigned i = 0; i < R.AggregateVal.size(); ++i)
00755             R.AggregateVal[i].DoubleVal = 
00756             fmod(Src1.AggregateVal[i].DoubleVal, Src2.AggregateVal[i].DoubleVal);
00757         else {
00758           dbgs() << "Unhandled type for Rem instruction: " << *Ty << "\n";
00759           llvm_unreachable(nullptr);
00760         }
00761       }
00762       break;
00763     }
00764   } else {
00765     switch (I.getOpcode()) {
00766     default:
00767       dbgs() << "Don't know how to handle this binary operator!\n-->" << I;
00768       llvm_unreachable(nullptr);
00769       break;
00770     case Instruction::Add:   R.IntVal = Src1.IntVal + Src2.IntVal; break;
00771     case Instruction::Sub:   R.IntVal = Src1.IntVal - Src2.IntVal; break;
00772     case Instruction::Mul:   R.IntVal = Src1.IntVal * Src2.IntVal; break;
00773     case Instruction::FAdd:  executeFAddInst(R, Src1, Src2, Ty); break;
00774     case Instruction::FSub:  executeFSubInst(R, Src1, Src2, Ty); break;
00775     case Instruction::FMul:  executeFMulInst(R, Src1, Src2, Ty); break;
00776     case Instruction::FDiv:  executeFDivInst(R, Src1, Src2, Ty); break;
00777     case Instruction::FRem:  executeFRemInst(R, Src1, Src2, Ty); break;
00778     case Instruction::UDiv:  R.IntVal = Src1.IntVal.udiv(Src2.IntVal); break;
00779     case Instruction::SDiv:  R.IntVal = Src1.IntVal.sdiv(Src2.IntVal); break;
00780     case Instruction::URem:  R.IntVal = Src1.IntVal.urem(Src2.IntVal); break;
00781     case Instruction::SRem:  R.IntVal = Src1.IntVal.srem(Src2.IntVal); break;
00782     case Instruction::And:   R.IntVal = Src1.IntVal & Src2.IntVal; break;
00783     case Instruction::Or:    R.IntVal = Src1.IntVal | Src2.IntVal; break;
00784     case Instruction::Xor:   R.IntVal = Src1.IntVal ^ Src2.IntVal; break;
00785     }
00786   }
00787   SetValue(&I, R, SF);
00788 }
00789 
00790 static GenericValue executeSelectInst(GenericValue Src1, GenericValue Src2,
00791                                       GenericValue Src3, const Type *Ty) {
00792     GenericValue Dest;
00793     if(Ty->isVectorTy()) {
00794       assert(Src1.AggregateVal.size() == Src2.AggregateVal.size());
00795       assert(Src2.AggregateVal.size() == Src3.AggregateVal.size());
00796       Dest.AggregateVal.resize( Src1.AggregateVal.size() );
00797       for (size_t i = 0; i < Src1.AggregateVal.size(); ++i)
00798         Dest.AggregateVal[i] = (Src1.AggregateVal[i].IntVal == 0) ?
00799           Src3.AggregateVal[i] : Src2.AggregateVal[i];
00800     } else {
00801       Dest = (Src1.IntVal == 0) ? Src3 : Src2;
00802     }
00803     return Dest;
00804 }
00805 
00806 void Interpreter::visitSelectInst(SelectInst &I) {
00807   ExecutionContext &SF = ECStack.back();
00808   const Type * Ty = I.getOperand(0)->getType();
00809   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
00810   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
00811   GenericValue Src3 = getOperandValue(I.getOperand(2), SF);
00812   GenericValue R = executeSelectInst(Src1, Src2, Src3, Ty);
00813   SetValue(&I, R, SF);
00814 }
00815 
00816 //===----------------------------------------------------------------------===//
00817 //                     Terminator Instruction Implementations
00818 //===----------------------------------------------------------------------===//
00819 
00820 void Interpreter::exitCalled(GenericValue GV) {
00821   // runAtExitHandlers() assumes there are no stack frames, but
00822   // if exit() was called, then it had a stack frame. Blow away
00823   // the stack before interpreting atexit handlers.
00824   ECStack.clear();
00825   runAtExitHandlers();
00826   exit(GV.IntVal.zextOrTrunc(32).getZExtValue());
00827 }
00828 
00829 /// Pop the last stack frame off of ECStack and then copy the result
00830 /// back into the result variable if we are not returning void. The
00831 /// result variable may be the ExitValue, or the Value of the calling
00832 /// CallInst if there was a previous stack frame. This method may
00833 /// invalidate any ECStack iterators you have. This method also takes
00834 /// care of switching to the normal destination BB, if we are returning
00835 /// from an invoke.
00836 ///
00837 void Interpreter::popStackAndReturnValueToCaller(Type *RetTy,
00838                                                  GenericValue Result) {
00839   // Pop the current stack frame.
00840   ECStack.pop_back();
00841 
00842   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
00843     if (RetTy && !RetTy->isVoidTy()) {          // Nonvoid return type?
00844       ExitValue = Result;   // Capture the exit value of the program
00845     } else {
00846       memset(&ExitValue.Untyped, 0, sizeof(ExitValue.Untyped));
00847     }
00848   } else {
00849     // If we have a previous stack frame, and we have a previous call,
00850     // fill in the return value...
00851     ExecutionContext &CallingSF = ECStack.back();
00852     if (Instruction *I = CallingSF.Caller.getInstruction()) {
00853       // Save result...
00854       if (!CallingSF.Caller.getType()->isVoidTy())
00855         SetValue(I, Result, CallingSF);
00856       if (InvokeInst *II = dyn_cast<InvokeInst> (I))
00857         SwitchToNewBasicBlock (II->getNormalDest (), CallingSF);
00858       CallingSF.Caller = CallSite();          // We returned from the call...
00859     }
00860   }
00861 }
00862 
00863 void Interpreter::visitReturnInst(ReturnInst &I) {
00864   ExecutionContext &SF = ECStack.back();
00865   Type *RetTy = Type::getVoidTy(I.getContext());
00866   GenericValue Result;
00867 
00868   // Save away the return value... (if we are not 'ret void')
00869   if (I.getNumOperands()) {
00870     RetTy  = I.getReturnValue()->getType();
00871     Result = getOperandValue(I.getReturnValue(), SF);
00872   }
00873 
00874   popStackAndReturnValueToCaller(RetTy, Result);
00875 }
00876 
00877 void Interpreter::visitUnreachableInst(UnreachableInst &I) {
00878   report_fatal_error("Program executed an 'unreachable' instruction!");
00879 }
00880 
00881 void Interpreter::visitBranchInst(BranchInst &I) {
00882   ExecutionContext &SF = ECStack.back();
00883   BasicBlock *Dest;
00884 
00885   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
00886   if (!I.isUnconditional()) {
00887     Value *Cond = I.getCondition();
00888     if (getOperandValue(Cond, SF).IntVal == 0) // If false cond...
00889       Dest = I.getSuccessor(1);
00890   }
00891   SwitchToNewBasicBlock(Dest, SF);
00892 }
00893 
00894 void Interpreter::visitSwitchInst(SwitchInst &I) {
00895   ExecutionContext &SF = ECStack.back();
00896   Value* Cond = I.getCondition();
00897   Type *ElTy = Cond->getType();
00898   GenericValue CondVal = getOperandValue(Cond, SF);
00899 
00900   // Check to see if any of the cases match...
00901   BasicBlock *Dest = nullptr;
00902   for (SwitchInst::CaseIt i = I.case_begin(), e = I.case_end(); i != e; ++i) {
00903     GenericValue CaseVal = getOperandValue(i.getCaseValue(), SF);
00904     if (executeICMP_EQ(CondVal, CaseVal, ElTy).IntVal != 0) {
00905       Dest = cast<BasicBlock>(i.getCaseSuccessor());
00906       break;
00907     }
00908   }
00909   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
00910   SwitchToNewBasicBlock(Dest, SF);
00911 }
00912 
00913 void Interpreter::visitIndirectBrInst(IndirectBrInst &I) {
00914   ExecutionContext &SF = ECStack.back();
00915   void *Dest = GVTOP(getOperandValue(I.getAddress(), SF));
00916   SwitchToNewBasicBlock((BasicBlock*)Dest, SF);
00917 }
00918 
00919 
00920 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
00921 // This function handles the actual updating of block and instruction iterators
00922 // as well as execution of all of the PHI nodes in the destination block.
00923 //
00924 // This method does this because all of the PHI nodes must be executed
00925 // atomically, reading their inputs before any of the results are updated.  Not
00926 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
00927 // their inputs.  If the input PHI node is updated before it is read, incorrect
00928 // results can happen.  Thus we use a two phase approach.
00929 //
00930 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
00931   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
00932   SF.CurBB   = Dest;                  // Update CurBB to branch destination
00933   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
00934 
00935   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
00936 
00937   // Loop over all of the PHI nodes in the current block, reading their inputs.
00938   std::vector<GenericValue> ResultValues;
00939 
00940   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
00941     // Search for the value corresponding to this previous bb...
00942     int i = PN->getBasicBlockIndex(PrevBB);
00943     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
00944     Value *IncomingValue = PN->getIncomingValue(i);
00945 
00946     // Save the incoming value for this PHI node...
00947     ResultValues.push_back(getOperandValue(IncomingValue, SF));
00948   }
00949 
00950   // Now loop over all of the PHI nodes setting their values...
00951   SF.CurInst = SF.CurBB->begin();
00952   for (unsigned i = 0; isa<PHINode>(SF.CurInst); ++SF.CurInst, ++i) {
00953     PHINode *PN = cast<PHINode>(SF.CurInst);
00954     SetValue(PN, ResultValues[i], SF);
00955   }
00956 }
00957 
00958 //===----------------------------------------------------------------------===//
00959 //                     Memory Instruction Implementations
00960 //===----------------------------------------------------------------------===//
00961 
00962 void Interpreter::visitAllocaInst(AllocaInst &I) {
00963   ExecutionContext &SF = ECStack.back();
00964 
00965   Type *Ty = I.getType()->getElementType();  // Type to be allocated
00966 
00967   // Get the number of elements being allocated by the array...
00968   unsigned NumElements = 
00969     getOperandValue(I.getOperand(0), SF).IntVal.getZExtValue();
00970 
00971   unsigned TypeSize = (size_t)TD.getTypeAllocSize(Ty);
00972 
00973   // Avoid malloc-ing zero bytes, use max()...
00974   unsigned MemToAlloc = std::max(1U, NumElements * TypeSize);
00975 
00976   // Allocate enough memory to hold the type...
00977   void *Memory = malloc(MemToAlloc);
00978 
00979   DEBUG(dbgs() << "Allocated Type: " << *Ty << " (" << TypeSize << " bytes) x " 
00980                << NumElements << " (Total: " << MemToAlloc << ") at "
00981                << uintptr_t(Memory) << '\n');
00982 
00983   GenericValue Result = PTOGV(Memory);
00984   assert(Result.PointerVal && "Null pointer returned by malloc!");
00985   SetValue(&I, Result, SF);
00986 
00987   if (I.getOpcode() == Instruction::Alloca)
00988     ECStack.back().Allocas.add(Memory);
00989 }
00990 
00991 // getElementOffset - The workhorse for getelementptr.
00992 //
00993 GenericValue Interpreter::executeGEPOperation(Value *Ptr, gep_type_iterator I,
00994                                               gep_type_iterator E,
00995                                               ExecutionContext &SF) {
00996   assert(Ptr->getType()->isPointerTy() &&
00997          "Cannot getElementOffset of a nonpointer type!");
00998 
00999   uint64_t Total = 0;
01000 
01001   for (; I != E; ++I) {
01002     if (StructType *STy = dyn_cast<StructType>(*I)) {
01003       const StructLayout *SLO = TD.getStructLayout(STy);
01004 
01005       const ConstantInt *CPU = cast<ConstantInt>(I.getOperand());
01006       unsigned Index = unsigned(CPU->getZExtValue());
01007 
01008       Total += SLO->getElementOffset(Index);
01009     } else {
01010       SequentialType *ST = cast<SequentialType>(*I);
01011       // Get the index number for the array... which must be long type...
01012       GenericValue IdxGV = getOperandValue(I.getOperand(), SF);
01013 
01014       int64_t Idx;
01015       unsigned BitWidth = 
01016         cast<IntegerType>(I.getOperand()->getType())->getBitWidth();
01017       if (BitWidth == 32)
01018         Idx = (int64_t)(int32_t)IdxGV.IntVal.getZExtValue();
01019       else {
01020         assert(BitWidth == 64 && "Invalid index type for getelementptr");
01021         Idx = (int64_t)IdxGV.IntVal.getZExtValue();
01022       }
01023       Total += TD.getTypeAllocSize(ST->getElementType())*Idx;
01024     }
01025   }
01026 
01027   GenericValue Result;
01028   Result.PointerVal = ((char*)getOperandValue(Ptr, SF).PointerVal) + Total;
01029   DEBUG(dbgs() << "GEP Index " << Total << " bytes.\n");
01030   return Result;
01031 }
01032 
01033 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
01034   ExecutionContext &SF = ECStack.back();
01035   SetValue(&I, executeGEPOperation(I.getPointerOperand(),
01036                                    gep_type_begin(I), gep_type_end(I), SF), SF);
01037 }
01038 
01039 void Interpreter::visitLoadInst(LoadInst &I) {
01040   ExecutionContext &SF = ECStack.back();
01041   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
01042   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
01043   GenericValue Result;
01044   LoadValueFromMemory(Result, Ptr, I.getType());
01045   SetValue(&I, Result, SF);
01046   if (I.isVolatile() && PrintVolatile)
01047     dbgs() << "Volatile load " << I;
01048 }
01049 
01050 void Interpreter::visitStoreInst(StoreInst &I) {
01051   ExecutionContext &SF = ECStack.back();
01052   GenericValue Val = getOperandValue(I.getOperand(0), SF);
01053   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
01054   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
01055                      I.getOperand(0)->getType());
01056   if (I.isVolatile() && PrintVolatile)
01057     dbgs() << "Volatile store: " << I;
01058 }
01059 
01060 //===----------------------------------------------------------------------===//
01061 //                 Miscellaneous Instruction Implementations
01062 //===----------------------------------------------------------------------===//
01063 
01064 void Interpreter::visitCallSite(CallSite CS) {
01065   ExecutionContext &SF = ECStack.back();
01066 
01067   // Check to see if this is an intrinsic function call...
01068   Function *F = CS.getCalledFunction();
01069   if (F && F->isDeclaration())
01070     switch (F->getIntrinsicID()) {
01071     case Intrinsic::not_intrinsic:
01072       break;
01073     case Intrinsic::vastart: { // va_start
01074       GenericValue ArgIndex;
01075       ArgIndex.UIntPairVal.first = ECStack.size() - 1;
01076       ArgIndex.UIntPairVal.second = 0;
01077       SetValue(CS.getInstruction(), ArgIndex, SF);
01078       return;
01079     }
01080     case Intrinsic::vaend:    // va_end is a noop for the interpreter
01081       return;
01082     case Intrinsic::vacopy:   // va_copy: dest = src
01083       SetValue(CS.getInstruction(), getOperandValue(*CS.arg_begin(), SF), SF);
01084       return;
01085     default:
01086       // If it is an unknown intrinsic function, use the intrinsic lowering
01087       // class to transform it into hopefully tasty LLVM code.
01088       //
01089       BasicBlock::iterator me(CS.getInstruction());
01090       BasicBlock *Parent = CS.getInstruction()->getParent();
01091       bool atBegin(Parent->begin() == me);
01092       if (!atBegin)
01093         --me;
01094       IL->LowerIntrinsicCall(cast<CallInst>(CS.getInstruction()));
01095 
01096       // Restore the CurInst pointer to the first instruction newly inserted, if
01097       // any.
01098       if (atBegin) {
01099         SF.CurInst = Parent->begin();
01100       } else {
01101         SF.CurInst = me;
01102         ++SF.CurInst;
01103       }
01104       return;
01105     }
01106 
01107 
01108   SF.Caller = CS;
01109   std::vector<GenericValue> ArgVals;
01110   const unsigned NumArgs = SF.Caller.arg_size();
01111   ArgVals.reserve(NumArgs);
01112   uint16_t pNum = 1;
01113   for (CallSite::arg_iterator i = SF.Caller.arg_begin(),
01114          e = SF.Caller.arg_end(); i != e; ++i, ++pNum) {
01115     Value *V = *i;
01116     ArgVals.push_back(getOperandValue(V, SF));
01117   }
01118 
01119   // To handle indirect calls, we must get the pointer value from the argument
01120   // and treat it as a function pointer.
01121   GenericValue SRC = getOperandValue(SF.Caller.getCalledValue(), SF);
01122   callFunction((Function*)GVTOP(SRC), ArgVals);
01123 }
01124 
01125 // auxiliary function for shift operations
01126 static unsigned getShiftAmount(uint64_t orgShiftAmount,
01127                                llvm::APInt valueToShift) {
01128   unsigned valueWidth = valueToShift.getBitWidth();
01129   if (orgShiftAmount < (uint64_t)valueWidth)
01130     return orgShiftAmount;
01131   // according to the llvm documentation, if orgShiftAmount > valueWidth,
01132   // the result is undfeined. but we do shift by this rule:
01133   return (NextPowerOf2(valueWidth-1) - 1) & orgShiftAmount;
01134 }
01135 
01136 
01137 void Interpreter::visitShl(BinaryOperator &I) {
01138   ExecutionContext &SF = ECStack.back();
01139   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
01140   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
01141   GenericValue Dest;
01142   const Type *Ty = I.getType();
01143 
01144   if (Ty->isVectorTy()) {
01145     uint32_t src1Size = uint32_t(Src1.AggregateVal.size());
01146     assert(src1Size == Src2.AggregateVal.size());
01147     for (unsigned i = 0; i < src1Size; i++) {
01148       GenericValue Result;
01149       uint64_t shiftAmount = Src2.AggregateVal[i].IntVal.getZExtValue();
01150       llvm::APInt valueToShift = Src1.AggregateVal[i].IntVal;
01151       Result.IntVal = valueToShift.shl(getShiftAmount(shiftAmount, valueToShift));
01152       Dest.AggregateVal.push_back(Result);
01153     }
01154   } else {
01155     // scalar
01156     uint64_t shiftAmount = Src2.IntVal.getZExtValue();
01157     llvm::APInt valueToShift = Src1.IntVal;
01158     Dest.IntVal = valueToShift.shl(getShiftAmount(shiftAmount, valueToShift));
01159   }
01160 
01161   SetValue(&I, Dest, SF);
01162 }
01163 
01164 void Interpreter::visitLShr(BinaryOperator &I) {
01165   ExecutionContext &SF = ECStack.back();
01166   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
01167   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
01168   GenericValue Dest;
01169   const Type *Ty = I.getType();
01170 
01171   if (Ty->isVectorTy()) {
01172     uint32_t src1Size = uint32_t(Src1.AggregateVal.size());
01173     assert(src1Size == Src2.AggregateVal.size());
01174     for (unsigned i = 0; i < src1Size; i++) {
01175       GenericValue Result;
01176       uint64_t shiftAmount = Src2.AggregateVal[i].IntVal.getZExtValue();
01177       llvm::APInt valueToShift = Src1.AggregateVal[i].IntVal;
01178       Result.IntVal = valueToShift.lshr(getShiftAmount(shiftAmount, valueToShift));
01179       Dest.AggregateVal.push_back(Result);
01180     }
01181   } else {
01182     // scalar
01183     uint64_t shiftAmount = Src2.IntVal.getZExtValue();
01184     llvm::APInt valueToShift = Src1.IntVal;
01185     Dest.IntVal = valueToShift.lshr(getShiftAmount(shiftAmount, valueToShift));
01186   }
01187 
01188   SetValue(&I, Dest, SF);
01189 }
01190 
01191 void Interpreter::visitAShr(BinaryOperator &I) {
01192   ExecutionContext &SF = ECStack.back();
01193   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
01194   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
01195   GenericValue Dest;
01196   const Type *Ty = I.getType();
01197 
01198   if (Ty->isVectorTy()) {
01199     size_t src1Size = Src1.AggregateVal.size();
01200     assert(src1Size == Src2.AggregateVal.size());
01201     for (unsigned i = 0; i < src1Size; i++) {
01202       GenericValue Result;
01203       uint64_t shiftAmount = Src2.AggregateVal[i].IntVal.getZExtValue();
01204       llvm::APInt valueToShift = Src1.AggregateVal[i].IntVal;
01205       Result.IntVal = valueToShift.ashr(getShiftAmount(shiftAmount, valueToShift));
01206       Dest.AggregateVal.push_back(Result);
01207     }
01208   } else {
01209     // scalar
01210     uint64_t shiftAmount = Src2.IntVal.getZExtValue();
01211     llvm::APInt valueToShift = Src1.IntVal;
01212     Dest.IntVal = valueToShift.ashr(getShiftAmount(shiftAmount, valueToShift));
01213   }
01214 
01215   SetValue(&I, Dest, SF);
01216 }
01217 
01218 GenericValue Interpreter::executeTruncInst(Value *SrcVal, Type *DstTy,
01219                                            ExecutionContext &SF) {
01220   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01221   Type *SrcTy = SrcVal->getType();
01222   if (SrcTy->isVectorTy()) {
01223     Type *DstVecTy = DstTy->getScalarType();
01224     unsigned DBitWidth = cast<IntegerType>(DstVecTy)->getBitWidth();
01225     unsigned NumElts = Src.AggregateVal.size();
01226     // the sizes of src and dst vectors must be equal
01227     Dest.AggregateVal.resize(NumElts);
01228     for (unsigned i = 0; i < NumElts; i++)
01229       Dest.AggregateVal[i].IntVal = Src.AggregateVal[i].IntVal.trunc(DBitWidth);
01230   } else {
01231     IntegerType *DITy = cast<IntegerType>(DstTy);
01232     unsigned DBitWidth = DITy->getBitWidth();
01233     Dest.IntVal = Src.IntVal.trunc(DBitWidth);
01234   }
01235   return Dest;
01236 }
01237 
01238 GenericValue Interpreter::executeSExtInst(Value *SrcVal, Type *DstTy,
01239                                           ExecutionContext &SF) {
01240   const Type *SrcTy = SrcVal->getType();
01241   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01242   if (SrcTy->isVectorTy()) {
01243     const Type *DstVecTy = DstTy->getScalarType();
01244     unsigned DBitWidth = cast<IntegerType>(DstVecTy)->getBitWidth();
01245     unsigned size = Src.AggregateVal.size();
01246     // the sizes of src and dst vectors must be equal.
01247     Dest.AggregateVal.resize(size);
01248     for (unsigned i = 0; i < size; i++)
01249       Dest.AggregateVal[i].IntVal = Src.AggregateVal[i].IntVal.sext(DBitWidth);
01250   } else {
01251     const IntegerType *DITy = cast<IntegerType>(DstTy);
01252     unsigned DBitWidth = DITy->getBitWidth();
01253     Dest.IntVal = Src.IntVal.sext(DBitWidth);
01254   }
01255   return Dest;
01256 }
01257 
01258 GenericValue Interpreter::executeZExtInst(Value *SrcVal, Type *DstTy,
01259                                           ExecutionContext &SF) {
01260   const Type *SrcTy = SrcVal->getType();
01261   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01262   if (SrcTy->isVectorTy()) {
01263     const Type *DstVecTy = DstTy->getScalarType();
01264     unsigned DBitWidth = cast<IntegerType>(DstVecTy)->getBitWidth();
01265 
01266     unsigned size = Src.AggregateVal.size();
01267     // the sizes of src and dst vectors must be equal.
01268     Dest.AggregateVal.resize(size);
01269     for (unsigned i = 0; i < size; i++)
01270       Dest.AggregateVal[i].IntVal = Src.AggregateVal[i].IntVal.zext(DBitWidth);
01271   } else {
01272     const IntegerType *DITy = cast<IntegerType>(DstTy);
01273     unsigned DBitWidth = DITy->getBitWidth();
01274     Dest.IntVal = Src.IntVal.zext(DBitWidth);
01275   }
01276   return Dest;
01277 }
01278 
01279 GenericValue Interpreter::executeFPTruncInst(Value *SrcVal, Type *DstTy,
01280                                              ExecutionContext &SF) {
01281   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01282 
01283   if (SrcVal->getType()->getTypeID() == Type::VectorTyID) {
01284     assert(SrcVal->getType()->getScalarType()->isDoubleTy() &&
01285            DstTy->getScalarType()->isFloatTy() &&
01286            "Invalid FPTrunc instruction");
01287 
01288     unsigned size = Src.AggregateVal.size();
01289     // the sizes of src and dst vectors must be equal.
01290     Dest.AggregateVal.resize(size);
01291     for (unsigned i = 0; i < size; i++)
01292       Dest.AggregateVal[i].FloatVal = (float)Src.AggregateVal[i].DoubleVal;
01293   } else {
01294     assert(SrcVal->getType()->isDoubleTy() && DstTy->isFloatTy() &&
01295            "Invalid FPTrunc instruction");
01296     Dest.FloatVal = (float)Src.DoubleVal;
01297   }
01298 
01299   return Dest;
01300 }
01301 
01302 GenericValue Interpreter::executeFPExtInst(Value *SrcVal, Type *DstTy,
01303                                            ExecutionContext &SF) {
01304   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01305 
01306   if (SrcVal->getType()->getTypeID() == Type::VectorTyID) {
01307     assert(SrcVal->getType()->getScalarType()->isFloatTy() &&
01308            DstTy->getScalarType()->isDoubleTy() && "Invalid FPExt instruction");
01309 
01310     unsigned size = Src.AggregateVal.size();
01311     // the sizes of src and dst vectors must be equal.
01312     Dest.AggregateVal.resize(size);
01313     for (unsigned i = 0; i < size; i++)
01314       Dest.AggregateVal[i].DoubleVal = (double)Src.AggregateVal[i].FloatVal;
01315   } else {
01316     assert(SrcVal->getType()->isFloatTy() && DstTy->isDoubleTy() &&
01317            "Invalid FPExt instruction");
01318     Dest.DoubleVal = (double)Src.FloatVal;
01319   }
01320 
01321   return Dest;
01322 }
01323 
01324 GenericValue Interpreter::executeFPToUIInst(Value *SrcVal, Type *DstTy,
01325                                             ExecutionContext &SF) {
01326   Type *SrcTy = SrcVal->getType();
01327   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01328 
01329   if (SrcTy->getTypeID() == Type::VectorTyID) {
01330     const Type *DstVecTy = DstTy->getScalarType();
01331     const Type *SrcVecTy = SrcTy->getScalarType();
01332     uint32_t DBitWidth = cast<IntegerType>(DstVecTy)->getBitWidth();
01333     unsigned size = Src.AggregateVal.size();
01334     // the sizes of src and dst vectors must be equal.
01335     Dest.AggregateVal.resize(size);
01336 
01337     if (SrcVecTy->getTypeID() == Type::FloatTyID) {
01338       assert(SrcVecTy->isFloatingPointTy() && "Invalid FPToUI instruction");
01339       for (unsigned i = 0; i < size; i++)
01340         Dest.AggregateVal[i].IntVal = APIntOps::RoundFloatToAPInt(
01341             Src.AggregateVal[i].FloatVal, DBitWidth);
01342     } else {
01343       for (unsigned i = 0; i < size; i++)
01344         Dest.AggregateVal[i].IntVal = APIntOps::RoundDoubleToAPInt(
01345             Src.AggregateVal[i].DoubleVal, DBitWidth);
01346     }
01347   } else {
01348     // scalar
01349     uint32_t DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
01350     assert(SrcTy->isFloatingPointTy() && "Invalid FPToUI instruction");
01351 
01352     if (SrcTy->getTypeID() == Type::FloatTyID)
01353       Dest.IntVal = APIntOps::RoundFloatToAPInt(Src.FloatVal, DBitWidth);
01354     else {
01355       Dest.IntVal = APIntOps::RoundDoubleToAPInt(Src.DoubleVal, DBitWidth);
01356     }
01357   }
01358 
01359   return Dest;
01360 }
01361 
01362 GenericValue Interpreter::executeFPToSIInst(Value *SrcVal, Type *DstTy,
01363                                             ExecutionContext &SF) {
01364   Type *SrcTy = SrcVal->getType();
01365   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01366 
01367   if (SrcTy->getTypeID() == Type::VectorTyID) {
01368     const Type *DstVecTy = DstTy->getScalarType();
01369     const Type *SrcVecTy = SrcTy->getScalarType();
01370     uint32_t DBitWidth = cast<IntegerType>(DstVecTy)->getBitWidth();
01371     unsigned size = Src.AggregateVal.size();
01372     // the sizes of src and dst vectors must be equal
01373     Dest.AggregateVal.resize(size);
01374 
01375     if (SrcVecTy->getTypeID() == Type::FloatTyID) {
01376       assert(SrcVecTy->isFloatingPointTy() && "Invalid FPToSI instruction");
01377       for (unsigned i = 0; i < size; i++)
01378         Dest.AggregateVal[i].IntVal = APIntOps::RoundFloatToAPInt(
01379             Src.AggregateVal[i].FloatVal, DBitWidth);
01380     } else {
01381       for (unsigned i = 0; i < size; i++)
01382         Dest.AggregateVal[i].IntVal = APIntOps::RoundDoubleToAPInt(
01383             Src.AggregateVal[i].DoubleVal, DBitWidth);
01384     }
01385   } else {
01386     // scalar
01387     unsigned DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
01388     assert(SrcTy->isFloatingPointTy() && "Invalid FPToSI instruction");
01389 
01390     if (SrcTy->getTypeID() == Type::FloatTyID)
01391       Dest.IntVal = APIntOps::RoundFloatToAPInt(Src.FloatVal, DBitWidth);
01392     else {
01393       Dest.IntVal = APIntOps::RoundDoubleToAPInt(Src.DoubleVal, DBitWidth);
01394     }
01395   }
01396   return Dest;
01397 }
01398 
01399 GenericValue Interpreter::executeUIToFPInst(Value *SrcVal, Type *DstTy,
01400                                             ExecutionContext &SF) {
01401   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01402 
01403   if (SrcVal->getType()->getTypeID() == Type::VectorTyID) {
01404     const Type *DstVecTy = DstTy->getScalarType();
01405     unsigned size = Src.AggregateVal.size();
01406     // the sizes of src and dst vectors must be equal
01407     Dest.AggregateVal.resize(size);
01408 
01409     if (DstVecTy->getTypeID() == Type::FloatTyID) {
01410       assert(DstVecTy->isFloatingPointTy() && "Invalid UIToFP instruction");
01411       for (unsigned i = 0; i < size; i++)
01412         Dest.AggregateVal[i].FloatVal =
01413             APIntOps::RoundAPIntToFloat(Src.AggregateVal[i].IntVal);
01414     } else {
01415       for (unsigned i = 0; i < size; i++)
01416         Dest.AggregateVal[i].DoubleVal =
01417             APIntOps::RoundAPIntToDouble(Src.AggregateVal[i].IntVal);
01418     }
01419   } else {
01420     // scalar
01421     assert(DstTy->isFloatingPointTy() && "Invalid UIToFP instruction");
01422     if (DstTy->getTypeID() == Type::FloatTyID)
01423       Dest.FloatVal = APIntOps::RoundAPIntToFloat(Src.IntVal);
01424     else {
01425       Dest.DoubleVal = APIntOps::RoundAPIntToDouble(Src.IntVal);
01426     }
01427   }
01428   return Dest;
01429 }
01430 
01431 GenericValue Interpreter::executeSIToFPInst(Value *SrcVal, Type *DstTy,
01432                                             ExecutionContext &SF) {
01433   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01434 
01435   if (SrcVal->getType()->getTypeID() == Type::VectorTyID) {
01436     const Type *DstVecTy = DstTy->getScalarType();
01437     unsigned size = Src.AggregateVal.size();
01438     // the sizes of src and dst vectors must be equal
01439     Dest.AggregateVal.resize(size);
01440 
01441     if (DstVecTy->getTypeID() == Type::FloatTyID) {
01442       assert(DstVecTy->isFloatingPointTy() && "Invalid SIToFP instruction");
01443       for (unsigned i = 0; i < size; i++)
01444         Dest.AggregateVal[i].FloatVal =
01445             APIntOps::RoundSignedAPIntToFloat(Src.AggregateVal[i].IntVal);
01446     } else {
01447       for (unsigned i = 0; i < size; i++)
01448         Dest.AggregateVal[i].DoubleVal =
01449             APIntOps::RoundSignedAPIntToDouble(Src.AggregateVal[i].IntVal);
01450     }
01451   } else {
01452     // scalar
01453     assert(DstTy->isFloatingPointTy() && "Invalid SIToFP instruction");
01454 
01455     if (DstTy->getTypeID() == Type::FloatTyID)
01456       Dest.FloatVal = APIntOps::RoundSignedAPIntToFloat(Src.IntVal);
01457     else {
01458       Dest.DoubleVal = APIntOps::RoundSignedAPIntToDouble(Src.IntVal);
01459     }
01460   }
01461 
01462   return Dest;
01463 }
01464 
01465 GenericValue Interpreter::executePtrToIntInst(Value *SrcVal, Type *DstTy,
01466                                               ExecutionContext &SF) {
01467   uint32_t DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
01468   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01469   assert(SrcVal->getType()->isPointerTy() && "Invalid PtrToInt instruction");
01470 
01471   Dest.IntVal = APInt(DBitWidth, (intptr_t) Src.PointerVal);
01472   return Dest;
01473 }
01474 
01475 GenericValue Interpreter::executeIntToPtrInst(Value *SrcVal, Type *DstTy,
01476                                               ExecutionContext &SF) {
01477   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01478   assert(DstTy->isPointerTy() && "Invalid PtrToInt instruction");
01479 
01480   uint32_t PtrSize = TD.getPointerSizeInBits();
01481   if (PtrSize != Src.IntVal.getBitWidth())
01482     Src.IntVal = Src.IntVal.zextOrTrunc(PtrSize);
01483 
01484   Dest.PointerVal = PointerTy(intptr_t(Src.IntVal.getZExtValue()));
01485   return Dest;
01486 }
01487 
01488 GenericValue Interpreter::executeBitCastInst(Value *SrcVal, Type *DstTy,
01489                                              ExecutionContext &SF) {
01490 
01491   // This instruction supports bitwise conversion of vectors to integers and
01492   // to vectors of other types (as long as they have the same size)
01493   Type *SrcTy = SrcVal->getType();
01494   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
01495 
01496   if ((SrcTy->getTypeID() == Type::VectorTyID) ||
01497       (DstTy->getTypeID() == Type::VectorTyID)) {
01498     // vector src bitcast to vector dst or vector src bitcast to scalar dst or
01499     // scalar src bitcast to vector dst
01500     bool isLittleEndian = TD.isLittleEndian();
01501     GenericValue TempDst, TempSrc, SrcVec;
01502     const Type *SrcElemTy;
01503     const Type *DstElemTy;
01504     unsigned SrcBitSize;
01505     unsigned DstBitSize;
01506     unsigned SrcNum;
01507     unsigned DstNum;
01508 
01509     if (SrcTy->getTypeID() == Type::VectorTyID) {
01510       SrcElemTy = SrcTy->getScalarType();
01511       SrcBitSize = SrcTy->getScalarSizeInBits();
01512       SrcNum = Src.AggregateVal.size();
01513       SrcVec = Src;
01514     } else {
01515       // if src is scalar value, make it vector <1 x type>
01516       SrcElemTy = SrcTy;
01517       SrcBitSize = SrcTy->getPrimitiveSizeInBits();
01518       SrcNum = 1;
01519       SrcVec.AggregateVal.push_back(Src);
01520     }
01521 
01522     if (DstTy->getTypeID() == Type::VectorTyID) {
01523       DstElemTy = DstTy->getScalarType();
01524       DstBitSize = DstTy->getScalarSizeInBits();
01525       DstNum = (SrcNum * SrcBitSize) / DstBitSize;
01526     } else {
01527       DstElemTy = DstTy;
01528       DstBitSize = DstTy->getPrimitiveSizeInBits();
01529       DstNum = 1;
01530     }
01531 
01532     if (SrcNum * SrcBitSize != DstNum * DstBitSize)
01533       llvm_unreachable("Invalid BitCast");
01534 
01535     // If src is floating point, cast to integer first.
01536     TempSrc.AggregateVal.resize(SrcNum);
01537     if (SrcElemTy->isFloatTy()) {
01538       for (unsigned i = 0; i < SrcNum; i++)
01539         TempSrc.AggregateVal[i].IntVal =
01540             APInt::floatToBits(SrcVec.AggregateVal[i].FloatVal);
01541 
01542     } else if (SrcElemTy->isDoubleTy()) {
01543       for (unsigned i = 0; i < SrcNum; i++)
01544         TempSrc.AggregateVal[i].IntVal =
01545             APInt::doubleToBits(SrcVec.AggregateVal[i].DoubleVal);
01546     } else if (SrcElemTy->isIntegerTy()) {
01547       for (unsigned i = 0; i < SrcNum; i++)
01548         TempSrc.AggregateVal[i].IntVal = SrcVec.AggregateVal[i].IntVal;
01549     } else {
01550       // Pointers are not allowed as the element type of vector.
01551       llvm_unreachable("Invalid Bitcast");
01552     }
01553 
01554     // now TempSrc is integer type vector
01555     if (DstNum < SrcNum) {
01556       // Example: bitcast <4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>
01557       unsigned Ratio = SrcNum / DstNum;
01558       unsigned SrcElt = 0;
01559       for (unsigned i = 0; i < DstNum; i++) {
01560         GenericValue Elt;
01561         Elt.IntVal = 0;
01562         Elt.IntVal = Elt.IntVal.zext(DstBitSize);
01563         unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize * (Ratio - 1);
01564         for (unsigned j = 0; j < Ratio; j++) {
01565           APInt Tmp;
01566           Tmp = Tmp.zext(SrcBitSize);
01567           Tmp = TempSrc.AggregateVal[SrcElt++].IntVal;
01568           Tmp = Tmp.zext(DstBitSize);
01569           Tmp = Tmp.shl(ShiftAmt);
01570           ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
01571           Elt.IntVal |= Tmp;
01572         }
01573         TempDst.AggregateVal.push_back(Elt);
01574       }
01575     } else {
01576       // Example: bitcast <2 x i64> <i64 0, i64 1> to <4 x i32>
01577       unsigned Ratio = DstNum / SrcNum;
01578       for (unsigned i = 0; i < SrcNum; i++) {
01579         unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize * (Ratio - 1);
01580         for (unsigned j = 0; j < Ratio; j++) {
01581           GenericValue Elt;
01582           Elt.IntVal = Elt.IntVal.zext(SrcBitSize);
01583           Elt.IntVal = TempSrc.AggregateVal[i].IntVal;
01584           Elt.IntVal = Elt.IntVal.lshr(ShiftAmt);
01585           // it could be DstBitSize == SrcBitSize, so check it
01586           if (DstBitSize < SrcBitSize)
01587             Elt.IntVal = Elt.IntVal.trunc(DstBitSize);
01588           ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
01589           TempDst.AggregateVal.push_back(Elt);
01590         }
01591       }
01592     }
01593 
01594     // convert result from integer to specified type
01595     if (DstTy->getTypeID() == Type::VectorTyID) {
01596       if (DstElemTy->isDoubleTy()) {
01597         Dest.AggregateVal.resize(DstNum);
01598         for (unsigned i = 0; i < DstNum; i++)
01599           Dest.AggregateVal[i].DoubleVal =
01600               TempDst.AggregateVal[i].IntVal.bitsToDouble();
01601       } else if (DstElemTy->isFloatTy()) {
01602         Dest.AggregateVal.resize(DstNum);
01603         for (unsigned i = 0; i < DstNum; i++)
01604           Dest.AggregateVal[i].FloatVal =
01605               TempDst.AggregateVal[i].IntVal.bitsToFloat();
01606       } else {
01607         Dest = TempDst;
01608       }
01609     } else {
01610       if (DstElemTy->isDoubleTy())
01611         Dest.DoubleVal = TempDst.AggregateVal[0].IntVal.bitsToDouble();
01612       else if (DstElemTy->isFloatTy()) {
01613         Dest.FloatVal = TempDst.AggregateVal[0].IntVal.bitsToFloat();
01614       } else {
01615         Dest.IntVal = TempDst.AggregateVal[0].IntVal;
01616       }
01617     }
01618   } else { //  if ((SrcTy->getTypeID() == Type::VectorTyID) ||
01619            //     (DstTy->getTypeID() == Type::VectorTyID))
01620 
01621     // scalar src bitcast to scalar dst
01622     if (DstTy->isPointerTy()) {
01623       assert(SrcTy->isPointerTy() && "Invalid BitCast");
01624       Dest.PointerVal = Src.PointerVal;
01625     } else if (DstTy->isIntegerTy()) {
01626       if (SrcTy->isFloatTy())
01627         Dest.IntVal = APInt::floatToBits(Src.FloatVal);
01628       else if (SrcTy->isDoubleTy()) {
01629         Dest.IntVal = APInt::doubleToBits(Src.DoubleVal);
01630       } else if (SrcTy->isIntegerTy()) {
01631         Dest.IntVal = Src.IntVal;
01632       } else {
01633         llvm_unreachable("Invalid BitCast");
01634       }
01635     } else if (DstTy->isFloatTy()) {
01636       if (SrcTy->isIntegerTy())
01637         Dest.FloatVal = Src.IntVal.bitsToFloat();
01638       else {
01639         Dest.FloatVal = Src.FloatVal;
01640       }
01641     } else if (DstTy->isDoubleTy()) {
01642       if (SrcTy->isIntegerTy())
01643         Dest.DoubleVal = Src.IntVal.bitsToDouble();
01644       else {
01645         Dest.DoubleVal = Src.DoubleVal;
01646       }
01647     } else {
01648       llvm_unreachable("Invalid Bitcast");
01649     }
01650   }
01651 
01652   return Dest;
01653 }
01654 
01655 void Interpreter::visitTruncInst(TruncInst &I) {
01656   ExecutionContext &SF = ECStack.back();
01657   SetValue(&I, executeTruncInst(I.getOperand(0), I.getType(), SF), SF);
01658 }
01659 
01660 void Interpreter::visitSExtInst(SExtInst &I) {
01661   ExecutionContext &SF = ECStack.back();
01662   SetValue(&I, executeSExtInst(I.getOperand(0), I.getType(), SF), SF);
01663 }
01664 
01665 void Interpreter::visitZExtInst(ZExtInst &I) {
01666   ExecutionContext &SF = ECStack.back();
01667   SetValue(&I, executeZExtInst(I.getOperand(0), I.getType(), SF), SF);
01668 }
01669 
01670 void Interpreter::visitFPTruncInst(FPTruncInst &I) {
01671   ExecutionContext &SF = ECStack.back();
01672   SetValue(&I, executeFPTruncInst(I.getOperand(0), I.getType(), SF), SF);
01673 }
01674 
01675 void Interpreter::visitFPExtInst(FPExtInst &I) {
01676   ExecutionContext &SF = ECStack.back();
01677   SetValue(&I, executeFPExtInst(I.getOperand(0), I.getType(), SF), SF);
01678 }
01679 
01680 void Interpreter::visitUIToFPInst(UIToFPInst &I) {
01681   ExecutionContext &SF = ECStack.back();
01682   SetValue(&I, executeUIToFPInst(I.getOperand(0), I.getType(), SF), SF);
01683 }
01684 
01685 void Interpreter::visitSIToFPInst(SIToFPInst &I) {
01686   ExecutionContext &SF = ECStack.back();
01687   SetValue(&I, executeSIToFPInst(I.getOperand(0), I.getType(), SF), SF);
01688 }
01689 
01690 void Interpreter::visitFPToUIInst(FPToUIInst &I) {
01691   ExecutionContext &SF = ECStack.back();
01692   SetValue(&I, executeFPToUIInst(I.getOperand(0), I.getType(), SF), SF);
01693 }
01694 
01695 void Interpreter::visitFPToSIInst(FPToSIInst &I) {
01696   ExecutionContext &SF = ECStack.back();
01697   SetValue(&I, executeFPToSIInst(I.getOperand(0), I.getType(), SF), SF);
01698 }
01699 
01700 void Interpreter::visitPtrToIntInst(PtrToIntInst &I) {
01701   ExecutionContext &SF = ECStack.back();
01702   SetValue(&I, executePtrToIntInst(I.getOperand(0), I.getType(), SF), SF);
01703 }
01704 
01705 void Interpreter::visitIntToPtrInst(IntToPtrInst &I) {
01706   ExecutionContext &SF = ECStack.back();
01707   SetValue(&I, executeIntToPtrInst(I.getOperand(0), I.getType(), SF), SF);
01708 }
01709 
01710 void Interpreter::visitBitCastInst(BitCastInst &I) {
01711   ExecutionContext &SF = ECStack.back();
01712   SetValue(&I, executeBitCastInst(I.getOperand(0), I.getType(), SF), SF);
01713 }
01714 
01715 #define IMPLEMENT_VAARG(TY) \
01716    case Type::TY##TyID: Dest.TY##Val = Src.TY##Val; break
01717 
01718 void Interpreter::visitVAArgInst(VAArgInst &I) {
01719   ExecutionContext &SF = ECStack.back();
01720 
01721   // Get the incoming valist parameter.  LLI treats the valist as a
01722   // (ec-stack-depth var-arg-index) pair.
01723   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
01724   GenericValue Dest;
01725   GenericValue Src = ECStack[VAList.UIntPairVal.first]
01726                       .VarArgs[VAList.UIntPairVal.second];
01727   Type *Ty = I.getType();
01728   switch (Ty->getTypeID()) {
01729   case Type::IntegerTyID:
01730     Dest.IntVal = Src.IntVal;
01731     break;
01732   IMPLEMENT_VAARG(Pointer);
01733   IMPLEMENT_VAARG(Float);
01734   IMPLEMENT_VAARG(Double);
01735   default:
01736     dbgs() << "Unhandled dest type for vaarg instruction: " << *Ty << "\n";
01737     llvm_unreachable(nullptr);
01738   }
01739 
01740   // Set the Value of this Instruction.
01741   SetValue(&I, Dest, SF);
01742 
01743   // Move the pointer to the next vararg.
01744   ++VAList.UIntPairVal.second;
01745 }
01746 
01747 void Interpreter::visitExtractElementInst(ExtractElementInst &I) {
01748   ExecutionContext &SF = ECStack.back();
01749   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
01750   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
01751   GenericValue Dest;
01752 
01753   Type *Ty = I.getType();
01754   const unsigned indx = unsigned(Src2.IntVal.getZExtValue());
01755 
01756   if(Src1.AggregateVal.size() > indx) {
01757     switch (Ty->getTypeID()) {
01758     default:
01759       dbgs() << "Unhandled destination type for extractelement instruction: "
01760       << *Ty << "\n";
01761       llvm_unreachable(nullptr);
01762       break;
01763     case Type::IntegerTyID:
01764       Dest.IntVal = Src1.AggregateVal[indx].IntVal;
01765       break;
01766     case Type::FloatTyID:
01767       Dest.FloatVal = Src1.AggregateVal[indx].FloatVal;
01768       break;
01769     case Type::DoubleTyID:
01770       Dest.DoubleVal = Src1.AggregateVal[indx].DoubleVal;
01771       break;
01772     }
01773   } else {
01774     dbgs() << "Invalid index in extractelement instruction\n";
01775   }
01776 
01777   SetValue(&I, Dest, SF);
01778 }
01779 
01780 void Interpreter::visitInsertElementInst(InsertElementInst &I) {
01781   ExecutionContext &SF = ECStack.back();
01782   Type *Ty = I.getType();
01783 
01784   if(!(Ty->isVectorTy()) )
01785     llvm_unreachable("Unhandled dest type for insertelement instruction");
01786 
01787   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
01788   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
01789   GenericValue Src3 = getOperandValue(I.getOperand(2), SF);
01790   GenericValue Dest;
01791 
01792   Type *TyContained = Ty->getContainedType(0);
01793 
01794   const unsigned indx = unsigned(Src3.IntVal.getZExtValue());
01795   Dest.AggregateVal = Src1.AggregateVal;
01796 
01797   if(Src1.AggregateVal.size() <= indx)
01798       llvm_unreachable("Invalid index in insertelement instruction");
01799   switch (TyContained->getTypeID()) {
01800     default:
01801       llvm_unreachable("Unhandled dest type for insertelement instruction");
01802     case Type::IntegerTyID:
01803       Dest.AggregateVal[indx].IntVal = Src2.IntVal;
01804       break;
01805     case Type::FloatTyID:
01806       Dest.AggregateVal[indx].FloatVal = Src2.FloatVal;
01807       break;
01808     case Type::DoubleTyID:
01809       Dest.AggregateVal[indx].DoubleVal = Src2.DoubleVal;
01810       break;
01811   }
01812   SetValue(&I, Dest, SF);
01813 }
01814 
01815 void Interpreter::visitShuffleVectorInst(ShuffleVectorInst &I){
01816   ExecutionContext &SF = ECStack.back();
01817 
01818   Type *Ty = I.getType();
01819   if(!(Ty->isVectorTy()))
01820     llvm_unreachable("Unhandled dest type for shufflevector instruction");
01821 
01822   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
01823   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
01824   GenericValue Src3 = getOperandValue(I.getOperand(2), SF);
01825   GenericValue Dest;
01826 
01827   // There is no need to check types of src1 and src2, because the compiled
01828   // bytecode can't contain different types for src1 and src2 for a
01829   // shufflevector instruction.
01830 
01831   Type *TyContained = Ty->getContainedType(0);
01832   unsigned src1Size = (unsigned)Src1.AggregateVal.size();
01833   unsigned src2Size = (unsigned)Src2.AggregateVal.size();
01834   unsigned src3Size = (unsigned)Src3.AggregateVal.size();
01835 
01836   Dest.AggregateVal.resize(src3Size);
01837 
01838   switch (TyContained->getTypeID()) {
01839     default:
01840       llvm_unreachable("Unhandled dest type for insertelement instruction");
01841       break;
01842     case Type::IntegerTyID:
01843       for( unsigned i=0; i<src3Size; i++) {
01844         unsigned j = Src3.AggregateVal[i].IntVal.getZExtValue();
01845         if(j < src1Size)
01846           Dest.AggregateVal[i].IntVal = Src1.AggregateVal[j].IntVal;
01847         else if(j < src1Size + src2Size)
01848           Dest.AggregateVal[i].IntVal = Src2.AggregateVal[j-src1Size].IntVal;
01849         else
01850           // The selector may not be greater than sum of lengths of first and
01851           // second operands and llasm should not allow situation like
01852           // %tmp = shufflevector <2 x i32> <i32 3, i32 4>, <2 x i32> undef,
01853           //                      <2 x i32> < i32 0, i32 5 >,
01854           // where i32 5 is invalid, but let it be additional check here:
01855           llvm_unreachable("Invalid mask in shufflevector instruction");
01856       }
01857       break;
01858     case Type::FloatTyID:
01859       for( unsigned i=0; i<src3Size; i++) {
01860         unsigned j = Src3.AggregateVal[i].IntVal.getZExtValue();
01861         if(j < src1Size)
01862           Dest.AggregateVal[i].FloatVal = Src1.AggregateVal[j].FloatVal;
01863         else if(j < src1Size + src2Size)
01864           Dest.AggregateVal[i].FloatVal = Src2.AggregateVal[j-src1Size].FloatVal;
01865         else
01866           llvm_unreachable("Invalid mask in shufflevector instruction");
01867         }
01868       break;
01869     case Type::DoubleTyID:
01870       for( unsigned i=0; i<src3Size; i++) {
01871         unsigned j = Src3.AggregateVal[i].IntVal.getZExtValue();
01872         if(j < src1Size)
01873           Dest.AggregateVal[i].DoubleVal = Src1.AggregateVal[j].DoubleVal;
01874         else if(j < src1Size + src2Size)
01875           Dest.AggregateVal[i].DoubleVal =
01876             Src2.AggregateVal[j-src1Size].DoubleVal;
01877         else
01878           llvm_unreachable("Invalid mask in shufflevector instruction");
01879       }
01880       break;
01881   }
01882   SetValue(&I, Dest, SF);
01883 }
01884 
01885 void Interpreter::visitExtractValueInst(ExtractValueInst &I) {
01886   ExecutionContext &SF = ECStack.back();
01887   Value *Agg = I.getAggregateOperand();
01888   GenericValue Dest;
01889   GenericValue Src = getOperandValue(Agg, SF);
01890 
01891   ExtractValueInst::idx_iterator IdxBegin = I.idx_begin();
01892   unsigned Num = I.getNumIndices();
01893   GenericValue *pSrc = &Src;
01894 
01895   for (unsigned i = 0 ; i < Num; ++i) {
01896     pSrc = &pSrc->AggregateVal[*IdxBegin];
01897     ++IdxBegin;
01898   }
01899 
01900   Type *IndexedType = ExtractValueInst::getIndexedType(Agg->getType(), I.getIndices());
01901   switch (IndexedType->getTypeID()) {
01902     default:
01903       llvm_unreachable("Unhandled dest type for extractelement instruction");
01904     break;
01905     case Type::IntegerTyID:
01906       Dest.IntVal = pSrc->IntVal;
01907     break;
01908     case Type::FloatTyID:
01909       Dest.FloatVal = pSrc->FloatVal;
01910     break;
01911     case Type::DoubleTyID:
01912       Dest.DoubleVal = pSrc->DoubleVal;
01913     break;
01914     case Type::ArrayTyID:
01915     case Type::StructTyID:
01916     case Type::VectorTyID:
01917       Dest.AggregateVal = pSrc->AggregateVal;
01918     break;
01919     case Type::PointerTyID:
01920       Dest.PointerVal = pSrc->PointerVal;
01921     break;
01922   }
01923 
01924   SetValue(&I, Dest, SF);
01925 }
01926 
01927 void Interpreter::visitInsertValueInst(InsertValueInst &I) {
01928 
01929   ExecutionContext &SF = ECStack.back();
01930   Value *Agg = I.getAggregateOperand();
01931 
01932   GenericValue Src1 = getOperandValue(Agg, SF);
01933   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
01934   GenericValue Dest = Src1; // Dest is a slightly changed Src1
01935 
01936   ExtractValueInst::idx_iterator IdxBegin = I.idx_begin();
01937   unsigned Num = I.getNumIndices();
01938 
01939   GenericValue *pDest = &Dest;
01940   for (unsigned i = 0 ; i < Num; ++i) {
01941     pDest = &pDest->AggregateVal[*IdxBegin];
01942     ++IdxBegin;
01943   }
01944   // pDest points to the target value in the Dest now
01945 
01946   Type *IndexedType = ExtractValueInst::getIndexedType(Agg->getType(), I.getIndices());
01947 
01948   switch (IndexedType->getTypeID()) {
01949     default:
01950       llvm_unreachable("Unhandled dest type for insertelement instruction");
01951     break;
01952     case Type::IntegerTyID:
01953       pDest->IntVal = Src2.IntVal;
01954     break;
01955     case Type::FloatTyID:
01956       pDest->FloatVal = Src2.FloatVal;
01957     break;
01958     case Type::DoubleTyID:
01959       pDest->DoubleVal = Src2.DoubleVal;
01960     break;
01961     case Type::ArrayTyID:
01962     case Type::StructTyID:
01963     case Type::VectorTyID:
01964       pDest->AggregateVal = Src2.AggregateVal;
01965     break;
01966     case Type::PointerTyID:
01967       pDest->PointerVal = Src2.PointerVal;
01968     break;
01969   }
01970 
01971   SetValue(&I, Dest, SF);
01972 }
01973 
01974 GenericValue Interpreter::getConstantExprValue (ConstantExpr *CE,
01975                                                 ExecutionContext &SF) {
01976   switch (CE->getOpcode()) {
01977   case Instruction::Trunc:
01978       return executeTruncInst(CE->getOperand(0), CE->getType(), SF);
01979   case Instruction::ZExt:
01980       return executeZExtInst(CE->getOperand(0), CE->getType(), SF);
01981   case Instruction::SExt:
01982       return executeSExtInst(CE->getOperand(0), CE->getType(), SF);
01983   case Instruction::FPTrunc:
01984       return executeFPTruncInst(CE->getOperand(0), CE->getType(), SF);
01985   case Instruction::FPExt:
01986       return executeFPExtInst(CE->getOperand(0), CE->getType(), SF);
01987   case Instruction::UIToFP:
01988       return executeUIToFPInst(CE->getOperand(0), CE->getType(), SF);
01989   case Instruction::SIToFP:
01990       return executeSIToFPInst(CE->getOperand(0), CE->getType(), SF);
01991   case Instruction::FPToUI:
01992       return executeFPToUIInst(CE->getOperand(0), CE->getType(), SF);
01993   case Instruction::FPToSI:
01994       return executeFPToSIInst(CE->getOperand(0), CE->getType(), SF);
01995   case Instruction::PtrToInt:
01996       return executePtrToIntInst(CE->getOperand(0), CE->getType(), SF);
01997   case Instruction::IntToPtr:
01998       return executeIntToPtrInst(CE->getOperand(0), CE->getType(), SF);
01999   case Instruction::BitCast:
02000       return executeBitCastInst(CE->getOperand(0), CE->getType(), SF);
02001   case Instruction::GetElementPtr:
02002     return executeGEPOperation(CE->getOperand(0), gep_type_begin(CE),
02003                                gep_type_end(CE), SF);
02004   case Instruction::FCmp:
02005   case Instruction::ICmp:
02006     return executeCmpInst(CE->getPredicate(),
02007                           getOperandValue(CE->getOperand(0), SF),
02008                           getOperandValue(CE->getOperand(1), SF),
02009                           CE->getOperand(0)->getType());
02010   case Instruction::Select:
02011     return executeSelectInst(getOperandValue(CE->getOperand(0), SF),
02012                              getOperandValue(CE->getOperand(1), SF),
02013                              getOperandValue(CE->getOperand(2), SF),
02014                              CE->getOperand(0)->getType());
02015   default :
02016     break;
02017   }
02018 
02019   // The cases below here require a GenericValue parameter for the result
02020   // so we initialize one, compute it and then return it.
02021   GenericValue Op0 = getOperandValue(CE->getOperand(0), SF);
02022   GenericValue Op1 = getOperandValue(CE->getOperand(1), SF);
02023   GenericValue Dest;
02024   Type * Ty = CE->getOperand(0)->getType();
02025   switch (CE->getOpcode()) {
02026   case Instruction::Add:  Dest.IntVal = Op0.IntVal + Op1.IntVal; break;
02027   case Instruction::Sub:  Dest.IntVal = Op0.IntVal - Op1.IntVal; break;
02028   case Instruction::Mul:  Dest.IntVal = Op0.IntVal * Op1.IntVal; break;
02029   case Instruction::FAdd: executeFAddInst(Dest, Op0, Op1, Ty); break;
02030   case Instruction::FSub: executeFSubInst(Dest, Op0, Op1, Ty); break;
02031   case Instruction::FMul: executeFMulInst(Dest, Op0, Op1, Ty); break;
02032   case Instruction::FDiv: executeFDivInst(Dest, Op0, Op1, Ty); break;
02033   case Instruction::FRem: executeFRemInst(Dest, Op0, Op1, Ty); break;
02034   case Instruction::SDiv: Dest.IntVal = Op0.IntVal.sdiv(Op1.IntVal); break;
02035   case Instruction::UDiv: Dest.IntVal = Op0.IntVal.udiv(Op1.IntVal); break;
02036   case Instruction::URem: Dest.IntVal = Op0.IntVal.urem(Op1.IntVal); break;
02037   case Instruction::SRem: Dest.IntVal = Op0.IntVal.srem(Op1.IntVal); break;
02038   case Instruction::And:  Dest.IntVal = Op0.IntVal & Op1.IntVal; break;
02039   case Instruction::Or:   Dest.IntVal = Op0.IntVal | Op1.IntVal; break;
02040   case Instruction::Xor:  Dest.IntVal = Op0.IntVal ^ Op1.IntVal; break;
02041   case Instruction::Shl:  
02042     Dest.IntVal = Op0.IntVal.shl(Op1.IntVal.getZExtValue());
02043     break;
02044   case Instruction::LShr: 
02045     Dest.IntVal = Op0.IntVal.lshr(Op1.IntVal.getZExtValue());
02046     break;
02047   case Instruction::AShr: 
02048     Dest.IntVal = Op0.IntVal.ashr(Op1.IntVal.getZExtValue());
02049     break;
02050   default:
02051     dbgs() << "Unhandled ConstantExpr: " << *CE << "\n";
02052     llvm_unreachable("Unhandled ConstantExpr");
02053   }
02054   return Dest;
02055 }
02056 
02057 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
02058   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
02059     return getConstantExprValue(CE, SF);
02060   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
02061     return getConstantValue(CPV);
02062   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
02063     return PTOGV(getPointerToGlobal(GV));
02064   } else {
02065     return SF.Values[V];
02066   }
02067 }
02068 
02069 //===----------------------------------------------------------------------===//
02070 //                        Dispatch and Execution Code
02071 //===----------------------------------------------------------------------===//
02072 
02073 //===----------------------------------------------------------------------===//
02074 // callFunction - Execute the specified function...
02075 //
02076 void Interpreter::callFunction(Function *F, ArrayRef<GenericValue> ArgVals) {
02077   assert((ECStack.empty() || !ECStack.back().Caller.getInstruction() ||
02078           ECStack.back().Caller.arg_size() == ArgVals.size()) &&
02079          "Incorrect number of arguments passed into function call!");
02080   // Make a new stack frame... and fill it in.
02081   ECStack.emplace_back();
02082   ExecutionContext &StackFrame = ECStack.back();
02083   StackFrame.CurFunction = F;
02084 
02085   // Special handling for external functions.
02086   if (F->isDeclaration()) {
02087     GenericValue Result = callExternalFunction (F, ArgVals);
02088     // Simulate a 'ret' instruction of the appropriate type.
02089     popStackAndReturnValueToCaller (F->getReturnType (), Result);
02090     return;
02091   }
02092 
02093   // Get pointers to first LLVM BB & Instruction in function.
02094   StackFrame.CurBB     = F->begin();
02095   StackFrame.CurInst   = StackFrame.CurBB->begin();
02096 
02097   // Run through the function arguments and initialize their values...
02098   assert((ArgVals.size() == F->arg_size() ||
02099          (ArgVals.size() > F->arg_size() && F->getFunctionType()->isVarArg()))&&
02100          "Invalid number of values passed to function invocation!");
02101 
02102   // Handle non-varargs arguments...
02103   unsigned i = 0;
02104   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 
02105        AI != E; ++AI, ++i)
02106     SetValue(AI, ArgVals[i], StackFrame);
02107 
02108   // Handle varargs arguments...
02109   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
02110 }
02111 
02112 
02113 void Interpreter::run() {
02114   while (!ECStack.empty()) {
02115     // Interpret a single instruction & increment the "PC".
02116     ExecutionContext &SF = ECStack.back();  // Current stack frame
02117     Instruction &I = *SF.CurInst++;         // Increment before execute
02118 
02119     // Track the number of dynamic instructions executed.
02120     ++NumDynamicInsts;
02121 
02122     DEBUG(dbgs() << "About to interpret: " << I);
02123     visit(I);   // Dispatch to one of the visit* methods...
02124 #if 0
02125     // This is not safe, as visiting the instruction could lower it and free I.
02126 DEBUG(
02127     if (!isa<CallInst>(I) && !isa<InvokeInst>(I) && 
02128         I.getType() != Type::VoidTy) {
02129       dbgs() << "  --> ";
02130       const GenericValue &Val = SF.Values[&I];
02131       switch (I.getType()->getTypeID()) {
02132       default: llvm_unreachable("Invalid GenericValue Type");
02133       case Type::VoidTyID:    dbgs() << "void"; break;
02134       case Type::FloatTyID:   dbgs() << "float " << Val.FloatVal; break;
02135       case Type::DoubleTyID:  dbgs() << "double " << Val.DoubleVal; break;
02136       case Type::PointerTyID: dbgs() << "void* " << intptr_t(Val.PointerVal);
02137         break;
02138       case Type::IntegerTyID: 
02139         dbgs() << "i" << Val.IntVal.getBitWidth() << " "
02140                << Val.IntVal.toStringUnsigned(10)
02141                << " (0x" << Val.IntVal.toStringUnsigned(16) << ")\n";
02142         break;
02143       }
02144     });
02145 #endif
02146   }
02147 }