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