blob: 92d8b663cc5315fef2a9b49aad08245aba12a7bb [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"
11#include "llvm/Type.h"
12#include "llvm/ConstPoolVals.h"
13#include "llvm/Assembly/Writer.h"
14
15static unsigned getOperandSlot(Value *V) {
16 SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
17 assert(SN && "Operand does not have a slot number annotation!");
18 return SN->SlotNum;
19}
20
21#define GET_CONST_VAL(TY, CLASS) \
22 case Type::TY##TyID: Result.TY##Val = ((CLASS*)CPV)->getValue(); break
23
24static GenericValue getOperandValue(Value *V, ExecutionContext &SF) {
25 if (ConstPoolVal *CPV = V->castConstant()) {
26 GenericValue Result;
27 switch (CPV->getType()->getPrimitiveID()) {
28 GET_CONST_VAL(Bool , ConstPoolBool);
29 GET_CONST_VAL(UByte , ConstPoolUInt);
30 GET_CONST_VAL(SByte , ConstPoolSInt);
31 GET_CONST_VAL(UShort , ConstPoolUInt);
32 GET_CONST_VAL(Short , ConstPoolSInt);
33 GET_CONST_VAL(UInt , ConstPoolUInt);
34 GET_CONST_VAL(Int , ConstPoolSInt);
35 GET_CONST_VAL(Float , ConstPoolFP);
36 GET_CONST_VAL(Double , ConstPoolFP);
37 default:
38 cout << "ERROR: Constant unimp for type: " << CPV->getType() << endl;
39 }
40 return Result;
41 } else {
42 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
43 return SF.Values[TyP][getOperandSlot(V)];
44 }
45}
46
47static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
48 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
49 SF.Values[TyP][getOperandSlot(V)] = Val;
50}
51
52
53
54//===----------------------------------------------------------------------===//
55// Binary Instruction Implementations
56//===----------------------------------------------------------------------===//
57
58#define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
59 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
60
61static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
62 const Type *Ty, ExecutionContext &SF) {
63 GenericValue Dest;
64 switch (Ty->getPrimitiveID()) {
65 IMPLEMENT_BINARY_OPERATOR(+, UByte);
66 IMPLEMENT_BINARY_OPERATOR(+, SByte);
67 IMPLEMENT_BINARY_OPERATOR(+, UShort);
68 IMPLEMENT_BINARY_OPERATOR(+, Short);
69 IMPLEMENT_BINARY_OPERATOR(+, UInt);
70 IMPLEMENT_BINARY_OPERATOR(+, Int);
71 IMPLEMENT_BINARY_OPERATOR(+, Float);
72 IMPLEMENT_BINARY_OPERATOR(+, Double);
73 case Type::ULongTyID:
74 case Type::LongTyID:
75 default:
76 cout << "Unhandled type for Add instruction: " << Ty << endl;
77 }
78 return Dest;
79}
80
81static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
82 const Type *Ty, ExecutionContext &SF) {
83 GenericValue Dest;
84 switch (Ty->getPrimitiveID()) {
85 IMPLEMENT_BINARY_OPERATOR(-, UByte);
86 IMPLEMENT_BINARY_OPERATOR(-, SByte);
87 IMPLEMENT_BINARY_OPERATOR(-, UShort);
88 IMPLEMENT_BINARY_OPERATOR(-, Short);
89 IMPLEMENT_BINARY_OPERATOR(-, UInt);
90 IMPLEMENT_BINARY_OPERATOR(-, Int);
91 IMPLEMENT_BINARY_OPERATOR(-, Float);
92 IMPLEMENT_BINARY_OPERATOR(-, Double);
93 case Type::ULongTyID:
94 case Type::LongTyID:
95 default:
96 cout << "Unhandled type for Sub instruction: " << Ty << endl;
97 }
98 return Dest;
99}
100
101#define IMPLEMENT_SETCC(OP, TY) \
102 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
103
104
105static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
106 const Type *Ty, ExecutionContext &SF) {
107 GenericValue Dest;
108 switch (Ty->getPrimitiveID()) {
109 IMPLEMENT_SETCC(==, UByte);
110 IMPLEMENT_SETCC(==, SByte);
111 IMPLEMENT_SETCC(==, UShort);
112 IMPLEMENT_SETCC(==, Short);
113 IMPLEMENT_SETCC(==, UInt);
114 IMPLEMENT_SETCC(==, Int);
115 IMPLEMENT_SETCC(==, Float);
116 IMPLEMENT_SETCC(==, Double);
117 case Type::ULongTyID:
118 case Type::LongTyID:
119 default:
120 cout << "Unhandled type for SetEQ instruction: " << Ty << endl;
121 }
122 return Dest;
123}
124
125static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
126 const Type *Ty, ExecutionContext &SF) {
127 GenericValue Dest;
128 switch (Ty->getPrimitiveID()) {
129 IMPLEMENT_SETCC(!=, UByte);
130 IMPLEMENT_SETCC(!=, SByte);
131 IMPLEMENT_SETCC(!=, UShort);
132 IMPLEMENT_SETCC(!=, Short);
133 IMPLEMENT_SETCC(!=, UInt);
134 IMPLEMENT_SETCC(!=, Int);
135 IMPLEMENT_SETCC(!=, Float);
136 IMPLEMENT_SETCC(!=, Double);
137 case Type::ULongTyID:
138 case Type::LongTyID:
139 default:
140 cout << "Unhandled type for SetNE instruction: " << Ty << endl;
141 }
142 return Dest;
143}
144
145static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
146 const Type *Ty, ExecutionContext &SF) {
147 GenericValue Dest;
148 switch (Ty->getPrimitiveID()) {
149 IMPLEMENT_SETCC(<=, UByte);
150 IMPLEMENT_SETCC(<=, SByte);
151 IMPLEMENT_SETCC(<=, UShort);
152 IMPLEMENT_SETCC(<=, Short);
153 IMPLEMENT_SETCC(<=, UInt);
154 IMPLEMENT_SETCC(<=, Int);
155 IMPLEMENT_SETCC(<=, Float);
156 IMPLEMENT_SETCC(<=, Double);
157 case Type::ULongTyID:
158 case Type::LongTyID:
159 default:
160 cout << "Unhandled type for SetLE instruction: " << Ty << endl;
161 }
162 return Dest;
163}
164
165static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
166 const Type *Ty, ExecutionContext &SF) {
167 GenericValue Dest;
168 switch (Ty->getPrimitiveID()) {
169 IMPLEMENT_SETCC(>=, UByte);
170 IMPLEMENT_SETCC(>=, SByte);
171 IMPLEMENT_SETCC(>=, UShort);
172 IMPLEMENT_SETCC(>=, Short);
173 IMPLEMENT_SETCC(>=, UInt);
174 IMPLEMENT_SETCC(>=, Int);
175 IMPLEMENT_SETCC(>=, Float);
176 IMPLEMENT_SETCC(>=, Double);
177 case Type::ULongTyID:
178 case Type::LongTyID:
179 default:
180 cout << "Unhandled type for SetGE instruction: " << Ty << endl;
181 }
182 return Dest;
183}
184
185static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
186 const Type *Ty, ExecutionContext &SF) {
187 GenericValue Dest;
188 switch (Ty->getPrimitiveID()) {
189 IMPLEMENT_SETCC(<, UByte);
190 IMPLEMENT_SETCC(<, SByte);
191 IMPLEMENT_SETCC(<, UShort);
192 IMPLEMENT_SETCC(<, Short);
193 IMPLEMENT_SETCC(<, UInt);
194 IMPLEMENT_SETCC(<, Int);
195 IMPLEMENT_SETCC(<, Float);
196 IMPLEMENT_SETCC(<, Double);
197 case Type::ULongTyID:
198 case Type::LongTyID:
199 default:
200 cout << "Unhandled type for SetLT instruction: " << Ty << endl;
201 }
202 return Dest;
203}
204
205static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
206 const Type *Ty, ExecutionContext &SF) {
207 GenericValue Dest;
208 switch (Ty->getPrimitiveID()) {
209 IMPLEMENT_SETCC(>, UByte);
210 IMPLEMENT_SETCC(>, SByte);
211 IMPLEMENT_SETCC(>, UShort);
212 IMPLEMENT_SETCC(>, Short);
213 IMPLEMENT_SETCC(>, UInt);
214 IMPLEMENT_SETCC(>, Int);
215 IMPLEMENT_SETCC(>, Float);
216 IMPLEMENT_SETCC(>, Double);
217 case Type::ULongTyID:
218 case Type::LongTyID:
219 default:
220 cout << "Unhandled type for SetGT instruction: " << Ty << endl;
221 }
222 return Dest;
223}
224
225static void executeBinaryInst(BinaryOperator *I, ExecutionContext &SF) {
226 const Type *Ty = I->getOperand(0)->getType();
227 GenericValue Src1 = getOperandValue(I->getOperand(0), SF);
228 GenericValue Src2 = getOperandValue(I->getOperand(1), SF);
229 GenericValue R; // Result
230
231 switch (I->getOpcode()) {
232 case Instruction::Add: R = executeAddInst(Src1, Src2, Ty, SF); break;
233 case Instruction::Sub: R = executeSubInst(Src1, Src2, Ty, SF); break;
234 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty, SF); break;
235 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty, SF); break;
236 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty, SF); break;
237 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty, SF); break;
238 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty, SF); break;
239 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty, SF); break;
240 default:
241 cout << "Don't know how to handle this binary operator!\n-->" << I;
242 }
243
244 SetValue(I, R, SF);
245}
246
247
248//===----------------------------------------------------------------------===//
249// Terminator Instruction Implementations
250//===----------------------------------------------------------------------===//
251
252void Interpreter::executeRetInst(ReturnInst *I, ExecutionContext &SF) {
253 const Type *RetTy = 0;
254 GenericValue Result;
255
256 // Save away the return value... (if we are not 'ret void')
257 if (I->getNumOperands()) {
258 RetTy = I->getReturnValue()->getType();
259 Result = getOperandValue(I->getReturnValue(), SF);
260 }
261
262 // Save previously executing meth
263 const Method *M = ECStack.back().CurMethod;
264
265 // Pop the current stack frame... this invalidates SF
266 ECStack.pop_back();
267
268 if (ECStack.empty()) { // Finished main. Put result into exit code...
269 if (RetTy) { // Nonvoid return type?
270 cout << "Method " << M->getType() << " \"" << M->getName()
271 << "\" returned ";
272 printValue(RetTy, Result);
273 cout << endl;
274
275 if (RetTy->isIntegral())
276 ExitCode = Result.SByteVal; // Capture the exit code of the program
277 } else {
278 ExitCode = 0;
279 }
280 return;
281 }
282
283 // If we have a previous stack frame, and we have a previous call, fill in
284 // the return value...
285 //
286 ExecutionContext &NewSF = ECStack.back();
287 if (NewSF.Caller) {
288 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
289 SetValue(NewSF.Caller, Result, NewSF);
290
291 NewSF.Caller = 0; // We returned from the call...
292 }
293}
294
295void Interpreter::executeBrInst(BranchInst *I, ExecutionContext &SF) {
296 SF.PrevBB = SF.CurBB; // Update PrevBB so that PHI nodes work...
297 BasicBlock *Dest;
298
299 Dest = I->getSuccessor(0); // Uncond branches have a fixed dest...
300 if (!I->isUnconditional()) {
301 if (getOperandValue(I->getCondition(), SF).BoolVal == 0) // If false cond...
302 Dest = I->getSuccessor(1);
303 }
304 SF.CurBB = Dest; // Update CurBB to branch destination
305 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
306}
307
308//===----------------------------------------------------------------------===//
309// Miscellaneous Instruction Implementations
310//===----------------------------------------------------------------------===//
311
312void Interpreter::executeCallInst(CallInst *I, ExecutionContext &SF) {
313 ECStack.back().Caller = I;
314 callMethod(I->getCalledMethod(), &ECStack.back());
315}
316
317static void executePHINode(PHINode *I, ExecutionContext &SF) {
318 BasicBlock *PrevBB = SF.PrevBB;
319 Value *IncomingValue = 0;
320
321 // Search for the value corresponding to this previous bb...
322 for (unsigned i = I->getNumIncomingValues(); i > 0;) {
323 if (I->getIncomingBlock(--i) == PrevBB) {
324 IncomingValue = I->getIncomingValue(i);
325 break;
326 }
327 }
328 assert(IncomingValue && "No PHI node predecessor for current PrevBB!");
329
330 // Found the value, set as the result...
331 SetValue(I, getOperandValue(IncomingValue, SF), SF);
332}
333
334
335
336
337
338//===----------------------------------------------------------------------===//
339// Dispatch and Execution Code
340//===----------------------------------------------------------------------===//
341
342MethodInfo::MethodInfo(Method *M) : Annotation(MethodInfoAID) {
343 // Assign slot numbers to the method arguments...
344 const Method::ArgumentListType &ArgList = M->getArgumentList();
345 for (Method::ArgumentListType::const_iterator AI = ArgList.begin(),
346 AE = ArgList.end(); AI != AE; ++AI) {
347 MethodArgument *MA = *AI;
348 MA->addAnnotation(new SlotNumber(getValueSlot(MA)));
349 }
350
351 // Iterate over all of the instructions...
352 unsigned InstNum = 0;
353 for (Method::inst_iterator MI = M->inst_begin(), ME = M->inst_end();
354 MI != ME; ++MI) {
355 Instruction *I = *MI; // For each instruction...
356 I->addAnnotation(new InstNumber(++InstNum, getValueSlot(I))); // Add Annote
357 }
358}
359
360unsigned MethodInfo::getValueSlot(const Value *V) {
361 unsigned Plane = V->getType()->getUniqueID();
362 if (Plane >= NumPlaneElements.size())
363 NumPlaneElements.resize(Plane+1, 0);
364 return NumPlaneElements[Plane]++;
365}
366
367
368void Interpreter::initializeExecutionEngine() {
369 AnnotationManager::registerAnnotationFactory(MethodInfoAID, CreateMethodInfo);
370}
371
372
373
374//===----------------------------------------------------------------------===//
375// callMethod - Execute the specified method...
376//
377void Interpreter::callMethod(Method *M, ExecutionContext *CallingSF = 0) {
378 if (M->isExternal()) {
379 // Handle builtin methods
380 cout << "Error: Method '" << M->getName() << "' is external!\n";
381 return;
382 }
383
384 // Process the method, assigning instruction numbers to the instructions in
385 // the method. Also calculate the number of values for each type slot active.
386 //
387 MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
388
389 ECStack.push_back(ExecutionContext()); // Make a new stack frame...
390 ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
391 StackFrame.CurMethod = M;
392 StackFrame.CurBB = M->front();
393 StackFrame.CurInst = StackFrame.CurBB->begin();
394 StackFrame.MethInfo = MethInfo;
395
396 // Initialize the values to nothing...
397 StackFrame.Values.resize(MethInfo->NumPlaneElements.size());
398 for (unsigned i = 0; i < MethInfo->NumPlaneElements.size(); ++i)
399 StackFrame.Values[i].resize(MethInfo->NumPlaneElements[i]);
400
401 StackFrame.PrevBB = 0; // No previous BB for PHI nodes...
402
403 // Run through the method arguments and initialize their values...
404 if (CallingSF) {
405 CallInst *Call = CallingSF->Caller;
406 assert(Call && "Caller improperly initialized!");
407
408 unsigned i = 0;
409 for (Method::ArgumentListType::iterator MI = M->getArgumentList().begin(),
410 ME = M->getArgumentList().end(); MI != ME; ++MI, ++i) {
411 Value *V = Call->getOperand(i+1);
412 MethodArgument *MA = *MI;
413
414 SetValue(MA, getOperandValue(V, *CallingSF), StackFrame);
415 }
416 }
417}
418
419// executeInstruction - Interpret a single instruction, increment the "PC", and
420// return true if the next instruction is a breakpoint...
421//
422bool Interpreter::executeInstruction() {
423 assert(!ECStack.empty() && "No program running, cannot execute inst!");
424
425 ExecutionContext &SF = ECStack.back(); // Current stack frame
426 Instruction *I = *SF.CurInst++; // Increment before execute
427
428 if (I->isBinaryOp()) {
429 executeBinaryInst((BinaryOperator*)I, SF);
430 } else {
431 switch (I->getOpcode()) {
432 case Instruction::Ret: executeRetInst ((ReturnInst*)I, SF); break;
433 case Instruction::Br: executeBrInst ((BranchInst*)I, SF); break;
434 case Instruction::Call: executeCallInst ((CallInst*) I, SF); break;
435 case Instruction::PHINode: executePHINode ((PHINode*) I, SF); break;
436 default:
437 cout << "Don't know how to execute this instruction!\n-->" << I;
438 }
439 }
440
441 // Reset the current frame location to the top of stack
442 CurFrame = ECStack.size()-1;
443
444 if (CurFrame == -1) return false; // No breakpoint if no code
445
446 // Return true if there is a breakpoint annotation on the instruction...
447 return (*ECStack[CurFrame].CurInst)->getAnnotation(BreakpointAID) != 0;
448}
449
450void Interpreter::stepInstruction() { // Do the 'step' command
451 if (ECStack.empty()) {
452 cout << "Error: no program running, cannot step!\n";
453 return;
454 }
455
456 // Run an instruction...
457 executeInstruction();
458
459 // Print the next instruction to execute...
460 printCurrentInstruction();
461}
462
463// --- UI Stuff...
464
465
466
467void Interpreter::nextInstruction() { // Do the 'next' command
468 if (ECStack.empty()) {
469 cout << "Error: no program running, cannot 'next'!\n";
470 return;
471 }
472
473 // If this is a call instruction, step over the call instruction...
474 // TODO: ICALL, CALL WITH, ...
475 if ((*ECStack.back().CurInst)->getOpcode() == Instruction::Call) {
476 // Step into the function...
477 if (executeInstruction()) {
478 // Hit a breakpoint, print current instruction, then return to user...
479 cout << "Breakpoint hit!\n";
480 printCurrentInstruction();
481 return;
482 }
483
484 // Finish executing the function...
485 finish();
486 } else {
487 // Normal instruction, just step...
488 stepInstruction();
489 }
490}
491
492void Interpreter::run() {
493 if (ECStack.empty()) {
494 cout << "Error: no program running, cannot run!\n";
495 return;
496 }
497
498 bool HitBreakpoint = false;
499 while (!ECStack.empty() && !HitBreakpoint) {
500 // Run an instruction...
501 HitBreakpoint = executeInstruction();
502 }
503
504 if (HitBreakpoint) {
505 cout << "Breakpoint hit!\n";
506 }
507
508 // Print the next instruction to execute...
509 printCurrentInstruction();
510}
511
512void Interpreter::finish() {
513 if (ECStack.empty()) {
514 cout << "Error: no program running, cannot run!\n";
515 return;
516 }
517
518 unsigned StackSize = ECStack.size();
519 bool HitBreakpoint = false;
520 while (ECStack.size() >= StackSize && !HitBreakpoint) {
521 // Run an instruction...
522 HitBreakpoint = executeInstruction();
523 }
524
525 if (HitBreakpoint) {
526 cout << "Breakpoint hit!\n";
527 }
528
529 // Print the next instruction to execute...
530 printCurrentInstruction();
531}
532
533
534
535// printCurrentInstruction - Print out the instruction that the virtual PC is
536// at, or fail silently if no program is running.
537//
538void Interpreter::printCurrentInstruction() {
539 if (!ECStack.empty()) {
540 Instruction *I = *ECStack.back().CurInst;
541 InstNumber *IN = (InstNumber*)I->getAnnotation(SlotNumberAID);
542 assert(IN && "Instruction has no numbering annotation!");
543 cout << "#" << IN->InstNum << I;
544 }
545}
546
547void Interpreter::printValue(const Type *Ty, GenericValue V) {
548 cout << Ty << " ";
549
550 switch (Ty->getPrimitiveID()) {
551 case Type::BoolTyID: cout << (V.BoolVal?"true":"false"); break;
552 case Type::SByteTyID: cout << V.SByteVal; break;
553 case Type::UByteTyID: cout << V.UByteVal; break;
554 case Type::ShortTyID: cout << V.ShortVal; break;
555 case Type::UShortTyID: cout << V.UShortVal; break;
556 case Type::IntTyID: cout << V.IntVal; break;
557 case Type::UIntTyID: cout << V.UIntVal; break;
558 case Type::FloatTyID: cout << V.FloatVal; break;
559 case Type::DoubleTyID: cout << V.DoubleVal; break;
560 default:
561 cout << "- Don't know how to print value of this type!";
562 break;
563 }
564}
565
566void Interpreter::printValue(const string &Name) {
567 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
568 if (!PickedVal) return;
569
570 if (const Method *M = PickedVal->castMethod()) {
571 cout << M; // Print the method
572 } else { // Otherwise there should be an annotation for the slot#
573 printValue(PickedVal->getType(),
574 getOperandValue(PickedVal, ECStack[CurFrame]));
575 cout << endl;
576 }
577
578}
579
580void Interpreter::list() {
581 if (ECStack.empty())
582 cout << "Error: No program executing!\n";
583 else
584 cout << ECStack[CurFrame].CurMethod; // Just print the method out...
585}
586
587void Interpreter::printStackTrace() {
588 if (ECStack.empty()) cout << "No program executing!\n";
589
590 for (unsigned i = 0; i < ECStack.size(); ++i) {
591 cout << (((int)i == CurFrame) ? '>' : '-');
592 cout << "#" << i << ". " << ECStack[i].CurMethod->getType() << " \""
593 << ECStack[i].CurMethod->getName() << "\"(";
594 // TODO: Print Args
595 cout << ")" << endl;
596 cout << *ECStack[i].CurInst;
597 }
598}