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