blob: 668ef6d713c89df069ec66c21310f1bdd4ecb865 [file] [log] [blame]
Chris Lattner92101ac2001-08-23 17:05:04 +00001//===-- 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/iOther.h"
10#include "llvm/iTerminators.h"
Chris Lattner86660982001-08-27 05:16:50 +000011#include "llvm/iMemory.h"
Chris Lattner92101ac2001-08-23 17:05:04 +000012#include "llvm/Type.h"
13#include "llvm/ConstPoolVals.h"
14#include "llvm/Assembly/Writer.h"
Chris Lattner86660982001-08-27 05:16:50 +000015#include "llvm/Support/DataTypes.h"
Chris Lattner41c2e5c2001-09-28 22:56:43 +000016#include "llvm/Target/TargetData.h"
Chris Lattner2e42d3a2001-10-15 05:51:48 +000017#include "llvm/GlobalVariable.h"
18
19// Create a TargetData structure to handle memory addressing and size/alignment
20// computations
21//
22static TargetData TD("lli Interpreter");
23
24//===----------------------------------------------------------------------===//
25// Annotation Wrangling code
26//===----------------------------------------------------------------------===//
27
28void Interpreter::initializeExecutionEngine() {
29 AnnotationManager::registerAnnotationFactory(MethodInfoAID,
30 &MethodInfo::Create);
31 AnnotationManager::registerAnnotationFactory(GlobalAddressAID,
32 &GlobalAddress::Create);
33}
34
35// InitializeMemory - Recursive function to apply a ConstPool value into the
36// specified memory location...
37//
38static void InitializeMemory(ConstPoolVal *Init, char *Addr) {
39#define INITIALIZE_MEMORY(TYID, CLASS, TY) \
40 case Type::TYID##TyID: { \
41 TY Tmp = cast<CLASS>(Init)->getValue(); \
42 memcpy(Addr, &Tmp, sizeof(TY)); \
43 } return
44
45 switch (Init->getType()->getPrimitiveID()) {
46 INITIALIZE_MEMORY(Bool , ConstPoolBool, bool);
47 INITIALIZE_MEMORY(UByte , ConstPoolUInt, unsigned char);
48 INITIALIZE_MEMORY(SByte , ConstPoolSInt, signed char);
49 INITIALIZE_MEMORY(UShort , ConstPoolUInt, unsigned short);
50 INITIALIZE_MEMORY(Short , ConstPoolSInt, signed short);
51 INITIALIZE_MEMORY(UInt , ConstPoolUInt, unsigned int);
52 INITIALIZE_MEMORY(Int , ConstPoolSInt, signed int);
53 INITIALIZE_MEMORY(ULong , ConstPoolUInt, uint64_t);
54 INITIALIZE_MEMORY(Long , ConstPoolSInt, int64_t);
55 INITIALIZE_MEMORY(Float , ConstPoolFP , float);
56 INITIALIZE_MEMORY(Double , ConstPoolFP , double);
57#undef INITIALIZE_MEMORY
58 case Type::ArrayTyID: {
59 ConstPoolArray *CPA = cast<ConstPoolArray>(Init);
60 const vector<Use> &Val = CPA->getValues();
61 unsigned ElementSize =
62 TD.getTypeSize(cast<ArrayType>(CPA->getType())->getElementType());
63 for (unsigned i = 0; i < Val.size(); ++i)
64 InitializeMemory(cast<ConstPoolVal>(Val[i].get()), Addr+i*ElementSize);
65 return;
66 }
67 // TODO: Struct and Pointer!
68 case Type::StructTyID:
69 case Type::PointerTyID:
70 default:
71 cout << "Bad Type: " << Init->getType()->getDescription() << endl;
72 assert(0 && "Unknown constant type to initialize memory with!");
73 }
74}
75
76Annotation *GlobalAddress::Create(AnnotationID AID, const Annotable *O, void *){
77 assert(AID == GlobalAddressAID);
78
79 // This annotation will only be created on GlobalValue objects...
80 GlobalValue *GVal = cast<GlobalValue>((Value*)O);
81
82 if (isa<Method>(GVal)) {
83 // The GlobalAddress object for a method is just a pointer to method itself.
84 // Don't delete it when the annotation is gone though!
85 return new GlobalAddress(GVal, false);
86 }
87
88 // Handle the case of a global variable...
89 assert(isa<GlobalVariable>(GVal) &&
90 "Global value found that isn't a method or global variable!");
91 GlobalVariable *GV = cast<GlobalVariable>(GVal);
92
93 // First off, we must allocate space for the global variable to point at...
94 const Type *Ty = GV->getType()->getValueType(); // Type to be allocated
95 unsigned NumElements = 1;
96
97 if (isa<ArrayType>(Ty) && cast<ArrayType>(Ty)->isUnsized()) {
98 assert(GV->hasInitializer() && "Const val must have an initializer!");
99 // Allocating a unsized array type?
100 Ty = cast<const ArrayType>(Ty)->getElementType(); // Get the actual type...
101
102 // Get the number of elements being allocated by the array...
103 NumElements =cast<ConstPoolArray>(GV->getInitializer())->getValues().size();
104 }
105
106 // Allocate enough memory to hold the type...
107 void *Addr = malloc(NumElements * TD.getTypeSize(Ty));
108 assert(Addr != 0 && "Null pointer returned by malloc!");
109
110 // Initialize the memory if there is an initializer...
111 if (GV->hasInitializer())
112 InitializeMemory(GV->getInitializer(), (char*)Addr);
113
114 return new GlobalAddress(Addr, true); // Simply invoke the ctor
115}
116
117//===----------------------------------------------------------------------===//
118// Value Manipulation code
119//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000120
121static unsigned getOperandSlot(Value *V) {
122 SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
123 assert(SN && "Operand does not have a slot number annotation!");
124 return SN->SlotNum;
125}
126
127#define GET_CONST_VAL(TY, CLASS) \
Chris Lattner2e42d3a2001-10-15 05:51:48 +0000128 case Type::TY##TyID: Result.TY##Val = cast<CLASS>(CPV)->getValue(); break
Chris Lattner92101ac2001-08-23 17:05:04 +0000129
130static GenericValue getOperandValue(Value *V, ExecutionContext &SF) {
Chris Lattner1d87bcf2001-10-01 20:11:19 +0000131 if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(V)) {
Chris Lattner92101ac2001-08-23 17:05:04 +0000132 GenericValue Result;
133 switch (CPV->getType()->getPrimitiveID()) {
134 GET_CONST_VAL(Bool , ConstPoolBool);
135 GET_CONST_VAL(UByte , ConstPoolUInt);
136 GET_CONST_VAL(SByte , ConstPoolSInt);
137 GET_CONST_VAL(UShort , ConstPoolUInt);
138 GET_CONST_VAL(Short , ConstPoolSInt);
139 GET_CONST_VAL(UInt , ConstPoolUInt);
140 GET_CONST_VAL(Int , ConstPoolSInt);
141 GET_CONST_VAL(Float , ConstPoolFP);
142 GET_CONST_VAL(Double , ConstPoolFP);
Chris Lattner2e42d3a2001-10-15 05:51:48 +0000143 case Type::PointerTyID:
144 if (isa<ConstPoolPointerNull>(CPV)) {
145 Result.PointerVal = 0;
146 } else if (ConstPoolPointerReference *CPR =
147 dyn_cast<ConstPoolPointerReference>(CPV)) {
148 assert(0 && "Not implemented!");
149 } else {
150 assert(0 && "Unknown constant pointer type!");
151 }
152 break;
Chris Lattner92101ac2001-08-23 17:05:04 +0000153 default:
154 cout << "ERROR: Constant unimp for type: " << CPV->getType() << endl;
155 }
156 return Result;
Chris Lattner2e42d3a2001-10-15 05:51:48 +0000157 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
158 GlobalAddress *Address =
159 (GlobalAddress*)GV->getOrCreateAnnotation(GlobalAddressAID);
160 GenericValue Result;
161 Result.PointerVal = (GenericValue*)Address->Ptr;
162 return Result;
Chris Lattner92101ac2001-08-23 17:05:04 +0000163 } else {
164 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
165 return SF.Values[TyP][getOperandSlot(V)];
166 }
167}
168
Chris Lattner86660982001-08-27 05:16:50 +0000169static void printOperandInfo(Value *V, ExecutionContext &SF) {
Chris Lattner2e42d3a2001-10-15 05:51:48 +0000170 if (isa<ConstPoolVal>(V)) {
171 cout << "Constant Pool Value\n";
172 } else if (isa<GlobalValue>(V)) {
173 cout << "Global Value\n";
174 } else {
Chris Lattner86660982001-08-27 05:16:50 +0000175 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
176 unsigned Slot = getOperandSlot(V);
177 cout << "Value=" << (void*)V << " TypeID=" << TyP << " Slot=" << Slot
178 << " Addr=" << &SF.Values[TyP][Slot] << " SF=" << &SF << endl;
179 }
180}
181
182
183
Chris Lattner92101ac2001-08-23 17:05:04 +0000184static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
185 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
Chris Lattner86660982001-08-27 05:16:50 +0000186
187 //cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)] << endl;
Chris Lattner92101ac2001-08-23 17:05:04 +0000188 SF.Values[TyP][getOperandSlot(V)] = Val;
189}
190
191
192
193//===----------------------------------------------------------------------===//
194// Binary Instruction Implementations
195//===----------------------------------------------------------------------===//
196
197#define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
198 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
Chris Lattner86660982001-08-27 05:16:50 +0000199#define IMPLEMENT_BINARY_PTR_OPERATOR(OP) \
200 case Type::PointerTyID: Dest.PointerVal = \
201 (GenericValue*)((unsigned long)Src1.PointerVal OP (unsigned long)Src2.PointerVal); break
Chris Lattner92101ac2001-08-23 17:05:04 +0000202
203static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
204 const Type *Ty, ExecutionContext &SF) {
205 GenericValue Dest;
206 switch (Ty->getPrimitiveID()) {
207 IMPLEMENT_BINARY_OPERATOR(+, UByte);
208 IMPLEMENT_BINARY_OPERATOR(+, SByte);
209 IMPLEMENT_BINARY_OPERATOR(+, UShort);
210 IMPLEMENT_BINARY_OPERATOR(+, Short);
211 IMPLEMENT_BINARY_OPERATOR(+, UInt);
212 IMPLEMENT_BINARY_OPERATOR(+, Int);
213 IMPLEMENT_BINARY_OPERATOR(+, Float);
214 IMPLEMENT_BINARY_OPERATOR(+, Double);
Chris Lattner86660982001-08-27 05:16:50 +0000215 IMPLEMENT_BINARY_PTR_OPERATOR(+);
Chris Lattner92101ac2001-08-23 17:05:04 +0000216 case Type::ULongTyID:
217 case Type::LongTyID:
218 default:
219 cout << "Unhandled type for Add instruction: " << Ty << endl;
220 }
221 return Dest;
222}
223
224static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
225 const Type *Ty, ExecutionContext &SF) {
226 GenericValue Dest;
227 switch (Ty->getPrimitiveID()) {
228 IMPLEMENT_BINARY_OPERATOR(-, UByte);
229 IMPLEMENT_BINARY_OPERATOR(-, SByte);
230 IMPLEMENT_BINARY_OPERATOR(-, UShort);
231 IMPLEMENT_BINARY_OPERATOR(-, Short);
232 IMPLEMENT_BINARY_OPERATOR(-, UInt);
233 IMPLEMENT_BINARY_OPERATOR(-, Int);
234 IMPLEMENT_BINARY_OPERATOR(-, Float);
235 IMPLEMENT_BINARY_OPERATOR(-, Double);
Chris Lattner86660982001-08-27 05:16:50 +0000236 IMPLEMENT_BINARY_PTR_OPERATOR(-);
Chris Lattner92101ac2001-08-23 17:05:04 +0000237 case Type::ULongTyID:
238 case Type::LongTyID:
239 default:
240 cout << "Unhandled type for Sub instruction: " << Ty << endl;
241 }
242 return Dest;
243}
244
245#define IMPLEMENT_SETCC(OP, TY) \
246 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
247
Chris Lattner92101ac2001-08-23 17:05:04 +0000248static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
249 const Type *Ty, ExecutionContext &SF) {
250 GenericValue Dest;
251 switch (Ty->getPrimitiveID()) {
252 IMPLEMENT_SETCC(==, UByte);
253 IMPLEMENT_SETCC(==, SByte);
254 IMPLEMENT_SETCC(==, UShort);
255 IMPLEMENT_SETCC(==, Short);
256 IMPLEMENT_SETCC(==, UInt);
257 IMPLEMENT_SETCC(==, Int);
258 IMPLEMENT_SETCC(==, Float);
259 IMPLEMENT_SETCC(==, Double);
Chris Lattner86660982001-08-27 05:16:50 +0000260 IMPLEMENT_SETCC(==, Pointer);
Chris Lattner92101ac2001-08-23 17:05:04 +0000261 case Type::ULongTyID:
262 case Type::LongTyID:
263 default:
264 cout << "Unhandled type for SetEQ instruction: " << Ty << endl;
265 }
266 return Dest;
267}
268
269static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
270 const Type *Ty, ExecutionContext &SF) {
271 GenericValue Dest;
272 switch (Ty->getPrimitiveID()) {
273 IMPLEMENT_SETCC(!=, UByte);
274 IMPLEMENT_SETCC(!=, SByte);
275 IMPLEMENT_SETCC(!=, UShort);
276 IMPLEMENT_SETCC(!=, Short);
277 IMPLEMENT_SETCC(!=, UInt);
278 IMPLEMENT_SETCC(!=, Int);
279 IMPLEMENT_SETCC(!=, Float);
280 IMPLEMENT_SETCC(!=, Double);
Chris Lattner86660982001-08-27 05:16:50 +0000281 IMPLEMENT_SETCC(!=, Pointer);
Chris Lattner92101ac2001-08-23 17:05:04 +0000282 case Type::ULongTyID:
283 case Type::LongTyID:
284 default:
285 cout << "Unhandled type for SetNE instruction: " << Ty << endl;
286 }
287 return Dest;
288}
289
290static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
291 const Type *Ty, ExecutionContext &SF) {
292 GenericValue Dest;
293 switch (Ty->getPrimitiveID()) {
294 IMPLEMENT_SETCC(<=, UByte);
295 IMPLEMENT_SETCC(<=, SByte);
296 IMPLEMENT_SETCC(<=, UShort);
297 IMPLEMENT_SETCC(<=, Short);
298 IMPLEMENT_SETCC(<=, UInt);
299 IMPLEMENT_SETCC(<=, Int);
300 IMPLEMENT_SETCC(<=, Float);
301 IMPLEMENT_SETCC(<=, Double);
Chris Lattner86660982001-08-27 05:16:50 +0000302 IMPLEMENT_SETCC(<=, Pointer);
Chris Lattner92101ac2001-08-23 17:05:04 +0000303 case Type::ULongTyID:
304 case Type::LongTyID:
305 default:
306 cout << "Unhandled type for SetLE instruction: " << Ty << endl;
307 }
308 return Dest;
309}
310
311static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
312 const Type *Ty, ExecutionContext &SF) {
313 GenericValue Dest;
314 switch (Ty->getPrimitiveID()) {
315 IMPLEMENT_SETCC(>=, UByte);
316 IMPLEMENT_SETCC(>=, SByte);
317 IMPLEMENT_SETCC(>=, UShort);
318 IMPLEMENT_SETCC(>=, Short);
319 IMPLEMENT_SETCC(>=, UInt);
320 IMPLEMENT_SETCC(>=, Int);
321 IMPLEMENT_SETCC(>=, Float);
322 IMPLEMENT_SETCC(>=, Double);
Chris Lattner86660982001-08-27 05:16:50 +0000323 IMPLEMENT_SETCC(>=, Pointer);
Chris Lattner92101ac2001-08-23 17:05:04 +0000324 case Type::ULongTyID:
325 case Type::LongTyID:
326 default:
327 cout << "Unhandled type for SetGE instruction: " << Ty << endl;
328 }
329 return Dest;
330}
331
332static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
333 const Type *Ty, ExecutionContext &SF) {
334 GenericValue Dest;
335 switch (Ty->getPrimitiveID()) {
336 IMPLEMENT_SETCC(<, UByte);
337 IMPLEMENT_SETCC(<, SByte);
338 IMPLEMENT_SETCC(<, UShort);
339 IMPLEMENT_SETCC(<, Short);
340 IMPLEMENT_SETCC(<, UInt);
341 IMPLEMENT_SETCC(<, Int);
342 IMPLEMENT_SETCC(<, Float);
343 IMPLEMENT_SETCC(<, Double);
Chris Lattner86660982001-08-27 05:16:50 +0000344 IMPLEMENT_SETCC(<, Pointer);
Chris Lattner92101ac2001-08-23 17:05:04 +0000345 case Type::ULongTyID:
346 case Type::LongTyID:
347 default:
348 cout << "Unhandled type for SetLT instruction: " << Ty << endl;
349 }
350 return Dest;
351}
352
353static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
354 const Type *Ty, ExecutionContext &SF) {
355 GenericValue Dest;
356 switch (Ty->getPrimitiveID()) {
357 IMPLEMENT_SETCC(>, UByte);
358 IMPLEMENT_SETCC(>, SByte);
359 IMPLEMENT_SETCC(>, UShort);
360 IMPLEMENT_SETCC(>, Short);
361 IMPLEMENT_SETCC(>, UInt);
362 IMPLEMENT_SETCC(>, Int);
363 IMPLEMENT_SETCC(>, Float);
364 IMPLEMENT_SETCC(>, Double);
Chris Lattner86660982001-08-27 05:16:50 +0000365 IMPLEMENT_SETCC(>, Pointer);
Chris Lattner92101ac2001-08-23 17:05:04 +0000366 case Type::ULongTyID:
367 case Type::LongTyID:
368 default:
369 cout << "Unhandled type for SetGT instruction: " << Ty << endl;
370 }
371 return Dest;
372}
373
374static void executeBinaryInst(BinaryOperator *I, ExecutionContext &SF) {
375 const Type *Ty = I->getOperand(0)->getType();
376 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
377 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
378 GenericValue R; // Result
379
380 switch (I->getOpcode()) {
381 case Instruction::Add: R = executeAddInst(Src1, Src2, Ty, SF); break;
382 case Instruction::Sub: R = executeSubInst(Src1, Src2, Ty, SF); break;
383 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty, SF); break;
384 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty, SF); break;
385 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty, SF); break;
386 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty, SF); break;
387 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty, SF); break;
388 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty, SF); break;
389 default:
390 cout << "Don't know how to handle this binary operator!\n-->" << I;
391 }
392
393 SetValue(I, R, SF);
394}
395
Chris Lattner92101ac2001-08-23 17:05:04 +0000396//===----------------------------------------------------------------------===//
397// Terminator Instruction Implementations
398//===----------------------------------------------------------------------===//
399
400void Interpreter::executeRetInst(ReturnInst *I, ExecutionContext &SF) {
401 const Type *RetTy = 0;
402 GenericValue Result;
403
404 // Save away the return value... (if we are not 'ret void')
405 if (I->getNumOperands()) {
406 RetTy = I->getReturnValue()->getType();
407 Result = getOperandValue(I->getReturnValue(), SF);
408 }
409
410 // Save previously executing meth
411 const Method *M = ECStack.back().CurMethod;
412
413 // Pop the current stack frame... this invalidates SF
414 ECStack.pop_back();
415
416 if (ECStack.empty()) { // Finished main. Put result into exit code...
417 if (RetTy) { // Nonvoid return type?
418 cout << "Method " << M->getType() << " \"" << M->getName()
419 << "\" returned ";
Chris Lattner2e42d3a2001-10-15 05:51:48 +0000420 print(RetTy, Result);
Chris Lattner92101ac2001-08-23 17:05:04 +0000421 cout << endl;
422
423 if (RetTy->isIntegral())
424 ExitCode = Result.SByteVal; // Capture the exit code of the program
425 } else {
426 ExitCode = 0;
427 }
428 return;
429 }
430
431 // If we have a previous stack frame, and we have a previous call, fill in
432 // the return value...
433 //
434 ExecutionContext &NewSF = ECStack.back();
435 if (NewSF.Caller) {
436 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
437 SetValue(NewSF.Caller, Result, NewSF);
438
439 NewSF.Caller = 0; // We returned from the call...
Chris Lattner365a76e2001-09-10 04:49:44 +0000440 } else {
441 // This must be a function that is executing because of a user 'call'
442 // instruction.
443 cout << "Method " << M->getType() << " \"" << M->getName()
444 << "\" returned ";
Chris Lattner2e42d3a2001-10-15 05:51:48 +0000445 print(RetTy, Result);
Chris Lattner365a76e2001-09-10 04:49:44 +0000446 cout << endl;
Chris Lattner92101ac2001-08-23 17:05:04 +0000447 }
448}
449
450void Interpreter::executeBrInst(BranchInst *I, ExecutionContext &SF) {
451 SF.PrevBB = SF.CurBB; // Update PrevBB so that PHI nodes work...
452 BasicBlock *Dest;
453
454 Dest = I->getSuccessor(0); // Uncond branches have a fixed dest...
455 if (!I->isUnconditional()) {
456 if (getOperandValue(I->getCondition(), SF).BoolVal == 0) // If false cond...
457 Dest = I->getSuccessor(1);
458 }
459 SF.CurBB = Dest; // Update CurBB to branch destination
460 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
461}
462
463//===----------------------------------------------------------------------===//
Chris Lattner86660982001-08-27 05:16:50 +0000464// Memory Instruction Implementations
465//===----------------------------------------------------------------------===//
466
Chris Lattner86660982001-08-27 05:16:50 +0000467void Interpreter::executeAllocInst(AllocationInst *I, ExecutionContext &SF) {
468 const Type *Ty = I->getType()->getValueType(); // Type to be allocated
469 unsigned NumElements = 1;
470
471 if (I->getNumOperands()) { // Allocating a unsized array type?
Chris Lattnerb00c5822001-10-02 03:41:24 +0000472 assert(isa<ArrayType>(Ty) && cast<const ArrayType>(Ty)->isUnsized() &&
Chris Lattner86660982001-08-27 05:16:50 +0000473 "Allocation inst with size operand for !unsized array type???");
Chris Lattnerb00c5822001-10-02 03:41:24 +0000474 Ty = cast<const ArrayType>(Ty)->getElementType(); // Get the actual type...
Chris Lattner86660982001-08-27 05:16:50 +0000475
476 // Get the number of elements being allocated by the array...
477 GenericValue NumEl = getOperandValue(I->getOperand(0), SF);
478 NumElements = NumEl.UIntVal;
479 }
480
481 // Allocate enough memory to hold the type...
482 GenericValue Result;
483 Result.PointerVal = (GenericValue*)malloc(NumElements * TD.getTypeSize(Ty));
484 assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
485 SetValue(I, Result, SF);
486
487 if (I->getOpcode() == Instruction::Alloca) {
Chris Lattner2e42d3a2001-10-15 05:51:48 +0000488 // TODO: FIXME: alloca should keep track of memory to free it later...
Chris Lattner86660982001-08-27 05:16:50 +0000489 }
490}
491
492static void executeFreeInst(FreeInst *I, ExecutionContext &SF) {
493 assert(I->getOperand(0)->getType()->isPointerType() && "Freeing nonptr?");
494 GenericValue Value = getOperandValue(I->getOperand(0), SF);
495 // TODO: Check to make sure memory is allocated
496 free(Value.PointerVal); // Free memory
497}
498
499static void executeLoadInst(LoadInst *I, ExecutionContext &SF) {
500 assert(I->getNumOperands() == 1 && "NI!");
501 GenericValue *Ptr = getOperandValue(I->getPtrOperand(), SF).PointerVal;
502 GenericValue Result;
503
504 switch (I->getType()->getPrimitiveID()) {
505 case Type::BoolTyID:
506 case Type::UByteTyID:
507 case Type::SByteTyID: Result.SByteVal = Ptr->SByteVal; break;
508 case Type::UShortTyID:
509 case Type::ShortTyID: Result.ShortVal = Ptr->ShortVal; break;
510 case Type::UIntTyID:
511 case Type::IntTyID: Result.IntVal = Ptr->IntVal; break;
512 //case Type::ULongTyID:
513 //case Type::LongTyID: Result.LongVal = Ptr->LongVal; break;
514 case Type::FloatTyID: Result.FloatVal = Ptr->FloatVal; break;
515 case Type::DoubleTyID: Result.DoubleVal = Ptr->DoubleVal; break;
516 case Type::PointerTyID: Result.PointerVal = Ptr->PointerVal; break;
517 default:
518 cout << "Cannot load value of type " << I->getType() << "!\n";
519 }
520
521 SetValue(I, Result, SF);
522}
523
524static void executeStoreInst(StoreInst *I, ExecutionContext &SF) {
525 GenericValue *Ptr = getOperandValue(I->getPtrOperand(), SF).PointerVal;
526 GenericValue Val = getOperandValue(I->getOperand(0), SF);
527 assert(I->getNumOperands() == 2 && "NI!");
528
529 switch (I->getOperand(0)->getType()->getPrimitiveID()) {
530 case Type::BoolTyID:
531 case Type::UByteTyID:
532 case Type::SByteTyID: Ptr->SByteVal = Val.SByteVal; break;
533 case Type::UShortTyID:
534 case Type::ShortTyID: Ptr->ShortVal = Val.ShortVal; break;
535 case Type::UIntTyID:
536 case Type::IntTyID: Ptr->IntVal = Val.IntVal; break;
537 //case Type::ULongTyID:
538 //case Type::LongTyID: Ptr->LongVal = Val.LongVal; break;
539 case Type::FloatTyID: Ptr->FloatVal = Val.FloatVal; break;
540 case Type::DoubleTyID: Ptr->DoubleVal = Val.DoubleVal; break;
541 case Type::PointerTyID: Ptr->PointerVal = Val.PointerVal; break;
542 default:
543 cout << "Cannot store value of type " << I->getType() << "!\n";
544 }
545}
546
547
548//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000549// Miscellaneous Instruction Implementations
550//===----------------------------------------------------------------------===//
551
552void Interpreter::executeCallInst(CallInst *I, ExecutionContext &SF) {
553 ECStack.back().Caller = I;
Chris Lattner365a76e2001-09-10 04:49:44 +0000554 vector<GenericValue> ArgVals;
555 ArgVals.reserve(I->getNumOperands()-1);
556 for (unsigned i = 1; i < I->getNumOperands(); ++i)
557 ArgVals.push_back(getOperandValue(I->getOperand(i), SF));
558
559 callMethod(I->getCalledMethod(), ArgVals);
Chris Lattner92101ac2001-08-23 17:05:04 +0000560}
561
562static void executePHINode(PHINode *I, ExecutionContext &SF) {
563 BasicBlock *PrevBB = SF.PrevBB;
564 Value *IncomingValue = 0;
565
566 // Search for the value corresponding to this previous bb...
567 for (unsigned i = I->getNumIncomingValues(); i > 0;) {
568 if (I->getIncomingBlock(--i) == PrevBB) {
569 IncomingValue = I->getIncomingValue(i);
570 break;
571 }
572 }
573 assert(IncomingValue && "No PHI node predecessor for current PrevBB!");
574
575 // Found the value, set as the result...
576 SetValue(I, getOperandValue(IncomingValue, SF), SF);
577}
578
Chris Lattner86660982001-08-27 05:16:50 +0000579#define IMPLEMENT_SHIFT(OP, TY) \
580 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
581
582static void executeShlInst(ShiftInst *I, ExecutionContext &SF) {
583 const Type *Ty = I->getOperand(0)->getType();
584 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
585 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
586 GenericValue Dest;
587
588 switch (Ty->getPrimitiveID()) {
589 IMPLEMENT_SHIFT(<<, UByte);
590 IMPLEMENT_SHIFT(<<, SByte);
591 IMPLEMENT_SHIFT(<<, UShort);
592 IMPLEMENT_SHIFT(<<, Short);
593 IMPLEMENT_SHIFT(<<, UInt);
594 IMPLEMENT_SHIFT(<<, Int);
595 case Type::ULongTyID:
596 case Type::LongTyID:
597 default:
598 cout << "Unhandled type for Shl instruction: " << Ty << endl;
599 }
600 SetValue(I, Dest, SF);
601}
602
603static void executeShrInst(ShiftInst *I, ExecutionContext &SF) {
604 const Type *Ty = I->getOperand(0)->getType();
605 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
606 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
607 GenericValue Dest;
608
609 switch (Ty->getPrimitiveID()) {
610 IMPLEMENT_SHIFT(>>, UByte);
611 IMPLEMENT_SHIFT(>>, SByte);
612 IMPLEMENT_SHIFT(>>, UShort);
613 IMPLEMENT_SHIFT(>>, Short);
614 IMPLEMENT_SHIFT(>>, UInt);
615 IMPLEMENT_SHIFT(>>, Int);
616 case Type::ULongTyID:
617 case Type::LongTyID:
618 default:
619 cout << "Unhandled type for Shr instruction: " << Ty << endl;
620 }
621 SetValue(I, Dest, SF);
622}
623
624#define IMPLEMENT_CAST(DTY, DCTY, STY) \
625 case Type::STY##TyID: Dest.DTY##Val = (DCTY)Src.STY##Val; break;
626
627#define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY) \
628 case Type::DESTTY##TyID: \
629 switch (SrcTy->getPrimitiveID()) { \
630 IMPLEMENT_CAST(DESTTY, DESTCTY, UByte); \
631 IMPLEMENT_CAST(DESTTY, DESTCTY, SByte); \
632 IMPLEMENT_CAST(DESTTY, DESTCTY, UShort); \
633 IMPLEMENT_CAST(DESTTY, DESTCTY, Short); \
634 IMPLEMENT_CAST(DESTTY, DESTCTY, UInt); \
635 IMPLEMENT_CAST(DESTTY, DESTCTY, Int);
636
637#define IMPLEMENT_CAST_CASE_PTR_IMP(DESTTY, DESTCTY) \
638 IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer)
639
640#define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
641 IMPLEMENT_CAST(DESTTY, DESTCTY, Float); \
642 IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
643
644#define IMPLEMENT_CAST_CASE_END() \
645 default: cout << "Unhandled cast: " << SrcTy << " to " << Ty << endl; \
646 break; \
647 } \
648 break
649
650#define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
651 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
652 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
653 IMPLEMENT_CAST_CASE_PTR_IMP(DESTTY, DESTCTY); \
654 IMPLEMENT_CAST_CASE_END()
655
656#define IMPLEMENT_CAST_CASE_FP(DESTTY, DESTCTY) \
657 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
658 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
659 IMPLEMENT_CAST_CASE_END()
660
661#define IMPLEMENT_CAST_CASE_PTR(DESTTY, DESTCTY) \
662 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
663 IMPLEMENT_CAST_CASE_PTR_IMP(DESTTY, DESTCTY); \
664 IMPLEMENT_CAST_CASE_END()
665
666static void executeCastInst(CastInst *I, ExecutionContext &SF) {
667 const Type *Ty = I->getType();
668 const Type *SrcTy = I->getOperand(0)->getType();
669 GenericValue Src = getOperandValue(I->getOperand(0), SF);
670 GenericValue Dest;
671
672 switch (Ty->getPrimitiveID()) {
673 IMPLEMENT_CAST_CASE(UByte , unsigned char);
674 IMPLEMENT_CAST_CASE(SByte , signed char);
675 IMPLEMENT_CAST_CASE(UShort, unsigned short);
676 IMPLEMENT_CAST_CASE(Short , signed char);
677 IMPLEMENT_CAST_CASE(UInt , unsigned int );
678 IMPLEMENT_CAST_CASE(Int , signed int );
679 IMPLEMENT_CAST_CASE_FP(Float , float);
680 IMPLEMENT_CAST_CASE_FP(Double, double);
681 IMPLEMENT_CAST_CASE_PTR(Pointer, GenericValue *);
682 case Type::ULongTyID:
683 case Type::LongTyID:
684 default:
685 cout << "Unhandled dest type for cast instruction: " << Ty << endl;
686 }
687 SetValue(I, Dest, SF);
688}
Chris Lattner92101ac2001-08-23 17:05:04 +0000689
690
691
692
693//===----------------------------------------------------------------------===//
694// Dispatch and Execution Code
695//===----------------------------------------------------------------------===//
696
697MethodInfo::MethodInfo(Method *M) : Annotation(MethodInfoAID) {
698 // Assign slot numbers to the method arguments...
699 const Method::ArgumentListType &ArgList = M->getArgumentList();
700 for (Method::ArgumentListType::const_iterator AI = ArgList.begin(),
701 AE = ArgList.end(); AI != AE; ++AI) {
702 MethodArgument *MA = *AI;
703 MA->addAnnotation(new SlotNumber(getValueSlot(MA)));
704 }
705
706 // Iterate over all of the instructions...
707 unsigned InstNum = 0;
708 for (Method::inst_iterator MI = M->inst_begin(), ME = M->inst_end();
709 MI != ME; ++MI) {
710 Instruction *I = *MI; // For each instruction...
711 I->addAnnotation(new InstNumber(++InstNum, getValueSlot(I))); // Add Annote
712 }
713}
714
715unsigned MethodInfo::getValueSlot(const Value *V) {
716 unsigned Plane = V->getType()->getUniqueID();
717 if (Plane >= NumPlaneElements.size())
718 NumPlaneElements.resize(Plane+1, 0);
719 return NumPlaneElements[Plane]++;
720}
721
722
Chris Lattner92101ac2001-08-23 17:05:04 +0000723//===----------------------------------------------------------------------===//
724// callMethod - Execute the specified method...
725//
Chris Lattner365a76e2001-09-10 04:49:44 +0000726void Interpreter::callMethod(Method *M, const vector<GenericValue> &ArgVals) {
727 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
728 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
729 "Incorrect number of arguments passed into function call!");
Chris Lattner92101ac2001-08-23 17:05:04 +0000730 if (M->isExternal()) {
Chris Lattner365a76e2001-09-10 04:49:44 +0000731 callExternalMethod(M, ArgVals);
Chris Lattner92101ac2001-08-23 17:05:04 +0000732 return;
733 }
734
735 // Process the method, assigning instruction numbers to the instructions in
736 // the method. Also calculate the number of values for each type slot active.
737 //
738 MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
Chris Lattner92101ac2001-08-23 17:05:04 +0000739 ECStack.push_back(ExecutionContext()); // Make a new stack frame...
Chris Lattner86660982001-08-27 05:16:50 +0000740
Chris Lattner92101ac2001-08-23 17:05:04 +0000741 ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
742 StackFrame.CurMethod = M;
743 StackFrame.CurBB = M->front();
744 StackFrame.CurInst = StackFrame.CurBB->begin();
745 StackFrame.MethInfo = MethInfo;
746
747 // Initialize the values to nothing...
748 StackFrame.Values.resize(MethInfo->NumPlaneElements.size());
749 for (unsigned i = 0; i < MethInfo->NumPlaneElements.size(); ++i)
750 StackFrame.Values[i].resize(MethInfo->NumPlaneElements[i]);
751
752 StackFrame.PrevBB = 0; // No previous BB for PHI nodes...
753
Chris Lattner92101ac2001-08-23 17:05:04 +0000754
Chris Lattner365a76e2001-09-10 04:49:44 +0000755 // Run through the method arguments and initialize their values...
756 unsigned i = 0;
757 for (Method::ArgumentListType::iterator MI = M->getArgumentList().begin(),
758 ME = M->getArgumentList().end(); MI != ME; ++MI, ++i) {
759 SetValue(*MI, ArgVals[i], StackFrame);
Chris Lattner92101ac2001-08-23 17:05:04 +0000760 }
761}
762
763// executeInstruction - Interpret a single instruction, increment the "PC", and
764// return true if the next instruction is a breakpoint...
765//
766bool Interpreter::executeInstruction() {
767 assert(!ECStack.empty() && "No program running, cannot execute inst!");
768
769 ExecutionContext &SF = ECStack.back(); // Current stack frame
770 Instruction *I = *SF.CurInst++; // Increment before execute
771
772 if (I->isBinaryOp()) {
773 executeBinaryInst((BinaryOperator*)I, SF);
774 } else {
775 switch (I->getOpcode()) {
Chris Lattner86660982001-08-27 05:16:50 +0000776 // Terminators
Chris Lattner92101ac2001-08-23 17:05:04 +0000777 case Instruction::Ret: executeRetInst ((ReturnInst*)I, SF); break;
778 case Instruction::Br: executeBrInst ((BranchInst*)I, SF); break;
Chris Lattner86660982001-08-27 05:16:50 +0000779 // Memory Instructions
780 case Instruction::Alloca:
781 case Instruction::Malloc: executeAllocInst ((AllocationInst*)I, SF); break;
Chris Lattnerb00c5822001-10-02 03:41:24 +0000782 case Instruction::Free: executeFreeInst (cast<FreeInst> (I), SF); break;
783 case Instruction::Load: executeLoadInst (cast<LoadInst> (I), SF); break;
784 case Instruction::Store: executeStoreInst (cast<StoreInst>(I), SF); break;
Chris Lattner86660982001-08-27 05:16:50 +0000785
786 // Miscellaneous Instructions
Chris Lattnerb00c5822001-10-02 03:41:24 +0000787 case Instruction::Call: executeCallInst (cast<CallInst> (I), SF); break;
788 case Instruction::PHINode: executePHINode (cast<PHINode> (I), SF); break;
789 case Instruction::Shl: executeShlInst (cast<ShiftInst>(I), SF); break;
790 case Instruction::Shr: executeShrInst (cast<ShiftInst>(I), SF); break;
791 case Instruction::Cast: executeCastInst (cast<CastInst> (I), SF); break;
Chris Lattner92101ac2001-08-23 17:05:04 +0000792 default:
793 cout << "Don't know how to execute this instruction!\n-->" << I;
794 }
795 }
796
797 // Reset the current frame location to the top of stack
798 CurFrame = ECStack.size()-1;
799
800 if (CurFrame == -1) return false; // No breakpoint if no code
801
802 // Return true if there is a breakpoint annotation on the instruction...
803 return (*ECStack[CurFrame].CurInst)->getAnnotation(BreakpointAID) != 0;
804}
805
806void Interpreter::stepInstruction() { // Do the 'step' command
807 if (ECStack.empty()) {
808 cout << "Error: no program running, cannot step!\n";
809 return;
810 }
811
812 // Run an instruction...
813 executeInstruction();
814
815 // Print the next instruction to execute...
816 printCurrentInstruction();
817}
818
819// --- UI Stuff...
Chris Lattner92101ac2001-08-23 17:05:04 +0000820void Interpreter::nextInstruction() { // Do the 'next' command
821 if (ECStack.empty()) {
822 cout << "Error: no program running, cannot 'next'!\n";
823 return;
824 }
825
826 // If this is a call instruction, step over the call instruction...
827 // TODO: ICALL, CALL WITH, ...
828 if ((*ECStack.back().CurInst)->getOpcode() == Instruction::Call) {
829 // Step into the function...
830 if (executeInstruction()) {
831 // Hit a breakpoint, print current instruction, then return to user...
832 cout << "Breakpoint hit!\n";
833 printCurrentInstruction();
834 return;
835 }
836
837 // Finish executing the function...
838 finish();
839 } else {
840 // Normal instruction, just step...
841 stepInstruction();
842 }
843}
844
845void Interpreter::run() {
846 if (ECStack.empty()) {
847 cout << "Error: no program running, cannot run!\n";
848 return;
849 }
850
851 bool HitBreakpoint = false;
852 while (!ECStack.empty() && !HitBreakpoint) {
853 // Run an instruction...
854 HitBreakpoint = executeInstruction();
855 }
856
857 if (HitBreakpoint) {
858 cout << "Breakpoint hit!\n";
859 }
Chris Lattner92101ac2001-08-23 17:05:04 +0000860 // Print the next instruction to execute...
861 printCurrentInstruction();
862}
863
864void Interpreter::finish() {
865 if (ECStack.empty()) {
866 cout << "Error: no program running, cannot run!\n";
867 return;
868 }
869
870 unsigned StackSize = ECStack.size();
871 bool HitBreakpoint = false;
872 while (ECStack.size() >= StackSize && !HitBreakpoint) {
873 // Run an instruction...
874 HitBreakpoint = executeInstruction();
875 }
876
877 if (HitBreakpoint) {
878 cout << "Breakpoint hit!\n";
879 }
880
881 // Print the next instruction to execute...
882 printCurrentInstruction();
883}
884
885
886
887// printCurrentInstruction - Print out the instruction that the virtual PC is
888// at, or fail silently if no program is running.
889//
890void Interpreter::printCurrentInstruction() {
891 if (!ECStack.empty()) {
892 Instruction *I = *ECStack.back().CurInst;
893 InstNumber *IN = (InstNumber*)I->getAnnotation(SlotNumberAID);
894 assert(IN && "Instruction has no numbering annotation!");
895 cout << "#" << IN->InstNum << I;
896 }
897}
898
899void Interpreter::printValue(const Type *Ty, GenericValue V) {
Chris Lattner92101ac2001-08-23 17:05:04 +0000900 switch (Ty->getPrimitiveID()) {
901 case Type::BoolTyID: cout << (V.BoolVal?"true":"false"); break;
902 case Type::SByteTyID: cout << V.SByteVal; break;
903 case Type::UByteTyID: cout << V.UByteVal; break;
904 case Type::ShortTyID: cout << V.ShortVal; break;
905 case Type::UShortTyID: cout << V.UShortVal; break;
906 case Type::IntTyID: cout << V.IntVal; break;
907 case Type::UIntTyID: cout << V.UIntVal; break;
908 case Type::FloatTyID: cout << V.FloatVal; break;
909 case Type::DoubleTyID: cout << V.DoubleVal; break;
Chris Lattner86660982001-08-27 05:16:50 +0000910 case Type::PointerTyID:cout << V.PointerVal; break;
Chris Lattner92101ac2001-08-23 17:05:04 +0000911 default:
912 cout << "- Don't know how to print value of this type!";
913 break;
914 }
915}
916
Chris Lattner2e42d3a2001-10-15 05:51:48 +0000917void Interpreter::print(const Type *Ty, GenericValue V) {
918 cout << Ty << " ";
919 printValue(Ty, V);
920}
921
922void Interpreter::print(const string &Name) {
Chris Lattner92101ac2001-08-23 17:05:04 +0000923 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
924 if (!PickedVal) return;
925
Chris Lattner9636a912001-10-01 16:18:37 +0000926 if (const Method *M = dyn_cast<const Method>(PickedVal)) {
Chris Lattner92101ac2001-08-23 17:05:04 +0000927 cout << M; // Print the method
928 } else { // Otherwise there should be an annotation for the slot#
Chris Lattner2e42d3a2001-10-15 05:51:48 +0000929 print(PickedVal->getType(),
930 getOperandValue(PickedVal, ECStack[CurFrame]));
Chris Lattner92101ac2001-08-23 17:05:04 +0000931 cout << endl;
932 }
933
934}
935
Chris Lattner86660982001-08-27 05:16:50 +0000936void Interpreter::infoValue(const string &Name) {
937 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
938 if (!PickedVal) return;
939
940 cout << "Value: ";
Chris Lattner2e42d3a2001-10-15 05:51:48 +0000941 print(PickedVal->getType(),
942 getOperandValue(PickedVal, ECStack[CurFrame]));
Chris Lattner86660982001-08-27 05:16:50 +0000943 cout << endl;
944 printOperandInfo(PickedVal, ECStack[CurFrame]);
945}
946
Chris Lattner92101ac2001-08-23 17:05:04 +0000947void Interpreter::list() {
948 if (ECStack.empty())
949 cout << "Error: No program executing!\n";
950 else
951 cout << ECStack[CurFrame].CurMethod; // Just print the method out...
952}
953
954void Interpreter::printStackTrace() {
955 if (ECStack.empty()) cout << "No program executing!\n";
956
957 for (unsigned i = 0; i < ECStack.size(); ++i) {
958 cout << (((int)i == CurFrame) ? '>' : '-');
959 cout << "#" << i << ". " << ECStack[i].CurMethod->getType() << " \""
960 << ECStack[i].CurMethod->getName() << "\"(";
961 // TODO: Print Args
962 cout << ")" << endl;
963 cout << *ECStack[i].CurInst;
964 }
965}