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