Put all LLVM code into the llvm namespace, as per bug 109.
[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 #include "Interpreter.h"
15 #include "llvm/Instructions.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Constants.h"
18 #include "Support/Statistic.h"
19 #include <cmath>  // For fmod
20
21 namespace llvm {
22
23 namespace {
24   Statistic<> NumDynamicInsts("lli", "Number of dynamic instructions executed");
25 }
26
27 Interpreter *TheEE = 0;
28
29 //===----------------------------------------------------------------------===//
30 //                     Value Manipulation code
31 //===----------------------------------------------------------------------===//
32
33 // Operations used by constant expr implementations...
34 static GenericValue executeCastOperation(Value *Src, const Type *DestTy,
35                                          ExecutionContext &SF);
36 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
37                                    const Type *Ty);
38
39 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
40   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
41     switch (CE->getOpcode()) {
42     case Instruction::Cast:
43       return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
44     case Instruction::GetElementPtr:
45       return TheEE->executeGEPOperation(CE->getOperand(0), CE->op_begin()+1,
46                                         CE->op_end(), SF);
47     case Instruction::Add:
48       return executeAddInst(getOperandValue(CE->getOperand(0), SF),
49                             getOperandValue(CE->getOperand(1), SF),
50                             CE->getType());
51     default:
52       std::cerr << "Unhandled ConstantExpr: " << CE << "\n";
53       abort();
54       return GenericValue();
55     }
56   } else if (Constant *CPV = dyn_cast<Constant>(V)) {
57     return TheEE->getConstantValue(CPV);
58   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
59     return PTOGV(TheEE->getPointerToGlobal(GV));
60   } else {
61     return SF.Values[V];
62   }
63 }
64
65 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
66   SF.Values[V] = Val;
67 }
68
69 //===----------------------------------------------------------------------===//
70 //                    Annotation Wrangling code
71 //===----------------------------------------------------------------------===//
72
73 void Interpreter::initializeExecutionEngine() {
74   TheEE = this;
75 }
76
77 //===----------------------------------------------------------------------===//
78 //                    Binary Instruction Implementations
79 //===----------------------------------------------------------------------===//
80
81 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
82    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
83
84 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
85                                    const Type *Ty) {
86   GenericValue Dest;
87   switch (Ty->getPrimitiveID()) {
88     IMPLEMENT_BINARY_OPERATOR(+, UByte);
89     IMPLEMENT_BINARY_OPERATOR(+, SByte);
90     IMPLEMENT_BINARY_OPERATOR(+, UShort);
91     IMPLEMENT_BINARY_OPERATOR(+, Short);
92     IMPLEMENT_BINARY_OPERATOR(+, UInt);
93     IMPLEMENT_BINARY_OPERATOR(+, Int);
94     IMPLEMENT_BINARY_OPERATOR(+, ULong);
95     IMPLEMENT_BINARY_OPERATOR(+, Long);
96     IMPLEMENT_BINARY_OPERATOR(+, Float);
97     IMPLEMENT_BINARY_OPERATOR(+, Double);
98   default:
99     std::cout << "Unhandled type for Add instruction: " << *Ty << "\n";
100     abort();
101   }
102   return Dest;
103 }
104
105 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2, 
106                                    const Type *Ty) {
107   GenericValue Dest;
108   switch (Ty->getPrimitiveID()) {
109     IMPLEMENT_BINARY_OPERATOR(-, UByte);
110     IMPLEMENT_BINARY_OPERATOR(-, SByte);
111     IMPLEMENT_BINARY_OPERATOR(-, UShort);
112     IMPLEMENT_BINARY_OPERATOR(-, Short);
113     IMPLEMENT_BINARY_OPERATOR(-, UInt);
114     IMPLEMENT_BINARY_OPERATOR(-, Int);
115     IMPLEMENT_BINARY_OPERATOR(-, ULong);
116     IMPLEMENT_BINARY_OPERATOR(-, Long);
117     IMPLEMENT_BINARY_OPERATOR(-, Float);
118     IMPLEMENT_BINARY_OPERATOR(-, Double);
119   default:
120     std::cout << "Unhandled type for Sub instruction: " << *Ty << "\n";
121     abort();
122   }
123   return Dest;
124 }
125
126 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2, 
127                                    const Type *Ty) {
128   GenericValue Dest;
129   switch (Ty->getPrimitiveID()) {
130     IMPLEMENT_BINARY_OPERATOR(*, UByte);
131     IMPLEMENT_BINARY_OPERATOR(*, SByte);
132     IMPLEMENT_BINARY_OPERATOR(*, UShort);
133     IMPLEMENT_BINARY_OPERATOR(*, Short);
134     IMPLEMENT_BINARY_OPERATOR(*, UInt);
135     IMPLEMENT_BINARY_OPERATOR(*, Int);
136     IMPLEMENT_BINARY_OPERATOR(*, ULong);
137     IMPLEMENT_BINARY_OPERATOR(*, Long);
138     IMPLEMENT_BINARY_OPERATOR(*, Float);
139     IMPLEMENT_BINARY_OPERATOR(*, Double);
140   default:
141     std::cout << "Unhandled type for Mul instruction: " << Ty << "\n";
142     abort();
143   }
144   return Dest;
145 }
146
147 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2, 
148                                    const Type *Ty) {
149   GenericValue Dest;
150   switch (Ty->getPrimitiveID()) {
151     IMPLEMENT_BINARY_OPERATOR(/, UByte);
152     IMPLEMENT_BINARY_OPERATOR(/, SByte);
153     IMPLEMENT_BINARY_OPERATOR(/, UShort);
154     IMPLEMENT_BINARY_OPERATOR(/, Short);
155     IMPLEMENT_BINARY_OPERATOR(/, UInt);
156     IMPLEMENT_BINARY_OPERATOR(/, Int);
157     IMPLEMENT_BINARY_OPERATOR(/, ULong);
158     IMPLEMENT_BINARY_OPERATOR(/, Long);
159     IMPLEMENT_BINARY_OPERATOR(/, Float);
160     IMPLEMENT_BINARY_OPERATOR(/, Double);
161   default:
162     std::cout << "Unhandled type for Div instruction: " << *Ty << "\n";
163     abort();
164   }
165   return Dest;
166 }
167
168 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2, 
169                                    const Type *Ty) {
170   GenericValue Dest;
171   switch (Ty->getPrimitiveID()) {
172     IMPLEMENT_BINARY_OPERATOR(%, UByte);
173     IMPLEMENT_BINARY_OPERATOR(%, SByte);
174     IMPLEMENT_BINARY_OPERATOR(%, UShort);
175     IMPLEMENT_BINARY_OPERATOR(%, Short);
176     IMPLEMENT_BINARY_OPERATOR(%, UInt);
177     IMPLEMENT_BINARY_OPERATOR(%, Int);
178     IMPLEMENT_BINARY_OPERATOR(%, ULong);
179     IMPLEMENT_BINARY_OPERATOR(%, Long);
180   case Type::FloatTyID:
181     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
182     break;
183   case Type::DoubleTyID:
184     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
185     break;
186   default:
187     std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
188     abort();
189   }
190   return Dest;
191 }
192
193 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2, 
194                                    const Type *Ty) {
195   GenericValue Dest;
196   switch (Ty->getPrimitiveID()) {
197     IMPLEMENT_BINARY_OPERATOR(&, Bool);
198     IMPLEMENT_BINARY_OPERATOR(&, UByte);
199     IMPLEMENT_BINARY_OPERATOR(&, SByte);
200     IMPLEMENT_BINARY_OPERATOR(&, UShort);
201     IMPLEMENT_BINARY_OPERATOR(&, Short);
202     IMPLEMENT_BINARY_OPERATOR(&, UInt);
203     IMPLEMENT_BINARY_OPERATOR(&, Int);
204     IMPLEMENT_BINARY_OPERATOR(&, ULong);
205     IMPLEMENT_BINARY_OPERATOR(&, Long);
206   default:
207     std::cout << "Unhandled type for And instruction: " << *Ty << "\n";
208     abort();
209   }
210   return Dest;
211 }
212
213 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2, 
214                                   const Type *Ty) {
215   GenericValue Dest;
216   switch (Ty->getPrimitiveID()) {
217     IMPLEMENT_BINARY_OPERATOR(|, Bool);
218     IMPLEMENT_BINARY_OPERATOR(|, UByte);
219     IMPLEMENT_BINARY_OPERATOR(|, SByte);
220     IMPLEMENT_BINARY_OPERATOR(|, UShort);
221     IMPLEMENT_BINARY_OPERATOR(|, Short);
222     IMPLEMENT_BINARY_OPERATOR(|, UInt);
223     IMPLEMENT_BINARY_OPERATOR(|, Int);
224     IMPLEMENT_BINARY_OPERATOR(|, ULong);
225     IMPLEMENT_BINARY_OPERATOR(|, Long);
226   default:
227     std::cout << "Unhandled type for Or instruction: " << *Ty << "\n";
228     abort();
229   }
230   return Dest;
231 }
232
233 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2, 
234                                    const Type *Ty) {
235   GenericValue Dest;
236   switch (Ty->getPrimitiveID()) {
237     IMPLEMENT_BINARY_OPERATOR(^, Bool);
238     IMPLEMENT_BINARY_OPERATOR(^, UByte);
239     IMPLEMENT_BINARY_OPERATOR(^, SByte);
240     IMPLEMENT_BINARY_OPERATOR(^, UShort);
241     IMPLEMENT_BINARY_OPERATOR(^, Short);
242     IMPLEMENT_BINARY_OPERATOR(^, UInt);
243     IMPLEMENT_BINARY_OPERATOR(^, Int);
244     IMPLEMENT_BINARY_OPERATOR(^, ULong);
245     IMPLEMENT_BINARY_OPERATOR(^, Long);
246   default:
247     std::cout << "Unhandled type for Xor instruction: " << *Ty << "\n";
248     abort();
249   }
250   return Dest;
251 }
252
253 #define IMPLEMENT_SETCC(OP, TY) \
254    case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
255
256 // Handle pointers specially because they must be compared with only as much
257 // width as the host has.  We _do not_ want to be comparing 64 bit values when
258 // running on a 32-bit target, otherwise the upper 32 bits might mess up
259 // comparisons if they contain garbage.
260 #define IMPLEMENT_POINTERSETCC(OP) \
261    case Type::PointerTyID: \
262         Dest.BoolVal = (void*)(intptr_t)Src1.PointerVal OP \
263                        (void*)(intptr_t)Src2.PointerVal; break
264
265 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2, 
266                                      const Type *Ty) {
267   GenericValue Dest;
268   switch (Ty->getPrimitiveID()) {
269     IMPLEMENT_SETCC(==, UByte);
270     IMPLEMENT_SETCC(==, SByte);
271     IMPLEMENT_SETCC(==, UShort);
272     IMPLEMENT_SETCC(==, Short);
273     IMPLEMENT_SETCC(==, UInt);
274     IMPLEMENT_SETCC(==, Int);
275     IMPLEMENT_SETCC(==, ULong);
276     IMPLEMENT_SETCC(==, Long);
277     IMPLEMENT_SETCC(==, Float);
278     IMPLEMENT_SETCC(==, Double);
279     IMPLEMENT_POINTERSETCC(==);
280   default:
281     std::cout << "Unhandled type for SetEQ instruction: " << *Ty << "\n";
282     abort();
283   }
284   return Dest;
285 }
286
287 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2, 
288                                      const Type *Ty) {
289   GenericValue Dest;
290   switch (Ty->getPrimitiveID()) {
291     IMPLEMENT_SETCC(!=, UByte);
292     IMPLEMENT_SETCC(!=, SByte);
293     IMPLEMENT_SETCC(!=, UShort);
294     IMPLEMENT_SETCC(!=, Short);
295     IMPLEMENT_SETCC(!=, UInt);
296     IMPLEMENT_SETCC(!=, Int);
297     IMPLEMENT_SETCC(!=, ULong);
298     IMPLEMENT_SETCC(!=, Long);
299     IMPLEMENT_SETCC(!=, Float);
300     IMPLEMENT_SETCC(!=, Double);
301     IMPLEMENT_POINTERSETCC(!=);
302
303   default:
304     std::cout << "Unhandled type for SetNE instruction: " << *Ty << "\n";
305     abort();
306   }
307   return Dest;
308 }
309
310 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2, 
311                                      const Type *Ty) {
312   GenericValue Dest;
313   switch (Ty->getPrimitiveID()) {
314     IMPLEMENT_SETCC(<=, UByte);
315     IMPLEMENT_SETCC(<=, SByte);
316     IMPLEMENT_SETCC(<=, UShort);
317     IMPLEMENT_SETCC(<=, Short);
318     IMPLEMENT_SETCC(<=, UInt);
319     IMPLEMENT_SETCC(<=, Int);
320     IMPLEMENT_SETCC(<=, ULong);
321     IMPLEMENT_SETCC(<=, Long);
322     IMPLEMENT_SETCC(<=, Float);
323     IMPLEMENT_SETCC(<=, Double);
324     IMPLEMENT_POINTERSETCC(<=);
325   default:
326     std::cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
327     abort();
328   }
329   return Dest;
330 }
331
332 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2, 
333                                      const Type *Ty) {
334   GenericValue Dest;
335   switch (Ty->getPrimitiveID()) {
336     IMPLEMENT_SETCC(>=, UByte);
337     IMPLEMENT_SETCC(>=, SByte);
338     IMPLEMENT_SETCC(>=, UShort);
339     IMPLEMENT_SETCC(>=, Short);
340     IMPLEMENT_SETCC(>=, UInt);
341     IMPLEMENT_SETCC(>=, Int);
342     IMPLEMENT_SETCC(>=, ULong);
343     IMPLEMENT_SETCC(>=, Long);
344     IMPLEMENT_SETCC(>=, Float);
345     IMPLEMENT_SETCC(>=, Double);
346     IMPLEMENT_POINTERSETCC(>=);
347   default:
348     std::cout << "Unhandled type for SetGE instruction: " << *Ty << "\n";
349     abort();
350   }
351   return Dest;
352 }
353
354 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2, 
355                                      const Type *Ty) {
356   GenericValue Dest;
357   switch (Ty->getPrimitiveID()) {
358     IMPLEMENT_SETCC(<, UByte);
359     IMPLEMENT_SETCC(<, SByte);
360     IMPLEMENT_SETCC(<, UShort);
361     IMPLEMENT_SETCC(<, Short);
362     IMPLEMENT_SETCC(<, UInt);
363     IMPLEMENT_SETCC(<, Int);
364     IMPLEMENT_SETCC(<, ULong);
365     IMPLEMENT_SETCC(<, Long);
366     IMPLEMENT_SETCC(<, Float);
367     IMPLEMENT_SETCC(<, Double);
368     IMPLEMENT_POINTERSETCC(<);
369   default:
370     std::cout << "Unhandled type for SetLT instruction: " << *Ty << "\n";
371     abort();
372   }
373   return Dest;
374 }
375
376 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2, 
377                                      const Type *Ty) {
378   GenericValue Dest;
379   switch (Ty->getPrimitiveID()) {
380     IMPLEMENT_SETCC(>, UByte);
381     IMPLEMENT_SETCC(>, SByte);
382     IMPLEMENT_SETCC(>, UShort);
383     IMPLEMENT_SETCC(>, Short);
384     IMPLEMENT_SETCC(>, UInt);
385     IMPLEMENT_SETCC(>, Int);
386     IMPLEMENT_SETCC(>, ULong);
387     IMPLEMENT_SETCC(>, Long);
388     IMPLEMENT_SETCC(>, Float);
389     IMPLEMENT_SETCC(>, Double);
390     IMPLEMENT_POINTERSETCC(>);
391   default:
392     std::cout << "Unhandled type for SetGT instruction: " << *Ty << "\n";
393     abort();
394   }
395   return Dest;
396 }
397
398 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
399   ExecutionContext &SF = ECStack.back();
400   const Type *Ty    = I.getOperand(0)->getType();
401   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
402   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
403   GenericValue R;   // Result
404
405   switch (I.getOpcode()) {
406   case Instruction::Add:   R = executeAddInst  (Src1, Src2, Ty); break;
407   case Instruction::Sub:   R = executeSubInst  (Src1, Src2, Ty); break;
408   case Instruction::Mul:   R = executeMulInst  (Src1, Src2, Ty); break;
409   case Instruction::Div:   R = executeDivInst  (Src1, Src2, Ty); break;
410   case Instruction::Rem:   R = executeRemInst  (Src1, Src2, Ty); break;
411   case Instruction::And:   R = executeAndInst  (Src1, Src2, Ty); break;
412   case Instruction::Or:    R = executeOrInst   (Src1, Src2, Ty); break;
413   case Instruction::Xor:   R = executeXorInst  (Src1, Src2, Ty); break;
414   case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty); break;
415   case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty); break;
416   case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty); break;
417   case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty); break;
418   case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty); break;
419   case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty); break;
420   default:
421     std::cout << "Don't know how to handle this binary operator!\n-->" << I;
422     abort();
423   }
424
425   SetValue(&I, R, SF);
426 }
427
428 //===----------------------------------------------------------------------===//
429 //                     Terminator Instruction Implementations
430 //===----------------------------------------------------------------------===//
431
432 void Interpreter::exitCalled(GenericValue GV) {
433   ExitCode = GV.SByteVal;
434   ECStack.clear();
435 }
436
437 /// Pop the last stack frame off of ECStack and then copy the result
438 /// back into the result variable if we are not returning void. The
439 /// result variable may be the ExitCode, or the Value of the calling
440 /// CallInst if there was a previous stack frame. This method may
441 /// invalidate any ECStack iterators you have. This method also takes
442 /// care of switching to the normal destination BB, if we are returning
443 /// from an invoke.
444 ///
445 void Interpreter::popStackAndReturnValueToCaller (const Type *RetTy,
446                                                   GenericValue Result) {
447   // Pop the current stack frame.
448   ECStack.pop_back();
449
450   if (ECStack.empty()) {  // Finished main.  Put result into exit code... 
451     if (RetTy && RetTy->isIntegral()) {          // Nonvoid return type?       
452       ExitCode = Result.IntVal;   // Capture the exit code of the program 
453     } else { 
454       ExitCode = 0; 
455     } 
456   } else { 
457     // If we have a previous stack frame, and we have a previous call, 
458     // fill in the return value... 
459     ExecutionContext &CallingSF = ECStack.back();
460     if (Instruction *I = CallingSF.Caller.getInstruction()) {
461       if (CallingSF.Caller.getType() != Type::VoidTy)      // Save result...
462         SetValue(I, Result, CallingSF);
463       if (InvokeInst *II = dyn_cast<InvokeInst> (I))
464         SwitchToNewBasicBlock (II->getNormalDest (), CallingSF);
465       CallingSF.Caller = CallSite();          // We returned from the call...
466     }
467   }
468 }
469
470 void Interpreter::visitReturnInst(ReturnInst &I) {
471   ExecutionContext &SF = ECStack.back();
472   const Type *RetTy = Type::VoidTy;
473   GenericValue Result;
474
475   // Save away the return value... (if we are not 'ret void')
476   if (I.getNumOperands()) {
477     RetTy  = I.getReturnValue()->getType();
478     Result = getOperandValue(I.getReturnValue(), SF);
479   }
480
481   popStackAndReturnValueToCaller(RetTy, Result);
482 }
483
484 void Interpreter::visitUnwindInst(UnwindInst &I) {
485   // Unwind stack
486   Instruction *Inst;
487   do {
488     ECStack.pop_back ();
489     if (ECStack.empty ())
490       abort ();
491     Inst = ECStack.back ().Caller.getInstruction ();
492   } while (!(Inst && isa<InvokeInst> (Inst)));
493
494   // Return from invoke
495   ExecutionContext &InvokingSF = ECStack.back ();
496   InvokingSF.Caller = CallSite ();
497
498   // Go to exceptional destination BB of invoke instruction
499   SwitchToNewBasicBlock (cast<InvokeInst> (Inst)->getExceptionalDest (),
500                          InvokingSF);
501 }
502
503 void Interpreter::visitBranchInst(BranchInst &I) {
504   ExecutionContext &SF = ECStack.back();
505   BasicBlock *Dest;
506
507   Dest = I.getSuccessor(0);          // Uncond branches have a fixed dest...
508   if (!I.isUnconditional()) {
509     Value *Cond = I.getCondition();
510     if (getOperandValue(Cond, SF).BoolVal == 0) // If false cond...
511       Dest = I.getSuccessor(1);    
512   }
513   SwitchToNewBasicBlock(Dest, SF);
514 }
515
516 void Interpreter::visitSwitchInst(SwitchInst &I) {
517   ExecutionContext &SF = ECStack.back();
518   GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
519   const Type *ElTy = I.getOperand(0)->getType();
520
521   // Check to see if any of the cases match...
522   BasicBlock *Dest = 0;
523   for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
524     if (executeSetEQInst(CondVal,
525                          getOperandValue(I.getOperand(i), SF), ElTy).BoolVal) {
526       Dest = cast<BasicBlock>(I.getOperand(i+1));
527       break;
528     }
529   
530   if (!Dest) Dest = I.getDefaultDest();   // No cases matched: use default
531   SwitchToNewBasicBlock(Dest, SF);
532 }
533
534 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
535 // This function handles the actual updating of block and instruction iterators
536 // as well as execution of all of the PHI nodes in the destination block.
537 //
538 // This method does this because all of the PHI nodes must be executed
539 // atomically, reading their inputs before any of the results are updated.  Not
540 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
541 // their inputs.  If the input PHI node is updated before it is read, incorrect
542 // results can happen.  Thus we use a two phase approach.
543 //
544 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
545   BasicBlock *PrevBB = SF.CurBB;      // Remember where we came from...
546   SF.CurBB   = Dest;                  // Update CurBB to branch destination
547   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
548
549   if (!isa<PHINode>(SF.CurInst)) return;  // Nothing fancy to do
550
551   // Loop over all of the PHI nodes in the current block, reading their inputs.
552   std::vector<GenericValue> ResultValues;
553
554   for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
555     // Search for the value corresponding to this previous bb...
556     int i = PN->getBasicBlockIndex(PrevBB);
557     assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
558     Value *IncomingValue = PN->getIncomingValue(i);
559     
560     // Save the incoming value for this PHI node...
561     ResultValues.push_back(getOperandValue(IncomingValue, SF));
562   }
563
564   // Now loop over all of the PHI nodes setting their values...
565   SF.CurInst = SF.CurBB->begin();
566   for (unsigned i = 0; PHINode *PN = dyn_cast<PHINode>(SF.CurInst);
567        ++SF.CurInst, ++i)
568     SetValue(PN, ResultValues[i], SF);
569 }
570
571 //===----------------------------------------------------------------------===//
572 //                     Memory Instruction Implementations
573 //===----------------------------------------------------------------------===//
574
575 void Interpreter::visitAllocationInst(AllocationInst &I) {
576   ExecutionContext &SF = ECStack.back();
577
578   const Type *Ty = I.getType()->getElementType();  // Type to be allocated
579
580   // Get the number of elements being allocated by the array...
581   unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
582
583   // Allocate enough memory to hold the type...
584   void *Memory = malloc(NumElements * TD.getTypeSize(Ty));
585
586   GenericValue Result = PTOGV(Memory);
587   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
588   SetValue(&I, Result, SF);
589
590   if (I.getOpcode() == Instruction::Alloca)
591     ECStack.back().Allocas.add(Memory);
592 }
593
594 void Interpreter::visitFreeInst(FreeInst &I) {
595   ExecutionContext &SF = ECStack.back();
596   assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
597   GenericValue Value = getOperandValue(I.getOperand(0), SF);
598   // TODO: Check to make sure memory is allocated
599   free(GVTOP(Value));   // Free memory
600 }
601
602 // getElementOffset - The workhorse for getelementptr.
603 //
604 GenericValue Interpreter::executeGEPOperation(Value *Ptr, User::op_iterator I,
605                                               User::op_iterator E,
606                                               ExecutionContext &SF) {
607   assert(isa<PointerType>(Ptr->getType()) &&
608          "Cannot getElementOffset of a nonpointer type!");
609
610   PointerTy Total = 0;
611   const Type *Ty = Ptr->getType();
612
613   for (; I != E; ++I) {
614     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
615       const StructLayout *SLO = TD.getStructLayout(STy);
616       
617       // Indices must be ubyte constants...
618       const ConstantUInt *CPU = cast<ConstantUInt>(*I);
619       assert(CPU->getType() == Type::UByteTy);
620       unsigned Index = CPU->getValue();
621       
622       Total += SLO->MemberOffsets[Index];
623       Ty = STy->getElementTypes()[Index];
624     } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
625       // Get the index number for the array... which must be long type...
626       assert((*I)->getType() == Type::LongTy);
627       unsigned Idx = getOperandValue(*I, SF).LongVal;
628       Ty = ST->getElementType();
629       unsigned Size = TD.getTypeSize(Ty);
630       Total += Size*Idx;
631     }
632   }
633
634   GenericValue Result;
635   Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
636   return Result;
637 }
638
639 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
640   ExecutionContext &SF = ECStack.back();
641   SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
642                                    I.idx_begin(), I.idx_end(), SF), SF);
643 }
644
645 void Interpreter::visitLoadInst(LoadInst &I) {
646   ExecutionContext &SF = ECStack.back();
647   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
648   GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
649   GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
650   SetValue(&I, Result, SF);
651 }
652
653 void Interpreter::visitStoreInst(StoreInst &I) {
654   ExecutionContext &SF = ECStack.back();
655   GenericValue Val = getOperandValue(I.getOperand(0), SF);
656   GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
657   StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
658                      I.getOperand(0)->getType());
659 }
660
661 //===----------------------------------------------------------------------===//
662 //                 Miscellaneous Instruction Implementations
663 //===----------------------------------------------------------------------===//
664
665 void Interpreter::visitCallSite(CallSite CS) {
666   ExecutionContext &SF = ECStack.back();
667   SF.Caller = CS;
668   std::vector<GenericValue> ArgVals;
669   const unsigned NumArgs = SF.Caller.arg_size();
670   ArgVals.reserve(NumArgs);
671   for (CallSite::arg_iterator i = SF.Caller.arg_begin(),
672          e = SF.Caller.arg_end(); i != e; ++i) {
673     Value *V = *i;
674     ArgVals.push_back(getOperandValue(V, SF));
675     // Promote all integral types whose size is < sizeof(int) into ints.  We do
676     // this by zero or sign extending the value as appropriate according to the
677     // source type.
678     const Type *Ty = V->getType();
679     if (Ty->isIntegral() && Ty->getPrimitiveSize() < 4) {
680       if (Ty == Type::ShortTy)
681         ArgVals.back().IntVal = ArgVals.back().ShortVal;
682       else if (Ty == Type::UShortTy)
683         ArgVals.back().UIntVal = ArgVals.back().UShortVal;
684       else if (Ty == Type::SByteTy)
685         ArgVals.back().IntVal = ArgVals.back().SByteVal;
686       else if (Ty == Type::UByteTy)
687         ArgVals.back().UIntVal = ArgVals.back().UByteVal;
688       else if (Ty == Type::BoolTy)
689         ArgVals.back().UIntVal = ArgVals.back().BoolVal;
690       else
691         assert(0 && "Unknown type!");
692     }
693   }
694
695   // To handle indirect calls, we must get the pointer value from the argument 
696   // and treat it as a function pointer.
697   GenericValue SRC = getOperandValue(SF.Caller.getCalledValue(), SF);  
698   callFunction((Function*)GVTOP(SRC), ArgVals);
699 }
700
701 #define IMPLEMENT_SHIFT(OP, TY) \
702    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
703
704 void Interpreter::visitShl(ShiftInst &I) {
705   ExecutionContext &SF = ECStack.back();
706   const Type *Ty    = I.getOperand(0)->getType();
707   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
708   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
709   GenericValue Dest;
710
711   switch (Ty->getPrimitiveID()) {
712     IMPLEMENT_SHIFT(<<, UByte);
713     IMPLEMENT_SHIFT(<<, SByte);
714     IMPLEMENT_SHIFT(<<, UShort);
715     IMPLEMENT_SHIFT(<<, Short);
716     IMPLEMENT_SHIFT(<<, UInt);
717     IMPLEMENT_SHIFT(<<, Int);
718     IMPLEMENT_SHIFT(<<, ULong);
719     IMPLEMENT_SHIFT(<<, Long);
720   default:
721     std::cout << "Unhandled type for Shl instruction: " << *Ty << "\n";
722   }
723   SetValue(&I, Dest, SF);
724 }
725
726 void Interpreter::visitShr(ShiftInst &I) {
727   ExecutionContext &SF = ECStack.back();
728   const Type *Ty    = I.getOperand(0)->getType();
729   GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
730   GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
731   GenericValue Dest;
732
733   switch (Ty->getPrimitiveID()) {
734     IMPLEMENT_SHIFT(>>, UByte);
735     IMPLEMENT_SHIFT(>>, SByte);
736     IMPLEMENT_SHIFT(>>, UShort);
737     IMPLEMENT_SHIFT(>>, Short);
738     IMPLEMENT_SHIFT(>>, UInt);
739     IMPLEMENT_SHIFT(>>, Int);
740     IMPLEMENT_SHIFT(>>, ULong);
741     IMPLEMENT_SHIFT(>>, Long);
742   default:
743     std::cout << "Unhandled type for Shr instruction: " << *Ty << "\n";
744     abort();
745   }
746   SetValue(&I, Dest, SF);
747 }
748
749 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
750    case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
751
752 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY)    \
753   case Type::DESTTY##TyID:                      \
754     switch (SrcTy->getPrimitiveID()) {          \
755       IMPLEMENT_CAST(DESTTY, DESTCTY, Bool);    \
756       IMPLEMENT_CAST(DESTTY, DESTCTY, UByte);   \
757       IMPLEMENT_CAST(DESTTY, DESTCTY, SByte);   \
758       IMPLEMENT_CAST(DESTTY, DESTCTY, UShort);  \
759       IMPLEMENT_CAST(DESTTY, DESTCTY, Short);   \
760       IMPLEMENT_CAST(DESTTY, DESTCTY, UInt);    \
761       IMPLEMENT_CAST(DESTTY, DESTCTY, Int);     \
762       IMPLEMENT_CAST(DESTTY, DESTCTY, ULong);   \
763       IMPLEMENT_CAST(DESTTY, DESTCTY, Long);    \
764       IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
765
766 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
767       IMPLEMENT_CAST(DESTTY, DESTCTY, Float);   \
768       IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
769
770 #define IMPLEMENT_CAST_CASE_END()    \
771     default: std::cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
772       abort();                                  \
773     }                                           \
774     break
775
776 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
777    IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY);   \
778    IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
779    IMPLEMENT_CAST_CASE_END()
780
781 GenericValue Interpreter::executeCastOperation(Value *SrcVal, const Type *Ty,
782                                                ExecutionContext &SF) {
783   const Type *SrcTy = SrcVal->getType();
784   GenericValue Dest, Src = getOperandValue(SrcVal, SF);
785
786   switch (Ty->getPrimitiveID()) {
787     IMPLEMENT_CAST_CASE(UByte  , (unsigned char));
788     IMPLEMENT_CAST_CASE(SByte  , (  signed char));
789     IMPLEMENT_CAST_CASE(UShort , (unsigned short));
790     IMPLEMENT_CAST_CASE(Short  , (  signed short));
791     IMPLEMENT_CAST_CASE(UInt   , (unsigned int ));
792     IMPLEMENT_CAST_CASE(Int    , (  signed int ));
793     IMPLEMENT_CAST_CASE(ULong  , (uint64_t));
794     IMPLEMENT_CAST_CASE(Long   , ( int64_t));
795     IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
796     IMPLEMENT_CAST_CASE(Float  , (float));
797     IMPLEMENT_CAST_CASE(Double , (double));
798     IMPLEMENT_CAST_CASE(Bool   , (bool));
799   default:
800     std::cout << "Unhandled dest type for cast instruction: " << *Ty << "\n";
801     abort();
802   }
803
804   return Dest;
805 }
806
807 void Interpreter::visitCastInst(CastInst &I) {
808   ExecutionContext &SF = ECStack.back();
809   SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
810 }
811
812 void Interpreter::visitVANextInst(VANextInst &I) {
813   ExecutionContext &SF = ECStack.back();
814
815   // Get the incoming valist element.  LLI treats the valist as an integer.
816   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
817   
818   // Move to the next operand.
819   unsigned Argument = VAList.IntVal++;
820   assert(Argument < SF.VarArgs.size() &&
821          "Accessing past the last vararg argument!");
822   SetValue(&I, VAList, SF);
823 }
824
825 #define IMPLEMENT_VAARG(TY) \
826    case Type::TY##TyID: Dest.TY##Val = Src.TY##Val; break
827
828 void Interpreter::visitVAArgInst(VAArgInst &I) {
829   ExecutionContext &SF = ECStack.back();
830
831   // Get the incoming valist element.  LLI treats the valist as an integer.
832   GenericValue VAList = getOperandValue(I.getOperand(0), SF);
833   unsigned Argument = VAList.IntVal;
834   assert(Argument < SF.VarArgs.size() &&
835          "Accessing past the last vararg argument!");
836   GenericValue Dest, Src = SF.VarArgs[Argument];
837   const Type *Ty = I.getType();
838   switch (Ty->getPrimitiveID()) {
839     IMPLEMENT_VAARG(UByte);
840     IMPLEMENT_VAARG(SByte);
841     IMPLEMENT_VAARG(UShort);
842     IMPLEMENT_VAARG(Short);
843     IMPLEMENT_VAARG(UInt);
844     IMPLEMENT_VAARG(Int);
845     IMPLEMENT_VAARG(ULong);
846     IMPLEMENT_VAARG(Long);
847     IMPLEMENT_VAARG(Pointer);
848     IMPLEMENT_VAARG(Float);
849     IMPLEMENT_VAARG(Double);
850     IMPLEMENT_VAARG(Bool);
851   default:
852     std::cout << "Unhandled dest type for vaarg instruction: " << *Ty << "\n";
853     abort();
854   }
855   
856   // Set the Value of this Instruction.
857   SetValue(&I, Dest, SF);
858 }
859
860 //===----------------------------------------------------------------------===//
861 //                        Dispatch and Execution Code
862 //===----------------------------------------------------------------------===//
863
864 //===----------------------------------------------------------------------===//
865 // callFunction - Execute the specified function...
866 //
867 void Interpreter::callFunction(Function *F,
868                                const std::vector<GenericValue> &ArgVals) {
869   assert((ECStack.empty() || ECStack.back().Caller.getInstruction() == 0 || 
870           ECStack.back().Caller.arg_size() == ArgVals.size()) &&
871          "Incorrect number of arguments passed into function call!");
872   // Make a new stack frame... and fill it in.
873   ECStack.push_back(ExecutionContext());
874   ExecutionContext &StackFrame = ECStack.back();
875   StackFrame.CurFunction = F;
876
877   // Special handling for external functions.
878   if (F->isExternal()) {
879     GenericValue Result = callExternalFunction (F, ArgVals);
880     // Simulate a 'ret' instruction of the appropriate type.
881     popStackAndReturnValueToCaller (F->getReturnType (), Result);
882     return;
883   }
884
885   // Get pointers to first LLVM BB & Instruction in function.
886   StackFrame.CurBB     = F->begin();
887   StackFrame.CurInst   = StackFrame.CurBB->begin();
888
889   // Run through the function arguments and initialize their values...
890   assert((ArgVals.size() == F->asize() ||
891          (ArgVals.size() > F->asize() && F->getFunctionType()->isVarArg())) &&
892          "Invalid number of values passed to function invocation!");
893
894   // Handle non-varargs arguments...
895   unsigned i = 0;
896   for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI, ++i)
897     SetValue(AI, ArgVals[i], StackFrame);
898
899   // Handle varargs arguments...
900   StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
901 }
902
903 void Interpreter::run() {
904   while (!ECStack.empty()) {
905     // Interpret a single instruction & increment the "PC".
906     ExecutionContext &SF = ECStack.back();  // Current stack frame
907     Instruction &I = *SF.CurInst++;         // Increment before execute
908     
909     // Track the number of dynamic instructions executed.
910     ++NumDynamicInsts;
911
912     visit(I);   // Dispatch to one of the visit* methods...
913   }
914 }
915
916 } // End llvm namespace