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