For PR950:
[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/Statistic.h"
22 #include "llvm/Support/Debug.h"
23 #include <cmath>  // For fmod
24 using namespace llvm;
25
26 namespace {
27   Statistic<> NumDynamicInsts("lli", "Number of dynamic instructions executed");
28
29   Interpreter *TheEE = 0;
30 }
31
32
33 //===----------------------------------------------------------------------===//
34 //                     Value Manipulation code
35 //===----------------------------------------------------------------------===//
36
37 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
38                                    const Type *Ty);
39 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
40                                    const Type *Ty);
41 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
42                                    const Type *Ty);
43 static GenericValue executeUDivInst(GenericValue Src1, GenericValue Src2,
44                                     const Type *Ty);
45 static GenericValue executeSDivInst(GenericValue Src1, GenericValue Src2,
46                                     const Type *Ty);
47 static GenericValue executeFDivInst(GenericValue Src1, GenericValue Src2,
48                                     const Type *Ty);
49 static GenericValue executeURemInst(GenericValue Src1, GenericValue Src2,
50                                     const Type *Ty);
51 static GenericValue executeSRemInst(GenericValue Src1, GenericValue Src2,
52                                     const Type *Ty);
53 static GenericValue executeFRemInst(GenericValue Src1, GenericValue Src2,
54                                     const Type *Ty);
55 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
56                                    const Type *Ty);
57 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
58                                    const Type *Ty);
59 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
60                                    const Type *Ty);
61 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
62                                    const Type *Ty);
63 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
64                                    const Type *Ty);
65 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
66                                    const Type *Ty);
67 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
68                                    const Type *Ty);
69 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
70                                    const Type *Ty);
71 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
72                                    const Type *Ty);
73 static GenericValue executeShlInst(GenericValue Src1, GenericValue Src2,
74                                    const Type *Ty);
75 static GenericValue executeLShrInst(GenericValue Src1, GenericValue Src2,
76                                     const Type *Ty);
77 static GenericValue executeAShrInst(GenericValue Src1, GenericValue Src2,
78                                     const Type *Ty);
79 static GenericValue executeSelectInst(GenericValue Src1, GenericValue Src2,
80                                       GenericValue Src3);
81
82 GenericValue Interpreter::getConstantExprValue (ConstantExpr *CE,
83                                                 ExecutionContext &SF) {
84   switch (CE->getOpcode()) {
85   case Instruction::Cast:
86     return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
87   case Instruction::GetElementPtr:
88     return executeGEPOperation(CE->getOperand(0), gep_type_begin(CE),
89                                gep_type_end(CE), SF);
90   case Instruction::Add:
91     return executeAddInst(getOperandValue(CE->getOperand(0), SF),
92                           getOperandValue(CE->getOperand(1), SF),
93                           CE->getOperand(0)->getType());
94   case Instruction::Sub:
95     return executeSubInst(getOperandValue(CE->getOperand(0), SF),
96                           getOperandValue(CE->getOperand(1), SF),
97                           CE->getOperand(0)->getType());
98   case Instruction::Mul:
99     return executeMulInst(getOperandValue(CE->getOperand(0), SF),
100                           getOperandValue(CE->getOperand(1), SF),
101                           CE->getOperand(0)->getType());
102   case Instruction::SDiv:
103     return executeSDivInst(getOperandValue(CE->getOperand(0), SF),
104                            getOperandValue(CE->getOperand(1), SF),
105                            CE->getOperand(0)->getType());
106   case Instruction::UDiv:
107     return executeUDivInst(getOperandValue(CE->getOperand(0), SF),
108                            getOperandValue(CE->getOperand(1), SF),
109                            CE->getOperand(0)->getType());
110   case Instruction::FDiv:
111     return executeFDivInst(getOperandValue(CE->getOperand(0), SF),
112                            getOperandValue(CE->getOperand(1), SF),
113                            CE->getOperand(0)->getType());
114   case Instruction::URem:
115     return executeURemInst(getOperandValue(CE->getOperand(0), SF),
116                           getOperandValue(CE->getOperand(1), SF),
117                           CE->getOperand(0)->getType());
118   case Instruction::SRem:
119     return executeSRemInst(getOperandValue(CE->getOperand(0), SF),
120                           getOperandValue(CE->getOperand(1), SF),
121                           CE->getOperand(0)->getType());
122   case Instruction::FRem:
123     return executeFRemInst(getOperandValue(CE->getOperand(0), SF),
124                            getOperandValue(CE->getOperand(1), SF),
125                            CE->getOperand(0)->getType());
126   case Instruction::And:
127     return executeAndInst(getOperandValue(CE->getOperand(0), SF),
128                           getOperandValue(CE->getOperand(1), SF),
129                           CE->getOperand(0)->getType());
130   case Instruction::Or:
131     return executeOrInst(getOperandValue(CE->getOperand(0), SF),
132                          getOperandValue(CE->getOperand(1), SF),
133                          CE->getOperand(0)->getType());
134   case Instruction::Xor:
135     return executeXorInst(getOperandValue(CE->getOperand(0), SF),
136                           getOperandValue(CE->getOperand(1), SF),
137                           CE->getOperand(0)->getType());
138   case Instruction::SetEQ:
139     return executeSetEQInst(getOperandValue(CE->getOperand(0), SF),
140                             getOperandValue(CE->getOperand(1), SF),
141                             CE->getOperand(0)->getType());
142   case Instruction::SetNE:
143     return executeSetNEInst(getOperandValue(CE->getOperand(0), SF),
144                             getOperandValue(CE->getOperand(1), SF),
145                             CE->getOperand(0)->getType());
146   case Instruction::SetLE:
147     return executeSetLEInst(getOperandValue(CE->getOperand(0), SF),
148                             getOperandValue(CE->getOperand(1), SF),
149                             CE->getOperand(0)->getType());
150   case Instruction::SetGE:
151     return executeSetGEInst(getOperandValue(CE->getOperand(0), SF),
152                             getOperandValue(CE->getOperand(1), SF),
153                             CE->getOperand(0)->getType());
154   case Instruction::SetLT:
155     return executeSetLTInst(getOperandValue(CE->getOperand(0), SF),
156                             getOperandValue(CE->getOperand(1), SF),
157                             CE->getOperand(0)->getType());
158   case Instruction::SetGT:
159     return executeSetGTInst(getOperandValue(CE->getOperand(0), SF),
160                             getOperandValue(CE->getOperand(1), SF),
161                             CE->getOperand(0)->getType());
162   case Instruction::Shl:
163     return executeShlInst(getOperandValue(CE->getOperand(0), SF),
164                           getOperandValue(CE->getOperand(1), SF),
165                           CE->getOperand(0)->getType());
166   case Instruction::LShr:
167     return executeLShrInst(getOperandValue(CE->getOperand(0), SF),
168                            getOperandValue(CE->getOperand(1), SF),
169                            CE->getOperand(0)->getType());
170   case Instruction::AShr:
171     return executeAShrInst(getOperandValue(CE->getOperand(0), SF),
172                            getOperandValue(CE->getOperand(1), SF),
173                            CE->getOperand(0)->getType());
174   case Instruction::Select:
175     return executeSelectInst(getOperandValue(CE->getOperand(0), SF),
176                              getOperandValue(CE->getOperand(1), SF),
177                              getOperandValue(CE->getOperand(2), SF));
178   default:
179     std::cerr << "Unhandled ConstantExpr: " << *CE << "\n";
180     abort();
181     return GenericValue();
182   }
183 }
184
185 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
186   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
187     return getConstantExprValue(CE, SF);
188   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
189     return getConstantValue(CPV);
190   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
191     return PTOGV(getPointerToGlobal(GV));
192   } else {
193     return SF.Values[V];
194   }
195 }
196
197 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
198   SF.Values[V] = Val;
199 }
200
201 void Interpreter::initializeExecutionEngine() {
202   TheEE = this;
203 }
204
205 //===----------------------------------------------------------------------===//
206 //                    Binary Instruction Implementations
207 //===----------------------------------------------------------------------===//
208
209 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
210    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
211
212 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
213                                    const Type *Ty) {
214   GenericValue Dest;
215   switch (Ty->getTypeID()) {
216     IMPLEMENT_BINARY_OPERATOR(+, UByte);
217     IMPLEMENT_BINARY_OPERATOR(+, SByte);
218     IMPLEMENT_BINARY_OPERATOR(+, UShort);
219     IMPLEMENT_BINARY_OPERATOR(+, Short);
220     IMPLEMENT_BINARY_OPERATOR(+, UInt);
221     IMPLEMENT_BINARY_OPERATOR(+, Int);
222     IMPLEMENT_BINARY_OPERATOR(+, ULong);
223     IMPLEMENT_BINARY_OPERATOR(+, Long);
224     IMPLEMENT_BINARY_OPERATOR(+, Float);
225     IMPLEMENT_BINARY_OPERATOR(+, Double);
226   default:
227     std::cout << "Unhandled type for Add instruction: " << *Ty << "\n";
228     abort();
229   }
230   return Dest;
231 }
232
233 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
234                                    const Type *Ty) {
235   GenericValue Dest;
236   switch (Ty->getTypeID()) {
237     IMPLEMENT_BINARY_OPERATOR(-, UByte);
238     IMPLEMENT_BINARY_OPERATOR(-, SByte);
239     IMPLEMENT_BINARY_OPERATOR(-, UShort);
240     IMPLEMENT_BINARY_OPERATOR(-, Short);
241     IMPLEMENT_BINARY_OPERATOR(-, UInt);
242     IMPLEMENT_BINARY_OPERATOR(-, Int);
243     IMPLEMENT_BINARY_OPERATOR(-, ULong);
244     IMPLEMENT_BINARY_OPERATOR(-, Long);
245     IMPLEMENT_BINARY_OPERATOR(-, Float);
246     IMPLEMENT_BINARY_OPERATOR(-, Double);
247   default:
248     std::cout << "Unhandled type for Sub instruction: " << *Ty << "\n";
249     abort();
250   }
251   return Dest;
252 }
253
254 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
255                                    const Type *Ty) {
256   GenericValue Dest;
257   switch (Ty->getTypeID()) {
258     IMPLEMENT_BINARY_OPERATOR(*, UByte);
259     IMPLEMENT_BINARY_OPERATOR(*, SByte);
260     IMPLEMENT_BINARY_OPERATOR(*, UShort);
261     IMPLEMENT_BINARY_OPERATOR(*, Short);
262     IMPLEMENT_BINARY_OPERATOR(*, UInt);
263     IMPLEMENT_BINARY_OPERATOR(*, Int);
264     IMPLEMENT_BINARY_OPERATOR(*, ULong);
265     IMPLEMENT_BINARY_OPERATOR(*, Long);
266     IMPLEMENT_BINARY_OPERATOR(*, Float);
267     IMPLEMENT_BINARY_OPERATOR(*, Double);
268   default:
269     std::cout << "Unhandled type for Mul instruction: " << *Ty << "\n";
270     abort();
271   }
272   return Dest;
273 }
274
275 #define IMPLEMENT_SIGNLESS_BINOP(OP, TY1, TY2) \
276    case Type::TY2##TyID: IMPLEMENT_BINARY_OPERATOR(OP, TY1)
277
278 static GenericValue executeUDivInst(GenericValue Src1, GenericValue Src2,
279                                    const Type *Ty) {
280   GenericValue Dest;
281   switch (Ty->getTypeID()) {
282     IMPLEMENT_SIGNLESS_BINOP(/, UByte,  SByte);
283     IMPLEMENT_SIGNLESS_BINOP(/, UShort, Short);
284     IMPLEMENT_SIGNLESS_BINOP(/, UInt,   Int);
285     IMPLEMENT_SIGNLESS_BINOP(/, ULong,  Long);
286   default:
287     std::cout << "Unhandled type for UDiv instruction: " << *Ty << "\n";
288     abort();
289   }
290   return Dest;
291 }
292
293 static GenericValue executeSDivInst(GenericValue Src1, GenericValue Src2,
294                                    const Type *Ty) {
295   GenericValue Dest;
296   switch (Ty->getTypeID()) {
297     IMPLEMENT_SIGNLESS_BINOP(/, SByte, UByte);
298     IMPLEMENT_SIGNLESS_BINOP(/, Short, UShort);
299     IMPLEMENT_SIGNLESS_BINOP(/, Int,   UInt);
300     IMPLEMENT_SIGNLESS_BINOP(/, Long,  ULong);
301   default:
302     std::cout << "Unhandled type for SDiv instruction: " << *Ty << "\n";
303     abort();
304   }
305   return Dest;
306 }
307
308 static GenericValue executeFDivInst(GenericValue Src1, GenericValue Src2,
309                                    const Type *Ty) {
310   GenericValue Dest;
311   switch (Ty->getTypeID()) {
312     IMPLEMENT_BINARY_OPERATOR(/, Float);
313     IMPLEMENT_BINARY_OPERATOR(/, Double);
314   default:
315     std::cout << "Unhandled type for Div instruction: " << *Ty << "\n";
316     abort();
317   }
318   return Dest;
319 }
320
321 static GenericValue executeURemInst(GenericValue Src1, GenericValue Src2,
322                                    const Type *Ty) {
323   GenericValue Dest;
324   switch (Ty->getTypeID()) {
325     IMPLEMENT_SIGNLESS_BINOP(%, UByte,  SByte);
326     IMPLEMENT_SIGNLESS_BINOP(%, UShort, Short);
327     IMPLEMENT_SIGNLESS_BINOP(%, UInt,   Int);
328     IMPLEMENT_SIGNLESS_BINOP(%, ULong,  Long);
329   default:
330     std::cout << "Unhandled type for URem instruction: " << *Ty << "\n";
331     abort();
332   }
333   return Dest;
334 }
335
336 static GenericValue executeSRemInst(GenericValue Src1, GenericValue Src2,
337                                    const Type *Ty) {
338   GenericValue Dest;
339   switch (Ty->getTypeID()) {
340     IMPLEMENT_SIGNLESS_BINOP(%, SByte, UByte);
341     IMPLEMENT_SIGNLESS_BINOP(%, Short, UShort);
342     IMPLEMENT_SIGNLESS_BINOP(%, Int,   UInt);
343     IMPLEMENT_SIGNLESS_BINOP(%, Long,  ULong);
344   default:
345     std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
346     abort();
347   }
348   return Dest;
349 }
350
351 static GenericValue executeFRemInst(GenericValue Src1, GenericValue Src2,
352                                    const Type *Ty) {
353   GenericValue Dest;
354   switch (Ty->getTypeID()) {
355   case Type::FloatTyID:
356     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
357     break;
358   case Type::DoubleTyID:
359     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
360     break;
361   default:
362     std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
363     abort();
364   }
365   return Dest;
366 }
367
368 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
369                                    const Type *Ty) {
370   GenericValue Dest;
371   switch (Ty->getTypeID()) {
372     IMPLEMENT_BINARY_OPERATOR(&, Bool);
373     IMPLEMENT_BINARY_OPERATOR(&, UByte);
374     IMPLEMENT_BINARY_OPERATOR(&, SByte);
375     IMPLEMENT_BINARY_OPERATOR(&, UShort);
376     IMPLEMENT_BINARY_OPERATOR(&, Short);
377     IMPLEMENT_BINARY_OPERATOR(&, UInt);
378     IMPLEMENT_BINARY_OPERATOR(&, Int);
379     IMPLEMENT_BINARY_OPERATOR(&, ULong);
380     IMPLEMENT_BINARY_OPERATOR(&, Long);
381   default:
382     std::cout << "Unhandled type for And instruction: " << *Ty << "\n";
383     abort();
384   }
385   return Dest;
386 }
387
388 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
389                                   const Type *Ty) {
390   GenericValue Dest;
391   switch (Ty->getTypeID()) {
392     IMPLEMENT_BINARY_OPERATOR(|, Bool);
393     IMPLEMENT_BINARY_OPERATOR(|, UByte);
394     IMPLEMENT_BINARY_OPERATOR(|, SByte);
395     IMPLEMENT_BINARY_OPERATOR(|, UShort);
396     IMPLEMENT_BINARY_OPERATOR(|, Short);
397     IMPLEMENT_BINARY_OPERATOR(|, UInt);
398     IMPLEMENT_BINARY_OPERATOR(|, Int);
399     IMPLEMENT_BINARY_OPERATOR(|, ULong);
400     IMPLEMENT_BINARY_OPERATOR(|, Long);
401   default:
402     std::cout << "Unhandled type for Or instruction: " << *Ty << "\n";
403     abort();
404   }
405   return Dest;
406 }
407
408 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
409                                    const Type *Ty) {
410   GenericValue Dest;
411   switch (Ty->getTypeID()) {
412     IMPLEMENT_BINARY_OPERATOR(^, Bool);
413     IMPLEMENT_BINARY_OPERATOR(^, UByte);
414     IMPLEMENT_BINARY_OPERATOR(^, SByte);
415     IMPLEMENT_BINARY_OPERATOR(^, UShort);
416     IMPLEMENT_BINARY_OPERATOR(^, Short);
417     IMPLEMENT_BINARY_OPERATOR(^, UInt);
418     IMPLEMENT_BINARY_OPERATOR(^, Int);
419     IMPLEMENT_BINARY_OPERATOR(^, ULong);
420     IMPLEMENT_BINARY_OPERATOR(^, Long);
421   default:
422     std::cout << "Unhandled type for Xor instruction: " << *Ty << "\n";
423     abort();
424   }
425   return Dest;
426 }
427
428 #define IMPLEMENT_SETCC(OP, TY) \
429    case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
430
431 // Handle pointers specially because they must be compared with only as much
432 // width as the host has.  We _do not_ want to be comparing 64 bit values when
433 // running on a 32-bit target, otherwise the upper 32 bits might mess up
434 // comparisons if they contain garbage.
435 #define IMPLEMENT_POINTERSETCC(OP) \
436    case Type::PointerTyID: \
437         Dest.BoolVal = (void*)(intptr_t)Src1.PointerVal OP \
438                        (void*)(intptr_t)Src2.PointerVal; break
439
440 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
441                                      const Type *Ty) {
442   GenericValue Dest;
443   switch (Ty->getTypeID()) {
444     IMPLEMENT_SETCC(==, UByte);
445     IMPLEMENT_SETCC(==, SByte);
446     IMPLEMENT_SETCC(==, UShort);
447     IMPLEMENT_SETCC(==, Short);
448     IMPLEMENT_SETCC(==, UInt);
449     IMPLEMENT_SETCC(==, Int);
450     IMPLEMENT_SETCC(==, ULong);
451     IMPLEMENT_SETCC(==, Long);
452     IMPLEMENT_SETCC(==, Float);
453     IMPLEMENT_SETCC(==, Double);
454     IMPLEMENT_POINTERSETCC(==);
455   default:
456     std::cout << "Unhandled type for SetEQ instruction: " << *Ty << "\n";
457     abort();
458   }
459   return Dest;
460 }
461
462 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
463                                      const Type *Ty) {
464   GenericValue Dest;
465   switch (Ty->getTypeID()) {
466     IMPLEMENT_SETCC(!=, UByte);
467     IMPLEMENT_SETCC(!=, SByte);
468     IMPLEMENT_SETCC(!=, UShort);
469     IMPLEMENT_SETCC(!=, Short);
470     IMPLEMENT_SETCC(!=, UInt);
471     IMPLEMENT_SETCC(!=, Int);
472     IMPLEMENT_SETCC(!=, ULong);
473     IMPLEMENT_SETCC(!=, Long);
474     IMPLEMENT_SETCC(!=, Float);
475     IMPLEMENT_SETCC(!=, Double);
476     IMPLEMENT_POINTERSETCC(!=);
477
478   default:
479     std::cout << "Unhandled type for SetNE instruction: " << *Ty << "\n";
480     abort();
481   }
482   return Dest;
483 }
484
485 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
486                                      const Type *Ty) {
487   GenericValue Dest;
488   switch (Ty->getTypeID()) {
489     IMPLEMENT_SETCC(<=, UByte);
490     IMPLEMENT_SETCC(<=, SByte);
491     IMPLEMENT_SETCC(<=, UShort);
492     IMPLEMENT_SETCC(<=, Short);
493     IMPLEMENT_SETCC(<=, UInt);
494     IMPLEMENT_SETCC(<=, Int);
495     IMPLEMENT_SETCC(<=, ULong);
496     IMPLEMENT_SETCC(<=, Long);
497     IMPLEMENT_SETCC(<=, Float);
498     IMPLEMENT_SETCC(<=, Double);
499     IMPLEMENT_POINTERSETCC(<=);
500   default:
501     std::cout << "Unhandled type for SetLE instruction: " << *Ty << "\n";
502     abort();
503   }
504   return Dest;
505 }
506
507 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
508                                      const Type *Ty) {
509   GenericValue Dest;
510   switch (Ty->getTypeID()) {
511     IMPLEMENT_SETCC(>=, UByte);
512     IMPLEMENT_SETCC(>=, SByte);
513     IMPLEMENT_SETCC(>=, UShort);
514     IMPLEMENT_SETCC(>=, Short);
515     IMPLEMENT_SETCC(>=, UInt);
516     IMPLEMENT_SETCC(>=, Int);
517     IMPLEMENT_SETCC(>=, ULong);
518     IMPLEMENT_SETCC(>=, Long);
519     IMPLEMENT_SETCC(>=, Float);
520     IMPLEMENT_SETCC(>=, Double);
521     IMPLEMENT_POINTERSETCC(>=);
522   default:
523     std::cout << "Unhandled type for SetGE instruction: " << *Ty << "\n";
524     abort();
525   }
526   return Dest;
527 }
528
529 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
530                                      const Type *Ty) {
531   GenericValue Dest;
532   switch (Ty->getTypeID()) {
533     IMPLEMENT_SETCC(<, UByte);
534     IMPLEMENT_SETCC(<, SByte);
535     IMPLEMENT_SETCC(<, UShort);
536     IMPLEMENT_SETCC(<, Short);
537     IMPLEMENT_SETCC(<, UInt);
538     IMPLEMENT_SETCC(<, Int);
539     IMPLEMENT_SETCC(<, ULong);
540     IMPLEMENT_SETCC(<, Long);
541     IMPLEMENT_SETCC(<, Float);
542     IMPLEMENT_SETCC(<, Double);
543     IMPLEMENT_POINTERSETCC(<);
544   default:
545     std::cout << "Unhandled type for SetLT instruction: " << *Ty << "\n";
546     abort();
547   }
548   return Dest;
549 }
550
551 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
552                                      const Type *Ty) {
553   GenericValue Dest;
554   switch (Ty->getTypeID()) {
555     IMPLEMENT_SETCC(>, UByte);
556     IMPLEMENT_SETCC(>, SByte);
557     IMPLEMENT_SETCC(>, UShort);
558     IMPLEMENT_SETCC(>, Short);
559     IMPLEMENT_SETCC(>, UInt);
560     IMPLEMENT_SETCC(>, Int);
561     IMPLEMENT_SETCC(>, ULong);
562     IMPLEMENT_SETCC(>, Long);
563     IMPLEMENT_SETCC(>, Float);
564     IMPLEMENT_SETCC(>, Double);
565     IMPLEMENT_POINTERSETCC(>);
566   default:
567     std::cout << "Unhandled type for SetGT instruction: " << *Ty << "\n";
568     abort();
569   }
570   return Dest;
571 }
572
573 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
574   ExecutionContext &SF = ECStack.back();
575   const Type *Ty    = I.getOperand(0)->getType();
576   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
577   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
578   GenericValue R;   // Result
579
580   switch (I.getOpcode()) {
581   case Instruction::Add:   R = executeAddInst  (Src1, Src2, Ty); break;
582   case Instruction::Sub:   R = executeSubInst  (Src1, Src2, Ty); break;
583   case Instruction::Mul:   R = executeMulInst  (Src1, Src2, Ty); break;
584   case Instruction::UDiv:  R = executeUDivInst (Src1, Src2, Ty); break;
585   case Instruction::SDiv:  R = executeSDivInst (Src1, Src2, Ty); break;
586   case Instruction::FDiv:  R = executeFDivInst (Src1, Src2, Ty); break;
587   case Instruction::URem:  R = executeURemInst (Src1, Src2, Ty); break;
588   case Instruction::SRem:  R = executeSRemInst (Src1, Src2, Ty); break;
589   case Instruction::FRem:  R = executeFRemInst (Src1, Src2, Ty); break;
590   case Instruction::And:   R = executeAndInst  (Src1, Src2, Ty); break;
591   case Instruction::Or:    R = executeOrInst   (Src1, Src2, Ty); break;
592   case Instruction::Xor:   R = executeXorInst  (Src1, Src2, Ty); break;
593   case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty); break;
594   case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty); break;
595   case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty); break;
596   case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty); break;
597   case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty); break;
598   case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty); break;
599   default:
600     std::cout << "Don't know how to handle this binary operator!\n-->" << I;
601     abort();
602   }
603
604   SetValue(&I, R, SF);
605 }
606
607 static GenericValue executeSelectInst(GenericValue Src1, GenericValue Src2,
608                                       GenericValue Src3) {
609   return Src1.BoolVal ? Src2 : Src3;
610 }
611
612 void Interpreter::visitSelectInst(SelectInst &I) {
613   ExecutionContext &SF = ECStack.back();
614   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
615   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
616   GenericValue Src3 = getOperandValue(I.getOperand(2), SF);
617   GenericValue R = executeSelectInst(Src1, Src2, Src3);
618   SetValue(&I, R, SF);
619 }
620
621
622 //===----------------------------------------------------------------------===//
623 //                     Terminator Instruction Implementations
624 //===----------------------------------------------------------------------===//
625
626 void Interpreter::exitCalled(GenericValue GV) {
627   // runAtExitHandlers() assumes there are no stack frames, but
628   // if exit() was called, then it had a stack frame. Blow away
629   // the stack before interpreting atexit handlers.
630   ECStack.clear ();
631   runAtExitHandlers ();
632   exit (GV.IntVal);
633 }
634
635 /// Pop the last stack frame off of ECStack and then copy the result
636 /// back into the result variable if we are not returning void. The
637 /// result variable may be the ExitValue, or the Value of the calling
638 /// CallInst if there was a previous stack frame. This method may
639 /// invalidate any ECStack iterators you have. This method also takes
640 /// care of switching to the normal destination BB, if we are returning
641 /// from an invoke.
642 ///
643 void Interpreter::popStackAndReturnValueToCaller (const Type *RetTy,
644                                                   GenericValue Result) {
645   // Pop the current stack frame.
646   ECStack.pop_back();
647
648   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
649     if (RetTy && RetTy->isIntegral()) {          // Nonvoid return type?
650       ExitValue = Result;   // Capture the exit value of the program
651     } else {
652       memset(&ExitValue, 0, sizeof(ExitValue));
653     }
654   } else {
655     // If we have a previous stack frame, and we have a previous call,
656     // fill in the return value...
657     ExecutionContext &CallingSF = ECStack.back();
658     if (Instruction *I = CallingSF.Caller.getInstruction()) {
659       if (CallingSF.Caller.getType() != Type::VoidTy)      // Save result...
660         SetValue(I, Result, CallingSF);
661       if (InvokeInst *II = dyn_cast<InvokeInst> (I))
662         SwitchToNewBasicBlock (II->getNormalDest (), CallingSF);
663       CallingSF.Caller = CallSite();          // We returned from the call...
664     }
665   }
666 }
667
668 void Interpreter::visitReturnInst(ReturnInst &I) {
669   ExecutionContext &SF = ECStack.back();
670   const Type *RetTy = Type::VoidTy;
671   GenericValue Result;
672
673   // Save away the return value... (if we are not 'ret void')
674   if (I.getNumOperands()) {
675     RetTy  = I.getReturnValue()->getType();
676     Result = getOperandValue(I.getReturnValue(), SF);
677   }
678
679   popStackAndReturnValueToCaller(RetTy, Result);
680 }
681
682 void Interpreter::visitUnwindInst(UnwindInst &I) {
683   // Unwind stack
684   Instruction *Inst;
685   do {
686     ECStack.pop_back ();
687     if (ECStack.empty ())
688       abort ();
689     Inst = ECStack.back ().Caller.getInstruction ();
690   } while (!(Inst && isa<InvokeInst> (Inst)));
691
692   // Return from invoke
693   ExecutionContext &InvokingSF = ECStack.back ();
694   InvokingSF.Caller = CallSite ();
695
696   // Go to exceptional destination BB of invoke instruction
697   SwitchToNewBasicBlock(cast<InvokeInst>(Inst)->getUnwindDest(), InvokingSF);
698 }
699
700 void Interpreter::visitUnreachableInst(UnreachableInst &I) {
701   std::cerr << "ERROR: Program executed an 'unreachable' instruction!\n";
702   abort();
703 }
704
705 void Interpreter::visitBranchInst(BranchInst &I) {
706   ExecutionContext &SF = ECStack.back();
707   BasicBlock *Dest;
708
709   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
710   if (!I.isUnconditional()) {
711     Value *Cond = I.getCondition();
712     if (getOperandValue(Cond, SF).BoolVal == 0) // If false cond...
713       Dest = I.getSuccessor(1);
714   }
715   SwitchToNewBasicBlock(Dest, SF);
716 }
717
718 void Interpreter::visitSwitchInst(SwitchInst &I) {
719   ExecutionContext &SF = ECStack.back();
720   GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
721   const Type *ElTy = I.getOperand(0)->getType();
722
723   // Check to see if any of the cases match...
724   BasicBlock *Dest = 0;
725   for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
726     if (executeSetEQInst(CondVal,
727                          getOperandValue(I.getOperand(i), SF), ElTy).BoolVal) {
728       Dest = cast<BasicBlock>(I.getOperand(i+1));
729       break;
730     }
731
732   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
733   SwitchToNewBasicBlock(Dest, SF);
734 }
735
736 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
737 // This function handles the actual updating of block and instruction iterators
738 // as well as execution of all of the PHI nodes in the destination block.
739 //
740 // This method does this because all of the PHI nodes must be executed
741 // atomically, reading their inputs before any of the results are updated.  Not
742 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
743 // their inputs.  If the input PHI node is updated before it is read, incorrect
744 // results can happen.  Thus we use a two phase approach.
745 //
746 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
747   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
748   SF.CurBB   = Dest;                  // Update CurBB to branch destination
749   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
750
751   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
752
753   // Loop over all of the PHI nodes in the current block, reading their inputs.
754   std::vector<GenericValue> ResultValues;
755
756   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
757     // Search for the value corresponding to this previous bb...
758     int i = PN->getBasicBlockIndex(PrevBB);
759     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
760     Value *IncomingValue = PN->getIncomingValue(i);
761
762     // Save the incoming value for this PHI node...
763     ResultValues.push_back(getOperandValue(IncomingValue, SF));
764   }
765
766   // Now loop over all of the PHI nodes setting their values...
767   SF.CurInst = SF.CurBB->begin();
768   for (unsigned i = 0; isa<PHINode>(SF.CurInst); ++SF.CurInst, ++i) {
769     PHINode *PN = cast<PHINode>(SF.CurInst);
770     SetValue(PN, ResultValues[i], SF);
771   }
772 }
773
774 //===----------------------------------------------------------------------===//
775 //                     Memory Instruction Implementations
776 //===----------------------------------------------------------------------===//
777
778 void Interpreter::visitAllocationInst(AllocationInst &I) {
779   ExecutionContext &SF = ECStack.back();
780
781   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
782
783   // Get the number of elements being allocated by the array...
784   unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
785
786   // Allocate enough memory to hold the type...
787   void *Memory = malloc(NumElements * (size_t)TD.getTypeSize(Ty));
788
789   GenericValue Result = PTOGV(Memory);
790   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
791   SetValue(&I, Result, SF);
792
793   if (I.getOpcode() == Instruction::Alloca)
794     ECStack.back().Allocas.add(Memory);
795 }
796
797 void Interpreter::visitFreeInst(FreeInst &I) {
798   ExecutionContext &SF = ECStack.back();
799   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
800   GenericValue Value = getOperandValue(I.getOperand(0), SF);
801   // TODO: Check to make sure memory is allocated
802   free(GVTOP(Value));   // Free memory
803 }
804
805 // getElementOffset - The workhorse for getelementptr.
806 //
807 GenericValue Interpreter::executeGEPOperation(Value *Ptr, gep_type_iterator I,
808                                               gep_type_iterator E,
809                                               ExecutionContext &SF) {
810   assert(isa<PointerType>(Ptr->getType()) &&
811          "Cannot getElementOffset of a nonpointer type!");
812
813   PointerTy Total = 0;
814
815   for (; I != E; ++I) {
816     if (const StructType *STy = dyn_cast<StructType>(*I)) {
817       const StructLayout *SLO = TD.getStructLayout(STy);
818
819       const ConstantInt *CPU = cast<ConstantInt>(I.getOperand());
820       unsigned Index = unsigned(CPU->getZExtValue());
821
822       Total += (PointerTy)SLO->MemberOffsets[Index];
823     } else {
824       const SequentialType *ST = cast<SequentialType>(*I);
825       // Get the index number for the array... which must be long type...
826       GenericValue IdxGV = getOperandValue(I.getOperand(), SF);
827
828       uint64_t Idx;
829       switch (I.getOperand()->getType()->getTypeID()) {
830       default: assert(0 && "Illegal getelementptr index for sequential type!");
831       case Type::SByteTyID:  Idx = IdxGV.SByteVal; break;
832       case Type::ShortTyID:  Idx = IdxGV.ShortVal; break;
833       case Type::IntTyID:    Idx = IdxGV.IntVal; break;
834       case Type::LongTyID:   Idx = IdxGV.LongVal; break;
835       case Type::UByteTyID:  Idx = IdxGV.UByteVal; break;
836       case Type::UShortTyID: Idx = IdxGV.UShortVal; break;
837       case Type::UIntTyID:   Idx = IdxGV.UIntVal; break;
838       case Type::ULongTyID:  Idx = IdxGV.ULongVal; break;
839       }
840       Total += PointerTy(TD.getTypeSize(ST->getElementType())*Idx);
841     }
842   }
843
844   GenericValue Result;
845   Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
846   return Result;
847 }
848
849 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
850   ExecutionContext &SF = ECStack.back();
851   SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
852                                    gep_type_begin(I), gep_type_end(I), SF), SF);
853 }
854
855 void Interpreter::visitLoadInst(LoadInst &I) {
856   ExecutionContext &SF = ECStack.back();
857   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
858   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
859   GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
860   SetValue(&I, Result, SF);
861 }
862
863 void Interpreter::visitStoreInst(StoreInst &I) {
864   ExecutionContext &SF = ECStack.back();
865   GenericValue Val = getOperandValue(I.getOperand(0), SF);
866   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
867   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
868                      I.getOperand(0)->getType());
869 }
870
871 //===----------------------------------------------------------------------===//
872 //                 Miscellaneous Instruction Implementations
873 //===----------------------------------------------------------------------===//
874
875 void Interpreter::visitCallSite(CallSite CS) {
876   ExecutionContext &SF = ECStack.back();
877
878   // Check to see if this is an intrinsic function call...
879   if (Function *F = CS.getCalledFunction())
880    if (F->isExternal ())
881     switch (F->getIntrinsicID()) {
882     case Intrinsic::not_intrinsic:
883       break;
884     case Intrinsic::vastart: { // va_start
885       GenericValue ArgIndex;
886       ArgIndex.UIntPairVal.first = ECStack.size() - 1;
887       ArgIndex.UIntPairVal.second = 0;
888       SetValue(CS.getInstruction(), ArgIndex, SF);
889       return;
890     }
891     case Intrinsic::vaend:    // va_end is a noop for the interpreter
892       return;
893     case Intrinsic::vacopy:   // va_copy: dest = src
894       SetValue(CS.getInstruction(), getOperandValue(*CS.arg_begin(), SF), SF);
895       return;
896     default:
897       // If it is an unknown intrinsic function, use the intrinsic lowering
898       // class to transform it into hopefully tasty LLVM code.
899       //
900       Instruction *Prev = CS.getInstruction()->getPrev();
901       BasicBlock *Parent = CS.getInstruction()->getParent();
902       IL->LowerIntrinsicCall(cast<CallInst>(CS.getInstruction()));
903
904       // Restore the CurInst pointer to the first instruction newly inserted, if
905       // any.
906       if (!Prev) {
907         SF.CurInst = Parent->begin();
908       } else {
909         SF.CurInst = Prev;
910         ++SF.CurInst;
911       }
912       return;
913     }
914
915   SF.Caller = CS;
916   std::vector<GenericValue> ArgVals;
917   const unsigned NumArgs = SF.Caller.arg_size();
918   ArgVals.reserve(NumArgs);
919   for (CallSite::arg_iterator i = SF.Caller.arg_begin(),
920          e = SF.Caller.arg_end(); i != e; ++i) {
921     Value *V = *i;
922     ArgVals.push_back(getOperandValue(V, SF));
923     // Promote all integral types whose size is < sizeof(int) into ints.  We do
924     // this by zero or sign extending the value as appropriate according to the
925     // source type.
926     const Type *Ty = V->getType();
927     if (Ty->isIntegral() && Ty->getPrimitiveSize() < 4) {
928       if (Ty == Type::ShortTy)
929         ArgVals.back().IntVal = ArgVals.back().ShortVal;
930       else if (Ty == Type::UShortTy)
931         ArgVals.back().UIntVal = ArgVals.back().UShortVal;
932       else if (Ty == Type::SByteTy)
933         ArgVals.back().IntVal = ArgVals.back().SByteVal;
934       else if (Ty == Type::UByteTy)
935         ArgVals.back().UIntVal = ArgVals.back().UByteVal;
936       else if (Ty == Type::BoolTy)
937         ArgVals.back().UIntVal = ArgVals.back().BoolVal;
938       else
939         assert(0 && "Unknown type!");
940     }
941   }
942
943   // To handle indirect calls, we must get the pointer value from the argument
944   // and treat it as a function pointer.
945   GenericValue SRC = getOperandValue(SF.Caller.getCalledValue(), SF);
946   callFunction((Function*)GVTOP(SRC), ArgVals);
947 }
948
949 #define IMPLEMENT_SHIFT(OP, TY) \
950    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
951
952 #define IMPLEMENT_SIGNLESS_SHIFT(OP, TY1, TY2) \
953    case Type::TY2##TyID: \
954    IMPLEMENT_SHIFT(OP, TY1) 
955
956 static GenericValue executeShlInst(GenericValue Src1, GenericValue Src2,
957                                    const Type *Ty) {
958   GenericValue Dest;
959   switch (Ty->getTypeID()) {
960     IMPLEMENT_SHIFT(<<, UByte);
961     IMPLEMENT_SHIFT(<<, SByte);
962     IMPLEMENT_SHIFT(<<, UShort);
963     IMPLEMENT_SHIFT(<<, Short);
964     IMPLEMENT_SHIFT(<<, UInt);
965     IMPLEMENT_SHIFT(<<, Int);
966     IMPLEMENT_SHIFT(<<, ULong);
967     IMPLEMENT_SHIFT(<<, Long);
968   default:
969     std::cout << "Unhandled type for Shl instruction: " << *Ty << "\n";
970   }
971   return Dest;
972 }
973
974 static GenericValue executeLShrInst(GenericValue Src1, GenericValue Src2,
975                                     const Type *Ty) {
976   GenericValue Dest;
977   switch (Ty->getTypeID()) {
978     IMPLEMENT_SIGNLESS_SHIFT(>>, UByte,  SByte);
979     IMPLEMENT_SIGNLESS_SHIFT(>>, UShort, Short);
980     IMPLEMENT_SIGNLESS_SHIFT(>>, UInt,   Int);
981     IMPLEMENT_SIGNLESS_SHIFT(>>, ULong,  Long);
982   default:
983     std::cout << "Unhandled type for LShr instruction: " << *Ty << "\n";
984     abort();
985   }
986   return Dest;
987 }
988
989 static GenericValue executeAShrInst(GenericValue Src1, GenericValue Src2,
990                                     const Type *Ty) {
991   GenericValue Dest;
992   switch (Ty->getTypeID()) {
993     IMPLEMENT_SIGNLESS_SHIFT(>>, SByte, UByte);
994     IMPLEMENT_SIGNLESS_SHIFT(>>, Short, UShort);
995     IMPLEMENT_SIGNLESS_SHIFT(>>, Int,   UInt);
996     IMPLEMENT_SIGNLESS_SHIFT(>>, Long,  ULong);
997   default:
998     std::cout << "Unhandled type for AShr instruction: " << *Ty << "\n";
999     abort();
1000   }
1001   return Dest;
1002 }
1003
1004 void Interpreter::visitShl(ShiftInst &I) {
1005   ExecutionContext &SF = ECStack.back();
1006   const Type *Ty    = I.getOperand(0)->getType();
1007   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1008   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1009   GenericValue Dest;
1010   Dest = executeShlInst (Src1, Src2, Ty);
1011   SetValue(&I, Dest, SF);
1012 }
1013
1014 void Interpreter::visitLShr(ShiftInst &I) {
1015   ExecutionContext &SF = ECStack.back();
1016   const Type *Ty    = I.getOperand(0)->getType();
1017   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1018   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1019   GenericValue Dest;
1020   Dest = executeLShrInst (Src1, Src2, Ty);
1021   SetValue(&I, Dest, SF);
1022 }
1023
1024 void Interpreter::visitAShr(ShiftInst &I) {
1025   ExecutionContext &SF = ECStack.back();
1026   const Type *Ty    = I.getOperand(0)->getType();
1027   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
1028   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
1029   GenericValue Dest;
1030   Dest = executeAShrInst (Src1, Src2, Ty);
1031   SetValue(&I, Dest, SF);
1032 }
1033
1034 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
1035    case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
1036
1037 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY)    \
1038   case Type::DESTTY##TyID:                      \
1039     switch (SrcTy->getTypeID()) {          \
1040       IMPLEMENT_CAST(DESTTY, DESTCTY, Bool);    \
1041       IMPLEMENT_CAST(DESTTY, DESTCTY, UByte);   \
1042       IMPLEMENT_CAST(DESTTY, DESTCTY, SByte);   \
1043       IMPLEMENT_CAST(DESTTY, DESTCTY, UShort);  \
1044       IMPLEMENT_CAST(DESTTY, DESTCTY, Short);   \
1045       IMPLEMENT_CAST(DESTTY, DESTCTY, UInt);    \
1046       IMPLEMENT_CAST(DESTTY, DESTCTY, Int);     \
1047       IMPLEMENT_CAST(DESTTY, DESTCTY, ULong);   \
1048       IMPLEMENT_CAST(DESTTY, DESTCTY, Long);    \
1049       IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
1050
1051 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
1052       IMPLEMENT_CAST(DESTTY, DESTCTY, Float);   \
1053       IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
1054
1055 #define IMPLEMENT_CAST_CASE_END()    \
1056     default: std::cout << "Unhandled cast: " << *SrcTy << " to " << *Ty << "\n"; \
1057       abort();                                  \
1058     }                                           \
1059     break
1060
1061 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
1062    IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY);   \
1063    IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
1064    IMPLEMENT_CAST_CASE_END()
1065
1066 GenericValue Interpreter::executeCastOperation(Value *SrcVal, const Type *Ty,
1067                                                ExecutionContext &SF) {
1068   const Type *SrcTy = SrcVal->getType();
1069   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
1070
1071   switch (Ty->getTypeID()) {
1072     IMPLEMENT_CAST_CASE(UByte  , (unsigned char));
1073     IMPLEMENT_CAST_CASE(SByte  , (  signed char));
1074     IMPLEMENT_CAST_CASE(UShort , (unsigned short));
1075     IMPLEMENT_CAST_CASE(Short  , (  signed short));
1076     IMPLEMENT_CAST_CASE(UInt   , (unsigned int ));
1077     IMPLEMENT_CAST_CASE(Int    , (  signed int ));
1078     IMPLEMENT_CAST_CASE(ULong  , (uint64_t));
1079     IMPLEMENT_CAST_CASE(Long   , ( int64_t));
1080     IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
1081     IMPLEMENT_CAST_CASE(Float  , (float));
1082     IMPLEMENT_CAST_CASE(Double , (double));
1083     IMPLEMENT_CAST_CASE(Bool   , (bool));
1084   default:
1085     std::cout << "Unhandled dest type for cast instruction: " << *Ty << "\n";
1086     abort();
1087   }
1088
1089   return Dest;
1090 }
1091
1092 void Interpreter::visitCastInst(CastInst &I) {
1093   ExecutionContext &SF = ECStack.back();
1094   SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
1095 }
1096
1097 #define IMPLEMENT_VAARG(TY) \
1098    case Type::TY##TyID: Dest.TY##Val = Src.TY##Val; break
1099
1100 void Interpreter::visitVAArgInst(VAArgInst &I) {
1101   ExecutionContext &SF = ECStack.back();
1102
1103   // Get the incoming valist parameter.  LLI treats the valist as a
1104   // (ec-stack-depth var-arg-index) pair.
1105   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
1106   GenericValue Dest;
1107   GenericValue Src = ECStack[VAList.UIntPairVal.first]
1108    .VarArgs[VAList.UIntPairVal.second];
1109   const Type *Ty = I.getType();
1110   switch (Ty->getTypeID()) {
1111     IMPLEMENT_VAARG(UByte);
1112     IMPLEMENT_VAARG(SByte);
1113     IMPLEMENT_VAARG(UShort);
1114     IMPLEMENT_VAARG(Short);
1115     IMPLEMENT_VAARG(UInt);
1116     IMPLEMENT_VAARG(Int);
1117     IMPLEMENT_VAARG(ULong);
1118     IMPLEMENT_VAARG(Long);
1119     IMPLEMENT_VAARG(Pointer);
1120     IMPLEMENT_VAARG(Float);
1121     IMPLEMENT_VAARG(Double);
1122     IMPLEMENT_VAARG(Bool);
1123   default:
1124     std::cout << "Unhandled dest type for vaarg instruction: " << *Ty << "\n";
1125     abort();
1126   }
1127
1128   // Set the Value of this Instruction.
1129   SetValue(&I, Dest, SF);
1130
1131   // Move the pointer to the next vararg.
1132   ++VAList.UIntPairVal.second;
1133 }
1134
1135 //===----------------------------------------------------------------------===//
1136 //                        Dispatch and Execution Code
1137 //===----------------------------------------------------------------------===//
1138
1139 //===----------------------------------------------------------------------===//
1140 // callFunction - Execute the specified function...
1141 //
1142 void Interpreter::callFunction(Function *F,
1143                                const std::vector<GenericValue> &ArgVals) {
1144   assert((ECStack.empty() || ECStack.back().Caller.getInstruction() == 0 ||
1145           ECStack.back().Caller.arg_size() == ArgVals.size()) &&
1146          "Incorrect number of arguments passed into function call!");
1147   // Make a new stack frame... and fill it in.
1148   ECStack.push_back(ExecutionContext());
1149   ExecutionContext &StackFrame = ECStack.back();
1150   StackFrame.CurFunction = F;
1151
1152   // Special handling for external functions.
1153   if (F->isExternal()) {
1154     GenericValue Result = callExternalFunction (F, ArgVals);
1155     // Simulate a 'ret' instruction of the appropriate type.
1156     popStackAndReturnValueToCaller (F->getReturnType (), Result);
1157     return;
1158   }
1159
1160   // Get pointers to first LLVM BB & Instruction in function.
1161   StackFrame.CurBB     = F->begin();
1162   StackFrame.CurInst   = StackFrame.CurBB->begin();
1163
1164   // Run through the function arguments and initialize their values...
1165   assert((ArgVals.size() == F->arg_size() ||
1166          (ArgVals.size() > F->arg_size() && F->getFunctionType()->isVarArg()))&&
1167          "Invalid number of values passed to function invocation!");
1168
1169   // Handle non-varargs arguments...
1170   unsigned i = 0;
1171   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; ++AI, ++i)
1172     SetValue(AI, ArgVals[i], StackFrame);
1173
1174   // Handle varargs arguments...
1175   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
1176 }
1177
1178 void Interpreter::run() {
1179   while (!ECStack.empty()) {
1180     // Interpret a single instruction & increment the "PC".
1181     ExecutionContext &SF = ECStack.back();  // Current stack frame
1182     Instruction &I = *SF.CurInst++;         // Increment before execute
1183
1184     // Track the number of dynamic instructions executed.
1185     ++NumDynamicInsts;
1186
1187     DEBUG(std::cerr << "About to interpret: " << I);
1188     visit(I);   // Dispatch to one of the visit* methods...
1189   }
1190 }