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 AnnotationManager::registerAnnotationFactory(FunctionInfoAID,
124 &FunctionInfo::Create);
125 initializeSignalHandlers();
128 //===----------------------------------------------------------------------===//
129 // Binary Instruction Implementations
130 //===----------------------------------------------------------------------===//
132 #define IMPLEMENT_BINARY_OPERATOR(OP, TY) \
133 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.TY##Val; break
135 static GenericValue executeAddInst(GenericValue Src1, GenericValue Src2,
138 switch (Ty->getPrimitiveID()) {
139 IMPLEMENT_BINARY_OPERATOR(+, UByte);
140 IMPLEMENT_BINARY_OPERATOR(+, SByte);
141 IMPLEMENT_BINARY_OPERATOR(+, UShort);
142 IMPLEMENT_BINARY_OPERATOR(+, Short);
143 IMPLEMENT_BINARY_OPERATOR(+, UInt);
144 IMPLEMENT_BINARY_OPERATOR(+, Int);
145 IMPLEMENT_BINARY_OPERATOR(+, ULong);
146 IMPLEMENT_BINARY_OPERATOR(+, Long);
147 IMPLEMENT_BINARY_OPERATOR(+, Float);
148 IMPLEMENT_BINARY_OPERATOR(+, Double);
150 std::cout << "Unhandled type for Add instruction: " << *Ty << "\n";
156 static GenericValue executeSubInst(GenericValue Src1, GenericValue Src2,
159 switch (Ty->getPrimitiveID()) {
160 IMPLEMENT_BINARY_OPERATOR(-, UByte);
161 IMPLEMENT_BINARY_OPERATOR(-, SByte);
162 IMPLEMENT_BINARY_OPERATOR(-, UShort);
163 IMPLEMENT_BINARY_OPERATOR(-, Short);
164 IMPLEMENT_BINARY_OPERATOR(-, UInt);
165 IMPLEMENT_BINARY_OPERATOR(-, Int);
166 IMPLEMENT_BINARY_OPERATOR(-, ULong);
167 IMPLEMENT_BINARY_OPERATOR(-, Long);
168 IMPLEMENT_BINARY_OPERATOR(-, Float);
169 IMPLEMENT_BINARY_OPERATOR(-, Double);
171 std::cout << "Unhandled type for Sub instruction: " << *Ty << "\n";
177 static GenericValue executeMulInst(GenericValue Src1, GenericValue Src2,
180 switch (Ty->getPrimitiveID()) {
181 IMPLEMENT_BINARY_OPERATOR(*, UByte);
182 IMPLEMENT_BINARY_OPERATOR(*, SByte);
183 IMPLEMENT_BINARY_OPERATOR(*, UShort);
184 IMPLEMENT_BINARY_OPERATOR(*, Short);
185 IMPLEMENT_BINARY_OPERATOR(*, UInt);
186 IMPLEMENT_BINARY_OPERATOR(*, Int);
187 IMPLEMENT_BINARY_OPERATOR(*, ULong);
188 IMPLEMENT_BINARY_OPERATOR(*, Long);
189 IMPLEMENT_BINARY_OPERATOR(*, Float);
190 IMPLEMENT_BINARY_OPERATOR(*, Double);
192 std::cout << "Unhandled type for Mul instruction: " << Ty << "\n";
198 static GenericValue executeDivInst(GenericValue Src1, GenericValue Src2,
201 switch (Ty->getPrimitiveID()) {
202 IMPLEMENT_BINARY_OPERATOR(/, UByte);
203 IMPLEMENT_BINARY_OPERATOR(/, SByte);
204 IMPLEMENT_BINARY_OPERATOR(/, UShort);
205 IMPLEMENT_BINARY_OPERATOR(/, Short);
206 IMPLEMENT_BINARY_OPERATOR(/, UInt);
207 IMPLEMENT_BINARY_OPERATOR(/, Int);
208 IMPLEMENT_BINARY_OPERATOR(/, ULong);
209 IMPLEMENT_BINARY_OPERATOR(/, Long);
210 IMPLEMENT_BINARY_OPERATOR(/, Float);
211 IMPLEMENT_BINARY_OPERATOR(/, Double);
213 std::cout << "Unhandled type for Div instruction: " << *Ty << "\n";
219 static GenericValue executeRemInst(GenericValue Src1, GenericValue Src2,
222 switch (Ty->getPrimitiveID()) {
223 IMPLEMENT_BINARY_OPERATOR(%, UByte);
224 IMPLEMENT_BINARY_OPERATOR(%, SByte);
225 IMPLEMENT_BINARY_OPERATOR(%, UShort);
226 IMPLEMENT_BINARY_OPERATOR(%, Short);
227 IMPLEMENT_BINARY_OPERATOR(%, UInt);
228 IMPLEMENT_BINARY_OPERATOR(%, Int);
229 IMPLEMENT_BINARY_OPERATOR(%, ULong);
230 IMPLEMENT_BINARY_OPERATOR(%, Long);
231 case Type::FloatTyID:
232 Dest.FloatVal = fmod(Src1.FloatVal, Src2.FloatVal);
234 case Type::DoubleTyID:
235 Dest.DoubleVal = fmod(Src1.DoubleVal, Src2.DoubleVal);
238 std::cout << "Unhandled type for Rem instruction: " << *Ty << "\n";
244 static GenericValue executeAndInst(GenericValue Src1, GenericValue Src2,
247 switch (Ty->getPrimitiveID()) {
248 IMPLEMENT_BINARY_OPERATOR(&, Bool);
249 IMPLEMENT_BINARY_OPERATOR(&, UByte);
250 IMPLEMENT_BINARY_OPERATOR(&, SByte);
251 IMPLEMENT_BINARY_OPERATOR(&, UShort);
252 IMPLEMENT_BINARY_OPERATOR(&, Short);
253 IMPLEMENT_BINARY_OPERATOR(&, UInt);
254 IMPLEMENT_BINARY_OPERATOR(&, Int);
255 IMPLEMENT_BINARY_OPERATOR(&, ULong);
256 IMPLEMENT_BINARY_OPERATOR(&, Long);
258 std::cout << "Unhandled type for And instruction: " << *Ty << "\n";
265 static GenericValue executeOrInst(GenericValue Src1, GenericValue Src2,
268 switch (Ty->getPrimitiveID()) {
269 IMPLEMENT_BINARY_OPERATOR(|, Bool);
270 IMPLEMENT_BINARY_OPERATOR(|, UByte);
271 IMPLEMENT_BINARY_OPERATOR(|, SByte);
272 IMPLEMENT_BINARY_OPERATOR(|, UShort);
273 IMPLEMENT_BINARY_OPERATOR(|, Short);
274 IMPLEMENT_BINARY_OPERATOR(|, UInt);
275 IMPLEMENT_BINARY_OPERATOR(|, Int);
276 IMPLEMENT_BINARY_OPERATOR(|, ULong);
277 IMPLEMENT_BINARY_OPERATOR(|, Long);
279 std::cout << "Unhandled type for Or instruction: " << *Ty << "\n";
286 static GenericValue executeXorInst(GenericValue Src1, GenericValue Src2,
289 switch (Ty->getPrimitiveID()) {
290 IMPLEMENT_BINARY_OPERATOR(^, Bool);
291 IMPLEMENT_BINARY_OPERATOR(^, UByte);
292 IMPLEMENT_BINARY_OPERATOR(^, SByte);
293 IMPLEMENT_BINARY_OPERATOR(^, UShort);
294 IMPLEMENT_BINARY_OPERATOR(^, Short);
295 IMPLEMENT_BINARY_OPERATOR(^, UInt);
296 IMPLEMENT_BINARY_OPERATOR(^, Int);
297 IMPLEMENT_BINARY_OPERATOR(^, ULong);
298 IMPLEMENT_BINARY_OPERATOR(^, Long);
300 std::cout << "Unhandled type for Xor instruction: " << *Ty << "\n";
307 #define IMPLEMENT_SETCC(OP, TY) \
308 case Type::TY##TyID: Dest.BoolVal = Src1.TY##Val OP Src2.TY##Val; break
310 // Handle pointers specially because they must be compared with only as much
311 // width as the host has. We _do not_ want to be comparing 64 bit values when
312 // running on a 32-bit target, otherwise the upper 32 bits might mess up
313 // comparisons if they contain garbage.
314 #define IMPLEMENT_POINTERSETCC(OP) \
315 case Type::PointerTyID: \
316 Dest.BoolVal = (void*)(intptr_t)Src1.PointerVal OP \
317 (void*)(intptr_t)Src2.PointerVal; break
319 static GenericValue executeSetEQInst(GenericValue Src1, GenericValue Src2,
322 switch (Ty->getPrimitiveID()) {
323 IMPLEMENT_SETCC(==, UByte);
324 IMPLEMENT_SETCC(==, SByte);
325 IMPLEMENT_SETCC(==, UShort);
326 IMPLEMENT_SETCC(==, Short);
327 IMPLEMENT_SETCC(==, UInt);
328 IMPLEMENT_SETCC(==, Int);
329 IMPLEMENT_SETCC(==, ULong);
330 IMPLEMENT_SETCC(==, Long);
331 IMPLEMENT_SETCC(==, Float);
332 IMPLEMENT_SETCC(==, Double);
333 IMPLEMENT_POINTERSETCC(==);
335 std::cout << "Unhandled type for SetEQ instruction: " << *Ty << "\n";
341 static GenericValue executeSetNEInst(GenericValue Src1, GenericValue Src2,
344 switch (Ty->getPrimitiveID()) {
345 IMPLEMENT_SETCC(!=, UByte);
346 IMPLEMENT_SETCC(!=, SByte);
347 IMPLEMENT_SETCC(!=, UShort);
348 IMPLEMENT_SETCC(!=, Short);
349 IMPLEMENT_SETCC(!=, UInt);
350 IMPLEMENT_SETCC(!=, Int);
351 IMPLEMENT_SETCC(!=, ULong);
352 IMPLEMENT_SETCC(!=, Long);
353 IMPLEMENT_SETCC(!=, Float);
354 IMPLEMENT_SETCC(!=, Double);
355 IMPLEMENT_POINTERSETCC(!=);
358 std::cout << "Unhandled type for SetNE instruction: " << *Ty << "\n";
364 static GenericValue executeSetLEInst(GenericValue Src1, GenericValue Src2,
367 switch (Ty->getPrimitiveID()) {
368 IMPLEMENT_SETCC(<=, UByte);
369 IMPLEMENT_SETCC(<=, SByte);
370 IMPLEMENT_SETCC(<=, UShort);
371 IMPLEMENT_SETCC(<=, Short);
372 IMPLEMENT_SETCC(<=, UInt);
373 IMPLEMENT_SETCC(<=, Int);
374 IMPLEMENT_SETCC(<=, ULong);
375 IMPLEMENT_SETCC(<=, Long);
376 IMPLEMENT_SETCC(<=, Float);
377 IMPLEMENT_SETCC(<=, Double);
378 IMPLEMENT_POINTERSETCC(<=);
380 std::cout << "Unhandled type for SetLE instruction: " << Ty << "\n";
386 static GenericValue executeSetGEInst(GenericValue Src1, GenericValue Src2,
389 switch (Ty->getPrimitiveID()) {
390 IMPLEMENT_SETCC(>=, UByte);
391 IMPLEMENT_SETCC(>=, SByte);
392 IMPLEMENT_SETCC(>=, UShort);
393 IMPLEMENT_SETCC(>=, Short);
394 IMPLEMENT_SETCC(>=, UInt);
395 IMPLEMENT_SETCC(>=, Int);
396 IMPLEMENT_SETCC(>=, ULong);
397 IMPLEMENT_SETCC(>=, Long);
398 IMPLEMENT_SETCC(>=, Float);
399 IMPLEMENT_SETCC(>=, Double);
400 IMPLEMENT_POINTERSETCC(>=);
402 std::cout << "Unhandled type for SetGE instruction: " << *Ty << "\n";
408 static GenericValue executeSetLTInst(GenericValue Src1, GenericValue Src2,
411 switch (Ty->getPrimitiveID()) {
412 IMPLEMENT_SETCC(<, UByte);
413 IMPLEMENT_SETCC(<, SByte);
414 IMPLEMENT_SETCC(<, UShort);
415 IMPLEMENT_SETCC(<, Short);
416 IMPLEMENT_SETCC(<, UInt);
417 IMPLEMENT_SETCC(<, Int);
418 IMPLEMENT_SETCC(<, ULong);
419 IMPLEMENT_SETCC(<, Long);
420 IMPLEMENT_SETCC(<, Float);
421 IMPLEMENT_SETCC(<, Double);
422 IMPLEMENT_POINTERSETCC(<);
424 std::cout << "Unhandled type for SetLT instruction: " << *Ty << "\n";
430 static GenericValue executeSetGTInst(GenericValue Src1, GenericValue Src2,
433 switch (Ty->getPrimitiveID()) {
434 IMPLEMENT_SETCC(>, UByte);
435 IMPLEMENT_SETCC(>, SByte);
436 IMPLEMENT_SETCC(>, UShort);
437 IMPLEMENT_SETCC(>, Short);
438 IMPLEMENT_SETCC(>, UInt);
439 IMPLEMENT_SETCC(>, Int);
440 IMPLEMENT_SETCC(>, ULong);
441 IMPLEMENT_SETCC(>, Long);
442 IMPLEMENT_SETCC(>, Float);
443 IMPLEMENT_SETCC(>, Double);
444 IMPLEMENT_POINTERSETCC(>);
446 std::cout << "Unhandled type for SetGT instruction: " << *Ty << "\n";
452 void Interpreter::visitBinaryOperator(BinaryOperator &I) {
453 ExecutionContext &SF = ECStack.back();
454 const Type *Ty = I.getOperand(0)->getType();
455 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
456 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
457 GenericValue R; // Result
459 switch (I.getOpcode()) {
460 case Instruction::Add: R = executeAddInst (Src1, Src2, Ty); break;
461 case Instruction::Sub: R = executeSubInst (Src1, Src2, Ty); break;
462 case Instruction::Mul: R = executeMulInst (Src1, Src2, Ty); break;
463 case Instruction::Div: R = executeDivInst (Src1, Src2, Ty); break;
464 case Instruction::Rem: R = executeRemInst (Src1, Src2, Ty); break;
465 case Instruction::And: R = executeAndInst (Src1, Src2, Ty); break;
466 case Instruction::Or: R = executeOrInst (Src1, Src2, Ty); break;
467 case Instruction::Xor: R = executeXorInst (Src1, Src2, Ty); break;
468 case Instruction::SetEQ: R = executeSetEQInst(Src1, Src2, Ty); break;
469 case Instruction::SetNE: R = executeSetNEInst(Src1, Src2, Ty); break;
470 case Instruction::SetLE: R = executeSetLEInst(Src1, Src2, Ty); break;
471 case Instruction::SetGE: R = executeSetGEInst(Src1, Src2, Ty); break;
472 case Instruction::SetLT: R = executeSetLTInst(Src1, Src2, Ty); break;
473 case Instruction::SetGT: R = executeSetGTInst(Src1, Src2, Ty); break;
475 std::cout << "Don't know how to handle this binary operator!\n-->" << I;
482 //===----------------------------------------------------------------------===//
483 // Terminator Instruction Implementations
484 //===----------------------------------------------------------------------===//
486 void Interpreter::exitCalled(GenericValue GV) {
488 std::cout << "Program returned ";
489 print(Type::IntTy, GV);
490 std::cout << " via 'void exit(int)'\n";
493 ExitCode = GV.SByteVal;
497 void Interpreter::visitReturnInst(ReturnInst &I) {
498 ExecutionContext &SF = ECStack.back();
499 const Type *RetTy = 0;
502 // Save away the return value... (if we are not 'ret void')
503 if (I.getNumOperands()) {
504 RetTy = I.getReturnValue()->getType();
505 Result = getOperandValue(I.getReturnValue(), SF);
508 // Save previously executing meth
509 const Function *M = ECStack.back().CurFunction;
511 // Pop the current stack frame... this invalidates SF
514 if (ECStack.empty()) { // Finished main. Put result into exit code...
515 if (RetTy) { // Nonvoid return type?
517 CW << "Function " << M->getType() << " \"" << M->getName()
519 print(RetTy, Result);
523 if (RetTy->isIntegral())
524 ExitCode = Result.IntVal; // Capture the exit code of the program
531 // If we have a previous stack frame, and we have a previous call, fill in
532 // the return value...
534 ExecutionContext &NewSF = ECStack.back();
536 if (NewSF.Caller->getType() != Type::VoidTy) // Save result...
537 SetValue(NewSF.Caller, Result, NewSF);
539 NewSF.Caller = 0; // We returned from the call...
540 } else if (!QuietMode) {
541 // This must be a function that is executing because of a user 'call'
543 CW << "Function " << M->getType() << " \"" << M->getName()
545 print(RetTy, Result);
550 void Interpreter::visitBranchInst(BranchInst &I) {
551 ExecutionContext &SF = ECStack.back();
554 Dest = I.getSuccessor(0); // Uncond branches have a fixed dest...
555 if (!I.isUnconditional()) {
556 Value *Cond = I.getCondition();
557 if (getOperandValue(Cond, SF).BoolVal == 0) // If false cond...
558 Dest = I.getSuccessor(1);
560 SwitchToNewBasicBlock(Dest, SF);
563 void Interpreter::visitSwitchInst(SwitchInst &I) {
564 ExecutionContext &SF = ECStack.back();
565 GenericValue CondVal = getOperandValue(I.getOperand(0), SF);
566 const Type *ElTy = I.getOperand(0)->getType();
568 // Check to see if any of the cases match...
569 BasicBlock *Dest = 0;
570 for (unsigned i = 2, e = I.getNumOperands(); i != e; i += 2)
571 if (executeSetEQInst(CondVal,
572 getOperandValue(I.getOperand(i), SF), ElTy).BoolVal) {
573 Dest = cast<BasicBlock>(I.getOperand(i+1));
577 if (!Dest) Dest = I.getDefaultDest(); // No cases matched: use default
578 SwitchToNewBasicBlock(Dest, SF);
581 // SwitchToNewBasicBlock - This method is used to jump to a new basic block.
582 // This function handles the actual updating of block and instruction iterators
583 // as well as execution of all of the PHI nodes in the destination block.
585 // This method does this because all of the PHI nodes must be executed
586 // atomically, reading their inputs before any of the results are updated. Not
587 // doing this can cause problems if the PHI nodes depend on other PHI nodes for
588 // their inputs. If the input PHI node is updated before it is read, incorrect
589 // results can happen. Thus we use a two phase approach.
591 void Interpreter::SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF){
592 BasicBlock *PrevBB = SF.CurBB; // Remember where we came from...
593 SF.CurBB = Dest; // Update CurBB to branch destination
594 SF.CurInst = SF.CurBB->begin(); // Update new instruction ptr...
596 if (!isa<PHINode>(SF.CurInst)) return; // Nothing fancy to do
598 // Loop over all of the PHI nodes in the current block, reading their inputs.
599 std::vector<GenericValue> ResultValues;
601 for (; PHINode *PN = dyn_cast<PHINode>(SF.CurInst); ++SF.CurInst) {
602 if (Trace) CW << "Run:" << PN;
604 // Search for the value corresponding to this previous bb...
605 int i = PN->getBasicBlockIndex(PrevBB);
606 assert(i != -1 && "PHINode doesn't contain entry for predecessor??");
607 Value *IncomingValue = PN->getIncomingValue(i);
609 // Save the incoming value for this PHI node...
610 ResultValues.push_back(getOperandValue(IncomingValue, SF));
613 // Now loop over all of the PHI nodes setting their values...
614 SF.CurInst = SF.CurBB->begin();
615 for (unsigned i = 0; PHINode *PN = dyn_cast<PHINode>(SF.CurInst);
617 SetValue(PN, ResultValues[i], SF);
621 //===----------------------------------------------------------------------===//
622 // Memory Instruction Implementations
623 //===----------------------------------------------------------------------===//
625 void Interpreter::visitAllocationInst(AllocationInst &I) {
626 ExecutionContext &SF = ECStack.back();
628 const Type *Ty = I.getType()->getElementType(); // Type to be allocated
630 // Get the number of elements being allocated by the array...
631 unsigned NumElements = getOperandValue(I.getOperand(0), SF).UIntVal;
633 // Allocate enough memory to hold the type...
634 // FIXME: Don't use CALLOC, use a tainted malloc.
635 void *Memory = calloc(NumElements, TD.getTypeSize(Ty));
637 GenericValue Result = PTOGV(Memory);
638 assert(Result.PointerVal != 0 && "Null pointer returned by malloc!");
639 SetValue(&I, Result, SF);
641 if (I.getOpcode() == Instruction::Alloca)
642 ECStack.back().Allocas.add(Memory);
645 void Interpreter::visitFreeInst(FreeInst &I) {
646 ExecutionContext &SF = ECStack.back();
647 assert(isa<PointerType>(I.getOperand(0)->getType()) && "Freeing nonptr?");
648 GenericValue Value = getOperandValue(I.getOperand(0), SF);
649 // TODO: Check to make sure memory is allocated
650 free(GVTOP(Value)); // Free memory
654 // getElementOffset - The workhorse for getelementptr.
656 GenericValue Interpreter::executeGEPOperation(Value *Ptr, User::op_iterator I,
658 ExecutionContext &SF) {
659 assert(isa<PointerType>(Ptr->getType()) &&
660 "Cannot getElementOffset of a nonpointer type!");
663 const Type *Ty = Ptr->getType();
665 for (; I != E; ++I) {
666 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
667 const StructLayout *SLO = TD.getStructLayout(STy);
669 // Indicies must be ubyte constants...
670 const ConstantUInt *CPU = cast<ConstantUInt>(*I);
671 assert(CPU->getType() == Type::UByteTy);
672 unsigned Index = CPU->getValue();
674 Total += SLO->MemberOffsets[Index];
675 Ty = STy->getElementTypes()[Index];
676 } else if (const SequentialType *ST = cast<SequentialType>(Ty)) {
678 // Get the index number for the array... which must be long type...
679 assert((*I)->getType() == Type::LongTy);
680 unsigned Idx = getOperandValue(*I, SF).LongVal;
681 if (const ArrayType *AT = dyn_cast<ArrayType>(ST))
682 if (Idx >= AT->getNumElements() && ArrayChecksEnabled) {
683 std::cerr << "Out of range memory access to element #" << Idx
684 << " of a " << AT->getNumElements() << " element array."
685 << " Subscript #" << *I << "\n";
687 siglongjmp(SignalRecoverBuffer, SIGTRAP);
690 Ty = ST->getElementType();
691 unsigned Size = TD.getTypeSize(Ty);
697 Result.PointerVal = getOperandValue(Ptr, SF).PointerVal + Total;
701 void Interpreter::visitGetElementPtrInst(GetElementPtrInst &I) {
702 ExecutionContext &SF = ECStack.back();
703 SetValue(&I, TheEE->executeGEPOperation(I.getPointerOperand(),
704 I.idx_begin(), I.idx_end(), SF), SF);
707 void Interpreter::visitLoadInst(LoadInst &I) {
708 ExecutionContext &SF = ECStack.back();
709 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
710 GenericValue *Ptr = (GenericValue*)GVTOP(SRC);
711 GenericValue Result = LoadValueFromMemory(Ptr, I.getType());
712 SetValue(&I, Result, SF);
715 void Interpreter::visitStoreInst(StoreInst &I) {
716 ExecutionContext &SF = ECStack.back();
717 GenericValue Val = getOperandValue(I.getOperand(0), SF);
718 GenericValue SRC = getOperandValue(I.getPointerOperand(), SF);
719 StoreValueToMemory(Val, (GenericValue *)GVTOP(SRC),
720 I.getOperand(0)->getType());
725 //===----------------------------------------------------------------------===//
726 // Miscellaneous Instruction Implementations
727 //===----------------------------------------------------------------------===//
729 void Interpreter::visitCallInst(CallInst &I) {
730 ExecutionContext &SF = ECStack.back();
732 std::vector<GenericValue> ArgVals;
733 ArgVals.reserve(I.getNumOperands()-1);
734 for (unsigned i = 1; i < I.getNumOperands(); ++i) {
735 ArgVals.push_back(getOperandValue(I.getOperand(i), SF));
736 // Promote all integral types whose size is < sizeof(int) into ints. We do
737 // this by zero or sign extending the value as appropriate according to the
739 if (I.getOperand(i)->getType()->isIntegral() &&
740 I.getOperand(i)->getType()->getPrimitiveSize() < 4) {
741 const Type *Ty = I.getOperand(i)->getType();
742 if (Ty == Type::ShortTy)
743 ArgVals.back().IntVal = ArgVals.back().ShortVal;
744 else if (Ty == Type::UShortTy)
745 ArgVals.back().UIntVal = ArgVals.back().UShortVal;
746 else if (Ty == Type::SByteTy)
747 ArgVals.back().IntVal = ArgVals.back().SByteVal;
748 else if (Ty == Type::UByteTy)
749 ArgVals.back().UIntVal = ArgVals.back().UByteVal;
750 else if (Ty == Type::BoolTy)
751 ArgVals.back().UIntVal = ArgVals.back().BoolVal;
753 assert(0 && "Unknown type!");
757 // To handle indirect calls, we must get the pointer value from the argument
758 // and treat it as a function pointer.
759 GenericValue SRC = getOperandValue(I.getCalledValue(), SF);
760 callFunction((Function*)GVTOP(SRC), ArgVals);
763 #define IMPLEMENT_SHIFT(OP, TY) \
764 case Type::TY##TyID: Dest.TY##Val = Src1.TY##Val OP Src2.UByteVal; break
766 void Interpreter::visitShl(ShiftInst &I) {
767 ExecutionContext &SF = ECStack.back();
768 const Type *Ty = I.getOperand(0)->getType();
769 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
770 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
773 switch (Ty->getPrimitiveID()) {
774 IMPLEMENT_SHIFT(<<, UByte);
775 IMPLEMENT_SHIFT(<<, SByte);
776 IMPLEMENT_SHIFT(<<, UShort);
777 IMPLEMENT_SHIFT(<<, Short);
778 IMPLEMENT_SHIFT(<<, UInt);
779 IMPLEMENT_SHIFT(<<, Int);
780 IMPLEMENT_SHIFT(<<, ULong);
781 IMPLEMENT_SHIFT(<<, Long);
783 std::cout << "Unhandled type for Shl instruction: " << *Ty << "\n";
785 SetValue(&I, Dest, SF);
788 void Interpreter::visitShr(ShiftInst &I) {
789 ExecutionContext &SF = ECStack.back();
790 const Type *Ty = I.getOperand(0)->getType();
791 GenericValue Src1 = getOperandValue(I.getOperand(0), SF);
792 GenericValue Src2 = getOperandValue(I.getOperand(1), SF);
795 switch (Ty->getPrimitiveID()) {
796 IMPLEMENT_SHIFT(>>, UByte);
797 IMPLEMENT_SHIFT(>>, SByte);
798 IMPLEMENT_SHIFT(>>, UShort);
799 IMPLEMENT_SHIFT(>>, Short);
800 IMPLEMENT_SHIFT(>>, UInt);
801 IMPLEMENT_SHIFT(>>, Int);
802 IMPLEMENT_SHIFT(>>, ULong);
803 IMPLEMENT_SHIFT(>>, Long);
805 std::cout << "Unhandled type for Shr instruction: " << *Ty << "\n";
808 SetValue(&I, Dest, SF);
811 #define IMPLEMENT_CAST(DTY, DCTY, STY) \
812 case Type::STY##TyID: Dest.DTY##Val = DCTY Src.STY##Val; break;
814 #define IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY) \
815 case Type::DESTTY##TyID: \
816 switch (SrcTy->getPrimitiveID()) { \
817 IMPLEMENT_CAST(DESTTY, DESTCTY, Bool); \
818 IMPLEMENT_CAST(DESTTY, DESTCTY, UByte); \
819 IMPLEMENT_CAST(DESTTY, DESTCTY, SByte); \
820 IMPLEMENT_CAST(DESTTY, DESTCTY, UShort); \
821 IMPLEMENT_CAST(DESTTY, DESTCTY, Short); \
822 IMPLEMENT_CAST(DESTTY, DESTCTY, UInt); \
823 IMPLEMENT_CAST(DESTTY, DESTCTY, Int); \
824 IMPLEMENT_CAST(DESTTY, DESTCTY, ULong); \
825 IMPLEMENT_CAST(DESTTY, DESTCTY, Long); \
826 IMPLEMENT_CAST(DESTTY, DESTCTY, Pointer);
828 #define IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY) \
829 IMPLEMENT_CAST(DESTTY, DESTCTY, Float); \
830 IMPLEMENT_CAST(DESTTY, DESTCTY, Double)
832 #define IMPLEMENT_CAST_CASE_END() \
833 default: std::cout << "Unhandled cast: " << SrcTy << " to " << Ty << "\n"; \
838 #define IMPLEMENT_CAST_CASE(DESTTY, DESTCTY) \
839 IMPLEMENT_CAST_CASE_START(DESTTY, DESTCTY); \
840 IMPLEMENT_CAST_CASE_FP_IMP(DESTTY, DESTCTY); \
841 IMPLEMENT_CAST_CASE_END()
843 GenericValue Interpreter::executeCastOperation(Value *SrcVal, const Type *Ty,
844 ExecutionContext &SF) {
845 const Type *SrcTy = SrcVal->getType();
846 GenericValue Dest, Src = getOperandValue(SrcVal, SF);
848 switch (Ty->getPrimitiveID()) {
849 IMPLEMENT_CAST_CASE(UByte , (unsigned char));
850 IMPLEMENT_CAST_CASE(SByte , ( signed char));
851 IMPLEMENT_CAST_CASE(UShort , (unsigned short));
852 IMPLEMENT_CAST_CASE(Short , ( signed short));
853 IMPLEMENT_CAST_CASE(UInt , (unsigned int ));
854 IMPLEMENT_CAST_CASE(Int , ( signed int ));
855 IMPLEMENT_CAST_CASE(ULong , (uint64_t));
856 IMPLEMENT_CAST_CASE(Long , ( int64_t));
857 IMPLEMENT_CAST_CASE(Pointer, (PointerTy));
858 IMPLEMENT_CAST_CASE(Float , (float));
859 IMPLEMENT_CAST_CASE(Double , (double));
860 IMPLEMENT_CAST_CASE(Bool , (bool));
862 std::cout << "Unhandled dest type for cast instruction: " << *Ty << "\n";
870 void Interpreter::visitCastInst(CastInst &I) {
871 ExecutionContext &SF = ECStack.back();
872 SetValue(&I, executeCastOperation(I.getOperand(0), I.getType(), SF), SF);
875 void Interpreter::visitVarArgInst(VarArgInst &I) {
876 ExecutionContext &SF = ECStack.back();
878 // Get the pointer to the valist element. LLI treats the valist in memory as
880 GenericValue VAListPtr = getOperandValue(I.getOperand(0), SF);
883 GenericValue VAList =
884 TheEE->LoadValueFromMemory((GenericValue *)GVTOP(VAListPtr), Type::UIntTy);
886 unsigned Argument = VAList.IntVal++;
888 // Update the valist to point to the next argument...
889 TheEE->StoreValueToMemory(VAList, (GenericValue *)GVTOP(VAListPtr),
893 assert(Argument < SF.VarArgs.size() &&
894 "Accessing past the last vararg argument!");
895 SetValue(&I, SF.VarArgs[Argument], SF);
898 //===----------------------------------------------------------------------===//
899 // Dispatch and Execution Code
900 //===----------------------------------------------------------------------===//
902 FunctionInfo::FunctionInfo(Function *F) : Annotation(FunctionInfoAID) {
903 // Assign slot numbers to the function arguments...
904 for (Function::const_aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
905 AI->addAnnotation(new SlotNumber(getValueSlot(AI)));
907 // Iterate over all of the instructions...
908 unsigned InstNum = 0;
909 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
910 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II)
911 // For each instruction... Add Annote
912 II->addAnnotation(new InstNumber(++InstNum, getValueSlot(II)));
915 unsigned FunctionInfo::getValueSlot(const Value *V) {
916 unsigned Plane = V->getType()->getUniqueID();
917 if (Plane >= NumPlaneElements.size())
918 NumPlaneElements.resize(Plane+1, 0);
919 return NumPlaneElements[Plane]++;
923 //===----------------------------------------------------------------------===//
924 // callFunction - Execute the specified function...
926 void Interpreter::callFunction(Function *F,
927 const std::vector<GenericValue> &ArgVals) {
928 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
929 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
930 "Incorrect number of arguments passed into function call!");
931 if (F->isExternal()) {
932 GenericValue Result = callExternalFunction(F, ArgVals);
933 const Type *RetTy = F->getReturnType();
935 // Copy the result back into the result variable if we are not returning
937 if (RetTy != Type::VoidTy) {
938 if (!ECStack.empty() && ECStack.back().Caller) {
939 ExecutionContext &SF = ECStack.back();
940 SetValue(SF.Caller, Result, SF);
942 SF.Caller = 0; // We returned from the call...
943 } else if (!QuietMode) {
945 CW << "Function " << F->getType() << " \"" << F->getName()
947 print(RetTy, Result);
950 if (RetTy->isIntegral())
951 ExitCode = Result.IntVal; // Capture the exit code of the program
958 // Process the function, assigning instruction numbers to the instructions in
959 // the function. Also calculate the number of values for each type slot
962 FunctionInfo *FuncInfo =
963 (FunctionInfo*)F->getOrCreateAnnotation(FunctionInfoAID);
964 ECStack.push_back(ExecutionContext()); // Make a new stack frame...
966 ExecutionContext &StackFrame = ECStack.back(); // Fill it in...
967 StackFrame.CurFunction = F;
968 StackFrame.CurBB = F->begin();
969 StackFrame.CurInst = StackFrame.CurBB->begin();
970 StackFrame.FuncInfo = FuncInfo;
972 // Initialize the values to nothing...
973 StackFrame.Values.resize(FuncInfo->NumPlaneElements.size());
974 for (unsigned i = 0; i < FuncInfo->NumPlaneElements.size(); ++i) {
975 StackFrame.Values[i].resize(FuncInfo->NumPlaneElements[i]);
977 // Taint the initial values of stuff
978 memset(&StackFrame.Values[i][0], 42,
979 FuncInfo->NumPlaneElements[i]*sizeof(GenericValue));
983 // Run through the function arguments and initialize their values...
984 assert((ArgVals.size() == F->asize() ||
985 (ArgVals.size() > F->asize() && F->getFunctionType()->isVarArg())) &&
986 "Invalid number of values passed to function invocation!");
988 // Handle non-varargs arguments...
990 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI, ++i)
991 SetValue(AI, ArgVals[i], StackFrame);
993 // Handle varargs arguments...
994 StackFrame.VarArgs.assign(ArgVals.begin()+i, ArgVals.end());
997 // executeInstruction - Interpret a single instruction & increment the "PC".
999 void Interpreter::executeInstruction() {
1000 assert(!ECStack.empty() && "No program running, cannot execute inst!");
1002 ExecutionContext &SF = ECStack.back(); // Current stack frame
1003 Instruction &I = *SF.CurInst++; // Increment before execute
1005 if (Trace) CW << "Run:" << I;
1007 // Track the number of dynamic instructions executed.
1010 // Set a sigsetjmp buffer so that we can recover if an error happens during
1011 // instruction execution...
1013 if (int SigNo = sigsetjmp(SignalRecoverBuffer, 1)) {
1014 std::cout << "EXCEPTION OCCURRED [" << strsignal(SigNo) << "]\n";
1018 InInstruction = true;
1019 visit(I); // Dispatch to one of the visit* methods...
1020 InInstruction = false;
1022 // Reset the current frame location to the top of stack
1023 CurFrame = ECStack.size()-1;
1026 void Interpreter::run() {
1027 while (!ECStack.empty()) {
1028 // Run an instruction...
1029 executeInstruction();
1033 void Interpreter::printValue(const Type *Ty, GenericValue V) {
1034 switch (Ty->getPrimitiveID()) {
1035 case Type::BoolTyID: std::cout << (V.BoolVal?"true":"false"); break;
1036 case Type::SByteTyID:
1037 std::cout << (int)V.SByteVal << " '" << V.SByteVal << "'"; break;
1038 case Type::UByteTyID:
1039 std::cout << (unsigned)V.UByteVal << " '" << V.UByteVal << "'"; break;
1040 case Type::ShortTyID: std::cout << V.ShortVal; break;
1041 case Type::UShortTyID: std::cout << V.UShortVal; break;
1042 case Type::IntTyID: std::cout << V.IntVal; break;
1043 case Type::UIntTyID: std::cout << V.UIntVal; break;
1044 case Type::LongTyID: std::cout << (long)V.LongVal; break;
1045 case Type::ULongTyID: std::cout << (unsigned long)V.ULongVal; break;
1046 case Type::FloatTyID: std::cout << V.FloatVal; break;
1047 case Type::DoubleTyID: std::cout << V.DoubleVal; break;
1048 case Type::PointerTyID:std::cout << (void*)GVTOP(V); break;
1050 std::cout << "- Don't know how to print value of this type!";
1055 void Interpreter::print(const Type *Ty, GenericValue V) {