1 //===-- Execution.cpp - Implement code to simulate the program ------------===//
3 // This file contains the actual instruction interpreter.
5 //===----------------------------------------------------------------------===//
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 <math.h> // For fmod
23 // Create a TargetData structure to handle memory addressing and size/alignment
26 static TargetData TD("lli Interpreter");
27 CachedWriter CW; // Object to accelerate printing of LLVM
30 #ifdef PROFILE_STRUCTURE_FIELDS
31 #include "Support/CommandLine.h"
32 static cl::Flag ProfileStructureFields("profilestructfields",
33 "Profile Structure Field Accesses");
35 static map<const StructType *, vector<unsigned> > FieldAccessCounts;
38 sigjmp_buf SignalRecoverBuffer;
39 static bool InInstruction = false;
42 static void SigHandler(int Signal) {
44 siglongjmp(SignalRecoverBuffer, Signal);
48 static void initializeSignalHandlers() {
49 struct sigaction Action;
50 Action.sa_handler = SigHandler;
51 Action.sa_flags = SA_SIGINFO;
52 sigemptyset(&Action.sa_mask);
53 sigaction(SIGSEGV, &Action, 0);
54 sigaction(SIGBUS, &Action, 0);
55 sigaction(SIGINT, &Action, 0);
56 sigaction(SIGFPE, &Action, 0);
60 //===----------------------------------------------------------------------===//
61 // Value Manipulation code
62 //===----------------------------------------------------------------------===//
64 static unsigned getOperandSlot(Value *V) {
65 SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
66 assert(SN && "Operand does not have a slot number annotation!");
70 #define GET_CONST_VAL(TY, CLASS) \
71 case Type::TY##TyID: Result.TY##Val = cast<CLASS>(CPV)->getValue(); break
73 static GenericValue getOperandValue(Value *V, ExecutionContext &SF) {
74 if (Constant *CPV = dyn_cast<Constant>(V)) {
76 switch (CPV->getType()->getPrimitiveID()) {
77 GET_CONST_VAL(Bool , ConstantBool);
78 GET_CONST_VAL(UByte , ConstantUInt);
79 GET_CONST_VAL(SByte , ConstantSInt);
80 GET_CONST_VAL(UShort , ConstantUInt);
81 GET_CONST_VAL(Short , ConstantSInt);
82 GET_CONST_VAL(UInt , ConstantUInt);
83 GET_CONST_VAL(Int , ConstantSInt);
84 GET_CONST_VAL(ULong , ConstantUInt);
85 GET_CONST_VAL(Long , ConstantSInt);
86 GET_CONST_VAL(Float , ConstantFP);
87 GET_CONST_VAL(Double , ConstantFP);
88 case Type::PointerTyID:
89 if (isa<ConstantPointerNull>(CPV)) {
90 Result.PointerVal = 0;
91 } else if (ConstantPointerRef *CPR =dyn_cast<ConstantPointerRef>(CPV)) {
92 assert(0 && "Not implemented!");
94 assert(0 && "Unknown constant pointer type!");
98 cout << "ERROR: Constant unimp for type: " << CPV->getType() << endl;
101 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
102 GlobalAddress *Address =
103 (GlobalAddress*)GV->getOrCreateAnnotation(GlobalAddressAID);
105 Result.PointerVal = (PointerTy)(GenericValue*)Address->Ptr;
108 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
109 unsigned OpSlot = getOperandSlot(V);
110 assert(TyP < SF.Values.size() &&
111 OpSlot < SF.Values[TyP].size() && "Value out of range!");
112 return SF.Values[TyP][getOperandSlot(V)];
116 static void printOperandInfo(Value *V, ExecutionContext &SF) {
117 if (isa<Constant>(V)) {
118 cout << "Constant Pool Value\n";
119 } else if (isa<GlobalValue>(V)) {
120 cout << "Global Value\n";
122 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
123 unsigned Slot = getOperandSlot(V);
124 cout << "Value=" << (void*)V << " TypeID=" << TyP << " Slot=" << Slot
125 << " Addr=" << &SF.Values[TyP][Slot] << " SF=" << &SF
128 const unsigned char *Buf = (const unsigned char*)&SF.Values[TyP][Slot];
129 for (unsigned i = 0; i < sizeof(GenericValue); ++i) {
130 unsigned char Cur = Buf[i];
131 cout << ( Cur >= 160? char((Cur>>4)+'A'-10) : char((Cur>>4) + '0'))
132 << ((Cur&15) >= 10? char((Cur&15)+'A'-10) : char((Cur&15) + '0'));
140 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
141 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
143 //cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)] << endl;
144 SF.Values[TyP][getOperandSlot(V)] = Val;
148 //===----------------------------------------------------------------------===//
149 // Annotation Wrangling code
150 //===----------------------------------------------------------------------===//
152 void Interpreter::initializeExecutionEngine() {
153 AnnotationManager::registerAnnotationFactory(MethodInfoAID,
154 &MethodInfo::Create);
155 AnnotationManager::registerAnnotationFactory(GlobalAddressAID,
156 &GlobalAddress::Create);
157 initializeSignalHandlers();
160 // InitializeMemory - Recursive function to apply a Constant value into the
161 // specified memory location...
163 static void InitializeMemory(Constant *Init, char *Addr) {
164 #define INITIALIZE_MEMORY(TYID, CLASS, TY) \
165 case Type::TYID##TyID: { \
166 TY Tmp = cast<CLASS>(Init)->getValue(); \
167 memcpy(Addr, &Tmp, sizeof(TY)); \
170 switch (Init->getType()->getPrimitiveID()) {
171 INITIALIZE_MEMORY(Bool , ConstantBool, bool);
172 INITIALIZE_MEMORY(UByte , ConstantUInt, unsigned char);
173 INITIALIZE_MEMORY(SByte , ConstantSInt, signed char);
174 INITIALIZE_MEMORY(UShort , ConstantUInt, unsigned short);
175 INITIALIZE_MEMORY(Short , ConstantSInt, signed short);
176 INITIALIZE_MEMORY(UInt , ConstantUInt, unsigned int);
177 INITIALIZE_MEMORY(Int , ConstantSInt, signed int);
178 INITIALIZE_MEMORY(ULong , ConstantUInt, uint64_t);
179 INITIALIZE_MEMORY(Long , ConstantSInt, int64_t);
180 INITIALIZE_MEMORY(Float , ConstantFP , float);
181 INITIALIZE_MEMORY(Double , ConstantFP , double);
182 #undef INITIALIZE_MEMORY
184 case Type::ArrayTyID: {
185 ConstantArray *CPA = cast<ConstantArray>(Init);
186 const vector<Use> &Val = CPA->getValues();
187 unsigned ElementSize =
188 TD.getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
189 for (unsigned i = 0; i < Val.size(); ++i)
190 InitializeMemory(cast<Constant>(Val[i].get()), Addr+i*ElementSize);
194 case Type::StructTyID: {
195 ConstantStruct *CPS = cast<ConstantStruct>(Init);
196 const StructLayout *SL=TD.getStructLayout(cast<StructType>(CPS->getType()));
197 const vector<Use> &Val = CPS->getValues();
198 for (unsigned i = 0; i < Val.size(); ++i)
199 InitializeMemory(cast<Constant>(Val[i].get()),
200 Addr+SL->MemberOffsets[i]);
204 case Type::PointerTyID:
205 if (isa<ConstantPointerNull>(Init)) {
207 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Init)) {
208 GlobalAddress *Address =
209 (GlobalAddress*)CPR->getValue()->getOrCreateAnnotation(GlobalAddressAID);
210 *(void**)Addr = (GenericValue*)Address->Ptr;
212 assert(0 && "Unknown Constant pointer type!");
217 CW << "Bad Type: " << Init->getType() << endl;
218 assert(0 && "Unknown constant type to initialize memory with!");
222 Annotation *GlobalAddress::Create(AnnotationID AID, const Annotable *O, void *){
223 assert(AID == GlobalAddressAID);
225 // This annotation will only be created on GlobalValue objects...
226 GlobalValue *GVal = cast<GlobalValue>((Value*)O);
228 if (isa<Method>(GVal)) {
229 // The GlobalAddress object for a method is just a pointer to method itself.
230 // Don't delete it when the annotation is gone though!
231 return new GlobalAddress(GVal, false);
234 // Handle the case of a global variable...
235 assert(isa<GlobalVariable>(GVal) &&
236 "Global value found that isn't a method or global variable!");
237 GlobalVariable *GV = cast<GlobalVariable>(GVal);
239 // First off, we must allocate space for the global variable to point at...
240 const Type *Ty = GV->getType()->getValueType(); // Type to be allocated
241 unsigned NumElements = 1;
243 if (isa<ArrayType>(Ty) && cast<ArrayType>(Ty)->isUnsized()) {
244 assert(GV->hasInitializer() && "Const val must have an initializer!");
245 // Allocating a unsized array type?
246 Ty = cast<const ArrayType>(Ty)->getElementType(); // Get the actual type...
248 // Get the number of elements being allocated by the array...
249 NumElements =cast<ConstantArray>(GV->getInitializer())->getValues().size();
252 // Allocate enough memory to hold the type...
253 void *Addr = calloc(NumElements, TD.getTypeSize(Ty));
254 assert(Addr != 0 && "Null pointer returned by malloc!");
256 // Initialize the memory if there is an initializer...
257 if (GV->hasInitializer())
258 InitializeMemory(GV->getInitializer(), (char*)Addr);
260 return new GlobalAddress(Addr, true); // Simply invoke the ctor
264 //===----------------------------------------------------------------------===//
265 // Binary Instruction Implementations
266 //===----------------------------------------------------------------------===//
268 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
269 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
271 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
272 const Type *Ty, ExecutionContext &SF) {
274 switch (Ty->getPrimitiveID()) {
275 IMPLEMENT_BINARY_OPERATOR(+, UByte);
276 IMPLEMENT_BINARY_OPERATOR(+, SByte);
277 IMPLEMENT_BINARY_OPERATOR(+, UShort);
278 IMPLEMENT_BINARY_OPERATOR(+, Short);
279 IMPLEMENT_BINARY_OPERATOR(+, UInt);
280 IMPLEMENT_BINARY_OPERATOR(+, Int);
281 IMPLEMENT_BINARY_OPERATOR(+, ULong);
282 IMPLEMENT_BINARY_OPERATOR(+, Long);
283 IMPLEMENT_BINARY_OPERATOR(+, Float);
284 IMPLEMENT_BINARY_OPERATOR(+, Double);
285 IMPLEMENT_BINARY_OPERATOR(+, Pointer);
287 cout << "Unhandled type for Add instruction: " << Ty << endl;
292 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
293 const Type *Ty, ExecutionContext &SF) {
295 switch (Ty->getPrimitiveID()) {
296 IMPLEMENT_BINARY_OPERATOR(-, UByte);
297 IMPLEMENT_BINARY_OPERATOR(-, SByte);
298 IMPLEMENT_BINARY_OPERATOR(-, UShort);
299 IMPLEMENT_BINARY_OPERATOR(-, Short);
300 IMPLEMENT_BINARY_OPERATOR(-, UInt);
301 IMPLEMENT_BINARY_OPERATOR(-, Int);
302 IMPLEMENT_BINARY_OPERATOR(-, ULong);
303 IMPLEMENT_BINARY_OPERATOR(-, Long);
304 IMPLEMENT_BINARY_OPERATOR(-, Float);
305 IMPLEMENT_BINARY_OPERATOR(-, Double);
306 IMPLEMENT_BINARY_OPERATOR(-, Pointer);
308 cout << "Unhandled type for Sub instruction: " << Ty << endl;
313 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
314 const Type *Ty, ExecutionContext &SF) {
316 switch (Ty->getPrimitiveID()) {
317 IMPLEMENT_BINARY_OPERATOR(*, UByte);
318 IMPLEMENT_BINARY_OPERATOR(*, SByte);
319 IMPLEMENT_BINARY_OPERATOR(*, UShort);
320 IMPLEMENT_BINARY_OPERATOR(*, Short);
321 IMPLEMENT_BINARY_OPERATOR(*, UInt);
322 IMPLEMENT_BINARY_OPERATOR(*, Int);
323 IMPLEMENT_BINARY_OPERATOR(*, ULong);
324 IMPLEMENT_BINARY_OPERATOR(*, Long);
325 IMPLEMENT_BINARY_OPERATOR(*, Float);
326 IMPLEMENT_BINARY_OPERATOR(*, Double);
327 IMPLEMENT_BINARY_OPERATOR(*, Pointer);
329 cout << "Unhandled type for Mul instruction: " << Ty << endl;
334 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2,
335 const Type *Ty, ExecutionContext &SF) {
337 switch (Ty->getPrimitiveID()) {
338 IMPLEMENT_BINARY_OPERATOR(/, UByte);
339 IMPLEMENT_BINARY_OPERATOR(/, SByte);
340 IMPLEMENT_BINARY_OPERATOR(/, UShort);
341 IMPLEMENT_BINARY_OPERATOR(/, Short);
342 IMPLEMENT_BINARY_OPERATOR(/, UInt);
343 IMPLEMENT_BINARY_OPERATOR(/, Int);
344 IMPLEMENT_BINARY_OPERATOR(/, ULong);
345 IMPLEMENT_BINARY_OPERATOR(/, Long);
346 IMPLEMENT_BINARY_OPERATOR(/, Float);
347 IMPLEMENT_BINARY_OPERATOR(/, Double);
348 IMPLEMENT_BINARY_OPERATOR(/, Pointer);
350 cout << "Unhandled type for Div instruction: " << Ty << endl;
355 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2,
356 const Type *Ty, ExecutionContext &SF) {
358 switch (Ty->getPrimitiveID()) {
359 IMPLEMENT_BINARY_OPERATOR(%, UByte);
360 IMPLEMENT_BINARY_OPERATOR(%, SByte);
361 IMPLEMENT_BINARY_OPERATOR(%, UShort);
362 IMPLEMENT_BINARY_OPERATOR(%, Short);
363 IMPLEMENT_BINARY_OPERATOR(%, UInt);
364 IMPLEMENT_BINARY_OPERATOR(%, Int);
365 IMPLEMENT_BINARY_OPERATOR(%, ULong);
366 IMPLEMENT_BINARY_OPERATOR(%, Long);
367 IMPLEMENT_BINARY_OPERATOR(%, Pointer);
368 case Type::FloatTyID:
369 Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
371 case Type::DoubleTyID:
372 Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
375 cout << "Unhandled type for Rem instruction: " << Ty << endl;
380 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
381 const Type *Ty, ExecutionContext &SF) {
383 switch (Ty->getPrimitiveID()) {
384 IMPLEMENT_BINARY_OPERATOR(&, UByte);
385 IMPLEMENT_BINARY_OPERATOR(&, SByte);
386 IMPLEMENT_BINARY_OPERATOR(&, UShort);
387 IMPLEMENT_BINARY_OPERATOR(&, Short);
388 IMPLEMENT_BINARY_OPERATOR(&, UInt);
389 IMPLEMENT_BINARY_OPERATOR(&, Int);
390 IMPLEMENT_BINARY_OPERATOR(&, ULong);
391 IMPLEMENT_BINARY_OPERATOR(&, Long);
392 IMPLEMENT_BINARY_OPERATOR(&, Pointer);
394 cout << "Unhandled type for And instruction: " << Ty << endl;
400 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
401 const Type *Ty, ExecutionContext &SF) {
403 switch (Ty->getPrimitiveID()) {
404 IMPLEMENT_BINARY_OPERATOR(|, UByte);
405 IMPLEMENT_BINARY_OPERATOR(|, SByte);
406 IMPLEMENT_BINARY_OPERATOR(|, UShort);
407 IMPLEMENT_BINARY_OPERATOR(|, Short);
408 IMPLEMENT_BINARY_OPERATOR(|, UInt);
409 IMPLEMENT_BINARY_OPERATOR(|, Int);
410 IMPLEMENT_BINARY_OPERATOR(|, ULong);
411 IMPLEMENT_BINARY_OPERATOR(|, Long);
412 IMPLEMENT_BINARY_OPERATOR(|, Pointer);
414 cout << "Unhandled type for Or instruction: " << Ty << endl;
420 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
421 const Type *Ty, ExecutionContext &SF) {
423 switch (Ty->getPrimitiveID()) {
424 IMPLEMENT_BINARY_OPERATOR(^, UByte);
425 IMPLEMENT_BINARY_OPERATOR(^, SByte);
426 IMPLEMENT_BINARY_OPERATOR(^, UShort);
427 IMPLEMENT_BINARY_OPERATOR(^, Short);
428 IMPLEMENT_BINARY_OPERATOR(^, UInt);
429 IMPLEMENT_BINARY_OPERATOR(^, Int);
430 IMPLEMENT_BINARY_OPERATOR(^, ULong);
431 IMPLEMENT_BINARY_OPERATOR(^, Long);
432 IMPLEMENT_BINARY_OPERATOR(^, Pointer);
434 cout << "Unhandled type for Xor instruction: " << Ty << endl;
440 #define IMPLEMENT_SETCC(OP, TY) \
441 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
443 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
444 const Type *Ty, ExecutionContext &SF) {
446 switch (Ty->getPrimitiveID()) {
447 IMPLEMENT_SETCC(==, UByte);
448 IMPLEMENT_SETCC(==, SByte);
449 IMPLEMENT_SETCC(==, UShort);
450 IMPLEMENT_SETCC(==, Short);
451 IMPLEMENT_SETCC(==, UInt);
452 IMPLEMENT_SETCC(==, Int);
453 IMPLEMENT_SETCC(==, ULong);
454 IMPLEMENT_SETCC(==, Long);
455 IMPLEMENT_SETCC(==, Float);
456 IMPLEMENT_SETCC(==, Double);
457 IMPLEMENT_SETCC(==, Pointer);
459 cout << "Unhandled type for SetEQ instruction: " << Ty << endl;
464 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
465 const Type *Ty, ExecutionContext &SF) {
467 switch (Ty->getPrimitiveID()) {
468 IMPLEMENT_SETCC(!=, UByte);
469 IMPLEMENT_SETCC(!=, SByte);
470 IMPLEMENT_SETCC(!=, UShort);
471 IMPLEMENT_SETCC(!=, Short);
472 IMPLEMENT_SETCC(!=, UInt);
473 IMPLEMENT_SETCC(!=, Int);
474 IMPLEMENT_SETCC(!=, ULong);
475 IMPLEMENT_SETCC(!=, Long);
476 IMPLEMENT_SETCC(!=, Float);
477 IMPLEMENT_SETCC(!=, Double);
478 IMPLEMENT_SETCC(!=, Pointer);
481 cout << "Unhandled type for SetNE instruction: " << Ty << endl;
486 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
487 const Type *Ty, ExecutionContext &SF) {
489 switch (Ty->getPrimitiveID()) {
490 IMPLEMENT_SETCC(<=, UByte);
491 IMPLEMENT_SETCC(<=, SByte);
492 IMPLEMENT_SETCC(<=, UShort);
493 IMPLEMENT_SETCC(<=, Short);
494 IMPLEMENT_SETCC(<=, UInt);
495 IMPLEMENT_SETCC(<=, Int);
496 IMPLEMENT_SETCC(<=, ULong);
497 IMPLEMENT_SETCC(<=, Long);
498 IMPLEMENT_SETCC(<=, Float);
499 IMPLEMENT_SETCC(<=, Double);
500 IMPLEMENT_SETCC(<=, Pointer);
502 cout << "Unhandled type for SetLE instruction: " << Ty << endl;
507 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
508 const Type *Ty, ExecutionContext &SF) {
510 switch (Ty->getPrimitiveID()) {
511 IMPLEMENT_SETCC(>=, UByte);
512 IMPLEMENT_SETCC(>=, SByte);
513 IMPLEMENT_SETCC(>=, UShort);
514 IMPLEMENT_SETCC(>=, Short);
515 IMPLEMENT_SETCC(>=, UInt);
516 IMPLEMENT_SETCC(>=, Int);
517 IMPLEMENT_SETCC(>=, ULong);
518 IMPLEMENT_SETCC(>=, Long);
519 IMPLEMENT_SETCC(>=, Float);
520 IMPLEMENT_SETCC(>=, Double);
521 IMPLEMENT_SETCC(>=, Pointer);
523 cout << "Unhandled type for SetGE instruction: " << Ty << endl;
528 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
529 const Type *Ty, ExecutionContext &SF) {
531 switch (Ty->getPrimitiveID()) {
532 IMPLEMENT_SETCC(<, UByte);
533 IMPLEMENT_SETCC(<, SByte);
534 IMPLEMENT_SETCC(<, UShort);
535 IMPLEMENT_SETCC(<, Short);
536 IMPLEMENT_SETCC(<, UInt);
537 IMPLEMENT_SETCC(<, Int);
538 IMPLEMENT_SETCC(<, ULong);
539 IMPLEMENT_SETCC(<, Long);
540 IMPLEMENT_SETCC(<, Float);
541 IMPLEMENT_SETCC(<, Double);
542 IMPLEMENT_SETCC(<, Pointer);
544 cout << "Unhandled type for SetLT instruction: " << Ty << endl;
549 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
550 const Type *Ty, ExecutionContext &SF) {
552 switch (Ty->getPrimitiveID()) {
553 IMPLEMENT_SETCC(>, UByte);
554 IMPLEMENT_SETCC(>, SByte);
555 IMPLEMENT_SETCC(>, UShort);
556 IMPLEMENT_SETCC(>, Short);
557 IMPLEMENT_SETCC(>, UInt);
558 IMPLEMENT_SETCC(>, Int);
559 IMPLEMENT_SETCC(>, ULong);
560 IMPLEMENT_SETCC(>, Long);
561 IMPLEMENT_SETCC(>, Float);
562 IMPLEMENT_SETCC(>, Double);
563 IMPLEMENT_SETCC(>, Pointer);
565 cout << "Unhandled type for SetGT instruction: " << Ty << endl;
570 static void executeBinaryInst(BinaryOperator *I, ExecutionContext &SF) {
571 const Type *Ty = I->getOperand(0)->getType();
572 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
573 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
574 GenericValue R; // Result
576 switch (I->getOpcode()) {
577 case Instruction::Add: R = executeAddInst (Src1, Src2, Ty, SF); break;
578 case Instruction::Sub: R = executeSubInst (Src1, Src2, Ty, SF); break;
579 case Instruction::Mul: R = executeMulInst (Src1, Src2, Ty, SF); break;
580 case Instruction::Div: R = executeDivInst (Src1, Src2, Ty, SF); break;
581 case Instruction::Rem: R = executeRemInst (Src1, Src2, Ty, SF); break;
582 case Instruction::And: R = executeAndInst (Src1, Src2, Ty, SF); break;
583 case Instruction::Or: R = executeOrInst (Src1, Src2, Ty, SF); break;
584 case Instruction::Xor: R = executeXorInst (Src1, Src2, Ty, SF); break;
585 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty, SF); break;
586 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty, SF); break;
587 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty, SF); break;
588 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty, SF); break;
589 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty, SF); break;
590 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty, SF); break;
592 cout << "Don't know how to handle this binary operator!\n-->" << I;
599 //===----------------------------------------------------------------------===//
600 // Terminator Instruction Implementations
601 //===----------------------------------------------------------------------===//
603 static void PerformExitStuff() {
604 #ifdef PROFILE_STRUCTURE_FIELDS
605 // Print out structure field accounting information...
606 if (!FieldAccessCounts.empty()) {
607 CW << "Profile Field Access Counts:\n";
608 map<const StructType *, vector<unsigned> >::iterator
609 I = FieldAccessCounts.begin(), E = FieldAccessCounts.end();
610 for (; I != E; ++I) {
611 vector<unsigned> &OfC = I->second;
612 CW << " '" << (Value*)I->first << "'\t- Sum=";
615 for (unsigned i = 0; i < OfC.size(); ++i)
619 for (unsigned i = 0; i < OfC.size(); ++i) {
627 CW << "Profile Field Access Percentages:\n";
629 for (I = FieldAccessCounts.begin(); I != E; ++I) {
630 vector<unsigned> &OfC = I->second;
632 for (unsigned i = 0; i < OfC.size(); ++i)
635 CW << " '" << (Value*)I->first << "'\t- ";
636 for (unsigned i = 0; i < OfC.size(); ++i) {
638 CW << double(OfC[i])/Sum;
644 FieldAccessCounts.clear();
649 void Interpreter::exitCalled(GenericValue GV) {
650 cout << "Program returned ";
651 print(Type::IntTy, GV);
652 cout << " via 'void exit(int)'\n";
654 ExitCode = GV.SByteVal;
659 void Interpreter::executeRetInst(ReturnInst *I, ExecutionContext &SF) {
660 const Type *RetTy = 0;
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);
669 // Save previously executing meth
670 const Method *M = ECStack.back().CurMethod;
672 // Pop the current stack frame... this invalidates SF
675 if (ECStack.empty()) { // Finished main. Put result into exit code...
676 if (RetTy) { // Nonvoid return type?
677 CW << "Method " << M->getType() << " \"" << M->getName()
679 print(RetTy, Result);
682 if (RetTy->isIntegral())
683 ExitCode = Result.SByteVal; // Capture the exit code of the program
692 // If we have a previous stack frame, and we have a previous call, fill in
693 // the return value...
695 ExecutionContext &NewSF = ECStack.back();
697 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
698 SetValue(NewSF.Caller, Result, NewSF);
700 NewSF.Caller = 0; // We returned from the call...
702 // This must be a function that is executing because of a user 'call'
704 CW << "Method " << M->getType() << " \"" << M->getName()
706 print(RetTy, Result);
711 void Interpreter::executeBrInst(BranchInst *I, ExecutionContext &SF) {
712 SF.PrevBB = SF.CurBB; // Update PrevBB so that PHI nodes work...
715 Dest = I->getSuccessor(0); // Uncond branches have a fixed dest...
716 if (!I->isUnconditional()) {
717 Value *Cond = I->getCondition();
718 GenericValue CondVal = getOperandValue(Cond, SF);
719 if (CondVal.BoolVal == 0) // If false cond...
720 Dest = I->getSuccessor(1);
722 SF.CurBB = Dest; // Update CurBB to branch destination
723 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
726 //===----------------------------------------------------------------------===//
727 // Memory Instruction Implementations
728 //===----------------------------------------------------------------------===//
730 void Interpreter::executeAllocInst(AllocationInst *I, ExecutionContext &SF) {
731 const Type *Ty = I->getType()->getValueType(); // Type to be allocated
732 unsigned NumElements = 1;
734 if (I->getNumOperands()) { // Allocating a unsized array type?
735 assert(isa<ArrayType>(Ty) && cast<const ArrayType>(Ty)->isUnsized() &&
736 "Allocation inst with size operand for !unsized array type???");
737 Ty = cast<const ArrayType>(Ty)->getElementType(); // Get the actual type...
739 // Get the number of elements being allocated by the array...
740 GenericValue NumEl = getOperandValue(I->getOperand(0), SF);
741 NumElements = NumEl.UIntVal;
744 // Allocate enough memory to hold the type...
746 // FIXME: Don't use CALLOC, use a tainted malloc.
747 Result.PointerVal = (PointerTy)calloc(NumElements, TD.getTypeSize(Ty));
748 assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
749 SetValue(I, Result, SF);
751 if (I->getOpcode() == Instruction::Alloca) {
752 // TODO: FIXME: alloca should keep track of memory to free it later...
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
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.
768 static PointerTy getElementOffset(MemAccessInst *I, ExecutionContext &SF) {
769 assert(isa<PointerType>(I->getPointerOperand()->getType()) &&
770 "Cannot getElementOffset of a nonpointer type!");
774 cast<PointerType>(I->getPointerOperand()->getType())->getValueType();
776 unsigned ArgOff = I->getFirstIndexOperandNumber();
777 while (ArgOff < I->getNumOperands()) {
778 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
779 const StructLayout *SLO = TD.getStructLayout(STy);
781 // Indicies must be ubyte constants...
782 const ConstantUInt *CPU = cast<ConstantUInt>(I->getOperand(ArgOff++));
783 assert(CPU->getType() == Type::UByteTy);
784 unsigned Index = CPU->getValue();
786 #ifdef PROFILE_STRUCTURE_FIELDS
787 if (ProfileStructureFields) {
788 // Do accounting for this field...
789 vector<unsigned> &OfC = FieldAccessCounts[STy];
790 if (OfC.size() == 0) OfC.resize(STy->getElementTypes().size());
795 Total += SLO->MemberOffsets[Index];
796 Ty = STy->getElementTypes()[Index];
798 const ArrayType *AT = cast<ArrayType>(Ty);
800 // Get the index number for the array... which must be uint type...
801 assert(I->getOperand(ArgOff)->getType() == Type::UIntTy);
802 unsigned Idx = getOperandValue(I->getOperand(ArgOff++), SF).UIntVal;
803 if (AT->isSized() && Idx >= (unsigned)AT->getNumElements()) {
804 cerr << "Out of range memory access to element #" << Idx
805 << " of a " << AT->getNumElements() << " element array."
806 << " Subscript #" << (ArgOff-I->getFirstIndexOperandNumber())
809 siglongjmp(SignalRecoverBuffer, -1);
812 Ty = AT->getElementType();
813 unsigned Size = TD.getTypeSize(Ty);
821 static void executeGEPInst(GetElementPtrInst *I, ExecutionContext &SF) {
822 GenericValue SRC = getOperandValue(I->getPointerOperand(), SF);
823 PointerTy SrcPtr = SRC.PointerVal;
826 Result.PointerVal = SrcPtr + getElementOffset(I, SF);
827 SetValue(I, Result, SF);
830 static void executeLoadInst(LoadInst *I, ExecutionContext &SF) {
831 GenericValue SRC = getOperandValue(I->getPointerOperand(), SF);
832 PointerTy SrcPtr = SRC.PointerVal;
833 PointerTy Offset = getElementOffset(I, SF); // Handle any structure indices
836 GenericValue *Ptr = (GenericValue*)SrcPtr;
839 switch (I->getType()->getPrimitiveID()) {
841 case Type::UByteTyID:
842 case Type::SByteTyID: Result.SByteVal = Ptr->SByteVal; break;
843 case Type::UShortTyID:
844 case Type::ShortTyID: Result.ShortVal = Ptr->ShortVal; break;
846 case Type::IntTyID: Result.IntVal = Ptr->IntVal; break;
847 case Type::ULongTyID:
848 case Type::LongTyID: Result.ULongVal = Ptr->ULongVal; break;
849 case Type::PointerTyID: Result.PointerVal = Ptr->PointerVal; break;
850 case Type::FloatTyID: Result.FloatVal = Ptr->FloatVal; break;
851 case Type::DoubleTyID: Result.DoubleVal = Ptr->DoubleVal; break;
853 cout << "Cannot load value of type " << I->getType() << "!\n";
856 SetValue(I, Result, SF);
859 static void executeStoreInst(StoreInst *I, ExecutionContext &SF) {
860 GenericValue SRC = getOperandValue(I->getPointerOperand(), SF);
861 PointerTy SrcPtr = SRC.PointerVal;
862 SrcPtr += getElementOffset(I, SF); // Handle any structure indices
864 GenericValue *Ptr = (GenericValue *)SrcPtr;
865 GenericValue Val = getOperandValue(I->getOperand(0), SF);
867 switch (I->getOperand(0)->getType()->getPrimitiveID()) {
869 case Type::UByteTyID:
870 case Type::SByteTyID: Ptr->SByteVal = Val.SByteVal; break;
871 case Type::UShortTyID:
872 case Type::ShortTyID: Ptr->ShortVal = Val.ShortVal; break;
874 case Type::IntTyID: Ptr->IntVal = Val.IntVal; break;
875 case Type::ULongTyID:
876 case Type::LongTyID: Ptr->LongVal = Val.LongVal; break;
877 case Type::PointerTyID: Ptr->PointerVal = Val.PointerVal; break;
878 case Type::FloatTyID: Ptr->FloatVal = Val.FloatVal; break;
879 case Type::DoubleTyID: Ptr->DoubleVal = Val.DoubleVal; break;
881 cout << "Cannot store value of type " << I->getType() << "!\n";
886 //===----------------------------------------------------------------------===//
887 // Miscellaneous Instruction Implementations
888 //===----------------------------------------------------------------------===//
890 void Interpreter::executeCallInst(CallInst *I, ExecutionContext &SF) {
891 ECStack.back().Caller = I;
892 vector<GenericValue> ArgVals;
893 ArgVals.reserve(I->getNumOperands()-1);
894 for (unsigned i = 1; i < I->getNumOperands(); ++i)
895 ArgVals.push_back(getOperandValue(I->getOperand(i), SF));
897 // To handle indirect calls, we must get the pointer value from the argument
898 // and treat it as a method pointer.
899 GenericValue SRC = getOperandValue(I->getCalledValue(), SF);
901 callMethod((Method*)SRC.PointerVal, ArgVals);
904 static void executePHINode(PHINode *I, ExecutionContext &SF) {
905 BasicBlock *PrevBB = SF.PrevBB;
906 Value *IncomingValue = 0;
908 // Search for the value corresponding to this previous bb...
909 for (unsigned i = I->getNumIncomingValues(); i > 0;) {
910 if (I->getIncomingBlock(--i) == PrevBB) {
911 IncomingValue = I->getIncomingValue(i);
915 assert(IncomingValue && "No PHI node predecessor for current PrevBB!");
917 // Found the value, set as the result...
918 SetValue(I, getOperandValue(IncomingValue, SF), SF);
921 #define IMPLEMENT_SHIFT(OP, TY) \
922 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
924 static void executeShlInst(ShiftInst *I, ExecutionContext &SF) {
925 const Type *Ty = I->getOperand(0)->getType();
926 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
927 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
930 switch (Ty->getPrimitiveID()) {
931 IMPLEMENT_SHIFT(<<, UByte);
932 IMPLEMENT_SHIFT(<<, SByte);
933 IMPLEMENT_SHIFT(<<, UShort);
934 IMPLEMENT_SHIFT(<<, Short);
935 IMPLEMENT_SHIFT(<<, UInt);
936 IMPLEMENT_SHIFT(<<, Int);
937 IMPLEMENT_SHIFT(<<, ULong);
938 IMPLEMENT_SHIFT(<<, Long);
940 cout << "Unhandled type for Shl instruction: " << Ty << endl;
942 SetValue(I, Dest, SF);
945 static void executeShrInst(ShiftInst *I, ExecutionContext &SF) {
946 const Type *Ty = I->getOperand(0)->getType();
947 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
948 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
951 switch (Ty->getPrimitiveID()) {
952 IMPLEMENT_SHIFT(>>, UByte);
953 IMPLEMENT_SHIFT(>>, SByte);
954 IMPLEMENT_SHIFT(>>, UShort);
955 IMPLEMENT_SHIFT(>>, Short);
956 IMPLEMENT_SHIFT(>>, UInt);
957 IMPLEMENT_SHIFT(>>, Int);
958 IMPLEMENT_SHIFT(>>, ULong);
959 IMPLEMENT_SHIFT(>>, Long);
961 cout << "Unhandled type for Shr instruction: " << Ty << endl;
963 SetValue(I, Dest, SF);
966 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
967 case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
969 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY) \
970 case Type::DESTTY##TyID: \
971 switch (SrcTy->getPrimitiveID()) { \
972 IMPLEMENT_CAST(DESTTY, DESTCTY, UByte); \
973 IMPLEMENT_CAST(DESTTY, DESTCTY, SByte); \
974 IMPLEMENT_CAST(DESTTY, DESTCTY, UShort); \
975 IMPLEMENT_CAST(DESTTY, DESTCTY, Short); \
976 IMPLEMENT_CAST(DESTTY, DESTCTY, UInt); \
977 IMPLEMENT_CAST(DESTTY, DESTCTY, Int); \
978 IMPLEMENT_CAST(DESTTY, DESTCTY, ULong); \
979 IMPLEMENT_CAST(DESTTY, DESTCTY, Long); \
980 IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
982 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
983 IMPLEMENT_CAST(DESTTY, DESTCTY, Float); \
984 IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
986 #define IMPLEMENT_CAST_CASE_END() \
987 default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << endl; \
992 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
993 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
994 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
995 IMPLEMENT_CAST_CASE_END()
997 static void executeCastInst(CastInst *I, ExecutionContext &SF) {
998 const Type *Ty = I->getType();
999 const Type *SrcTy = I->getOperand(0)->getType();
1000 GenericValue Src = getOperandValue(I->getOperand(0), SF);
1003 switch (Ty->getPrimitiveID()) {
1004 IMPLEMENT_CAST_CASE(UByte , (unsigned char));
1005 IMPLEMENT_CAST_CASE(SByte , ( signed char));
1006 IMPLEMENT_CAST_CASE(UShort , (unsigned short));
1007 IMPLEMENT_CAST_CASE(Short , ( signed char));
1008 IMPLEMENT_CAST_CASE(UInt , (unsigned int ));
1009 IMPLEMENT_CAST_CASE(Int , ( signed int ));
1010 IMPLEMENT_CAST_CASE(ULong , (uint64_t));
1011 IMPLEMENT_CAST_CASE(Long , ( int64_t));
1012 IMPLEMENT_CAST_CASE(Pointer, (PointerTy)(uint32_t));
1013 IMPLEMENT_CAST_CASE(Float , (float));
1014 IMPLEMENT_CAST_CASE(Double , (double));
1016 cout << "Unhandled dest type for cast instruction: " << Ty << endl;
1018 SetValue(I, Dest, SF);
1024 //===----------------------------------------------------------------------===//
1025 // Dispatch and Execution Code
1026 //===----------------------------------------------------------------------===//
1028 MethodInfo::MethodInfo(Method *M) : Annotation(MethodInfoAID) {
1029 // Assign slot numbers to the method arguments...
1030 const Method::ArgumentListType &ArgList = M->getArgumentList();
1031 for (Method::ArgumentListType::const_iterator AI = ArgList.begin(),
1032 AE = ArgList.end(); AI != AE; ++AI) {
1033 MethodArgument *MA = *AI;
1034 MA->addAnnotation(new SlotNumber(getValueSlot(MA)));
1037 // Iterate over all of the instructions...
1038 unsigned InstNum = 0;
1039 for (Method::inst_iterator MI = M->inst_begin(), ME = M->inst_end();
1041 Instruction *I = *MI; // For each instruction...
1042 I->addAnnotation(new InstNumber(++InstNum, getValueSlot(I))); // Add Annote
1046 unsigned MethodInfo::getValueSlot(const Value *V) {
1047 unsigned Plane = V->getType()->getUniqueID();
1048 if (Plane >= NumPlaneElements.size())
1049 NumPlaneElements.resize(Plane+1, 0);
1050 return NumPlaneElements[Plane]++;
1054 //===----------------------------------------------------------------------===//
1055 // callMethod - Execute the specified method...
1057 void Interpreter::callMethod(Method *M, const vector<GenericValue> &ArgVals) {
1058 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
1059 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
1060 "Incorrect number of arguments passed into function call!");
1061 if (M->isExternal()) {
1062 GenericValue Result = callExternalMethod(M, ArgVals);
1063 const Type *RetTy = M->getReturnType();
1065 // Copy the result back into the result variable if we are not returning
1067 if (RetTy != Type::VoidTy) {
1068 if (!ECStack.empty() && ECStack.back().Caller) {
1069 ExecutionContext &SF = ECStack.back();
1070 CallInst *Caller = SF.Caller;
1071 SetValue(SF.Caller, Result, SF);
1073 SF.Caller = 0; // We returned from the call...
1076 CW << "Method " << M->getType() << " \"" << M->getName()
1078 print(RetTy, Result);
1081 if (RetTy->isIntegral())
1082 ExitCode = Result.SByteVal; // Capture the exit code of the program
1089 // Process the method, assigning instruction numbers to the instructions in
1090 // the method. Also calculate the number of values for each type slot active.
1092 MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
1093 ECStack.push_back(ExecutionContext()); // Make a new stack frame...
1095 ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
1096 StackFrame.CurMethod = M;
1097 StackFrame.CurBB = M->front();
1098 StackFrame.CurInst = StackFrame.CurBB->begin();
1099 StackFrame.MethInfo = MethInfo;
1101 // Initialize the values to nothing...
1102 StackFrame.Values.resize(MethInfo->NumPlaneElements.size());
1103 for (unsigned i = 0; i < MethInfo->NumPlaneElements.size(); ++i) {
1104 StackFrame.Values[i].resize(MethInfo->NumPlaneElements[i]);
1106 // Taint the initial values of stuff
1107 memset(&StackFrame.Values[i][0], 42,
1108 MethInfo->NumPlaneElements[i]*sizeof(GenericValue));
1111 StackFrame.PrevBB = 0; // No previous BB for PHI nodes...
1114 // Run through the method arguments and initialize their values...
1115 assert(ArgVals.size() == M->getArgumentList().size() &&
1116 "Invalid number of values passed to method invocation!");
1118 for (Method::ArgumentListType::iterator MI = M->getArgumentList().begin(),
1119 ME = M->getArgumentList().end(); MI != ME; ++MI, ++i) {
1120 SetValue(*MI, ArgVals[i], StackFrame);
1124 // executeInstruction - Interpret a single instruction, increment the "PC", and
1125 // return true if the next instruction is a breakpoint...
1127 bool Interpreter::executeInstruction() {
1128 assert(!ECStack.empty() && "No program running, cannot execute inst!");
1130 ExecutionContext &SF = ECStack.back(); // Current stack frame
1131 Instruction *I = *SF.CurInst++; // Increment before execute
1136 // Set a sigsetjmp buffer so that we can recover if an error happens during
1137 // instruction execution...
1139 if (int SigNo = sigsetjmp(SignalRecoverBuffer, 1)) {
1140 --SF.CurInst; // Back up to erroring instruction
1141 if (SigNo != SIGINT && SigNo != -1) {
1142 cout << "EXCEPTION OCCURRED [" << _sys_siglistp[SigNo] << "]:\n";
1144 } else if (SigNo == SIGINT) {
1145 cout << "CTRL-C Detected, execution halted.\n";
1147 InInstruction = false;
1151 InInstruction = true;
1152 if (I->isBinaryOp()) {
1153 executeBinaryInst(cast<BinaryOperator>(I), SF);
1155 switch (I->getOpcode()) {
1157 case Instruction::Ret: executeRetInst (cast<ReturnInst>(I), SF); break;
1158 case Instruction::Br: executeBrInst (cast<BranchInst>(I), SF); break;
1159 // Memory Instructions
1160 case Instruction::Alloca:
1161 case Instruction::Malloc: executeAllocInst((AllocationInst*)I, SF); break;
1162 case Instruction::Free: executeFreeInst (cast<FreeInst> (I), SF); break;
1163 case Instruction::Load: executeLoadInst (cast<LoadInst> (I), SF); break;
1164 case Instruction::Store: executeStoreInst(cast<StoreInst>(I), SF); break;
1165 case Instruction::GetElementPtr:
1166 executeGEPInst(cast<GetElementPtrInst>(I), SF); break;
1168 // Miscellaneous Instructions
1169 case Instruction::Call: executeCallInst (cast<CallInst> (I), SF); break;
1170 case Instruction::PHINode: executePHINode (cast<PHINode> (I), SF); break;
1171 case Instruction::Shl: executeShlInst (cast<ShiftInst>(I), SF); break;
1172 case Instruction::Shr: executeShrInst (cast<ShiftInst>(I), SF); break;
1173 case Instruction::Cast: executeCastInst (cast<CastInst> (I), SF); break;
1175 cout << "Don't know how to execute this instruction!\n-->" << I;
1178 InInstruction = false;
1180 // Reset the current frame location to the top of stack
1181 CurFrame = ECStack.size()-1;
1183 if (CurFrame == -1) return false; // No breakpoint if no code
1185 // Return true if there is a breakpoint annotation on the instruction...
1186 return (*ECStack[CurFrame].CurInst)->getAnnotation(BreakpointAID) != 0;
1189 void Interpreter::stepInstruction() { // Do the 'step' command
1190 if (ECStack.empty()) {
1191 cout << "Error: no program running, cannot step!\n";
1195 // Run an instruction...
1196 executeInstruction();
1198 // Print the next instruction to execute...
1199 printCurrentInstruction();
1203 void Interpreter::nextInstruction() { // Do the 'next' command
1204 if (ECStack.empty()) {
1205 cout << "Error: no program running, cannot 'next'!\n";
1209 // If this is a call instruction, step over the call instruction...
1210 // TODO: ICALL, CALL WITH, ...
1211 if ((*ECStack.back().CurInst)->getOpcode() == Instruction::Call) {
1212 unsigned StackSize = ECStack.size();
1213 // Step into the function...
1214 if (executeInstruction()) {
1215 // Hit a breakpoint, print current instruction, then return to user...
1216 cout << "Breakpoint hit!\n";
1217 printCurrentInstruction();
1221 // If we we able to step into the function, finish it now. We might not be
1222 // able the step into a function, if it's external for example.
1223 if (ECStack.size() != StackSize)
1224 finish(); // Finish executing the function...
1226 printCurrentInstruction();
1229 // Normal instruction, just step...
1234 void Interpreter::run() {
1235 if (ECStack.empty()) {
1236 cout << "Error: no program running, cannot run!\n";
1240 bool HitBreakpoint = false;
1241 while (!ECStack.empty() && !HitBreakpoint) {
1242 // Run an instruction...
1243 HitBreakpoint = executeInstruction();
1246 if (HitBreakpoint) {
1247 cout << "Breakpoint hit!\n";
1249 // Print the next instruction to execute...
1250 printCurrentInstruction();
1253 void Interpreter::finish() {
1254 if (ECStack.empty()) {
1255 cout << "Error: no program running, cannot run!\n";
1259 unsigned StackSize = ECStack.size();
1260 bool HitBreakpoint = false;
1261 while (ECStack.size() >= StackSize && !HitBreakpoint) {
1262 // Run an instruction...
1263 HitBreakpoint = executeInstruction();
1266 if (HitBreakpoint) {
1267 cout << "Breakpoint hit!\n";
1270 // Print the next instruction to execute...
1271 printCurrentInstruction();
1276 // printCurrentInstruction - Print out the instruction that the virtual PC is
1277 // at, or fail silently if no program is running.
1279 void Interpreter::printCurrentInstruction() {
1280 if (!ECStack.empty()) {
1281 if (ECStack.back().CurBB->begin() == ECStack.back().CurInst) // print label
1282 WriteAsOperand(cout, ECStack.back().CurBB) << ":\n";
1284 Instruction *I = *ECStack.back().CurInst;
1285 InstNumber *IN = (InstNumber*)I->getAnnotation(SlotNumberAID);
1286 assert(IN && "Instruction has no numbering annotation!");
1287 cout << "#" << IN->InstNum << I;
1291 void Interpreter::printValue(const Type *Ty, GenericValue V) {
1292 switch (Ty->getPrimitiveID()) {
1293 case Type::BoolTyID: cout << (V.BoolVal?"true":"false"); break;
1294 case Type::SByteTyID: cout << V.SByteVal; break;
1295 case Type::UByteTyID: cout << V.UByteVal; break;
1296 case Type::ShortTyID: cout << V.ShortVal; break;
1297 case Type::UShortTyID: cout << V.UShortVal; break;
1298 case Type::IntTyID: cout << V.IntVal; break;
1299 case Type::UIntTyID: cout << V.UIntVal; break;
1300 case Type::LongTyID: cout << V.LongVal; break;
1301 case Type::ULongTyID: cout << V.ULongVal; break;
1302 case Type::FloatTyID: cout << V.FloatVal; break;
1303 case Type::DoubleTyID: cout << V.DoubleVal; break;
1304 case Type::PointerTyID:cout << (void*)V.PointerVal; break;
1306 cout << "- Don't know how to print value of this type!";
1311 void Interpreter::print(const Type *Ty, GenericValue V) {
1316 void Interpreter::print(const string &Name) {
1317 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1318 if (!PickedVal) return;
1320 if (const Method *M = dyn_cast<const Method>(PickedVal)) {
1321 CW << M; // Print the method
1322 } else if (const Type *Ty = dyn_cast<const Type>(PickedVal)) {
1323 CW << "type %" << Name << " = " << Ty->getDescription() << endl;
1324 } else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(PickedVal)) {
1325 CW << BB; // Print the basic block
1326 } else { // Otherwise there should be an annotation for the slot#
1327 print(PickedVal->getType(),
1328 getOperandValue(PickedVal, ECStack[CurFrame]));
1333 void Interpreter::infoValue(const string &Name) {
1334 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
1335 if (!PickedVal) return;
1338 print(PickedVal->getType(),
1339 getOperandValue(PickedVal, ECStack[CurFrame]));
1341 printOperandInfo(PickedVal, ECStack[CurFrame]);
1344 // printStackFrame - Print information about the specified stack frame, or -1
1345 // for the default one.
1347 void Interpreter::printStackFrame(int FrameNo = -1) {
1348 if (FrameNo == -1) FrameNo = CurFrame;
1349 Method *Meth = ECStack[FrameNo].CurMethod;
1350 const Type *RetTy = Meth->getReturnType();
1352 CW << ((FrameNo == CurFrame) ? '>' : '-') << "#" << FrameNo << ". "
1353 << (Value*)RetTy << " \"" << Meth->getName() << "\"(";
1355 Method::ArgumentListType &Args = Meth->getArgumentList();
1356 for (unsigned i = 0; i < Args.size(); ++i) {
1357 if (i != 0) cout << ", ";
1358 CW << (Value*)Args[i] << "=";
1360 printValue(Args[i]->getType(), getOperandValue(Args[i], ECStack[FrameNo]));
1363 cout << ")" << endl;
1364 CW << *(ECStack[FrameNo].CurInst-(FrameNo != int(ECStack.size()-1)));