Split the PHINode class out from the iOther.h file into the iPHINode.h file
[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/iPHINode.h"
10 #include "llvm/iOther.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/Type.h"
14 #include "llvm/ConstPoolVals.h"
15 #include "llvm/Assembly/Writer.h"
16 #include "llvm/Target/TargetData.h"
17 #include "llvm/GlobalVariable.h"
18 #include <math.h>  // For fmod
19 #include <signal.h>
20 #include <setjmp.h>
21
22 // Create a TargetData structure to handle memory addressing and size/alignment
23 // computations
24 //
25 static TargetData TD("lli Interpreter");
26 CachedWriter CW;     // Object to accelerate printing of LLVM
27
28
29 #ifdef PROFILE_STRUCTURE_FIELDS
30 #include "Support/CommandLine.h"
31 static cl::Flag ProfileStructureFields("profilestructfields", 
32                                        "Profile Structure Field Accesses");
33 #include <map>
34 static map<const StructType *, vector<unsigned> > FieldAccessCounts;
35 #endif
36
37 sigjmp_buf SignalRecoverBuffer;
38 static bool InInstruction = false;
39
40 extern "C" {
41 static void SigHandler(int Signal) {
42   if (InInstruction)
43     siglongjmp(SignalRecoverBuffer, Signal);
44 }
45 }
46
47 static void initializeSignalHandlers() {
48   struct sigaction Action;
49   Action.sa_handler = SigHandler;
50   Action.sa_flags   = SA_SIGINFO;
51   sigemptyset(&Action.sa_mask);
52   sigaction(SIGSEGV, &Action, 0);
53   sigaction(SIGBUS, &Action, 0);
54   sigaction(SIGINT, &Action, 0);
55   sigaction(SIGFPE, &Action, 0);
56 }
57
58
59 //===----------------------------------------------------------------------===//
60 //                     Value Manipulation code
61 //===----------------------------------------------------------------------===//
62
63 static unsigned getOperandSlot(Value *V) {
64   SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
65   assert(SN && "Operand does not have a slot number annotation!");
66   return SN->SlotNum;
67 }
68
69 #define GET_CONST_VAL(TY, CLASS) \
70   case Type::TY##TyID: Result.TY##Val = cast<CLASS>(CPV)->getValue(); break
71
72 static GenericValue getOperandValue(Value *V, ExecutionContext &SF) {
73   if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(V)) {
74     GenericValue Result;
75     switch (CPV->getType()->getPrimitiveID()) {
76       GET_CONST_VAL(Bool   , ConstPoolBool);
77       GET_CONST_VAL(UByte  , ConstPoolUInt);
78       GET_CONST_VAL(SByte  , ConstPoolSInt);
79       GET_CONST_VAL(UShort , ConstPoolUInt);
80       GET_CONST_VAL(Short  , ConstPoolSInt);
81       GET_CONST_VAL(UInt   , ConstPoolUInt);
82       GET_CONST_VAL(Int    , ConstPoolSInt);
83       GET_CONST_VAL(ULong  , ConstPoolUInt);
84       GET_CONST_VAL(Long   , ConstPoolSInt);
85       GET_CONST_VAL(Float  , ConstPoolFP);
86       GET_CONST_VAL(Double , ConstPoolFP);
87     case Type::PointerTyID:
88       if (isa<ConstPoolPointerNull>(CPV)) {
89         Result.PointerVal = 0;
90       } else if (ConstPoolPointerRef *CPR =dyn_cast<ConstPoolPointerRef>(CPV)) {
91         assert(0 && "Not implemented!");
92       } else {
93         assert(0 && "Unknown constant pointer type!");
94       }
95       break;
96     default:
97       cout << "ERROR: Constant unimp for type: " << CPV->getType() << endl;
98     }
99     return Result;
100   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
101     GlobalAddress *Address = 
102       (GlobalAddress*)GV->getOrCreateAnnotation(GlobalAddressAID);
103     GenericValue Result;
104     Result.PointerVal = (PointerTy)(GenericValue*)Address->Ptr;
105     return Result;
106   } else {
107     unsigned TyP = V->getType()->getUniqueID();   // TypePlane for value
108     unsigned OpSlot = getOperandSlot(V);
109     assert(TyP < SF.Values.size() && 
110            OpSlot < SF.Values[TyP].size() && "Value out of range!");
111     return SF.Values[TyP][getOperandSlot(V)];
112   }
113 }
114
115 static void printOperandInfo(Value *V, ExecutionContext &SF) {
116   if (isa<ConstPoolVal>(V)) {
117     cout << "Constant Pool Value\n";
118   } else if (isa<GlobalValue>(V)) {
119     cout << "Global Value\n";
120   } else {
121     unsigned TyP  = V->getType()->getUniqueID();   // TypePlane for value
122     unsigned Slot = getOperandSlot(V);
123     cout << "Value=" << (void*)V << " TypeID=" << TyP << " Slot=" << Slot
124          << " Addr=" << &SF.Values[TyP][Slot] << " SF=" << &SF
125          << " Contents=0x";
126
127     const unsigned char *Buf = (const unsigned char*)&SF.Values[TyP][Slot];
128     for (unsigned i = 0; i < sizeof(GenericValue); ++i) {
129       unsigned char Cur = Buf[i];
130       cout << ( Cur     >= 160? char((Cur>>4)+'A'-10) : char((Cur>>4) + '0'))
131            << ((Cur&15) >=  10? char((Cur&15)+'A'-10) : char((Cur&15) + '0'));
132     }
133     cout << endl;
134   }
135 }
136
137
138
139 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
140   unsigned TyP = V->getType()->getUniqueID();   // TypePlane for value
141
142   //cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)] << endl;
143   SF.Values[TyP][getOperandSlot(V)] = Val;
144 }
145
146
147 //===----------------------------------------------------------------------===//
148 //                    Annotation Wrangling code
149 //===----------------------------------------------------------------------===//
150
151 void Interpreter::initializeExecutionEngine() {
152   AnnotationManager::registerAnnotationFactory(MethodInfoAID,
153                                                &MethodInfo::Create);
154   AnnotationManager::registerAnnotationFactory(GlobalAddressAID, 
155                                                &GlobalAddress::Create);
156   initializeSignalHandlers();
157 }
158
159 // InitializeMemory - Recursive function to apply a ConstPool value into the
160 // specified memory location...
161 //
162 static void InitializeMemory(ConstPoolVal *Init, char *Addr) {
163 #define INITIALIZE_MEMORY(TYID, CLASS, TY)  \
164   case Type::TYID##TyID: {                  \
165     TY Tmp = cast<CLASS>(Init)->getValue(); \
166     memcpy(Addr, &Tmp, sizeof(TY));         \
167   } return
168
169   switch (Init->getType()->getPrimitiveID()) {
170     INITIALIZE_MEMORY(Bool   , ConstPoolBool, bool);
171     INITIALIZE_MEMORY(UByte  , ConstPoolUInt, unsigned char);
172     INITIALIZE_MEMORY(SByte  , ConstPoolSInt, signed   char);
173     INITIALIZE_MEMORY(UShort , ConstPoolUInt, unsigned short);
174     INITIALIZE_MEMORY(Short  , ConstPoolSInt, signed   short);
175     INITIALIZE_MEMORY(UInt   , ConstPoolUInt, unsigned int);
176     INITIALIZE_MEMORY(Int    , ConstPoolSInt, signed   int);
177     INITIALIZE_MEMORY(ULong  , ConstPoolUInt, uint64_t);
178     INITIALIZE_MEMORY(Long   , ConstPoolSInt,  int64_t);
179     INITIALIZE_MEMORY(Float  , ConstPoolFP  , float);
180     INITIALIZE_MEMORY(Double , ConstPoolFP  , double);
181 #undef INITIALIZE_MEMORY
182
183   case Type::ArrayTyID: {
184     ConstPoolArray *CPA = cast<ConstPoolArray>(Init);
185     const vector<Use> &Val = CPA->getValues();
186     unsigned ElementSize = 
187       TD.getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
188     for (unsigned i = 0; i < Val.size(); ++i)
189       InitializeMemory(cast<ConstPoolVal>(Val[i].get()), Addr+i*ElementSize);
190     return;
191   }
192
193   case Type::StructTyID: {
194     ConstPoolStruct *CPS = cast<ConstPoolStruct>(Init);
195     const StructLayout *SL=TD.getStructLayout(cast<StructType>(CPS->getType()));
196     const vector<Use> &Val = CPS->getValues();
197     for (unsigned i = 0; i < Val.size(); ++i)
198       InitializeMemory(cast<ConstPoolVal>(Val[i].get()),
199                        Addr+SL->MemberOffsets[i]);
200     return;
201   }
202
203   case Type::PointerTyID:
204     if (isa<ConstPoolPointerNull>(Init)) {
205       *(void**)Addr = 0;
206     } else if (ConstPoolPointerRef *CPR = dyn_cast<ConstPoolPointerRef>(Init)) {
207       GlobalAddress *Address = 
208        (GlobalAddress*)CPR->getValue()->getOrCreateAnnotation(GlobalAddressAID);
209       *(void**)Addr = (GenericValue*)Address->Ptr;
210     } else {
211       assert(0 && "Unknown Constant pointer type!");
212     }
213     return;
214
215   default:
216     CW << "Bad Type: " << Init->getType() << endl;
217     assert(0 && "Unknown constant type to initialize memory with!");
218   }
219 }
220
221 Annotation *GlobalAddress::Create(AnnotationID AID, const Annotable *O, void *){
222   assert(AID == GlobalAddressAID);
223
224   // This annotation will only be created on GlobalValue objects...
225   GlobalValue *GVal = cast<GlobalValue>((Value*)O);
226
227   if (isa<Method>(GVal)) {
228     // The GlobalAddress object for a method is just a pointer to method itself.
229     // Don't delete it when the annotation is gone though!
230     return new GlobalAddress(GVal, false);
231   }
232
233   // Handle the case of a global variable...
234   assert(isa<GlobalVariable>(GVal) && 
235          "Global value found that isn't a method or global variable!");
236   GlobalVariable *GV = cast<GlobalVariable>(GVal);
237   
238   // First off, we must allocate space for the global variable to point at...
239   const Type *Ty = GV->getType()->getValueType();  // Type to be allocated
240   unsigned NumElements = 1;
241
242   if (isa<ArrayType>(Ty) && cast<ArrayType>(Ty)->isUnsized()) {
243     assert(GV->hasInitializer() && "Const val must have an initializer!");
244     // Allocating a unsized array type?
245     Ty = cast<const ArrayType>(Ty)->getElementType();  // Get the actual type...
246
247     // Get the number of elements being allocated by the array...
248     NumElements =cast<ConstPoolArray>(GV->getInitializer())->getValues().size();
249   }
250
251   // Allocate enough memory to hold the type...
252   void *Addr = calloc(NumElements, TD.getTypeSize(Ty));
253   assert(Addr != 0 && "Null pointer returned by malloc!");
254
255   // Initialize the memory if there is an initializer...
256   if (GV->hasInitializer())
257     InitializeMemory(GV->getInitializer(), (char*)Addr);
258
259   return new GlobalAddress(Addr, true);  // Simply invoke the ctor
260 }
261
262
263 //===----------------------------------------------------------------------===//
264 //                    Binary Instruction Implementations
265 //===----------------------------------------------------------------------===//
266
267 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
268    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
269
270 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2, 
271                                    const Type *Ty, ExecutionContext &SF) {
272   GenericValue Dest;
273   switch (Ty->getPrimitiveID()) {
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     IMPLEMENT_BINARY_OPERATOR(+, Float);
283     IMPLEMENT_BINARY_OPERATOR(+, Double);
284     IMPLEMENT_BINARY_OPERATOR(+, Pointer);
285   default:
286     cout << "Unhandled type for Add instruction: " << Ty << endl;
287   }
288   return Dest;
289 }
290
291 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2, 
292                                    const Type *Ty, ExecutionContext &SF) {
293   GenericValue Dest;
294   switch (Ty->getPrimitiveID()) {
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     IMPLEMENT_BINARY_OPERATOR(-, Float);
304     IMPLEMENT_BINARY_OPERATOR(-, Double);
305     IMPLEMENT_BINARY_OPERATOR(-, Pointer);
306   default:
307     cout << "Unhandled type for Sub instruction: " << Ty << endl;
308   }
309   return Dest;
310 }
311
312 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2, 
313                                    const Type *Ty, ExecutionContext &SF) {
314   GenericValue Dest;
315   switch (Ty->getPrimitiveID()) {
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     IMPLEMENT_BINARY_OPERATOR(*, Float);
325     IMPLEMENT_BINARY_OPERATOR(*, Double);
326     IMPLEMENT_BINARY_OPERATOR(*, Pointer);
327   default:
328     cout << "Unhandled type for Mul instruction: " << Ty << endl;
329   }
330   return Dest;
331 }
332
333 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2, 
334                                    const Type *Ty, ExecutionContext &SF) {
335   GenericValue Dest;
336   switch (Ty->getPrimitiveID()) {
337     IMPLEMENT_BINARY_OPERATOR(/, UByte);
338     IMPLEMENT_BINARY_OPERATOR(/, SByte);
339     IMPLEMENT_BINARY_OPERATOR(/, UShort);
340     IMPLEMENT_BINARY_OPERATOR(/, Short);
341     IMPLEMENT_BINARY_OPERATOR(/, UInt);
342     IMPLEMENT_BINARY_OPERATOR(/, Int);
343     IMPLEMENT_BINARY_OPERATOR(/, ULong);
344     IMPLEMENT_BINARY_OPERATOR(/, Long);
345     IMPLEMENT_BINARY_OPERATOR(/, Float);
346     IMPLEMENT_BINARY_OPERATOR(/, Double);
347     IMPLEMENT_BINARY_OPERATOR(/, Pointer);
348   default:
349     cout << "Unhandled type for Div instruction: " << Ty << endl;
350   }
351   return Dest;
352 }
353
354 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2, 
355                                    const Type *Ty, ExecutionContext &SF) {
356   GenericValue Dest;
357   switch (Ty->getPrimitiveID()) {
358     IMPLEMENT_BINARY_OPERATOR(%, UByte);
359     IMPLEMENT_BINARY_OPERATOR(%, SByte);
360     IMPLEMENT_BINARY_OPERATOR(%, UShort);
361     IMPLEMENT_BINARY_OPERATOR(%, Short);
362     IMPLEMENT_BINARY_OPERATOR(%, UInt);
363     IMPLEMENT_BINARY_OPERATOR(%, Int);
364     IMPLEMENT_BINARY_OPERATOR(%, ULong);
365     IMPLEMENT_BINARY_OPERATOR(%, Long);
366     IMPLEMENT_BINARY_OPERATOR(%, Pointer);
367   case Type::FloatTyID:
368     Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
369     break;
370   case Type::DoubleTyID:
371     Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
372     break;
373   default:
374     cout << "Unhandled type for Rem instruction: " << Ty << endl;
375   }
376   return Dest;
377 }
378
379 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2, 
380                                    const Type *Ty, ExecutionContext &SF) {
381   GenericValue Dest;
382   switch (Ty->getPrimitiveID()) {
383     IMPLEMENT_BINARY_OPERATOR(&, UByte);
384     IMPLEMENT_BINARY_OPERATOR(&, SByte);
385     IMPLEMENT_BINARY_OPERATOR(&, UShort);
386     IMPLEMENT_BINARY_OPERATOR(&, Short);
387     IMPLEMENT_BINARY_OPERATOR(&, UInt);
388     IMPLEMENT_BINARY_OPERATOR(&, Int);
389     IMPLEMENT_BINARY_OPERATOR(&, ULong);
390     IMPLEMENT_BINARY_OPERATOR(&, Long);
391     IMPLEMENT_BINARY_OPERATOR(&, Pointer);
392   default:
393     cout << "Unhandled type for And instruction: " << Ty << endl;
394   }
395   return Dest;
396 }
397
398
399 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2, 
400                                   const Type *Ty, ExecutionContext &SF) {
401   GenericValue Dest;
402   switch (Ty->getPrimitiveID()) {
403     IMPLEMENT_BINARY_OPERATOR(|, UByte);
404     IMPLEMENT_BINARY_OPERATOR(|, SByte);
405     IMPLEMENT_BINARY_OPERATOR(|, UShort);
406     IMPLEMENT_BINARY_OPERATOR(|, Short);
407     IMPLEMENT_BINARY_OPERATOR(|, UInt);
408     IMPLEMENT_BINARY_OPERATOR(|, Int);
409     IMPLEMENT_BINARY_OPERATOR(|, ULong);
410     IMPLEMENT_BINARY_OPERATOR(|, Long);
411     IMPLEMENT_BINARY_OPERATOR(|, Pointer);
412   default:
413     cout << "Unhandled type for Or instruction: " << Ty << endl;
414   }
415   return Dest;
416 }
417
418
419 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2, 
420                                    const Type *Ty, ExecutionContext &SF) {
421   GenericValue Dest;
422   switch (Ty->getPrimitiveID()) {
423     IMPLEMENT_BINARY_OPERATOR(^, UByte);
424     IMPLEMENT_BINARY_OPERATOR(^, SByte);
425     IMPLEMENT_BINARY_OPERATOR(^, UShort);
426     IMPLEMENT_BINARY_OPERATOR(^, Short);
427     IMPLEMENT_BINARY_OPERATOR(^, UInt);
428     IMPLEMENT_BINARY_OPERATOR(^, Int);
429     IMPLEMENT_BINARY_OPERATOR(^, ULong);
430     IMPLEMENT_BINARY_OPERATOR(^, Long);
431     IMPLEMENT_BINARY_OPERATOR(^, Pointer);
432   default:
433     cout << "Unhandled type for Xor instruction: " << Ty << endl;
434   }
435   return Dest;
436 }
437
438
439 #define IMPLEMENT_SETCC(OP, TY) \
440    case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
441
442 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2, 
443                                      const Type *Ty, ExecutionContext &SF) {
444   GenericValue Dest;
445   switch (Ty->getPrimitiveID()) {
446     IMPLEMENT_SETCC(==, UByte);
447     IMPLEMENT_SETCC(==, SByte);
448     IMPLEMENT_SETCC(==, UShort);
449     IMPLEMENT_SETCC(==, Short);
450     IMPLEMENT_SETCC(==, UInt);
451     IMPLEMENT_SETCC(==, Int);
452     IMPLEMENT_SETCC(==, ULong);
453     IMPLEMENT_SETCC(==, Long);
454     IMPLEMENT_SETCC(==, Float);
455     IMPLEMENT_SETCC(==, Double);
456     IMPLEMENT_SETCC(==, Pointer);
457   default:
458     cout << "Unhandled type for SetEQ instruction: " << Ty << endl;
459   }
460   return Dest;
461 }
462
463 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2, 
464                                      const Type *Ty, ExecutionContext &SF) {
465   GenericValue Dest;
466   switch (Ty->getPrimitiveID()) {
467     IMPLEMENT_SETCC(!=, UByte);
468     IMPLEMENT_SETCC(!=, SByte);
469     IMPLEMENT_SETCC(!=, UShort);
470     IMPLEMENT_SETCC(!=, Short);
471     IMPLEMENT_SETCC(!=, UInt);
472     IMPLEMENT_SETCC(!=, Int);
473     IMPLEMENT_SETCC(!=, ULong);
474     IMPLEMENT_SETCC(!=, Long);
475     IMPLEMENT_SETCC(!=, Float);
476     IMPLEMENT_SETCC(!=, Double);
477     IMPLEMENT_SETCC(!=, Pointer);
478
479   default:
480     cout << "Unhandled type for SetNE instruction: " << Ty << endl;
481   }
482   return Dest;
483 }
484
485 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2, 
486                                      const Type *Ty, ExecutionContext &SF) {
487   GenericValue Dest;
488   switch (Ty->getPrimitiveID()) {
489     IMPLEMENT_SETCC(<=, UByte);
490     IMPLEMENT_SETCC(<=, SByte);
491     IMPLEMENT_SETCC(<=, UShort);
492     IMPLEMENT_SETCC(<=, Short);
493     IMPLEMENT_SETCC(<=, UInt);
494     IMPLEMENT_SETCC(<=, Int);
495     IMPLEMENT_SETCC(<=, ULong);
496     IMPLEMENT_SETCC(<=, Long);
497     IMPLEMENT_SETCC(<=, Float);
498     IMPLEMENT_SETCC(<=, Double);
499     IMPLEMENT_SETCC(<=, Pointer);
500   default:
501     cout << "Unhandled type for SetLE instruction: " << Ty << endl;
502   }
503   return Dest;
504 }
505
506 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2, 
507                                      const Type *Ty, ExecutionContext &SF) {
508   GenericValue Dest;
509   switch (Ty->getPrimitiveID()) {
510     IMPLEMENT_SETCC(>=, UByte);
511     IMPLEMENT_SETCC(>=, SByte);
512     IMPLEMENT_SETCC(>=, UShort);
513     IMPLEMENT_SETCC(>=, Short);
514     IMPLEMENT_SETCC(>=, UInt);
515     IMPLEMENT_SETCC(>=, Int);
516     IMPLEMENT_SETCC(>=, ULong);
517     IMPLEMENT_SETCC(>=, Long);
518     IMPLEMENT_SETCC(>=, Float);
519     IMPLEMENT_SETCC(>=, Double);
520     IMPLEMENT_SETCC(>=, Pointer);
521   default:
522     cout << "Unhandled type for SetGE instruction: " << Ty << endl;
523   }
524   return Dest;
525 }
526
527 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2, 
528                                      const Type *Ty, ExecutionContext &SF) {
529   GenericValue Dest;
530   switch (Ty->getPrimitiveID()) {
531     IMPLEMENT_SETCC(<, UByte);
532     IMPLEMENT_SETCC(<, SByte);
533     IMPLEMENT_SETCC(<, UShort);
534     IMPLEMENT_SETCC(<, Short);
535     IMPLEMENT_SETCC(<, UInt);
536     IMPLEMENT_SETCC(<, Int);
537     IMPLEMENT_SETCC(<, ULong);
538     IMPLEMENT_SETCC(<, Long);
539     IMPLEMENT_SETCC(<, Float);
540     IMPLEMENT_SETCC(<, Double);
541     IMPLEMENT_SETCC(<, Pointer);
542   default:
543     cout << "Unhandled type for SetLT instruction: " << Ty << endl;
544   }
545   return Dest;
546 }
547
548 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2, 
549                                      const Type *Ty, ExecutionContext &SF) {
550   GenericValue Dest;
551   switch (Ty->getPrimitiveID()) {
552     IMPLEMENT_SETCC(>, UByte);
553     IMPLEMENT_SETCC(>, SByte);
554     IMPLEMENT_SETCC(>, UShort);
555     IMPLEMENT_SETCC(>, Short);
556     IMPLEMENT_SETCC(>, UInt);
557     IMPLEMENT_SETCC(>, Int);
558     IMPLEMENT_SETCC(>, ULong);
559     IMPLEMENT_SETCC(>, Long);
560     IMPLEMENT_SETCC(>, Float);
561     IMPLEMENT_SETCC(>, Double);
562     IMPLEMENT_SETCC(>, Pointer);
563   default:
564     cout << "Unhandled type for SetGT instruction: " << Ty << endl;
565   }
566   return Dest;
567 }
568
569 static void executeBinaryInst(BinaryOperator *I, ExecutionContext &SF) {
570   const Type *Ty = I->getOperand(0)->getType();
571   GenericValue Src1  = getOperandValue(I->getOperand(0), SF);
572   GenericValue Src2  = getOperandValue(I->getOperand(1), SF);
573   GenericValue R;   // Result
574
575   switch (I->getOpcode()) {
576   case Instruction::Add:   R = executeAddInst  (Src1, Src2, Ty, SF); break;
577   case Instruction::Sub:   R = executeSubInst  (Src1, Src2, Ty, SF); break;
578   case Instruction::Mul:   R = executeMulInst  (Src1, Src2, Ty, SF); break;
579   case Instruction::Div:   R = executeDivInst  (Src1, Src2, Ty, SF); break;
580   case Instruction::Rem:   R = executeRemInst  (Src1, Src2, Ty, SF); break;
581   case Instruction::And:   R = executeAndInst  (Src1, Src2, Ty, SF); break;
582   case Instruction::Or:    R = executeOrInst   (Src1, Src2, Ty, SF); break;
583   case Instruction::Xor:   R = executeXorInst  (Src1, Src2, Ty, SF); break;
584   case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty, SF); break;
585   case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty, SF); break;
586   case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty, SF); break;
587   case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty, SF); break;
588   case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty, SF); break;
589   case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty, SF); break;
590   default:
591     cout << "Don't know how to handle this binary operator!\n-->" << I;
592     R = Src1;
593   }
594
595   SetValue(I, R, SF);
596 }
597
598 //===----------------------------------------------------------------------===//
599 //                     Terminator Instruction Implementations
600 //===----------------------------------------------------------------------===//
601
602 static void PerformExitStuff() {
603 #ifdef PROFILE_STRUCTURE_FIELDS
604   // Print out structure field accounting information...
605   if (!FieldAccessCounts.empty()) {
606     CW << "Profile Field Access Counts:\n";
607     map<const StructType *, vector<unsigned> >::iterator 
608       I = FieldAccessCounts.begin(), E = FieldAccessCounts.end();
609     for (; I != E; ++I) {
610       vector<unsigned> &OfC = I->second;
611       CW << "  '" << (Value*)I->first << "'\t- Sum=";
612       
613       unsigned Sum = 0;
614       for (unsigned i = 0; i < OfC.size(); ++i)
615         Sum += OfC[i];
616       CW << Sum << " - ";
617       
618       for (unsigned i = 0; i < OfC.size(); ++i) {
619         if (i) CW << ", ";
620         CW << OfC[i];
621       }
622       CW << endl;
623     }
624     CW << endl;
625
626     CW << "Profile Field Access Percentages:\n";
627     cout.precision(3);
628     for (I = FieldAccessCounts.begin(); I != E; ++I) {
629       vector<unsigned> &OfC = I->second;
630       unsigned Sum = 0;
631       for (unsigned i = 0; i < OfC.size(); ++i)
632         Sum += OfC[i];
633       
634       CW << "  '" << (Value*)I->first << "'\t- ";
635       for (unsigned i = 0; i < OfC.size(); ++i) {
636         if (i) CW << ", ";
637         CW << double(OfC[i])/Sum;
638       }
639       CW << endl;
640     }
641     CW << endl;
642
643     FieldAccessCounts.clear();
644   }
645 #endif
646 }
647
648 void Interpreter::exitCalled(GenericValue GV) {
649   cout << "Program returned ";
650   print(Type::IntTy, GV);
651   cout << " via 'void exit(int)'\n";
652
653   ExitCode = GV.SByteVal;
654   ECStack.clear();
655   PerformExitStuff();
656 }
657
658 void Interpreter::executeRetInst(ReturnInst *I, ExecutionContext &SF) {
659   const Type *RetTy = 0;
660   GenericValue Result;
661
662   // Save away the return value... (if we are not 'ret void')
663   if (I->getNumOperands()) {
664     RetTy  = I->getReturnValue()->getType();
665     Result = getOperandValue(I->getReturnValue(), SF);
666   }
667
668   // Save previously executing meth
669   const Method *M = ECStack.back().CurMethod;
670
671   // Pop the current stack frame... this invalidates SF
672   ECStack.pop_back();
673
674   if (ECStack.empty()) {  // Finished main.  Put result into exit code...
675     if (RetTy) {          // Nonvoid return type?
676       CW << "Method " << M->getType() << " \"" << M->getName()
677          << "\" returned ";
678       print(RetTy, Result);
679       cout << endl;
680
681       if (RetTy->isIntegral())
682         ExitCode = Result.SByteVal;   // Capture the exit code of the program
683     } else {
684       ExitCode = 0;
685     }
686
687     PerformExitStuff();
688     return;
689   }
690
691   // If we have a previous stack frame, and we have a previous call, fill in
692   // the return value...
693   //
694   ExecutionContext &NewSF = ECStack.back();
695   if (NewSF.Caller) {
696     if (NewSF.Caller->getType() != Type::VoidTy)             // Save result...
697       SetValue(NewSF.Caller, Result, NewSF);
698
699     NewSF.Caller = 0;          // We returned from the call...
700   } else {
701     // This must be a function that is executing because of a user 'call'
702     // instruction.
703     CW << "Method " << M->getType() << " \"" << M->getName()
704        << "\" returned ";
705     print(RetTy, Result);
706     cout << endl;
707   }
708 }
709
710 void Interpreter::executeBrInst(BranchInst *I, ExecutionContext &SF) {
711   SF.PrevBB = SF.CurBB;               // Update PrevBB so that PHI nodes work...
712   BasicBlock *Dest;
713
714   Dest = I->getSuccessor(0);          // Uncond branches have a fixed dest...
715   if (!I->isUnconditional()) {
716     Value *Cond = I->getCondition();
717     GenericValue CondVal = getOperandValue(Cond, SF);
718     if (CondVal.BoolVal == 0) // If false cond...
719       Dest = I->getSuccessor(1);    
720   }
721   SF.CurBB   = Dest;                  // Update CurBB to branch destination
722   SF.CurInst = SF.CurBB->begin();     // Update new instruction ptr...
723 }
724
725 //===----------------------------------------------------------------------===//
726 //                     Memory Instruction Implementations
727 //===----------------------------------------------------------------------===//
728
729 void Interpreter::executeAllocInst(AllocationInst *I, ExecutionContext &SF) {
730   const Type *Ty = I->getType()->getValueType();  // Type to be allocated
731   unsigned NumElements = 1;
732
733   if (I->getNumOperands()) {   // Allocating a unsized array type?
734     assert(isa<ArrayType>(Ty) && cast<const ArrayType>(Ty)->isUnsized() && 
735            "Allocation inst with size operand for !unsized array type???");
736     Ty = cast<const ArrayType>(Ty)->getElementType();  // Get the actual type...
737
738     // Get the number of elements being allocated by the array...
739     GenericValue NumEl = getOperandValue(I->getOperand(0), SF);
740     NumElements = NumEl.UIntVal;
741   }
742
743   // Allocate enough memory to hold the type...
744   GenericValue Result;
745   // FIXME: Don't use CALLOC, use a tainted malloc.
746   Result.PointerVal = (PointerTy)calloc(NumElements, TD.getTypeSize(Ty));
747   assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
748   SetValue(I, Result, SF);
749
750   if (I->getOpcode() == Instruction::Alloca) {
751     // TODO: FIXME: alloca should keep track of memory to free it later...
752   }
753 }
754
755 static void executeFreeInst(FreeInst *I, ExecutionContext &SF) {
756   assert(I->getOperand(0)->getType()->isPointerType() && "Freeing nonptr?");
757   GenericValue Value = getOperandValue(I->getOperand(0), SF);
758   // TODO: Check to make sure memory is allocated
759   free((void*)Value.PointerVal);   // Free memory
760 }
761
762
763 // getElementOffset - The workhorse for getelementptr, load and store.  This 
764 // function returns the offset that arguments ArgOff+1 -> NumArgs specify for
765 // the pointer type specified by argument Arg.
766 //
767 static PointerTy getElementOffset(MemAccessInst *I, ExecutionContext &SF) {
768   assert(isa<PointerType>(I->getPointerOperand()->getType()) &&
769          "Cannot getElementOffset of a nonpointer type!");
770
771   PointerTy Total = 0;
772   const Type *Ty =
773     cast<PointerType>(I->getPointerOperand()->getType())->getValueType();
774   
775   unsigned ArgOff = I->getFirstIndexOperandNumber();
776   while (ArgOff < I->getNumOperands()) {
777     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
778       const StructLayout *SLO = TD.getStructLayout(STy);
779       
780       // Indicies must be ubyte constants...
781       const ConstPoolUInt *CPU = cast<ConstPoolUInt>(I->getOperand(ArgOff++));
782       assert(CPU->getType() == Type::UByteTy);
783       unsigned Index = CPU->getValue();
784       
785 #ifdef PROFILE_STRUCTURE_FIELDS
786       if (ProfileStructureFields) {
787         // Do accounting for this field...
788         vector<unsigned> &OfC = FieldAccessCounts[STy];
789         if (OfC.size() == 0) OfC.resize(STy->getElementTypes().size());
790         OfC[Index]++;
791       }
792 #endif
793       
794       Total += SLO->MemberOffsets[Index];
795       Ty = STy->getElementTypes()[Index];
796     } else {
797       const ArrayType *AT = cast<ArrayType>(Ty);
798
799       // Get the index number for the array... which must be uint type...
800       assert(I->getOperand(ArgOff)->getType() == Type::UIntTy);
801       unsigned Idx = getOperandValue(I->getOperand(ArgOff++), SF).UIntVal;
802       if (AT->isSized() && Idx >= (unsigned)AT->getNumElements()) {
803         cerr << "Out of range memory access to element #" << Idx
804              << " of a " << AT->getNumElements() << " element array."
805              << " Subscript #" << (ArgOff-I->getFirstIndexOperandNumber())
806              << "\n";
807         // Get outta here!!!
808         siglongjmp(SignalRecoverBuffer, -1);
809       }
810
811       Ty = AT->getElementType();
812       unsigned Size = TD.getTypeSize(Ty);
813       Total += Size*Idx;
814     }  
815   }
816
817   return Total;
818 }
819
820 static void executeGEPInst(GetElementPtrInst *I, ExecutionContext &SF) {
821   GenericValue SRC = getOperandValue(I->getPointerOperand(), SF);
822   PointerTy SrcPtr = SRC.PointerVal;
823
824   GenericValue Result;
825   Result.PointerVal = SrcPtr + getElementOffset(I, SF);
826   SetValue(I, Result, SF);
827 }
828
829 static void executeLoadInst(LoadInst *I, ExecutionContext &SF) {
830   GenericValue SRC = getOperandValue(I->getPointerOperand(), SF);
831   PointerTy SrcPtr = SRC.PointerVal;
832   PointerTy Offset = getElementOffset(I, SF);  // Handle any structure indices
833   SrcPtr += Offset;
834
835   GenericValue *Ptr = (GenericValue*)SrcPtr;
836   GenericValue Result;
837
838   switch (I->getType()->getPrimitiveID()) {
839   case Type::BoolTyID:
840   case Type::UByteTyID:
841   case Type::SByteTyID:   Result.SByteVal   = Ptr->SByteVal; break;
842   case Type::UShortTyID:
843   case Type::ShortTyID:   Result.ShortVal   = Ptr->ShortVal; break;
844   case Type::UIntTyID:
845   case Type::IntTyID:     Result.IntVal     = Ptr->IntVal; break;
846   case Type::ULongTyID:
847   case Type::LongTyID:    Result.ULongVal   = Ptr->ULongVal; break;
848   case Type::PointerTyID: Result.PointerVal = Ptr->PointerVal; break;
849   case Type::FloatTyID:   Result.FloatVal   = Ptr->FloatVal; break;
850   case Type::DoubleTyID:  Result.DoubleVal  = Ptr->DoubleVal; break;
851   default:
852     cout << "Cannot load value of type " << I->getType() << "!\n";
853   }
854
855   SetValue(I, Result, SF);
856 }
857
858 static void executeStoreInst(StoreInst *I, ExecutionContext &SF) {
859   GenericValue SRC = getOperandValue(I->getPointerOperand(), SF);
860   PointerTy SrcPtr = SRC.PointerVal;
861   SrcPtr += getElementOffset(I, SF);  // Handle any structure indices
862
863   GenericValue *Ptr = (GenericValue *)SrcPtr;
864   GenericValue Val = getOperandValue(I->getOperand(0), SF);
865
866   switch (I->getOperand(0)->getType()->getPrimitiveID()) {
867   case Type::BoolTyID:
868   case Type::UByteTyID:
869   case Type::SByteTyID:   Ptr->SByteVal = Val.SByteVal; break;
870   case Type::UShortTyID:
871   case Type::ShortTyID:   Ptr->ShortVal = Val.ShortVal; break;
872   case Type::UIntTyID:
873   case Type::IntTyID:     Ptr->IntVal = Val.IntVal; break;
874   case Type::ULongTyID:
875   case Type::LongTyID:    Ptr->LongVal = Val.LongVal; break;
876   case Type::PointerTyID: Ptr->PointerVal = Val.PointerVal; break;
877   case Type::FloatTyID:   Ptr->FloatVal = Val.FloatVal; break;
878   case Type::DoubleTyID:  Ptr->DoubleVal = Val.DoubleVal; break;
879   default:
880     cout << "Cannot store value of type " << I->getType() << "!\n";
881   }
882 }
883
884
885 //===----------------------------------------------------------------------===//
886 //                 Miscellaneous Instruction Implementations
887 //===----------------------------------------------------------------------===//
888
889 void Interpreter::executeCallInst(CallInst *I, ExecutionContext &SF) {
890   ECStack.back().Caller = I;
891   vector<GenericValue> ArgVals;
892   ArgVals.reserve(I->getNumOperands()-1);
893   for (unsigned i = 1; i < I->getNumOperands(); ++i)
894     ArgVals.push_back(getOperandValue(I->getOperand(i), SF));
895
896   // To handle indirect calls, we must get the pointer value from the argument 
897   // and treat it as a method pointer.
898   GenericValue SRC = getOperandValue(I->getCalledValue(), SF);
899   
900   callMethod((Method*)SRC.PointerVal, ArgVals);
901 }
902
903 static void executePHINode(PHINode *I, ExecutionContext &SF) {
904   BasicBlock *PrevBB = SF.PrevBB;
905   Value *IncomingValue = 0;
906
907   // Search for the value corresponding to this previous bb...
908   for (unsigned i = I->getNumIncomingValues(); i > 0;) {
909     if (I->getIncomingBlock(--i) == PrevBB) {
910       IncomingValue = I->getIncomingValue(i);
911       break;
912     }
913   }
914   assert(IncomingValue && "No PHI node predecessor for current PrevBB!");
915
916   // Found the value, set as the result...
917   SetValue(I, getOperandValue(IncomingValue, SF), SF);
918 }
919
920 #define IMPLEMENT_SHIFT(OP, TY) \
921    case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
922
923 static void executeShlInst(ShiftInst *I, ExecutionContext &SF) {
924   const Type *Ty = I->getOperand(0)->getType();
925   GenericValue Src1  = getOperandValue(I->getOperand(0), SF);
926   GenericValue Src2  = getOperandValue(I->getOperand(1), SF);
927   GenericValue Dest;
928
929   switch (Ty->getPrimitiveID()) {
930     IMPLEMENT_SHIFT(<<, UByte);
931     IMPLEMENT_SHIFT(<<, SByte);
932     IMPLEMENT_SHIFT(<<, UShort);
933     IMPLEMENT_SHIFT(<<, Short);
934     IMPLEMENT_SHIFT(<<, UInt);
935     IMPLEMENT_SHIFT(<<, Int);
936     IMPLEMENT_SHIFT(<<, ULong);
937     IMPLEMENT_SHIFT(<<, Long);
938   default:
939     cout << "Unhandled type for Shl instruction: " << Ty << endl;
940   }
941   SetValue(I, Dest, SF);
942 }
943
944 static void executeShrInst(ShiftInst *I, ExecutionContext &SF) {
945   const Type *Ty = I->getOperand(0)->getType();
946   GenericValue Src1  = getOperandValue(I->getOperand(0), SF);
947   GenericValue Src2  = getOperandValue(I->getOperand(1), SF);
948   GenericValue Dest;
949
950   switch (Ty->getPrimitiveID()) {
951     IMPLEMENT_SHIFT(>>, UByte);
952     IMPLEMENT_SHIFT(>>, SByte);
953     IMPLEMENT_SHIFT(>>, UShort);
954     IMPLEMENT_SHIFT(>>, Short);
955     IMPLEMENT_SHIFT(>>, UInt);
956     IMPLEMENT_SHIFT(>>, Int);
957     IMPLEMENT_SHIFT(>>, ULong);
958     IMPLEMENT_SHIFT(>>, Long);
959   default:
960     cout << "Unhandled type for Shr instruction: " << Ty << endl;
961   }
962   SetValue(I, Dest, SF);
963 }
964
965 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
966    case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
967
968 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY)    \
969   case Type::DESTTY##TyID:                      \
970     switch (SrcTy->getPrimitiveID()) {          \
971       IMPLEMENT_CAST(DESTTY, DESTCTY, UByte);   \
972       IMPLEMENT_CAST(DESTTY, DESTCTY, SByte);   \
973       IMPLEMENT_CAST(DESTTY, DESTCTY, UShort);  \
974       IMPLEMENT_CAST(DESTTY, DESTCTY, Short);   \
975       IMPLEMENT_CAST(DESTTY, DESTCTY, UInt);    \
976       IMPLEMENT_CAST(DESTTY, DESTCTY, Int);     \
977       IMPLEMENT_CAST(DESTTY, DESTCTY, ULong);   \
978       IMPLEMENT_CAST(DESTTY, DESTCTY, Long);    \
979       IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
980
981 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
982       IMPLEMENT_CAST(DESTTY, DESTCTY, Float);   \
983       IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
984
985 #define IMPLEMENT_CAST_CASE_END()    \
986     default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << endl;  \
987       break;                                    \
988     }                                           \
989     break
990
991 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
992    IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY);   \
993    IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
994    IMPLEMENT_CAST_CASE_END()
995
996 static void executeCastInst(CastInst *I, ExecutionContext &SF) {
997   const Type *Ty = I->getType();
998   const Type *SrcTy = I->getOperand(0)->getType();
999   GenericValue Src  = getOperandValue(I->getOperand(0), SF);
1000   GenericValue Dest;
1001
1002   switch (Ty->getPrimitiveID()) {
1003     IMPLEMENT_CAST_CASE(UByte  , (unsigned char));
1004     IMPLEMENT_CAST_CASE(SByte  , (  signed char));
1005     IMPLEMENT_CAST_CASE(UShort , (unsigned short));
1006     IMPLEMENT_CAST_CASE(Short  , (  signed char));
1007     IMPLEMENT_CAST_CASE(UInt   , (unsigned int ));
1008     IMPLEMENT_CAST_CASE(Int    , (  signed int ));
1009     IMPLEMENT_CAST_CASE(ULong  , (uint64_t));
1010     IMPLEMENT_CAST_CASE(Long   , ( int64_t));
1011     IMPLEMENT_CAST_CASE(Pointer, (PointerTy)(uint32_t));
1012     IMPLEMENT_CAST_CASE(Float  , (float));
1013     IMPLEMENT_CAST_CASE(Double , (double));
1014   default:
1015     cout << "Unhandled dest type for cast instruction: " << Ty << endl;
1016   }
1017   SetValue(I, Dest, SF);
1018 }
1019
1020
1021
1022
1023 //===----------------------------------------------------------------------===//
1024 //                        Dispatch and Execution Code
1025 //===----------------------------------------------------------------------===//
1026
1027 MethodInfo::MethodInfo(Method *M) : Annotation(MethodInfoAID) {
1028   // Assign slot numbers to the method arguments...
1029   const Method::ArgumentListType &ArgList = M->getArgumentList();
1030   for (Method::ArgumentListType::const_iterator AI = ArgList.begin(), 
1031          AE = ArgList.end(); AI != AE; ++AI) {
1032     MethodArgument *MA = *AI;
1033     MA->addAnnotation(new SlotNumber(getValueSlot(MA)));
1034   }
1035
1036   // Iterate over all of the instructions...
1037   unsigned InstNum = 0;
1038   for (Method::inst_iterator MI = M->inst_begin(), ME = M->inst_end();
1039        MI != ME; ++MI) {
1040     Instruction *I = *MI;                          // For each instruction...
1041     I->addAnnotation(new InstNumber(++InstNum, getValueSlot(I))); // Add Annote
1042   }
1043 }
1044
1045 unsigned MethodInfo::getValueSlot(const Value *V) {
1046   unsigned Plane = V->getType()->getUniqueID();
1047   if (Plane >= NumPlaneElements.size())
1048     NumPlaneElements.resize(Plane+1, 0);
1049   return NumPlaneElements[Plane]++;
1050 }
1051
1052
1053 //===----------------------------------------------------------------------===//
1054 // callMethod - Execute the specified method...
1055 //
1056 void Interpreter::callMethod(Method *M, const vector<GenericValue> &ArgVals) {
1057   assert((ECStack.empty() || ECStack.back().Caller == 0 || 
1058           ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
1059          "Incorrect number of arguments passed into function call!");
1060   if (M->isExternal()) {
1061     GenericValue Result = callExternalMethod(M, ArgVals);
1062     const Type *RetTy = M->getReturnType();
1063
1064     // Copy the result back into the result variable if we are not returning
1065     // void.
1066     if (RetTy != Type::VoidTy) {
1067       if (!ECStack.empty() && ECStack.back().Caller) {
1068         ExecutionContext &SF = ECStack.back();
1069         CallInst *Caller = SF.Caller;
1070         SetValue(SF.Caller, Result, SF);
1071       
1072         SF.Caller = 0;          // We returned from the call...
1073       } else {
1074         // print it.
1075         CW << "Method " << M->getType() << " \"" << M->getName()
1076            << "\" returned ";
1077         print(RetTy, Result); 
1078         cout << endl;
1079         
1080         if (RetTy->isIntegral())
1081           ExitCode = Result.SByteVal;   // Capture the exit code of the program
1082       }
1083     }
1084
1085     return;
1086   }
1087
1088   // Process the method, assigning instruction numbers to the instructions in
1089   // the method.  Also calculate the number of values for each type slot active.
1090   //
1091   MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
1092   ECStack.push_back(ExecutionContext());         // Make a new stack frame...
1093
1094   ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
1095   StackFrame.CurMethod = M;
1096   StackFrame.CurBB     = M->front();
1097   StackFrame.CurInst   = StackFrame.CurBB->begin();
1098   StackFrame.MethInfo  = MethInfo;
1099
1100   // Initialize the values to nothing...
1101   StackFrame.Values.resize(MethInfo->NumPlaneElements.size());
1102   for (unsigned i = 0; i < MethInfo->NumPlaneElements.size(); ++i) {
1103     StackFrame.Values[i].resize(MethInfo->NumPlaneElements[i]);
1104
1105     // Taint the initial values of stuff
1106     memset(&StackFrame.Values[i][0], 42,
1107            MethInfo->NumPlaneElements[i]*sizeof(GenericValue));
1108   }
1109
1110   StackFrame.PrevBB = 0;  // No previous BB for PHI nodes...
1111
1112
1113   // Run through the method arguments and initialize their values...
1114   assert(ArgVals.size() == M->getArgumentList().size() &&
1115          "Invalid number of values passed to method invocation!");
1116   unsigned i = 0;
1117   for (Method::ArgumentListType::iterator MI = M->getArgumentList().begin(),
1118          ME = M->getArgumentList().end(); MI != ME; ++MI, ++i) {
1119     SetValue(*MI, ArgVals[i], StackFrame);
1120   }
1121 }
1122
1123 // executeInstruction - Interpret a single instruction, increment the "PC", and
1124 // return true if the next instruction is a breakpoint...
1125 //
1126 bool Interpreter::executeInstruction() {
1127   assert(!ECStack.empty() && "No program running, cannot execute inst!");
1128
1129   ExecutionContext &SF = ECStack.back();  // Current stack frame
1130   Instruction *I = *SF.CurInst++;         // Increment before execute
1131
1132   if (Trace)
1133     CW << "Run:" << I;
1134
1135   // Set a sigsetjmp buffer so that we can recover if an error happens during
1136   // instruction execution...
1137   //
1138   if (int SigNo = sigsetjmp(SignalRecoverBuffer, 1)) {
1139     --SF.CurInst;   // Back up to erroring instruction
1140     if (SigNo != SIGINT && SigNo != -1) {
1141       cout << "EXCEPTION OCCURRED [" << _sys_siglistp[SigNo] << "]:\n";
1142       printStackTrace();
1143     } else if (SigNo == SIGINT) {
1144       cout << "CTRL-C Detected, execution halted.\n";
1145     }
1146     InInstruction = false;
1147     return true;
1148   }
1149
1150   InInstruction = true;
1151   if (I->isBinaryOp()) {
1152     executeBinaryInst(cast<BinaryOperator>(I), SF);
1153   } else {
1154     switch (I->getOpcode()) {
1155       // Terminators
1156     case Instruction::Ret:     executeRetInst  (cast<ReturnInst>(I), SF); break;
1157     case Instruction::Br:      executeBrInst   (cast<BranchInst>(I), SF); break;
1158       // Memory Instructions
1159     case Instruction::Alloca:
1160     case Instruction::Malloc:  executeAllocInst((AllocationInst*)I, SF); break;
1161     case Instruction::Free:    executeFreeInst (cast<FreeInst> (I), SF); break;
1162     case Instruction::Load:    executeLoadInst (cast<LoadInst> (I), SF); break;
1163     case Instruction::Store:   executeStoreInst(cast<StoreInst>(I), SF); break;
1164     case Instruction::GetElementPtr:
1165                           executeGEPInst(cast<GetElementPtrInst>(I), SF); break;
1166
1167       // Miscellaneous Instructions
1168     case Instruction::Call:    executeCallInst (cast<CallInst> (I), SF); break;
1169     case Instruction::PHINode: executePHINode  (cast<PHINode>  (I), SF); break;
1170     case Instruction::Shl:     executeShlInst  (cast<ShiftInst>(I), SF); break;
1171     case Instruction::Shr:     executeShrInst  (cast<ShiftInst>(I), SF); break;
1172     case Instruction::Cast:    executeCastInst (cast<CastInst> (I), SF); break;
1173     default:
1174       cout << "Don't know how to execute this instruction!\n-->" << I;
1175     }
1176   }
1177   InInstruction = false;
1178   
1179   // Reset the current frame location to the top of stack
1180   CurFrame = ECStack.size()-1;
1181
1182   if (CurFrame == -1) return false;  // No breakpoint if no code
1183
1184   // Return true if there is a breakpoint annotation on the instruction...
1185   return (*ECStack[CurFrame].CurInst)->getAnnotation(BreakpointAID) != 0;
1186 }
1187
1188 void Interpreter::stepInstruction() {  // Do the 'step' command
1189   if (ECStack.empty()) {
1190     cout << "Error: no program running, cannot step!\n";
1191     return;
1192   }
1193
1194   // Run an instruction...
1195   executeInstruction();
1196
1197   // Print the next instruction to execute...
1198   printCurrentInstruction();
1199 }
1200
1201 // --- UI Stuff...
1202 void Interpreter::nextInstruction() {  // Do the 'next' command
1203   if (ECStack.empty()) {
1204     cout << "Error: no program running, cannot 'next'!\n";
1205     return;
1206   }
1207
1208   // If this is a call instruction, step over the call instruction...
1209   // TODO: ICALL, CALL WITH, ...
1210   if ((*ECStack.back().CurInst)->getOpcode() == Instruction::Call) {
1211     unsigned StackSize = ECStack.size();
1212     // Step into the function...
1213     if (executeInstruction()) {
1214       // Hit a breakpoint, print current instruction, then return to user...
1215       cout << "Breakpoint hit!\n";
1216       printCurrentInstruction();
1217       return;
1218     }
1219
1220     // If we we able to step into the function, finish it now.  We might not be
1221     // able the step into a function, if it's external for example.
1222     if (ECStack.size() != StackSize)
1223       finish(); // Finish executing the function...
1224     else
1225       printCurrentInstruction();
1226
1227   } else {
1228     // Normal instruction, just step...
1229     stepInstruction();
1230   }
1231 }
1232
1233 void Interpreter::run() {
1234   if (ECStack.empty()) {
1235     cout << "Error: no program running, cannot run!\n";
1236     return;
1237   }
1238
1239   bool HitBreakpoint = false;
1240   while (!ECStack.empty() && !HitBreakpoint) {
1241     // Run an instruction...
1242     HitBreakpoint = executeInstruction();
1243   }
1244
1245   if (HitBreakpoint) {
1246     cout << "Breakpoint hit!\n";
1247   }
1248   // Print the next instruction to execute...
1249   printCurrentInstruction();
1250 }
1251
1252 void Interpreter::finish() {
1253   if (ECStack.empty()) {
1254     cout << "Error: no program running, cannot run!\n";
1255     return;
1256   }
1257
1258   unsigned StackSize = ECStack.size();
1259   bool HitBreakpoint = false;
1260   while (ECStack.size() >= StackSize && !HitBreakpoint) {
1261     // Run an instruction...
1262     HitBreakpoint = executeInstruction();
1263   }
1264
1265   if (HitBreakpoint) {
1266     cout << "Breakpoint hit!\n";
1267   }
1268
1269   // Print the next instruction to execute...
1270   printCurrentInstruction();
1271 }
1272
1273
1274
1275 // printCurrentInstruction - Print out the instruction that the virtual PC is
1276 // at, or fail silently if no program is running.
1277 //
1278 void Interpreter::printCurrentInstruction() {
1279   if (!ECStack.empty()) {
1280     if (ECStack.back().CurBB->begin() == ECStack.back().CurInst)  // print label
1281       WriteAsOperand(cout, ECStack.back().CurBB) << ":\n";
1282
1283     Instruction *I = *ECStack.back().CurInst;
1284     InstNumber *IN = (InstNumber*)I->getAnnotation(SlotNumberAID);
1285     assert(IN && "Instruction has no numbering annotation!");
1286     cout << "#" << IN->InstNum << I;
1287   }
1288 }
1289
1290 void Interpreter::printValue(const Type *Ty, GenericValue V) {
1291   switch (Ty->getPrimitiveID()) {
1292   case Type::BoolTyID:   cout << (V.BoolVal?"true":"false"); break;
1293   case Type::SByteTyID:  cout << V.SByteVal;  break;
1294   case Type::UByteTyID:  cout << V.UByteVal;  break;
1295   case Type::ShortTyID:  cout << V.ShortVal;  break;
1296   case Type::UShortTyID: cout << V.UShortVal; break;
1297   case Type::IntTyID:    cout << V.IntVal;    break;
1298   case Type::UIntTyID:   cout << V.UIntVal;   break;
1299   case Type::LongTyID:   cout << V.LongVal;   break;
1300   case Type::ULongTyID:  cout << V.ULongVal;  break;
1301   case Type::FloatTyID:  cout << V.FloatVal;  break;
1302   case Type::DoubleTyID: cout << V.DoubleVal; break;
1303   case Type::PointerTyID:cout << (void*)V.PointerVal; break;
1304   default:
1305     cout << "- Don't know how to print value of this type!";
1306     break;
1307   }
1308 }
1309
1310 void Interpreter::print(const Type *Ty, GenericValue V) {
1311   CW << Ty << " ";
1312   printValue(Ty, V);
1313 }
1314
1315 void Interpreter::print(const string &Name) {
1316   Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1317   if (!PickedVal) return;
1318
1319   if (const Method *M = dyn_cast<const Method>(PickedVal)) {
1320     CW << M;  // Print the method
1321   } else if (const Type *Ty = dyn_cast<const Type>(PickedVal)) {
1322     CW << "type %" << Name << " = " << Ty->getDescription() << endl;
1323   } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(PickedVal)) {
1324     CW << BB;   // Print the basic block
1325   } else {      // Otherwise there should be an annotation for the slot#
1326     print(PickedVal->getType(), 
1327           getOperandValue(PickedVal, ECStack[CurFrame]));
1328     cout << endl;
1329   }
1330 }
1331
1332 void Interpreter::infoValue(const string &Name) {
1333   Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1334   if (!PickedVal) return;
1335
1336   cout << "Value: ";
1337   print(PickedVal->getType(), 
1338         getOperandValue(PickedVal, ECStack[CurFrame]));
1339   cout << endl;
1340   printOperandInfo(PickedVal, ECStack[CurFrame]);
1341 }
1342
1343 // printStackFrame - Print information about the specified stack frame, or -1
1344 // for the default one.
1345 //
1346 void Interpreter::printStackFrame(int FrameNo = -1) {
1347   if (FrameNo == -1) FrameNo = CurFrame;
1348   Method *Meth = ECStack[FrameNo].CurMethod;
1349   const Type *RetTy = Meth->getReturnType();
1350
1351   CW << ((FrameNo == CurFrame) ? '>' : '-') << "#" << FrameNo << ". "
1352      << (Value*)RetTy << " \"" << Meth->getName() << "\"(";
1353   
1354   Method::ArgumentListType &Args = Meth->getArgumentList();
1355   for (unsigned i = 0; i < Args.size(); ++i) {
1356     if (i != 0) cout << ", ";
1357     CW << (Value*)Args[i] << "=";
1358     
1359     printValue(Args[i]->getType(), getOperandValue(Args[i], ECStack[FrameNo]));
1360   }
1361
1362   cout << ")" << endl;
1363   CW << *(ECStack[FrameNo].CurInst-(FrameNo != int(ECStack.size()-1)));
1364 }
1365