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