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