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/Module.h"
10 #include "llvm/Instructions.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/Constants.h"
13 #include "llvm/Assembly/Writer.h"
14 #include "Support/CommandLine.h"
15 #include "Support/Statistic.h"
16 #include <math.h> // For fmod
20 Interpreter *TheEE = 0;
23 Statistic<> NumDynamicInsts("lli", "Number of dynamic instructions executed");
26 QuietMode("quiet", cl::desc("Do not emit any non-program output"),
30 QuietModeA("q", cl::desc("Alias for -quiet"), cl::aliasopt(QuietMode));
33 ArrayChecksEnabled("array-checks", cl::desc("Enable array bound checks"));
36 // Create a TargetData structure to handle memory addressing and size/alignment
39 CachedWriter CW; // Object to accelerate printing of LLVM
41 sigjmp_buf SignalRecoverBuffer;
42 static bool InInstruction = false;
45 static void SigHandler(int Signal) {
47 siglongjmp(SignalRecoverBuffer, Signal);
51 static void initializeSignalHandlers() {
52 struct sigaction Action;
53 Action.sa_handler = SigHandler;
54 Action.sa_flags = SA_SIGINFO;
55 sigemptyset(&Action.sa_mask);
56 sigaction(SIGSEGV, &Action, 0);
57 sigaction(SIGBUS, &Action, 0);
58 sigaction(SIGINT, &Action, 0);
59 sigaction(SIGFPE, &Action, 0);
63 //===----------------------------------------------------------------------===//
64 // Value Manipulation code
65 //===----------------------------------------------------------------------===//
67 static unsigned getOperandSlot(Value *V) {
68 SlotNumber *SN = (SlotNumber*)V->getAnnotation(SlotNumberAID);
69 assert(SN && "Operand does not have a slot number annotation!");
73 // Operations used by constant expr implementations...
74 static GenericValue executeCastOperation(Value *Src, const Type *DestTy,
75 ExecutionContext &SF);
76 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
80 GenericValue Interpreter::getOperandValue(Value *V, ExecutionContext &SF) {
81 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
82 switch (CE->getOpcode()) {
83 case Instruction::Cast:
84 return executeCastOperation(CE->getOperand(0), CE->getType(), SF);
85 case Instruction::GetElementPtr:
86 return TheEE->executeGEPOperation(CE->getOperand(0), CE->op_begin()+1,
88 case Instruction::Add:
89 return executeAddInst(getOperandValue(CE->getOperand(0), SF),
90 getOperandValue(CE->getOperand(1), SF),
93 std::cerr << "Unhandled ConstantExpr: " << CE << "\n";
95 return GenericValue();
97 } else if (Constant *CPV = dyn_cast<Constant>(V)) {
98 return TheEE->getConstantValue(CPV);
99 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
100 return PTOGV(TheEE->getPointerToGlobal(GV));
102 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
103 unsigned OpSlot = getOperandSlot(V);
104 assert(TyP < SF.Values.size() &&
105 OpSlot < SF.Values[TyP].size() && "Value out of range!");
106 return SF.Values[TyP][getOperandSlot(V)];
110 static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF) {
111 unsigned TyP = V->getType()->getUniqueID(); // TypePlane for value
113 //std::cout << "Setting value: " << &SF.Values[TyP][getOperandSlot(V)]<< "\n";
114 SF.Values[TyP][getOperandSlot(V)] = Val;
117 //===----------------------------------------------------------------------===//
118 // Annotation Wrangling code
119 //===----------------------------------------------------------------------===//
121 void Interpreter::initializeExecutionEngine() {
123 initializeSignalHandlers();
126 //===----------------------------------------------------------------------===//
127 // Binary Instruction Implementations
128 //===----------------------------------------------------------------------===//
130 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
131 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
133 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
136 switch (Ty->getPrimitiveID()) {
137 IMPLEMENT_BINARY_OPERATOR(+, UByte);
138 IMPLEMENT_BINARY_OPERATOR(+, SByte);
139 IMPLEMENT_BINARY_OPERATOR(+, UShort);
140 IMPLEMENT_BINARY_OPERATOR(+, Short);
141 IMPLEMENT_BINARY_OPERATOR(+, UInt);
142 IMPLEMENT_BINARY_OPERATOR(+, Int);
143 IMPLEMENT_BINARY_OPERATOR(+, ULong);
144 IMPLEMENT_BINARY_OPERATOR(+, Long);
145 IMPLEMENT_BINARY_OPERATOR(+, Float);
146 IMPLEMENT_BINARY_OPERATOR(+, Double);
148 std::cout << "Unhandled type for Add instruction: " << *Ty << "\n";
154 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
157 switch (Ty->getPrimitiveID()) {
158 IMPLEMENT_BINARY_OPERATOR(-, UByte);
159 IMPLEMENT_BINARY_OPERATOR(-, SByte);
160 IMPLEMENT_BINARY_OPERATOR(-, UShort);
161 IMPLEMENT_BINARY_OPERATOR(-, Short);
162 IMPLEMENT_BINARY_OPERATOR(-, UInt);
163 IMPLEMENT_BINARY_OPERATOR(-, Int);
164 IMPLEMENT_BINARY_OPERATOR(-, ULong);
165 IMPLEMENT_BINARY_OPERATOR(-, Long);
166 IMPLEMENT_BINARY_OPERATOR(-, Float);
167 IMPLEMENT_BINARY_OPERATOR(-, Double);
169 std::cout << "Unhandled type for Sub instruction: " << *Ty << "\n";
175 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
178 switch (Ty->getPrimitiveID()) {
179 IMPLEMENT_BINARY_OPERATOR(*, UByte);
180 IMPLEMENT_BINARY_OPERATOR(*, SByte);
181 IMPLEMENT_BINARY_OPERATOR(*, UShort);
182 IMPLEMENT_BINARY_OPERATOR(*, Short);
183 IMPLEMENT_BINARY_OPERATOR(*, UInt);
184 IMPLEMENT_BINARY_OPERATOR(*, Int);
185 IMPLEMENT_BINARY_OPERATOR(*, ULong);
186 IMPLEMENT_BINARY_OPERATOR(*, Long);
187 IMPLEMENT_BINARY_OPERATOR(*, Float);
188 IMPLEMENT_BINARY_OPERATOR(*, Double);
190 std::cout << "Unhandled type for Mul instruction: " << Ty << "\n";
196 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2,
199 switch (Ty->getPrimitiveID()) {
200 IMPLEMENT_BINARY_OPERATOR(/, UByte);
201 IMPLEMENT_BINARY_OPERATOR(/, SByte);
202 IMPLEMENT_BINARY_OPERATOR(/, UShort);
203 IMPLEMENT_BINARY_OPERATOR(/, Short);
204 IMPLEMENT_BINARY_OPERATOR(/, UInt);
205 IMPLEMENT_BINARY_OPERATOR(/, Int);
206 IMPLEMENT_BINARY_OPERATOR(/, ULong);
207 IMPLEMENT_BINARY_OPERATOR(/, Long);
208 IMPLEMENT_BINARY_OPERATOR(/, Float);
209 IMPLEMENT_BINARY_OPERATOR(/, Double);
211 std::cout << "Unhandled type for Div instruction: " << *Ty << "\n";
217 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2,
220 switch (Ty->getPrimitiveID()) {
221 IMPLEMENT_BINARY_OPERATOR(%, UByte);
222 IMPLEMENT_BINARY_OPERATOR(%, SByte);
223 IMPLEMENT_BINARY_OPERATOR(%, UShort);
224 IMPLEMENT_BINARY_OPERATOR(%, Short);
225 IMPLEMENT_BINARY_OPERATOR(%, UInt);
226 IMPLEMENT_BINARY_OPERATOR(%, Int);
227 IMPLEMENT_BINARY_OPERATOR(%, ULong);
228 IMPLEMENT_BINARY_OPERATOR(%, Long);
229 case Type::FloatTyID:
230 Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
232 case Type::DoubleTyID:
233 Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
236 std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
242 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
245 switch (Ty->getPrimitiveID()) {
246 IMPLEMENT_BINARY_OPERATOR(&, Bool);
247 IMPLEMENT_BINARY_OPERATOR(&, UByte);
248 IMPLEMENT_BINARY_OPERATOR(&, SByte);
249 IMPLEMENT_BINARY_OPERATOR(&, UShort);
250 IMPLEMENT_BINARY_OPERATOR(&, Short);
251 IMPLEMENT_BINARY_OPERATOR(&, UInt);
252 IMPLEMENT_BINARY_OPERATOR(&, Int);
253 IMPLEMENT_BINARY_OPERATOR(&, ULong);
254 IMPLEMENT_BINARY_OPERATOR(&, Long);
256 std::cout << "Unhandled type for And instruction: " << *Ty << "\n";
263 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
266 switch (Ty->getPrimitiveID()) {
267 IMPLEMENT_BINARY_OPERATOR(|, Bool);
268 IMPLEMENT_BINARY_OPERATOR(|, UByte);
269 IMPLEMENT_BINARY_OPERATOR(|, SByte);
270 IMPLEMENT_BINARY_OPERATOR(|, UShort);
271 IMPLEMENT_BINARY_OPERATOR(|, Short);
272 IMPLEMENT_BINARY_OPERATOR(|, UInt);
273 IMPLEMENT_BINARY_OPERATOR(|, Int);
274 IMPLEMENT_BINARY_OPERATOR(|, ULong);
275 IMPLEMENT_BINARY_OPERATOR(|, Long);
277 std::cout << "Unhandled type for Or instruction: " << *Ty << "\n";
284 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
287 switch (Ty->getPrimitiveID()) {
288 IMPLEMENT_BINARY_OPERATOR(^, Bool);
289 IMPLEMENT_BINARY_OPERATOR(^, UByte);
290 IMPLEMENT_BINARY_OPERATOR(^, SByte);
291 IMPLEMENT_BINARY_OPERATOR(^, UShort);
292 IMPLEMENT_BINARY_OPERATOR(^, Short);
293 IMPLEMENT_BINARY_OPERATOR(^, UInt);
294 IMPLEMENT_BINARY_OPERATOR(^, Int);
295 IMPLEMENT_BINARY_OPERATOR(^, ULong);
296 IMPLEMENT_BINARY_OPERATOR(^, Long);
298 std::cout << "Unhandled type for Xor instruction: " << *Ty << "\n";
305 #define IMPLEMENT_SETCC(OP, TY) \
306 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
308 // Handle pointers specially because they must be compared with only as much
309 // width as the host has. We _do not_ want to be comparing 64 bit values when
310 // running on a 32-bit target, otherwise the upper 32 bits might mess up
311 // comparisons if they contain garbage.
312 #define IMPLEMENT_POINTERSETCC(OP) \
313 case Type::PointerTyID: \
314 Dest.BoolVal = (void*)(intptr_t)Src1.PointerVal OP \
315 (void*)(intptr_t)Src2.PointerVal; break
317 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
320 switch (Ty->getPrimitiveID()) {
321 IMPLEMENT_SETCC(==, UByte);
322 IMPLEMENT_SETCC(==, SByte);
323 IMPLEMENT_SETCC(==, UShort);
324 IMPLEMENT_SETCC(==, Short);
325 IMPLEMENT_SETCC(==, UInt);
326 IMPLEMENT_SETCC(==, Int);
327 IMPLEMENT_SETCC(==, ULong);
328 IMPLEMENT_SETCC(==, Long);
329 IMPLEMENT_SETCC(==, Float);
330 IMPLEMENT_SETCC(==, Double);
331 IMPLEMENT_POINTERSETCC(==);
333 std::cout << "Unhandled type for SetEQ instruction: " << *Ty << "\n";
339 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
342 switch (Ty->getPrimitiveID()) {
343 IMPLEMENT_SETCC(!=, UByte);
344 IMPLEMENT_SETCC(!=, SByte);
345 IMPLEMENT_SETCC(!=, UShort);
346 IMPLEMENT_SETCC(!=, Short);
347 IMPLEMENT_SETCC(!=, UInt);
348 IMPLEMENT_SETCC(!=, Int);
349 IMPLEMENT_SETCC(!=, ULong);
350 IMPLEMENT_SETCC(!=, Long);
351 IMPLEMENT_SETCC(!=, Float);
352 IMPLEMENT_SETCC(!=, Double);
353 IMPLEMENT_POINTERSETCC(!=);
356 std::cout << "Unhandled type for SetNE instruction: " << *Ty << "\n";
362 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
365 switch (Ty->getPrimitiveID()) {
366 IMPLEMENT_SETCC(<=, UByte);
367 IMPLEMENT_SETCC(<=, SByte);
368 IMPLEMENT_SETCC(<=, UShort);
369 IMPLEMENT_SETCC(<=, Short);
370 IMPLEMENT_SETCC(<=, UInt);
371 IMPLEMENT_SETCC(<=, Int);
372 IMPLEMENT_SETCC(<=, ULong);
373 IMPLEMENT_SETCC(<=, Long);
374 IMPLEMENT_SETCC(<=, Float);
375 IMPLEMENT_SETCC(<=, Double);
376 IMPLEMENT_POINTERSETCC(<=);
378 std::cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
384 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
387 switch (Ty->getPrimitiveID()) {
388 IMPLEMENT_SETCC(>=, UByte);
389 IMPLEMENT_SETCC(>=, SByte);
390 IMPLEMENT_SETCC(>=, UShort);
391 IMPLEMENT_SETCC(>=, Short);
392 IMPLEMENT_SETCC(>=, UInt);
393 IMPLEMENT_SETCC(>=, Int);
394 IMPLEMENT_SETCC(>=, ULong);
395 IMPLEMENT_SETCC(>=, Long);
396 IMPLEMENT_SETCC(>=, Float);
397 IMPLEMENT_SETCC(>=, Double);
398 IMPLEMENT_POINTERSETCC(>=);
400 std::cout << "Unhandled type for SetGE instruction: " << *Ty << "\n";
406 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
409 switch (Ty->getPrimitiveID()) {
410 IMPLEMENT_SETCC(<, UByte);
411 IMPLEMENT_SETCC(<, SByte);
412 IMPLEMENT_SETCC(<, UShort);
413 IMPLEMENT_SETCC(<, Short);
414 IMPLEMENT_SETCC(<, UInt);
415 IMPLEMENT_SETCC(<, Int);
416 IMPLEMENT_SETCC(<, ULong);
417 IMPLEMENT_SETCC(<, Long);
418 IMPLEMENT_SETCC(<, Float);
419 IMPLEMENT_SETCC(<, Double);
420 IMPLEMENT_POINTERSETCC(<);
422 std::cout << "Unhandled type for SetLT instruction: " << *Ty << "\n";
428 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
431 switch (Ty->getPrimitiveID()) {
432 IMPLEMENT_SETCC(>, UByte);
433 IMPLEMENT_SETCC(>, SByte);
434 IMPLEMENT_SETCC(>, UShort);
435 IMPLEMENT_SETCC(>, Short);
436 IMPLEMENT_SETCC(>, UInt);
437 IMPLEMENT_SETCC(>, Int);
438 IMPLEMENT_SETCC(>, ULong);
439 IMPLEMENT_SETCC(>, Long);
440 IMPLEMENT_SETCC(>, Float);
441 IMPLEMENT_SETCC(>, Double);
442 IMPLEMENT_POINTERSETCC(>);
444 std::cout << "Unhandled type for SetGT instruction: " << *Ty << "\n";
450 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
451 ExecutionContext &SF = ECStack.back();
452 const Type *Ty = I.getOperand(0)->getType();
453 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
454 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
455 GenericValue R; // Result
457 switch (I.getOpcode()) {
458 case Instruction::Add: R = executeAddInst (Src1, Src2, Ty); break;
459 case Instruction::Sub: R = executeSubInst (Src1, Src2, Ty); break;
460 case Instruction::Mul: R = executeMulInst (Src1, Src2, Ty); break;
461 case Instruction::Div: R = executeDivInst (Src1, Src2, Ty); break;
462 case Instruction::Rem: R = executeRemInst (Src1, Src2, Ty); break;
463 case Instruction::And: R = executeAndInst (Src1, Src2, Ty); break;
464 case Instruction::Or: R = executeOrInst (Src1, Src2, Ty); break;
465 case Instruction::Xor: R = executeXorInst (Src1, Src2, Ty); break;
466 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty); break;
467 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty); break;
468 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty); break;
469 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty); break;
470 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty); break;
471 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty); break;
473 std::cout << "Don't know how to handle this binary operator!\n-->" << I;
480 //===----------------------------------------------------------------------===//
481 // Terminator Instruction Implementations
482 //===----------------------------------------------------------------------===//
484 void Interpreter::exitCalled(GenericValue GV) {
486 std::cout << "Program returned ";
487 print(Type::IntTy, GV);
488 std::cout << " via 'void exit(int)'\n";
491 ExitCode = GV.SByteVal;
495 void Interpreter::visitReturnInst(ReturnInst &I) {
496 ExecutionContext &SF = ECStack.back();
497 const Type *RetTy = 0;
500 // Save away the return value... (if we are not 'ret void')
501 if (I.getNumOperands()) {
502 RetTy = I.getReturnValue()->getType();
503 Result = getOperandValue(I.getReturnValue(), SF);
506 // Save previously executing meth
507 const Function *M = ECStack.back().CurFunction;
509 // Pop the current stack frame... this invalidates SF
512 if (ECStack.empty()) { // Finished main. Put result into exit code...
513 if (RetTy) { // Nonvoid return type?
515 CW << "Function " << M->getType() << " \"" << M->getName()
517 print(RetTy, Result);
521 if (RetTy->isIntegral())
522 ExitCode = Result.IntVal; // Capture the exit code of the program
529 // If we have a previous stack frame, and we have a previous call, fill in
530 // the return value...
532 ExecutionContext &NewSF = ECStack.back();
534 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
535 SetValue(NewSF.Caller, Result, NewSF);
537 NewSF.Caller = 0; // We returned from the call...
538 } else if (!QuietMode) {
539 // This must be a function that is executing because of a user 'call'
541 CW << "Function " << M->getType() << " \"" << M->getName()
543 print(RetTy, Result);
548 void Interpreter::visitBranchInst(BranchInst &I) {
549 ExecutionContext &SF = ECStack.back();
552 Dest = I.getSuccessor(0); // Uncond branches have a fixed dest...
553 if (!I.isUnconditional()) {
554 Value *Cond = I.getCondition();
555 if (getOperandValue(Cond, SF).BoolVal == 0) // If false cond...
556 Dest = I.getSuccessor(1);
558 SwitchToNewBasicBlock(Dest, SF);
561 void Interpreter::visitSwitchInst(SwitchInst &I) {
562 ExecutionContext &SF = ECStack.back();
563 GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
564 const Type *ElTy = I.getOperand(0)->getType();
566 // Check to see if any of the cases match...
567 BasicBlock *Dest = 0;
568 for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
569 if (executeSetEQInst(CondVal,
570 getOperandValue(I.getOperand(i), SF), ElTy).BoolVal) {
571 Dest = cast<BasicBlock>(I.getOperand(i+1));
575 if (!Dest) Dest = I.getDefaultDest(); // No cases matched: use default
576 SwitchToNewBasicBlock(Dest, SF);
579 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
580 // This function handles the actual updating of block and instruction iterators
581 // as well as execution of all of the PHI nodes in the destination block.
583 // This method does this because all of the PHI nodes must be executed
584 // atomically, reading their inputs before any of the results are updated. Not
585 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
586 // their inputs. If the input PHI node is updated before it is read, incorrect
587 // results can happen. Thus we use a two phase approach.
589 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
590 BasicBlock *PrevBB = SF.CurBB; // Remember where we came from...
591 SF.CurBB = Dest; // Update CurBB to branch destination
592 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
594 if (!isa<PHINode>(SF.CurInst)) return; // Nothing fancy to do
596 // Loop over all of the PHI nodes in the current block, reading their inputs.
597 std::vector<GenericValue> ResultValues;
599 for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
600 if (Trace) CW << "Run:" << PN;
602 // Search for the value corresponding to this previous bb...
603 int i = PN->getBasicBlockIndex(PrevBB);
604 assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
605 Value *IncomingValue = PN->getIncomingValue(i);
607 // Save the incoming value for this PHI node...
608 ResultValues.push_back(getOperandValue(IncomingValue, SF));
611 // Now loop over all of the PHI nodes setting their values...
612 SF.CurInst = SF.CurBB->begin();
613 for (unsigned i = 0; PHINode *PN = dyn_cast<PHINode>(SF.CurInst);
615 SetValue(PN, ResultValues[i], SF);
619 //===----------------------------------------------------------------------===//
620 // Memory Instruction Implementations
621 //===----------------------------------------------------------------------===//
623 void Interpreter::visitAllocationInst(AllocationInst &I) {
624 ExecutionContext &SF = ECStack.back();
626 const Type *Ty = I.getType()->getElementType(); // Type to be allocated
628 // Get the number of elements being allocated by the array...
629 unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
631 // Allocate enough memory to hold the type...
632 // FIXME: Don't use CALLOC, use a tainted malloc.
633 void *Memory = calloc(NumElements, TD.getTypeSize(Ty));
635 GenericValue Result = PTOGV(Memory);
636 assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
637 SetValue(&I, Result, SF);
639 if (I.getOpcode() == Instruction::Alloca)
640 ECStack.back().Allocas.add(Memory);
643 void Interpreter::visitFreeInst(FreeInst &I) {
644 ExecutionContext &SF = ECStack.back();
645 assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
646 GenericValue Value = getOperandValue(I.getOperand(0), SF);
647 // TODO: Check to make sure memory is allocated
648 free(GVTOP(Value)); // Free memory
652 // getElementOffset - The workhorse for getelementptr.
654 GenericValue Interpreter::executeGEPOperation(Value *Ptr, User::op_iterator I,
656 ExecutionContext &SF) {
657 assert(isa<PointerType>(Ptr->getType()) &&
658 "Cannot getElementOffset of a nonpointer type!");
661 const Type *Ty = Ptr->getType();
663 for (; I != E; ++I) {
664 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
665 const StructLayout *SLO = TD.getStructLayout(STy);
667 // Indicies must be ubyte constants...
668 const ConstantUInt *CPU = cast<ConstantUInt>(*I);
669 assert(CPU->getType() == Type::UByteTy);
670 unsigned Index = CPU->getValue();
672 Total += SLO->MemberOffsets[Index];
673 Ty = STy->getElementTypes()[Index];
674 } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
676 // Get the index number for the array... which must be long type...
677 assert((*I)->getType() == Type::LongTy);
678 unsigned Idx = getOperandValue(*I, SF).LongVal;
679 if (const ArrayType *AT = dyn_cast<ArrayType>(ST))
680 if (Idx >= AT->getNumElements() && ArrayChecksEnabled) {
681 std::cerr << "Out of range memory access to element #" << Idx
682 << " of a " << AT->getNumElements() << " element array."
683 << " Subscript #" << *I << "\n";
685 siglongjmp(SignalRecoverBuffer, SIGTRAP);
688 Ty = ST->getElementType();
689 unsigned Size = TD.getTypeSize(Ty);
695 Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
699 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
700 ExecutionContext &SF = ECStack.back();
701 SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
702 I.idx_begin(), I.idx_end(), SF), SF);
705 void Interpreter::visitLoadInst(LoadInst &I) {
706 ExecutionContext &SF = ECStack.back();
707 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
708 GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
709 GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
710 SetValue(&I, Result, SF);
713 void Interpreter::visitStoreInst(StoreInst &I) {
714 ExecutionContext &SF = ECStack.back();
715 GenericValue Val = getOperandValue(I.getOperand(0), SF);
716 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
717 StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
718 I.getOperand(0)->getType());
723 //===----------------------------------------------------------------------===//
724 // Miscellaneous Instruction Implementations
725 //===----------------------------------------------------------------------===//
727 void Interpreter::visitCallInst(CallInst &I) {
728 ExecutionContext &SF = ECStack.back();
730 std::vector<GenericValue> ArgVals;
731 ArgVals.reserve(I.getNumOperands()-1);
732 for (unsigned i = 1; i < I.getNumOperands(); ++i) {
733 ArgVals.push_back(getOperandValue(I.getOperand(i), SF));
734 // Promote all integral types whose size is < sizeof(int) into ints. We do
735 // this by zero or sign extending the value as appropriate according to the
737 if (I.getOperand(i)->getType()->isIntegral() &&
738 I.getOperand(i)->getType()->getPrimitiveSize() < 4) {
739 const Type *Ty = I.getOperand(i)->getType();
740 if (Ty == Type::ShortTy)
741 ArgVals.back().IntVal = ArgVals.back().ShortVal;
742 else if (Ty == Type::UShortTy)
743 ArgVals.back().UIntVal = ArgVals.back().UShortVal;
744 else if (Ty == Type::SByteTy)
745 ArgVals.back().IntVal = ArgVals.back().SByteVal;
746 else if (Ty == Type::UByteTy)
747 ArgVals.back().UIntVal = ArgVals.back().UByteVal;
748 else if (Ty == Type::BoolTy)
749 ArgVals.back().UIntVal = ArgVals.back().BoolVal;
751 assert(0 && "Unknown type!");
755 // To handle indirect calls, we must get the pointer value from the argument
756 // and treat it as a function pointer.
757 GenericValue SRC = getOperandValue(I.getCalledValue(), SF);
758 callFunction((Function*)GVTOP(SRC), ArgVals);
761 #define IMPLEMENT_SHIFT(OP, TY) \
762 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
764 void Interpreter::visitShl(ShiftInst &I) {
765 ExecutionContext &SF = ECStack.back();
766 const Type *Ty = I.getOperand(0)->getType();
767 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
768 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
771 switch (Ty->getPrimitiveID()) {
772 IMPLEMENT_SHIFT(<<, UByte);
773 IMPLEMENT_SHIFT(<<, SByte);
774 IMPLEMENT_SHIFT(<<, UShort);
775 IMPLEMENT_SHIFT(<<, Short);
776 IMPLEMENT_SHIFT(<<, UInt);
777 IMPLEMENT_SHIFT(<<, Int);
778 IMPLEMENT_SHIFT(<<, ULong);
779 IMPLEMENT_SHIFT(<<, Long);
781 std::cout << "Unhandled type for Shl instruction: " << *Ty << "\n";
783 SetValue(&I, Dest, SF);
786 void Interpreter::visitShr(ShiftInst &I) {
787 ExecutionContext &SF = ECStack.back();
788 const Type *Ty = I.getOperand(0)->getType();
789 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
790 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
793 switch (Ty->getPrimitiveID()) {
794 IMPLEMENT_SHIFT(>>, UByte);
795 IMPLEMENT_SHIFT(>>, SByte);
796 IMPLEMENT_SHIFT(>>, UShort);
797 IMPLEMENT_SHIFT(>>, Short);
798 IMPLEMENT_SHIFT(>>, UInt);
799 IMPLEMENT_SHIFT(>>, Int);
800 IMPLEMENT_SHIFT(>>, ULong);
801 IMPLEMENT_SHIFT(>>, Long);
803 std::cout << "Unhandled type for Shr instruction: " << *Ty << "\n";
806 SetValue(&I, Dest, SF);
809 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
810 case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
812 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY) \
813 case Type::DESTTY##TyID: \
814 switch (SrcTy->getPrimitiveID()) { \
815 IMPLEMENT_CAST(DESTTY, DESTCTY, Bool); \
816 IMPLEMENT_CAST(DESTTY, DESTCTY, UByte); \
817 IMPLEMENT_CAST(DESTTY, DESTCTY, SByte); \
818 IMPLEMENT_CAST(DESTTY, DESTCTY, UShort); \
819 IMPLEMENT_CAST(DESTTY, DESTCTY, Short); \
820 IMPLEMENT_CAST(DESTTY, DESTCTY, UInt); \
821 IMPLEMENT_CAST(DESTTY, DESTCTY, Int); \
822 IMPLEMENT_CAST(DESTTY, DESTCTY, ULong); \
823 IMPLEMENT_CAST(DESTTY, DESTCTY, Long); \
824 IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
826 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
827 IMPLEMENT_CAST(DESTTY, DESTCTY, Float); \
828 IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
830 #define IMPLEMENT_CAST_CASE_END() \
831 default: std::cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
836 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
837 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
838 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
839 IMPLEMENT_CAST_CASE_END()
841 GenericValue Interpreter::executeCastOperation(Value *SrcVal, const Type *Ty,
842 ExecutionContext &SF) {
843 const Type *SrcTy = SrcVal->getType();
844 GenericValue Dest, Src = getOperandValue(SrcVal, SF);
846 switch (Ty->getPrimitiveID()) {
847 IMPLEMENT_CAST_CASE(UByte , (unsigned char));
848 IMPLEMENT_CAST_CASE(SByte , ( signed char));
849 IMPLEMENT_CAST_CASE(UShort , (unsigned short));
850 IMPLEMENT_CAST_CASE(Short , ( signed short));
851 IMPLEMENT_CAST_CASE(UInt , (unsigned int ));
852 IMPLEMENT_CAST_CASE(Int , ( signed int ));
853 IMPLEMENT_CAST_CASE(ULong , (uint64_t));
854 IMPLEMENT_CAST_CASE(Long , ( int64_t));
855 IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
856 IMPLEMENT_CAST_CASE(Float , (float));
857 IMPLEMENT_CAST_CASE(Double , (double));
858 IMPLEMENT_CAST_CASE(Bool , (bool));
860 std::cout << "Unhandled dest type for cast instruction: " << *Ty << "\n";
868 void Interpreter::visitCastInst(CastInst &I) {
869 ExecutionContext &SF = ECStack.back();
870 SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
873 void Interpreter::visitVarArgInst(VarArgInst &I) {
874 ExecutionContext &SF = ECStack.back();
876 // Get the pointer to the valist element. LLI treats the valist in memory as
878 GenericValue VAListPtr = getOperandValue(I.getOperand(0), SF);
881 GenericValue VAList =
882 TheEE->LoadValueFromMemory((GenericValue *)GVTOP(VAListPtr), Type::UIntTy);
884 unsigned Argument = VAList.IntVal++;
886 // Update the valist to point to the next argument...
887 TheEE->StoreValueToMemory(VAList, (GenericValue *)GVTOP(VAListPtr),
891 assert(Argument < SF.VarArgs.size() &&
892 "Accessing past the last vararg argument!");
893 SetValue(&I, SF.VarArgs[Argument], SF);
896 //===----------------------------------------------------------------------===//
897 // Dispatch and Execution Code
898 //===----------------------------------------------------------------------===//
900 FunctionInfo::FunctionInfo(Function *F) {
901 // Assign slot numbers to the function arguments...
902 for (Function::const_aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
903 AI->addAnnotation(new SlotNumber(getValueSlot(AI)));
905 // Iterate over all of the instructions...
906 unsigned InstNum = 0;
907 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
908 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II)
909 // For each instruction... Add Annote
910 II->addAnnotation(new InstNumber(++InstNum, getValueSlot(II)));
913 unsigned FunctionInfo::getValueSlot(const Value *V) {
914 unsigned Plane = V->getType()->getUniqueID();
915 if (Plane >= NumPlaneElements.size())
916 NumPlaneElements.resize(Plane+1, 0);
917 return NumPlaneElements[Plane]++;
921 //===----------------------------------------------------------------------===//
922 // callFunction - Execute the specified function...
924 void Interpreter::callFunction(Function *F,
925 const std::vector<GenericValue> &ArgVals) {
926 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
927 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
928 "Incorrect number of arguments passed into function call!");
929 if (F->isExternal()) {
930 GenericValue Result = callExternalFunction(F, ArgVals);
931 const Type *RetTy = F->getReturnType();
933 // Copy the result back into the result variable if we are not returning
935 if (RetTy != Type::VoidTy) {
936 if (!ECStack.empty() && ECStack.back().Caller) {
937 ExecutionContext &SF = ECStack.back();
938 SetValue(SF.Caller, Result, SF);
940 SF.Caller = 0; // We returned from the call...
941 } else if (!QuietMode) {
943 CW << "Function " << F->getType() << " \"" << F->getName()
945 print(RetTy, Result);
948 if (RetTy->isIntegral())
949 ExitCode = Result.IntVal; // Capture the exit code of the program
956 // Process the function, assigning instruction numbers to the instructions in
957 // the function. Also calculate the number of values for each type slot
960 FunctionInfo *&FuncInfo = FunctionInfoMap[F];
961 if (!FuncInfo) FuncInfo = new FunctionInfo(F);
963 // Make a new stack frame... and fill it in.
964 ECStack.push_back(ExecutionContext());
965 ExecutionContext &StackFrame = ECStack.back();
966 StackFrame.CurFunction = F;
967 StackFrame.CurBB = F->begin();
968 StackFrame.CurInst = StackFrame.CurBB->begin();
969 StackFrame.FuncInfo = FuncInfo;
971 // Initialize the values to nothing...
972 StackFrame.Values.resize(FuncInfo->NumPlaneElements.size());
973 for (unsigned i = 0; i < FuncInfo->NumPlaneElements.size(); ++i) {
974 StackFrame.Values[i].resize(FuncInfo->NumPlaneElements[i]);
976 // Taint the initial values of stuff
977 memset(&StackFrame.Values[i][0], 42,
978 FuncInfo->NumPlaneElements[i]*sizeof(GenericValue));
982 // Run through the function arguments and initialize their values...
983 assert((ArgVals.size() == F->asize() ||
984 (ArgVals.size() > F->asize() && F->getFunctionType()->isVarArg())) &&
985 "Invalid number of values passed to function invocation!");
987 // Handle non-varargs arguments...
989 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI, ++i)
990 SetValue(AI, ArgVals[i], StackFrame);
992 // Handle varargs arguments...
993 StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
996 // executeInstruction - Interpret a single instruction & increment the "PC".
998 void Interpreter::executeInstruction() {
999 assert(!ECStack.empty() && "No program running, cannot execute inst!");
1001 ExecutionContext &SF = ECStack.back(); // Current stack frame
1002 Instruction &I = *SF.CurInst++; // Increment before execute
1004 if (Trace) CW << "Run:" << I;
1006 // Track the number of dynamic instructions executed.
1009 // Set a sigsetjmp buffer so that we can recover if an error happens during
1010 // instruction execution...
1012 if (int SigNo = sigsetjmp(SignalRecoverBuffer, 1)) {
1013 std::cout << "EXCEPTION OCCURRED [" << strsignal(SigNo) << "]\n";
1017 InInstruction = true;
1018 visit(I); // Dispatch to one of the visit* methods...
1019 InInstruction = false;
1021 // Reset the current frame location to the top of stack
1022 CurFrame = ECStack.size()-1;
1025 void Interpreter::run() {
1026 while (!ECStack.empty()) {
1027 // Run an instruction...
1028 executeInstruction();
1032 void Interpreter::printValue(const Type *Ty, GenericValue V) {
1033 switch (Ty->getPrimitiveID()) {
1034 case Type::BoolTyID: std::cout << (V.BoolVal?"true":"false"); break;
1035 case Type::SByteTyID:
1036 std::cout << (int)V.SByteVal << " '" << V.SByteVal << "'"; break;
1037 case Type::UByteTyID:
1038 std::cout << (unsigned)V.UByteVal << " '" << V.UByteVal << "'"; break;
1039 case Type::ShortTyID: std::cout << V.ShortVal; break;
1040 case Type::UShortTyID: std::cout << V.UShortVal; break;
1041 case Type::IntTyID: std::cout << V.IntVal; break;
1042 case Type::UIntTyID: std::cout << V.UIntVal; break;
1043 case Type::LongTyID: std::cout << (long)V.LongVal; break;
1044 case Type::ULongTyID: std::cout << (unsigned long)V.ULongVal; break;
1045 case Type::FloatTyID: std::cout << V.FloatVal; break;
1046 case Type::DoubleTyID: std::cout << V.DoubleVal; break;
1047 case Type::PointerTyID:std::cout << (void*)GVTOP(V); break;
1049 std::cout << "- Don't know how to print value of this type!";
1054 void Interpreter::print(const Type *Ty, GenericValue V) {