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