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