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