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