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