639415d7feadefad78b9c8b4c3071142f7c8f988
[oota-llvm.git] / lib / ExecutionEngine / Interpreter / Execution.cpp
1 //===-- Execution.cpp - Implement code to simulate the program ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file contains the actual instruction interpreter.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "interpreter"
15 #include "Interpreter.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/CodeGen/IntrinsicLowering.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MathExtras.h"
26 #include <algorithm>
27 #include <cmath>
28 #include <cstring>
29 using namespace llvm;
30
31 STATISTIC(NumDynamicInsts, "Number of dynamic instructions executed");
32 static Interpreter *TheEE = 0;
33
34 static cl::opt<bool> PrintVolatile("interpreter-print-volatile", cl::Hidden,
35           cl::desc("make the interpreter print every volatile load and store"));
36
37 //===----------------------------------------------------------------------===//
38 //                     Various Helper Functions
39 //===----------------------------------------------------------------------===//
40
41 static inline uint64_t doSignExtension(uint64_t Val, const IntegerType* ITy) {
42   // Determine if the value is signed or not
43   bool isSigned = (Val & (1 << (ITy->getBitWidth()-1))) != 0;
44   // If its signed, extend the sign bits
45   if (isSigned)
46     Val |= ~ITy->getBitMask();
47   return Val;
48 }
49
50 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
51   SF.Values[V] = Val;
52 }
53
54 void Interpreter::initializeExecutionEngine() {
55   TheEE = this;
56 }
57
58 //===----------------------------------------------------------------------===//
59 //                    Binary Instruction Implementations
60 //===----------------------------------------------------------------------===//
61
62 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
63    case Type::TY##TyID: \
64      Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; \
65      break
66
67 #define IMPLEMENT_INTEGER_BINOP1(OP, TY) \
68    case Type::IntegerTyID: { \
69      Dest.IntVal = Src1.IntVal OP Src2.IntVal; \
70      break; \
71    }
72
73
74 static void executeAddInst(GenericValue &Dest, GenericValue Src1, 
75                            GenericValue Src2, const Type *Ty) {
76   switch (Ty->getTypeID()) {
77     IMPLEMENT_INTEGER_BINOP1(+, Ty);
78     IMPLEMENT_BINARY_OPERATOR(+, Float);
79     IMPLEMENT_BINARY_OPERATOR(+, Double);
80   default:
81     cerr << "Unhandled type for Add instruction: " << *Ty << "\n";
82     abort();
83   }
84 }
85
86 static void executeSubInst(GenericValue &Dest, GenericValue Src1, 
87                            GenericValue Src2, const Type *Ty) {
88   switch (Ty->getTypeID()) {
89     IMPLEMENT_INTEGER_BINOP1(-, Ty);
90     IMPLEMENT_BINARY_OPERATOR(-, Float);
91     IMPLEMENT_BINARY_OPERATOR(-, Double);
92   default:
93     cerr << "Unhandled type for Sub instruction: " << *Ty << "\n";
94     abort();
95   }
96 }
97
98 static void executeMulInst(GenericValue &Dest, GenericValue Src1, 
99                            GenericValue Src2, const Type *Ty) {
100   switch (Ty->getTypeID()) {
101     IMPLEMENT_INTEGER_BINOP1(*, Ty);
102     IMPLEMENT_BINARY_OPERATOR(*, Float);
103     IMPLEMENT_BINARY_OPERATOR(*, Double);
104   default:
105     cerr << "Unhandled type for Mul instruction: " << *Ty << "\n";
106     abort();
107   }
108 }
109
110 static void executeFDivInst(GenericValue &Dest, GenericValue Src1, 
111                             GenericValue Src2, const Type *Ty) {
112   switch (Ty->getTypeID()) {
113     IMPLEMENT_BINARY_OPERATOR(/, Float);
114     IMPLEMENT_BINARY_OPERATOR(/, Double);
115   default:
116     cerr << "Unhandled type for FDiv instruction: " << *Ty << "\n";
117     abort();
118   }
119 }
120
121 static void executeFRemInst(GenericValue &Dest, GenericValue Src1, 
122                             GenericValue Src2, const Type *Ty) {
123   switch (Ty->getTypeID()) {
124   case Type::FloatTyID:
125     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
126     break;
127   case Type::DoubleTyID:
128     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
129     break;
130   default:
131     cerr << "Unhandled type for Rem instruction: " << *Ty << "\n";
132     abort();
133   }
134 }
135
136 #define IMPLEMENT_INTEGER_ICMP(OP, TY) \
137    case Type::IntegerTyID:  \
138       Dest.IntVal = APInt(1,Src1.IntVal.OP(Src2.IntVal)); \
139       break;
140
141 // Handle pointers specially because they must be compared with only as much
142 // width as the host has.  We _do not_ want to be comparing 64 bit values when
143 // running on a 32-bit target, otherwise the upper 32 bits might mess up
144 // comparisons if they contain garbage.
145 #define IMPLEMENT_POINTER_ICMP(OP) \
146    case Type::PointerTyID: \
147       Dest.IntVal = APInt(1,(void*)(intptr_t)Src1.PointerVal OP \
148                             (void*)(intptr_t)Src2.PointerVal); \
149       break;
150
151 static GenericValue executeICMP_EQ(GenericValue Src1, GenericValue Src2,
152                                    const Type *Ty) {
153   GenericValue Dest;
154   switch (Ty->getTypeID()) {
155     IMPLEMENT_INTEGER_ICMP(eq,Ty);
156     IMPLEMENT_POINTER_ICMP(==);
157   default:
158     cerr << "Unhandled type for ICMP_EQ predicate: " << *Ty << "\n";
159     abort();
160   }
161   return Dest;
162 }
163
164 static GenericValue executeICMP_NE(GenericValue Src1, GenericValue Src2,
165                                    const Type *Ty) {
166   GenericValue Dest;
167   switch (Ty->getTypeID()) {
168     IMPLEMENT_INTEGER_ICMP(ne,Ty);
169     IMPLEMENT_POINTER_ICMP(!=);
170   default:
171     cerr << "Unhandled type for ICMP_NE predicate: " << *Ty << "\n";
172     abort();
173   }
174   return Dest;
175 }
176
177 static GenericValue executeICMP_ULT(GenericValue Src1, GenericValue Src2,
178                                     const Type *Ty) {
179   GenericValue Dest;
180   switch (Ty->getTypeID()) {
181     IMPLEMENT_INTEGER_ICMP(ult,Ty);
182     IMPLEMENT_POINTER_ICMP(<);
183   default:
184     cerr << "Unhandled type for ICMP_ULT predicate: " << *Ty << "\n";
185     abort();
186   }
187   return Dest;
188 }
189
190 static GenericValue executeICMP_SLT(GenericValue Src1, GenericValue Src2,
191                                     const Type *Ty) {
192   GenericValue Dest;
193   switch (Ty->getTypeID()) {
194     IMPLEMENT_INTEGER_ICMP(slt,Ty);
195     IMPLEMENT_POINTER_ICMP(<);
196   default:
197     cerr << "Unhandled type for ICMP_SLT predicate: " << *Ty << "\n";
198     abort();
199   }
200   return Dest;
201 }
202
203 static GenericValue executeICMP_UGT(GenericValue Src1, GenericValue Src2,
204                                     const Type *Ty) {
205   GenericValue Dest;
206   switch (Ty->getTypeID()) {
207     IMPLEMENT_INTEGER_ICMP(ugt,Ty);
208     IMPLEMENT_POINTER_ICMP(>);
209   default:
210     cerr << "Unhandled type for ICMP_UGT predicate: " << *Ty << "\n";
211     abort();
212   }
213   return Dest;
214 }
215
216 static GenericValue executeICMP_SGT(GenericValue Src1, GenericValue Src2,
217                                     const Type *Ty) {
218   GenericValue Dest;
219   switch (Ty->getTypeID()) {
220     IMPLEMENT_INTEGER_ICMP(sgt,Ty);
221     IMPLEMENT_POINTER_ICMP(>);
222   default:
223     cerr << "Unhandled type for ICMP_SGT predicate: " << *Ty << "\n";
224     abort();
225   }
226   return Dest;
227 }
228
229 static GenericValue executeICMP_ULE(GenericValue Src1, GenericValue Src2,
230                                     const Type *Ty) {
231   GenericValue Dest;
232   switch (Ty->getTypeID()) {
233     IMPLEMENT_INTEGER_ICMP(ule,Ty);
234     IMPLEMENT_POINTER_ICMP(<=);
235   default:
236     cerr << "Unhandled type for ICMP_ULE predicate: " << *Ty << "\n";
237     abort();
238   }
239   return Dest;
240 }
241
242 static GenericValue executeICMP_SLE(GenericValue Src1, GenericValue Src2,
243                                     const Type *Ty) {
244   GenericValue Dest;
245   switch (Ty->getTypeID()) {
246     IMPLEMENT_INTEGER_ICMP(sle,Ty);
247     IMPLEMENT_POINTER_ICMP(<=);
248   default:
249     cerr << "Unhandled type for ICMP_SLE predicate: " << *Ty << "\n";
250     abort();
251   }
252   return Dest;
253 }
254
255 static GenericValue executeICMP_UGE(GenericValue Src1, GenericValue Src2,
256                                     const Type *Ty) {
257   GenericValue Dest;
258   switch (Ty->getTypeID()) {
259     IMPLEMENT_INTEGER_ICMP(uge,Ty);
260     IMPLEMENT_POINTER_ICMP(>=);
261   default:
262     cerr << "Unhandled type for ICMP_UGE predicate: " << *Ty << "\n";
263     abort();
264   }
265   return Dest;
266 }
267
268 static GenericValue executeICMP_SGE(GenericValue Src1, GenericValue Src2,
269                                     const Type *Ty) {
270   GenericValue Dest;
271   switch (Ty->getTypeID()) {
272     IMPLEMENT_INTEGER_ICMP(sge,Ty);
273     IMPLEMENT_POINTER_ICMP(>=);
274   default:
275     cerr << "Unhandled type for ICMP_SGE predicate: " << *Ty << "\n";
276     abort();
277   }
278   return Dest;
279 }
280
281 void Interpreter::visitICmpInst(ICmpInst &I) {
282   ExecutionContext &SF = ECStack.back();
283   const Type *Ty    = I.getOperand(0)->getType();
284   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
285   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
286   GenericValue R;   // Result
287   
288   switch (I.getPredicate()) {
289   case ICmpInst::ICMP_EQ:  R = executeICMP_EQ(Src1,  Src2, Ty); break;
290   case ICmpInst::ICMP_NE:  R = executeICMP_NE(Src1,  Src2, Ty); break;
291   case ICmpInst::ICMP_ULT: R = executeICMP_ULT(Src1, Src2, Ty); break;
292   case ICmpInst::ICMP_SLT: R = executeICMP_SLT(Src1, Src2, Ty); break;
293   case ICmpInst::ICMP_UGT: R = executeICMP_UGT(Src1, Src2, Ty); break;
294   case ICmpInst::ICMP_SGT: R = executeICMP_SGT(Src1, Src2, Ty); break;
295   case ICmpInst::ICMP_ULE: R = executeICMP_ULE(Src1, Src2, Ty); break;
296   case ICmpInst::ICMP_SLE: R = executeICMP_SLE(Src1, Src2, Ty); break;
297   case ICmpInst::ICMP_UGE: R = executeICMP_UGE(Src1, Src2, Ty); break;
298   case ICmpInst::ICMP_SGE: R = executeICMP_SGE(Src1, Src2, Ty); break;
299   default:
300     cerr << "Don't know how to handle this ICmp predicate!\n-->" << I;
301     abort();
302   }
303  
304   SetValue(&I, R, SF);
305 }
306
307 #define IMPLEMENT_FCMP(OP, TY) \
308    case Type::TY##TyID: \
309      Dest.IntVal = APInt(1,Src1.TY##Val OP Src2.TY##Val); \
310      break
311
312 static GenericValue executeFCMP_OEQ(GenericValue Src1, GenericValue Src2,
313                                    const Type *Ty) {
314   GenericValue Dest;
315   switch (Ty->getTypeID()) {
316     IMPLEMENT_FCMP(==, Float);
317     IMPLEMENT_FCMP(==, Double);
318   default:
319     cerr << "Unhandled type for FCmp EQ instruction: " << *Ty << "\n";
320     abort();
321   }
322   return Dest;
323 }
324
325 static GenericValue executeFCMP_ONE(GenericValue Src1, GenericValue Src2,
326                                    const Type *Ty) {
327   GenericValue Dest;
328   switch (Ty->getTypeID()) {
329     IMPLEMENT_FCMP(!=, Float);
330     IMPLEMENT_FCMP(!=, Double);
331
332   default:
333     cerr << "Unhandled type for FCmp NE instruction: " << *Ty << "\n";
334     abort();
335   }
336   return Dest;
337 }
338
339 static GenericValue executeFCMP_OLE(GenericValue Src1, GenericValue Src2,
340                                    const Type *Ty) {
341   GenericValue Dest;
342   switch (Ty->getTypeID()) {
343     IMPLEMENT_FCMP(<=, Float);
344     IMPLEMENT_FCMP(<=, Double);
345   default:
346     cerr << "Unhandled type for FCmp LE instruction: " << *Ty << "\n";
347     abort();
348   }
349   return Dest;
350 }
351
352 static GenericValue executeFCMP_OGE(GenericValue Src1, GenericValue Src2,
353                                    const Type *Ty) {
354   GenericValue Dest;
355   switch (Ty->getTypeID()) {
356     IMPLEMENT_FCMP(>=, Float);
357     IMPLEMENT_FCMP(>=, Double);
358   default:
359     cerr << "Unhandled type for FCmp GE instruction: " << *Ty << "\n";
360     abort();
361   }
362   return Dest;
363 }
364
365 static GenericValue executeFCMP_OLT(GenericValue Src1, GenericValue Src2,
366                                    const Type *Ty) {
367   GenericValue Dest;
368   switch (Ty->getTypeID()) {
369     IMPLEMENT_FCMP(<, Float);
370     IMPLEMENT_FCMP(<, Double);
371   default:
372     cerr << "Unhandled type for FCmp LT instruction: " << *Ty << "\n";
373     abort();
374   }
375   return Dest;
376 }
377
378 static GenericValue executeFCMP_OGT(GenericValue Src1, GenericValue Src2,
379                                      const Type *Ty) {
380   GenericValue Dest;
381   switch (Ty->getTypeID()) {
382     IMPLEMENT_FCMP(>, Float);
383     IMPLEMENT_FCMP(>, Double);
384   default:
385     cerr << "Unhandled type for FCmp GT instruction: " << *Ty << "\n";
386     abort();
387   }
388   return Dest;
389 }
390
391 #define IMPLEMENT_UNORDERED(TY, X,Y)                                     \
392   if (TY == Type::FloatTy) {                                             \
393     if (X.FloatVal != X.FloatVal || Y.FloatVal != Y.FloatVal) {          \
394       Dest.IntVal = APInt(1,true);                                       \
395       return Dest;                                                       \
396     }                                                                    \
397   } else if (X.DoubleVal != X.DoubleVal || Y.DoubleVal != Y.DoubleVal) { \
398     Dest.IntVal = APInt(1,true);                                         \
399     return Dest;                                                         \
400   }
401
402
403 static GenericValue executeFCMP_UEQ(GenericValue Src1, GenericValue Src2,
404                                    const Type *Ty) {
405   GenericValue Dest;
406   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
407   return executeFCMP_OEQ(Src1, Src2, Ty);
408 }
409
410 static GenericValue executeFCMP_UNE(GenericValue Src1, GenericValue Src2,
411                                    const Type *Ty) {
412   GenericValue Dest;
413   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
414   return executeFCMP_ONE(Src1, Src2, Ty);
415 }
416
417 static GenericValue executeFCMP_ULE(GenericValue Src1, GenericValue Src2,
418                                    const Type *Ty) {
419   GenericValue Dest;
420   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
421   return executeFCMP_OLE(Src1, Src2, Ty);
422 }
423
424 static GenericValue executeFCMP_UGE(GenericValue Src1, GenericValue Src2,
425                                    const Type *Ty) {
426   GenericValue Dest;
427   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
428   return executeFCMP_OGE(Src1, Src2, Ty);
429 }
430
431 static GenericValue executeFCMP_ULT(GenericValue Src1, GenericValue Src2,
432                                    const Type *Ty) {
433   GenericValue Dest;
434   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
435   return executeFCMP_OLT(Src1, Src2, Ty);
436 }
437
438 static GenericValue executeFCMP_UGT(GenericValue Src1, GenericValue Src2,
439                                      const Type *Ty) {
440   GenericValue Dest;
441   IMPLEMENT_UNORDERED(Ty, Src1, Src2)
442   return executeFCMP_OGT(Src1, Src2, Ty);
443 }
444
445 static GenericValue executeFCMP_ORD(GenericValue Src1, GenericValue Src2,
446                                      const Type *Ty) {
447   GenericValue Dest;
448   if (Ty == Type::FloatTy)
449     Dest.IntVal = APInt(1,(Src1.FloatVal == Src1.FloatVal && 
450                            Src2.FloatVal == Src2.FloatVal));
451   else
452     Dest.IntVal = APInt(1,(Src1.DoubleVal == Src1.DoubleVal && 
453                            Src2.DoubleVal == Src2.DoubleVal));
454   return Dest;
455 }
456
457 static GenericValue executeFCMP_UNO(GenericValue Src1, GenericValue Src2,
458                                      const Type *Ty) {
459   GenericValue Dest;
460   if (Ty == Type::FloatTy)
461     Dest.IntVal = APInt(1,(Src1.FloatVal != Src1.FloatVal || 
462                            Src2.FloatVal != Src2.FloatVal));
463   else
464     Dest.IntVal = APInt(1,(Src1.DoubleVal != Src1.DoubleVal || 
465                            Src2.DoubleVal != Src2.DoubleVal));
466   return Dest;
467 }
468
469 void Interpreter::visitFCmpInst(FCmpInst &I) {
470   ExecutionContext &SF = ECStack.back();
471   const Type *Ty    = I.getOperand(0)->getType();
472   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
473   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
474   GenericValue R;   // Result
475   
476   switch (I.getPredicate()) {
477   case FCmpInst::FCMP_FALSE: R.IntVal = APInt(1,false); break;
478   case FCmpInst::FCMP_TRUE:  R.IntVal = APInt(1,true); break;
479   case FCmpInst::FCMP_ORD:   R = executeFCMP_ORD(Src1, Src2, Ty); break;
480   case FCmpInst::FCMP_UNO:   R = executeFCMP_UNO(Src1, Src2, Ty); break;
481   case FCmpInst::FCMP_UEQ:   R = executeFCMP_UEQ(Src1, Src2, Ty); break;
482   case FCmpInst::FCMP_OEQ:   R = executeFCMP_OEQ(Src1, Src2, Ty); break;
483   case FCmpInst::FCMP_UNE:   R = executeFCMP_UNE(Src1, Src2, Ty); break;
484   case FCmpInst::FCMP_ONE:   R = executeFCMP_ONE(Src1, Src2, Ty); break;
485   case FCmpInst::FCMP_ULT:   R = executeFCMP_ULT(Src1, Src2, Ty); break;
486   case FCmpInst::FCMP_OLT:   R = executeFCMP_OLT(Src1, Src2, Ty); break;
487   case FCmpInst::FCMP_UGT:   R = executeFCMP_UGT(Src1, Src2, Ty); break;
488   case FCmpInst::FCMP_OGT:   R = executeFCMP_OGT(Src1, Src2, Ty); break;
489   case FCmpInst::FCMP_ULE:   R = executeFCMP_ULE(Src1, Src2, Ty); break;
490   case FCmpInst::FCMP_OLE:   R = executeFCMP_OLE(Src1, Src2, Ty); break;
491   case FCmpInst::FCMP_UGE:   R = executeFCMP_UGE(Src1, Src2, Ty); break;
492   case FCmpInst::FCMP_OGE:   R = executeFCMP_OGE(Src1, Src2, Ty); break;
493   default:
494     cerr << "Don't know how to handle this FCmp predicate!\n-->" << I;
495     abort();
496   }
497  
498   SetValue(&I, R, SF);
499 }
500
501 static GenericValue executeCmpInst(unsigned predicate, GenericValue Src1, 
502                                    GenericValue Src2, const Type *Ty) {
503   GenericValue Result;
504   switch (predicate) {
505   case ICmpInst::ICMP_EQ:    return executeICMP_EQ(Src1, Src2, Ty);
506   case ICmpInst::ICMP_NE:    return executeICMP_NE(Src1, Src2, Ty);
507   case ICmpInst::ICMP_UGT:   return executeICMP_UGT(Src1, Src2, Ty);
508   case ICmpInst::ICMP_SGT:   return executeICMP_SGT(Src1, Src2, Ty);
509   case ICmpInst::ICMP_ULT:   return executeICMP_ULT(Src1, Src2, Ty);
510   case ICmpInst::ICMP_SLT:   return executeICMP_SLT(Src1, Src2, Ty);
511   case ICmpInst::ICMP_UGE:   return executeICMP_UGE(Src1, Src2, Ty);
512   case ICmpInst::ICMP_SGE:   return executeICMP_SGE(Src1, Src2, Ty);
513   case ICmpInst::ICMP_ULE:   return executeICMP_ULE(Src1, Src2, Ty);
514   case ICmpInst::ICMP_SLE:   return executeICMP_SLE(Src1, Src2, Ty);
515   case FCmpInst::FCMP_ORD:   return executeFCMP_ORD(Src1, Src2, Ty);
516   case FCmpInst::FCMP_UNO:   return executeFCMP_UNO(Src1, Src2, Ty);
517   case FCmpInst::FCMP_OEQ:   return executeFCMP_OEQ(Src1, Src2, Ty);
518   case FCmpInst::FCMP_UEQ:   return executeFCMP_UEQ(Src1, Src2, Ty);
519   case FCmpInst::FCMP_ONE:   return executeFCMP_ONE(Src1, Src2, Ty);
520   case FCmpInst::FCMP_UNE:   return executeFCMP_UNE(Src1, Src2, Ty);
521   case FCmpInst::FCMP_OLT:   return executeFCMP_OLT(Src1, Src2, Ty);
522   case FCmpInst::FCMP_ULT:   return executeFCMP_ULT(Src1, Src2, Ty);
523   case FCmpInst::FCMP_OGT:   return executeFCMP_OGT(Src1, Src2, Ty);
524   case FCmpInst::FCMP_UGT:   return executeFCMP_UGT(Src1, Src2, Ty);
525   case FCmpInst::FCMP_OLE:   return executeFCMP_OLE(Src1, Src2, Ty);
526   case FCmpInst::FCMP_ULE:   return executeFCMP_ULE(Src1, Src2, Ty);
527   case FCmpInst::FCMP_OGE:   return executeFCMP_OGE(Src1, Src2, Ty);
528   case FCmpInst::FCMP_UGE:   return executeFCMP_UGE(Src1, Src2, Ty);
529   case FCmpInst::FCMP_FALSE: { 
530     GenericValue Result;
531     Result.IntVal = APInt(1, false);
532     return Result;
533   }
534   case FCmpInst::FCMP_TRUE: {
535     GenericValue Result;
536     Result.IntVal = APInt(1, true);
537     return Result;
538   }
539   default:
540     cerr << "Unhandled Cmp predicate\n";
541     abort();
542   }
543 }
544
545 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
546   ExecutionContext &SF = ECStack.back();
547   const Type *Ty    = I.getOperand(0)->getType();
548   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
549   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
550   GenericValue R;   // Result
551
552   switch (I.getOpcode()) {
553   case Instruction::Add:   executeAddInst  (R, Src1, Src2, Ty); break;
554   case Instruction::Sub:   executeSubInst  (R, Src1, Src2, Ty); break;
555   case Instruction::Mul:   executeMulInst  (R, Src1, Src2, Ty); break;
556   case Instruction::FDiv:  executeFDivInst (R, Src1, Src2, Ty); break;
557   case Instruction::FRem:  executeFRemInst (R, Src1, Src2, Ty); break;
558   case Instruction::UDiv:  R.IntVal = Src1.IntVal.udiv(Src2.IntVal); break;
559   case Instruction::SDiv:  R.IntVal = Src1.IntVal.sdiv(Src2.IntVal); break;
560   case Instruction::URem:  R.IntVal = Src1.IntVal.urem(Src2.IntVal); break;
561   case Instruction::SRem:  R.IntVal = Src1.IntVal.srem(Src2.IntVal); break;
562   case Instruction::And:   R.IntVal = Src1.IntVal & Src2.IntVal; break;
563   case Instruction::Or:    R.IntVal = Src1.IntVal | Src2.IntVal; break;
564   case Instruction::Xor:   R.IntVal = Src1.IntVal ^ Src2.IntVal; break;
565   default:
566     cerr << "Don't know how to handle this binary operator!\n-->" << I;
567     abort();
568   }
569
570   SetValue(&I, R, SF);
571 }
572
573 static GenericValue executeSelectInst(GenericValue Src1, GenericValue Src2,
574                                       GenericValue Src3) {
575   return Src1.IntVal == 0 ? Src3 : Src2;
576 }
577
578 void Interpreter::visitSelectInst(SelectInst &I) {
579   ExecutionContext &SF = ECStack.back();
580   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
581   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
582   GenericValue Src3 = getOperandValue(I.getOperand(2), SF);
583   GenericValue R = executeSelectInst(Src1, Src2, Src3);
584   SetValue(&I, R, SF);
585 }
586
587
588 //===----------------------------------------------------------------------===//
589 //                     Terminator Instruction Implementations
590 //===----------------------------------------------------------------------===//
591
592 void Interpreter::exitCalled(GenericValue GV) {
593   // runAtExitHandlers() assumes there are no stack frames, but
594   // if exit() was called, then it had a stack frame. Blow away
595   // the stack before interpreting atexit handlers.
596   ECStack.clear ();
597   runAtExitHandlers ();
598   exit (GV.IntVal.zextOrTrunc(32).getZExtValue());
599 }
600
601 /// Pop the last stack frame off of ECStack and then copy the result
602 /// back into the result variable if we are not returning void. The
603 /// result variable may be the ExitValue, or the Value of the calling
604 /// CallInst if there was a previous stack frame. This method may
605 /// invalidate any ECStack iterators you have. This method also takes
606 /// care of switching to the normal destination BB, if we are returning
607 /// from an invoke.
608 ///
609 void Interpreter::popStackAndReturnValueToCaller (const Type *RetTy,
610                                                   GenericValue Result) {
611   // Pop the current stack frame.
612   ECStack.pop_back();
613
614   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
615     if (RetTy && RetTy->isInteger()) {          // Nonvoid return type?
616       ExitValue = Result;   // Capture the exit value of the program
617     } else {
618       memset(&ExitValue.Untyped, 0, sizeof(ExitValue.Untyped));
619     }
620   } else {
621     // If we have a previous stack frame, and we have a previous call,
622     // fill in the return value...
623     ExecutionContext &CallingSF = ECStack.back();
624     if (Instruction *I = CallingSF.Caller.getInstruction()) {
625       if (CallingSF.Caller.getType() != Type::VoidTy)      // Save result...
626         SetValue(I, Result, CallingSF);
627       if (InvokeInst *II = dyn_cast<InvokeInst> (I))
628         SwitchToNewBasicBlock (II->getNormalDest (), CallingSF);
629       CallingSF.Caller = CallSite();          // We returned from the call...
630     }
631   }
632 }
633
634 void Interpreter::visitReturnInst(ReturnInst &I) {
635   ExecutionContext &SF = ECStack.back();
636   const Type *RetTy = Type::VoidTy;
637   GenericValue Result;
638
639   // Save away the return value... (if we are not 'ret void')
640   if (I.getNumOperands()) {
641     RetTy  = I.getReturnValue()->getType();
642     Result = getOperandValue(I.getReturnValue(), SF);
643   }
644
645   popStackAndReturnValueToCaller(RetTy, Result);
646 }
647
648 void Interpreter::visitUnwindInst(UnwindInst &I) {
649   // Unwind stack
650   Instruction *Inst;
651   do {
652     ECStack.pop_back ();
653     if (ECStack.empty ())
654       abort ();
655     Inst = ECStack.back ().Caller.getInstruction ();
656   } while (!(Inst && isa<InvokeInst> (Inst)));
657
658   // Return from invoke
659   ExecutionContext &InvokingSF = ECStack.back ();
660   InvokingSF.Caller = CallSite ();
661
662   // Go to exceptional destination BB of invoke instruction
663   SwitchToNewBasicBlock(cast<InvokeInst>(Inst)->getUnwindDest(), InvokingSF);
664 }
665
666 void Interpreter::visitUnreachableInst(UnreachableInst &I) {
667   cerr << "ERROR: Program executed an 'unreachable' instruction!\n";
668   abort();
669 }
670
671 void Interpreter::visitBranchInst(BranchInst &I) {
672   ExecutionContext &SF = ECStack.back();
673   BasicBlock *Dest;
674
675   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
676   if (!I.isUnconditional()) {
677     Value *Cond = I.getCondition();
678     if (getOperandValue(Cond, SF).IntVal == 0) // If false cond...
679       Dest = I.getSuccessor(1);
680   }
681   SwitchToNewBasicBlock(Dest, SF);
682 }
683
684 void Interpreter::visitSwitchInst(SwitchInst &I) {
685   ExecutionContext &SF = ECStack.back();
686   GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
687   const Type *ElTy = I.getOperand(0)->getType();
688
689   // Check to see if any of the cases match...
690   BasicBlock *Dest = 0;
691   for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
692     if (executeICMP_EQ(CondVal, getOperandValue(I.getOperand(i), SF), ElTy)
693         .IntVal != 0) {
694       Dest = cast<BasicBlock>(I.getOperand(i+1));
695       break;
696     }
697
698   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
699   SwitchToNewBasicBlock(Dest, SF);
700 }
701
702 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
703 // This function handles the actual updating of block and instruction iterators
704 // as well as execution of all of the PHI nodes in the destination block.
705 //
706 // This method does this because all of the PHI nodes must be executed
707 // atomically, reading their inputs before any of the results are updated.  Not
708 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
709 // their inputs.  If the input PHI node is updated before it is read, incorrect
710 // results can happen.  Thus we use a two phase approach.
711 //
712 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
713   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
714   SF.CurBB   = Dest;                  // Update CurBB to branch destination
715   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
716
717   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
718
719   // Loop over all of the PHI nodes in the current block, reading their inputs.
720   std::vector<GenericValue> ResultValues;
721
722   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
723     // Search for the value corresponding to this previous bb...
724     int i = PN->getBasicBlockIndex(PrevBB);
725     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
726     Value *IncomingValue = PN->getIncomingValue(i);
727
728     // Save the incoming value for this PHI node...
729     ResultValues.push_back(getOperandValue(IncomingValue, SF));
730   }
731
732   // Now loop over all of the PHI nodes setting their values...
733   SF.CurInst = SF.CurBB->begin();
734   for (unsigned i = 0; isa<PHINode>(SF.CurInst); ++SF.CurInst, ++i) {
735     PHINode *PN = cast<PHINode>(SF.CurInst);
736     SetValue(PN, ResultValues[i], SF);
737   }
738 }
739
740 //===----------------------------------------------------------------------===//
741 //                     Memory Instruction Implementations
742 //===----------------------------------------------------------------------===//
743
744 void Interpreter::visitAllocationInst(AllocationInst &I) {
745   ExecutionContext &SF = ECStack.back();
746
747   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
748
749   // Get the number of elements being allocated by the array...
750   unsigned NumElements = 
751     getOperandValue(I.getOperand(0), SF).IntVal.getZExtValue();
752
753   unsigned TypeSize = (size_t)TD.getABITypeSize(Ty);
754
755   // Avoid malloc-ing zero bytes, use max()...
756   unsigned MemToAlloc = std::max(1U, NumElements * TypeSize);
757
758   // Allocate enough memory to hold the type...
759   void *Memory = malloc(MemToAlloc);
760
761   DOUT << "Allocated Type: " << *Ty << " (" << TypeSize << " bytes) x " 
762        << NumElements << " (Total: " << MemToAlloc << ") at "
763        << uintptr_t(Memory) << '\n';
764
765   GenericValue Result = PTOGV(Memory);
766   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
767   SetValue(&I, Result, SF);
768
769   if (I.getOpcode() == Instruction::Alloca)
770     ECStack.back().Allocas.add(Memory);
771 }
772
773 void Interpreter::visitFreeInst(FreeInst &I) {
774   ExecutionContext &SF = ECStack.back();
775   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
776   GenericValue Value = getOperandValue(I.getOperand(0), SF);
777   // TODO: Check to make sure memory is allocated
778   free(GVTOP(Value));   // Free memory
779 }
780
781 // getElementOffset - The workhorse for getelementptr.
782 //
783 GenericValue Interpreter::executeGEPOperation(Value *Ptr, gep_type_iterator I,
784                                               gep_type_iterator E,
785                                               ExecutionContext &SF) {
786   assert(isa<PointerType>(Ptr->getType()) &&
787          "Cannot getElementOffset of a nonpointer type!");
788
789   uint64_t Total = 0;
790
791   for (; I != E; ++I) {
792     if (const StructType *STy = dyn_cast<StructType>(*I)) {
793       const StructLayout *SLO = TD.getStructLayout(STy);
794
795       const ConstantInt *CPU = cast<ConstantInt>(I.getOperand());
796       unsigned Index = unsigned(CPU->getZExtValue());
797
798       Total += SLO->getElementOffset(Index);
799     } else {
800       const SequentialType *ST = cast<SequentialType>(*I);
801       // Get the index number for the array... which must be long type...
802       GenericValue IdxGV = getOperandValue(I.getOperand(), SF);
803
804       int64_t Idx;
805       unsigned BitWidth = 
806         cast<IntegerType>(I.getOperand()->getType())->getBitWidth();
807       if (BitWidth == 32)
808         Idx = (int64_t)(int32_t)IdxGV.IntVal.getZExtValue();
809       else {
810         assert(BitWidth == 64 && "Invalid index type for getelementptr");
811         Idx = (int64_t)IdxGV.IntVal.getZExtValue();
812       }
813       Total += TD.getABITypeSize(ST->getElementType())*Idx;
814     }
815   }
816
817   GenericValue Result;
818   Result.PointerVal = ((char*)getOperandValue(Ptr, SF).PointerVal) + Total;
819   DOUT << "GEP Index " << Total << " bytes.\n";
820   return Result;
821 }
822
823 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
824   ExecutionContext &SF = ECStack.back();
825   SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
826                                    gep_type_begin(I), gep_type_end(I), SF), SF);
827 }
828
829 void Interpreter::visitLoadInst(LoadInst &I) {
830   ExecutionContext &SF = ECStack.back();
831   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
832   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
833   GenericValue Result;
834   LoadValueFromMemory(Result, Ptr, I.getType());
835   SetValue(&I, Result, SF);
836   if (I.isVolatile() && PrintVolatile)
837     cerr << "Volatile load " << I;
838 }
839
840 void Interpreter::visitStoreInst(StoreInst &I) {
841   ExecutionContext &SF = ECStack.back();
842   GenericValue Val = getOperandValue(I.getOperand(0), SF);
843   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
844   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
845                      I.getOperand(0)->getType());
846   if (I.isVolatile() && PrintVolatile)
847     cerr << "Volatile store: " << I;
848 }
849
850 //===----------------------------------------------------------------------===//
851 //                 Miscellaneous Instruction Implementations
852 //===----------------------------------------------------------------------===//
853
854 void Interpreter::visitCallSite(CallSite CS) {
855   ExecutionContext &SF = ECStack.back();
856
857   // Check to see if this is an intrinsic function call...
858   Function *F = CS.getCalledFunction();
859   if (F && F->isDeclaration ())
860     switch (F->getIntrinsicID()) {
861     case Intrinsic::not_intrinsic:
862       break;
863     case Intrinsic::vastart: { // va_start
864       GenericValue ArgIndex;
865       ArgIndex.UIntPairVal.first = ECStack.size() - 1;
866       ArgIndex.UIntPairVal.second = 0;
867       SetValue(CS.getInstruction(), ArgIndex, SF);
868       return;
869     }
870     case Intrinsic::vaend:    // va_end is a noop for the interpreter
871       return;
872     case Intrinsic::vacopy:   // va_copy: dest = src
873       SetValue(CS.getInstruction(), getOperandValue(*CS.arg_begin(), SF), SF);
874       return;
875     default:
876       // If it is an unknown intrinsic function, use the intrinsic lowering
877       // class to transform it into hopefully tasty LLVM code.
878       //
879       BasicBlock::iterator me(CS.getInstruction());
880       BasicBlock *Parent = CS.getInstruction()->getParent();
881       bool atBegin(Parent->begin() == me);
882       if (!atBegin)
883         --me;
884       IL->LowerIntrinsicCall(cast<CallInst>(CS.getInstruction()));
885
886       // Restore the CurInst pointer to the first instruction newly inserted, if
887       // any.
888       if (atBegin) {
889         SF.CurInst = Parent->begin();
890       } else {
891         SF.CurInst = me;
892         ++SF.CurInst;
893       }
894       return;
895     }
896
897
898   SF.Caller = CS;
899   std::vector<GenericValue> ArgVals;
900   const unsigned NumArgs = SF.Caller.arg_size();
901   ArgVals.reserve(NumArgs);
902   uint16_t pNum = 1;
903   for (CallSite::arg_iterator i = SF.Caller.arg_begin(),
904          e = SF.Caller.arg_end(); i != e; ++i, ++pNum) {
905     Value *V = *i;
906     ArgVals.push_back(getOperandValue(V, SF));
907     // Promote all integral types whose size is < sizeof(i32) into i32.
908     // We do this by zero or sign extending the value as appropriate
909     // according to the parameter attributes
910     const Type *Ty = V->getType();
911     if (Ty->isInteger() && (ArgVals.back().IntVal.getBitWidth() < 32)) {
912       if (CS.paramHasAttr(pNum, Attribute::ZExt))
913         ArgVals.back().IntVal = ArgVals.back().IntVal.zext(32);
914       else if (CS.paramHasAttr(pNum, Attribute::SExt))
915         ArgVals.back().IntVal = ArgVals.back().IntVal.sext(32);
916     }
917   }
918
919   // To handle indirect calls, we must get the pointer value from the argument
920   // and treat it as a function pointer.
921   GenericValue SRC = getOperandValue(SF.Caller.getCalledValue(), SF);
922   callFunction((Function*)GVTOP(SRC), ArgVals);
923 }
924
925 void Interpreter::visitShl(BinaryOperator &I) {
926   ExecutionContext &SF = ECStack.back();
927   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
928   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
929   GenericValue Dest;
930   Dest.IntVal = Src1.IntVal.shl(Src2.IntVal.getZExtValue());
931   SetValue(&I, Dest, SF);
932 }
933
934 void Interpreter::visitLShr(BinaryOperator &I) {
935   ExecutionContext &SF = ECStack.back();
936   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
937   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
938   GenericValue Dest;
939   Dest.IntVal =  Src1.IntVal.lshr(Src2.IntVal.getZExtValue());
940   SetValue(&I, Dest, SF);
941 }
942
943 void Interpreter::visitAShr(BinaryOperator &I) {
944   ExecutionContext &SF = ECStack.back();
945   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
946   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
947   GenericValue Dest; 
948   Dest.IntVal = Src1.IntVal.ashr(Src2.IntVal.getZExtValue());
949   SetValue(&I, Dest, SF);
950 }
951
952 GenericValue Interpreter::executeTruncInst(Value *SrcVal, const Type *DstTy,
953                                            ExecutionContext &SF) {
954   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
955   const IntegerType *DITy = cast<IntegerType>(DstTy);
956   unsigned DBitWidth = DITy->getBitWidth();
957   Dest.IntVal = Src.IntVal.trunc(DBitWidth);
958   return Dest;
959 }
960
961 GenericValue Interpreter::executeSExtInst(Value *SrcVal, const Type *DstTy,
962                                           ExecutionContext &SF) {
963   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
964   const IntegerType *DITy = cast<IntegerType>(DstTy);
965   unsigned DBitWidth = DITy->getBitWidth();
966   Dest.IntVal = Src.IntVal.sext(DBitWidth);
967   return Dest;
968 }
969
970 GenericValue Interpreter::executeZExtInst(Value *SrcVal, const Type *DstTy,
971                                           ExecutionContext &SF) {
972   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
973   const IntegerType *DITy = cast<IntegerType>(DstTy);
974   unsigned DBitWidth = DITy->getBitWidth();
975   Dest.IntVal = Src.IntVal.zext(DBitWidth);
976   return Dest;
977 }
978
979 GenericValue Interpreter::executeFPTruncInst(Value *SrcVal, const Type *DstTy,
980                                              ExecutionContext &SF) {
981   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
982   assert(SrcVal->getType() == Type::DoubleTy && DstTy == Type::FloatTy &&
983          "Invalid FPTrunc instruction");
984   Dest.FloatVal = (float) Src.DoubleVal;
985   return Dest;
986 }
987
988 GenericValue Interpreter::executeFPExtInst(Value *SrcVal, const Type *DstTy,
989                                            ExecutionContext &SF) {
990   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
991   assert(SrcVal->getType() == Type::FloatTy && DstTy == Type::DoubleTy &&
992          "Invalid FPTrunc instruction");
993   Dest.DoubleVal = (double) Src.FloatVal;
994   return Dest;
995 }
996
997 GenericValue Interpreter::executeFPToUIInst(Value *SrcVal, const Type *DstTy,
998                                             ExecutionContext &SF) {
999   const Type *SrcTy = SrcVal->getType();
1000   uint32_t DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
1001   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1002   assert(SrcTy->isFloatingPoint() && "Invalid FPToUI instruction");
1003
1004   if (SrcTy->getTypeID() == Type::FloatTyID)
1005     Dest.IntVal = APIntOps::RoundFloatToAPInt(Src.FloatVal, DBitWidth);
1006   else
1007     Dest.IntVal = APIntOps::RoundDoubleToAPInt(Src.DoubleVal, DBitWidth);
1008   return Dest;
1009 }
1010
1011 GenericValue Interpreter::executeFPToSIInst(Value *SrcVal, const Type *DstTy,
1012                                             ExecutionContext &SF) {
1013   const Type *SrcTy = SrcVal->getType();
1014   uint32_t DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
1015   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1016   assert(SrcTy->isFloatingPoint() && "Invalid FPToSI instruction");
1017
1018   if (SrcTy->getTypeID() == Type::FloatTyID)
1019     Dest.IntVal = APIntOps::RoundFloatToAPInt(Src.FloatVal, DBitWidth);
1020   else
1021     Dest.IntVal = APIntOps::RoundDoubleToAPInt(Src.DoubleVal, DBitWidth);
1022   return Dest;
1023 }
1024
1025 GenericValue Interpreter::executeUIToFPInst(Value *SrcVal, const Type *DstTy,
1026                                             ExecutionContext &SF) {
1027   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1028   assert(DstTy->isFloatingPoint() && "Invalid UIToFP instruction");
1029
1030   if (DstTy->getTypeID() == Type::FloatTyID)
1031     Dest.FloatVal = APIntOps::RoundAPIntToFloat(Src.IntVal);
1032   else
1033     Dest.DoubleVal = APIntOps::RoundAPIntToDouble(Src.IntVal);
1034   return Dest;
1035 }
1036
1037 GenericValue Interpreter::executeSIToFPInst(Value *SrcVal, const Type *DstTy,
1038                                             ExecutionContext &SF) {
1039   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1040   assert(DstTy->isFloatingPoint() && "Invalid SIToFP instruction");
1041
1042   if (DstTy->getTypeID() == Type::FloatTyID)
1043     Dest.FloatVal = APIntOps::RoundSignedAPIntToFloat(Src.IntVal);
1044   else
1045     Dest.DoubleVal = APIntOps::RoundSignedAPIntToDouble(Src.IntVal);
1046   return Dest;
1047
1048 }
1049
1050 GenericValue Interpreter::executePtrToIntInst(Value *SrcVal, const Type *DstTy,
1051                                               ExecutionContext &SF) {
1052   uint32_t DBitWidth = cast<IntegerType>(DstTy)->getBitWidth();
1053   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1054   assert(isa<PointerType>(SrcVal->getType()) && "Invalid PtrToInt instruction");
1055
1056   Dest.IntVal = APInt(DBitWidth, (intptr_t) Src.PointerVal);
1057   return Dest;
1058 }
1059
1060 GenericValue Interpreter::executeIntToPtrInst(Value *SrcVal, const Type *DstTy,
1061                                               ExecutionContext &SF) {
1062   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1063   assert(isa<PointerType>(DstTy) && "Invalid PtrToInt instruction");
1064
1065   uint32_t PtrSize = TD.getPointerSizeInBits();
1066   if (PtrSize != Src.IntVal.getBitWidth())
1067     Src.IntVal = Src.IntVal.zextOrTrunc(PtrSize);
1068
1069   Dest.PointerVal = PointerTy(intptr_t(Src.IntVal.getZExtValue()));
1070   return Dest;
1071 }
1072
1073 GenericValue Interpreter::executeBitCastInst(Value *SrcVal, const Type *DstTy,
1074                                              ExecutionContext &SF) {
1075   
1076   const Type *SrcTy = SrcVal->getType();
1077   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1078   if (isa<PointerType>(DstTy)) {
1079     assert(isa<PointerType>(SrcTy) && "Invalid BitCast");
1080     Dest.PointerVal = Src.PointerVal;
1081   } else if (DstTy->isInteger()) {
1082     if (SrcTy == Type::FloatTy) {
1083       Dest.IntVal.zext(sizeof(Src.FloatVal) * 8);
1084       Dest.IntVal.floatToBits(Src.FloatVal);
1085     } else if (SrcTy == Type::DoubleTy) {
1086       Dest.IntVal.zext(sizeof(Src.DoubleVal) * 8);
1087       Dest.IntVal.doubleToBits(Src.DoubleVal);
1088     } else if (SrcTy->isInteger()) {
1089       Dest.IntVal = Src.IntVal;
1090     } else 
1091       assert(0 && "Invalid BitCast");
1092   } else if (DstTy == Type::FloatTy) {
1093     if (SrcTy->isInteger())
1094       Dest.FloatVal = Src.IntVal.bitsToFloat();
1095     else
1096       Dest.FloatVal = Src.FloatVal;
1097   } else if (DstTy == Type::DoubleTy) {
1098     if (SrcTy->isInteger())
1099       Dest.DoubleVal = Src.IntVal.bitsToDouble();
1100     else
1101       Dest.DoubleVal = Src.DoubleVal;
1102   } else
1103     assert(0 && "Invalid Bitcast");
1104
1105   return Dest;
1106 }
1107
1108 void Interpreter::visitTruncInst(TruncInst &I) {
1109   ExecutionContext &SF = ECStack.back();
1110   SetValue(&I, executeTruncInst(I.getOperand(0), I.getType(), SF), SF);
1111 }
1112
1113 void Interpreter::visitSExtInst(SExtInst &I) {
1114   ExecutionContext &SF = ECStack.back();
1115   SetValue(&I, executeSExtInst(I.getOperand(0), I.getType(), SF), SF);
1116 }
1117
1118 void Interpreter::visitZExtInst(ZExtInst &I) {
1119   ExecutionContext &SF = ECStack.back();
1120   SetValue(&I, executeZExtInst(I.getOperand(0), I.getType(), SF), SF);
1121 }
1122
1123 void Interpreter::visitFPTruncInst(FPTruncInst &I) {
1124   ExecutionContext &SF = ECStack.back();
1125   SetValue(&I, executeFPTruncInst(I.getOperand(0), I.getType(), SF), SF);
1126 }
1127
1128 void Interpreter::visitFPExtInst(FPExtInst &I) {
1129   ExecutionContext &SF = ECStack.back();
1130   SetValue(&I, executeFPExtInst(I.getOperand(0), I.getType(), SF), SF);
1131 }
1132
1133 void Interpreter::visitUIToFPInst(UIToFPInst &I) {
1134   ExecutionContext &SF = ECStack.back();
1135   SetValue(&I, executeUIToFPInst(I.getOperand(0), I.getType(), SF), SF);
1136 }
1137
1138 void Interpreter::visitSIToFPInst(SIToFPInst &I) {
1139   ExecutionContext &SF = ECStack.back();
1140   SetValue(&I, executeSIToFPInst(I.getOperand(0), I.getType(), SF), SF);
1141 }
1142
1143 void Interpreter::visitFPToUIInst(FPToUIInst &I) {
1144   ExecutionContext &SF = ECStack.back();
1145   SetValue(&I, executeFPToUIInst(I.getOperand(0), I.getType(), SF), SF);
1146 }
1147
1148 void Interpreter::visitFPToSIInst(FPToSIInst &I) {
1149   ExecutionContext &SF = ECStack.back();
1150   SetValue(&I, executeFPToSIInst(I.getOperand(0), I.getType(), SF), SF);
1151 }
1152
1153 void Interpreter::visitPtrToIntInst(PtrToIntInst &I) {
1154   ExecutionContext &SF = ECStack.back();
1155   SetValue(&I, executePtrToIntInst(I.getOperand(0), I.getType(), SF), SF);
1156 }
1157
1158 void Interpreter::visitIntToPtrInst(IntToPtrInst &I) {
1159   ExecutionContext &SF = ECStack.back();
1160   SetValue(&I, executeIntToPtrInst(I.getOperand(0), I.getType(), SF), SF);
1161 }
1162
1163 void Interpreter::visitBitCastInst(BitCastInst &I) {
1164   ExecutionContext &SF = ECStack.back();
1165   SetValue(&I, executeBitCastInst(I.getOperand(0), I.getType(), SF), SF);
1166 }
1167
1168 #define IMPLEMENT_VAARG(TY) \
1169    case Type::TY##TyID: Dest.TY##Val = Src.TY##Val; break
1170
1171 void Interpreter::visitVAArgInst(VAArgInst &I) {
1172   ExecutionContext &SF = ECStack.back();
1173
1174   // Get the incoming valist parameter.  LLI treats the valist as a
1175   // (ec-stack-depth var-arg-index) pair.
1176   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
1177   GenericValue Dest;
1178   GenericValue Src = ECStack[VAList.UIntPairVal.first]
1179                       .VarArgs[VAList.UIntPairVal.second];
1180   const Type *Ty = I.getType();
1181   switch (Ty->getTypeID()) {
1182     case Type::IntegerTyID: Dest.IntVal = Src.IntVal;
1183     IMPLEMENT_VAARG(Pointer);
1184     IMPLEMENT_VAARG(Float);
1185     IMPLEMENT_VAARG(Double);
1186   default:
1187     cerr << "Unhandled dest type for vaarg instruction: " << *Ty << "\n";
1188     abort();
1189   }
1190
1191   // Set the Value of this Instruction.
1192   SetValue(&I, Dest, SF);
1193
1194   // Move the pointer to the next vararg.
1195   ++VAList.UIntPairVal.second;
1196 }
1197
1198 GenericValue Interpreter::getConstantExprValue (ConstantExpr *CE,
1199                                                 ExecutionContext &SF) {
1200   switch (CE->getOpcode()) {
1201   case Instruction::Trunc:   
1202       return executeTruncInst(CE->getOperand(0), CE->getType(), SF);
1203   case Instruction::ZExt:
1204       return executeZExtInst(CE->getOperand(0), CE->getType(), SF);
1205   case Instruction::SExt:
1206       return executeSExtInst(CE->getOperand(0), CE->getType(), SF);
1207   case Instruction::FPTrunc:
1208       return executeFPTruncInst(CE->getOperand(0), CE->getType(), SF);
1209   case Instruction::FPExt:
1210       return executeFPExtInst(CE->getOperand(0), CE->getType(), SF);
1211   case Instruction::UIToFP:
1212       return executeUIToFPInst(CE->getOperand(0), CE->getType(), SF);
1213   case Instruction::SIToFP:
1214       return executeSIToFPInst(CE->getOperand(0), CE->getType(), SF);
1215   case Instruction::FPToUI:
1216       return executeFPToUIInst(CE->getOperand(0), CE->getType(), SF);
1217   case Instruction::FPToSI:
1218       return executeFPToSIInst(CE->getOperand(0), CE->getType(), SF);
1219   case Instruction::PtrToInt:
1220       return executePtrToIntInst(CE->getOperand(0), CE->getType(), SF);
1221   case Instruction::IntToPtr:
1222       return executeIntToPtrInst(CE->getOperand(0), CE->getType(), SF);
1223   case Instruction::BitCast:
1224       return executeBitCastInst(CE->getOperand(0), CE->getType(), SF);
1225   case Instruction::GetElementPtr:
1226     return executeGEPOperation(CE->getOperand(0), gep_type_begin(CE),
1227                                gep_type_end(CE), SF);
1228   case Instruction::FCmp:
1229   case Instruction::ICmp:
1230     return executeCmpInst(CE->getPredicate(),
1231                           getOperandValue(CE->getOperand(0), SF),
1232                           getOperandValue(CE->getOperand(1), SF),
1233                           CE->getOperand(0)->getType());
1234   case Instruction::Select:
1235     return executeSelectInst(getOperandValue(CE->getOperand(0), SF),
1236                              getOperandValue(CE->getOperand(1), SF),
1237                              getOperandValue(CE->getOperand(2), SF));
1238   default :
1239     break;
1240   }
1241
1242   // The cases below here require a GenericValue parameter for the result
1243   // so we initialize one, compute it and then return it.
1244   GenericValue Op0 = getOperandValue(CE->getOperand(0), SF);
1245   GenericValue Op1 = getOperandValue(CE->getOperand(1), SF);
1246   GenericValue Dest;
1247   const Type * Ty = CE->getOperand(0)->getType();
1248   switch (CE->getOpcode()) {
1249   case Instruction::Add:  executeAddInst (Dest, Op0, Op1, Ty); break;
1250   case Instruction::Sub:  executeSubInst (Dest, Op0, Op1, Ty); break;
1251   case Instruction::Mul:  executeMulInst (Dest, Op0, Op1, Ty); break;
1252   case Instruction::FDiv: executeFDivInst(Dest, Op0, Op1, Ty); break;
1253   case Instruction::FRem: executeFRemInst(Dest, Op0, Op1, Ty); break;
1254   case Instruction::SDiv: Dest.IntVal = Op0.IntVal.sdiv(Op1.IntVal); break;
1255   case Instruction::UDiv: Dest.IntVal = Op0.IntVal.udiv(Op1.IntVal); break;
1256   case Instruction::URem: Dest.IntVal = Op0.IntVal.urem(Op1.IntVal); break;
1257   case Instruction::SRem: Dest.IntVal = Op0.IntVal.srem(Op1.IntVal); break;
1258   case Instruction::And:  Dest.IntVal = Op0.IntVal.And(Op1.IntVal); break;
1259   case Instruction::Or:   Dest.IntVal = Op0.IntVal.Or(Op1.IntVal); break;
1260   case Instruction::Xor:  Dest.IntVal = Op0.IntVal.Xor(Op1.IntVal); break;
1261   case Instruction::Shl:  
1262     Dest.IntVal = Op0.IntVal.shl(Op1.IntVal.getZExtValue());
1263     break;
1264   case Instruction::LShr: 
1265     Dest.IntVal = Op0.IntVal.lshr(Op1.IntVal.getZExtValue());
1266     break;
1267   case Instruction::AShr: 
1268     Dest.IntVal = Op0.IntVal.ashr(Op1.IntVal.getZExtValue());
1269     break;
1270   default:
1271     cerr << "Unhandled ConstantExpr: " << *CE << "\n";
1272     abort();
1273     return GenericValue();
1274   }
1275   return Dest;
1276 }
1277
1278 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
1279   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1280     return getConstantExprValue(CE, SF);
1281   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
1282     return getConstantValue(CPV);
1283   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1284     return PTOGV(getPointerToGlobal(GV));
1285   } else {
1286     return SF.Values[V];
1287   }
1288 }
1289
1290 //===----------------------------------------------------------------------===//
1291 //                        Dispatch and Execution Code
1292 //===----------------------------------------------------------------------===//
1293
1294 //===----------------------------------------------------------------------===//
1295 // callFunction - Execute the specified function...
1296 //
1297 void Interpreter::callFunction(Function *F,
1298                                const std::vector<GenericValue> &ArgVals) {
1299   assert((ECStack.empty() || ECStack.back().Caller.getInstruction() == 0 ||
1300           ECStack.back().Caller.arg_size() == ArgVals.size()) &&
1301          "Incorrect number of arguments passed into function call!");
1302   // Make a new stack frame... and fill it in.
1303   ECStack.push_back(ExecutionContext());
1304   ExecutionContext &StackFrame = ECStack.back();
1305   StackFrame.CurFunction = F;
1306
1307   // Special handling for external functions.
1308   if (F->isDeclaration()) {
1309     GenericValue Result = callExternalFunction (F, ArgVals);
1310     // Simulate a 'ret' instruction of the appropriate type.
1311     popStackAndReturnValueToCaller (F->getReturnType (), Result);
1312     return;
1313   }
1314
1315   // Get pointers to first LLVM BB & Instruction in function.
1316   StackFrame.CurBB     = F->begin();
1317   StackFrame.CurInst   = StackFrame.CurBB->begin();
1318
1319   // Run through the function arguments and initialize their values...
1320   assert((ArgVals.size() == F->arg_size() ||
1321          (ArgVals.size() > F->arg_size() && F->getFunctionType()->isVarArg()))&&
1322          "Invalid number of values passed to function invocation!");
1323
1324   // Handle non-varargs arguments...
1325   unsigned i = 0;
1326   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 
1327        AI != E; ++AI, ++i)
1328     SetValue(AI, ArgVals[i], StackFrame);
1329
1330   // Handle varargs arguments...
1331   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
1332 }
1333
1334
1335 void Interpreter::run() {
1336   while (!ECStack.empty()) {
1337     // Interpret a single instruction & increment the "PC".
1338     ExecutionContext &SF = ECStack.back();  // Current stack frame
1339     Instruction &I = *SF.CurInst++;         // Increment before execute
1340
1341     // Track the number of dynamic instructions executed.
1342     ++NumDynamicInsts;
1343
1344     DOUT << "About to interpret: " << I;
1345     visit(I);   // Dispatch to one of the visit* methods...
1346 #if 0
1347     // This is not safe, as visiting the instruction could lower it and free I.
1348 #ifndef NDEBUG
1349     if (!isa<CallInst>(I) && !isa<InvokeInst>(I) && 
1350         I.getType() != Type::VoidTy) {
1351       DOUT << "  --> ";
1352       const GenericValue &Val = SF.Values[&I];
1353       switch (I.getType()->getTypeID()) {
1354       default: assert(0 && "Invalid GenericValue Type");
1355       case Type::VoidTyID:    DOUT << "void"; break;
1356       case Type::FloatTyID:   DOUT << "float " << Val.FloatVal; break;
1357       case Type::DoubleTyID:  DOUT << "double " << Val.DoubleVal; break;
1358       case Type::PointerTyID: DOUT << "void* " << intptr_t(Val.PointerVal);
1359         break;
1360       case Type::IntegerTyID: 
1361         DOUT << "i" << Val.IntVal.getBitWidth() << " "
1362         << Val.IntVal.toStringUnsigned(10)
1363         << " (0x" << Val.IntVal.toStringUnsigned(16) << ")\n";
1364         break;
1365       }
1366     }
1367 #endif
1368 #endif
1369   }
1370 }