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