Interpreter.h revision 832254e1c2387c0cbeb0a820b8315fbe85cb003a
1//===-- Interpreter.h ------------------------------------------*- C++ -*--===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This header file defines the interpreter structure
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLI_INTERPRETER_H
15#define LLI_INTERPRETER_H
16
17#include "llvm/Function.h"
18#include "llvm/ExecutionEngine/ExecutionEngine.h"
19#include "llvm/ExecutionEngine/GenericValue.h"
20#include "llvm/Support/InstVisitor.h"
21#include "llvm/Support/CallSite.h"
22#include "llvm/Target/TargetData.h"
23#include "llvm/Support/DataTypes.h"
24
25namespace llvm {
26
27class IntrinsicLowering;
28struct FunctionInfo;
29template<typename T> class generic_gep_type_iterator;
30class ConstantExpr;
31typedef generic_gep_type_iterator<User::const_op_iterator> gep_type_iterator;
32
33
34// AllocaHolder - Object to track all of the blocks of memory allocated by
35// alloca.  When the function returns, this object is popped off the execution
36// stack, which causes the dtor to be run, which frees all the alloca'd memory.
37//
38class AllocaHolder {
39  friend class AllocaHolderHandle;
40  std::vector<void*> Allocations;
41  unsigned RefCnt;
42public:
43  AllocaHolder() : RefCnt(0) {}
44  void add(void *mem) { Allocations.push_back(mem); }
45  ~AllocaHolder() {
46    for (unsigned i = 0; i < Allocations.size(); ++i)
47      free(Allocations[i]);
48  }
49};
50
51// AllocaHolderHandle gives AllocaHolder value semantics so we can stick it into
52// a vector...
53//
54class AllocaHolderHandle {
55  AllocaHolder *H;
56public:
57  AllocaHolderHandle() : H(new AllocaHolder()) { H->RefCnt++; }
58  AllocaHolderHandle(const AllocaHolderHandle &AH) : H(AH.H) { H->RefCnt++; }
59  ~AllocaHolderHandle() { if (--H->RefCnt == 0) delete H; }
60
61  void add(void *mem) { H->add(mem); }
62};
63
64typedef std::vector<GenericValue> ValuePlaneTy;
65
66// ExecutionContext struct - This struct represents one stack frame currently
67// executing.
68//
69struct ExecutionContext {
70  Function             *CurFunction;// The currently executing function
71  BasicBlock           *CurBB;      // The currently executing BB
72  BasicBlock::iterator  CurInst;    // The next instruction to execute
73  std::map<Value *, GenericValue> Values; // LLVM values used in this invocation
74  std::vector<GenericValue>  VarArgs; // Values passed through an ellipsis
75  CallSite             Caller;     // Holds the call that called subframes.
76                                   // NULL if main func or debugger invoked fn
77  AllocaHolderHandle    Allocas;    // Track memory allocated by alloca
78};
79
80// Interpreter - This class represents the entirety of the interpreter.
81//
82class Interpreter : public ExecutionEngine, public InstVisitor<Interpreter> {
83  GenericValue ExitValue;          // The return value of the called function
84  TargetData TD;
85  IntrinsicLowering *IL;
86
87  // The runtime stack of executing code.  The top of the stack is the current
88  // function record.
89  std::vector<ExecutionContext> ECStack;
90
91  // AtExitHandlers - List of functions to call when the program exits,
92  // registered with the atexit() library function.
93  std::vector<Function*> AtExitHandlers;
94
95public:
96  Interpreter(Module *M);
97  ~Interpreter();
98
99  /// runAtExitHandlers - Run any functions registered by the program's calls to
100  /// atexit(3), which we intercept and store in AtExitHandlers.
101  ///
102  void runAtExitHandlers();
103
104  static void Register() {
105    InterpCtor = create;
106  }
107
108  /// create - Create an interpreter ExecutionEngine. This can never fail.
109  ///
110  static ExecutionEngine *create(ModuleProvider *M);
111
112  /// run - Start execution with the specified function and arguments.
113  ///
114  virtual GenericValue runFunction(Function *F,
115                                   const std::vector<GenericValue> &ArgValues);
116
117  /// recompileAndRelinkFunction - For the interpreter, functions are always
118  /// up-to-date.
119  ///
120  virtual void *recompileAndRelinkFunction(Function *F) {
121    return getPointerToFunction(F);
122  }
123
124  /// freeMachineCodeForFunction - The interpreter does not generate any code.
125  ///
126  void freeMachineCodeForFunction(Function *F) { }
127
128  // Methods used to execute code:
129  // Place a call on the stack
130  void callFunction(Function *F, const std::vector<GenericValue> &ArgVals);
131  void run();                // Execute instructions until nothing left to do
132
133  // Opcode Implementations
134  void visitReturnInst(ReturnInst &I);
135  void visitBranchInst(BranchInst &I);
136  void visitSwitchInst(SwitchInst &I);
137
138  void visitBinaryOperator(BinaryOperator &I);
139  void visitICmpInst(ICmpInst &I);
140  void visitFCmpInst(FCmpInst &I);
141  void visitAllocationInst(AllocationInst &I);
142  void visitFreeInst(FreeInst &I);
143  void visitLoadInst(LoadInst &I);
144  void visitStoreInst(StoreInst &I);
145  void visitGetElementPtrInst(GetElementPtrInst &I);
146  void visitPHINode(PHINode &PN) { assert(0 && "PHI nodes already handled!"); }
147  void visitTruncInst(TruncInst &I);
148  void visitZExtInst(ZExtInst &I);
149  void visitSExtInst(SExtInst &I);
150  void visitFPTruncInst(FPTruncInst &I);
151  void visitFPExtInst(FPExtInst &I);
152  void visitUIToFPInst(UIToFPInst &I);
153  void visitSIToFPInst(SIToFPInst &I);
154  void visitFPToUIInst(FPToUIInst &I);
155  void visitFPToSIInst(FPToSIInst &I);
156  void visitPtrToIntInst(PtrToIntInst &I);
157  void visitIntToPtrInst(IntToPtrInst &I);
158  void visitBitCastInst(BitCastInst &I);
159  void visitSelectInst(SelectInst &I);
160
161
162  void visitCallSite(CallSite CS);
163  void visitCallInst(CallInst &I) { visitCallSite (CallSite (&I)); }
164  void visitInvokeInst(InvokeInst &I) { visitCallSite (CallSite (&I)); }
165  void visitUnwindInst(UnwindInst &I);
166  void visitUnreachableInst(UnreachableInst &I);
167
168  void visitShl(BinaryOperator &I);
169  void visitLShr(BinaryOperator &I);
170  void visitAShr(BinaryOperator &I);
171
172  void visitVAArgInst(VAArgInst &I);
173  void visitInstruction(Instruction &I) {
174    cerr << I;
175    assert(0 && "Instruction not interpretable yet!");
176  }
177
178  GenericValue callExternalFunction(Function *F,
179                                    const std::vector<GenericValue> &ArgVals);
180  void exitCalled(GenericValue GV);
181
182  void addAtExitHandler(Function *F) {
183    AtExitHandlers.push_back(F);
184  }
185
186  GenericValue *getFirstVarArg () {
187    return &(ECStack.back ().VarArgs[0]);
188  }
189
190  //FIXME: private:
191public:
192  GenericValue executeGEPOperation(Value *Ptr, gep_type_iterator I,
193                                   gep_type_iterator E, ExecutionContext &SF);
194
195private:  // Helper functions
196  // SwitchToNewBasicBlock - Start execution in a new basic block and run any
197  // PHI nodes in the top of the block.  This is used for intraprocedural
198  // control flow.
199  //
200  void SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF);
201
202  void *getPointerToFunction(Function *F) { return (void*)F; }
203
204  void initializeExecutionEngine();
205  void initializeExternalFunctions();
206  GenericValue getConstantExprValue(ConstantExpr *CE, ExecutionContext &SF);
207  GenericValue getOperandValue(Value *V, ExecutionContext &SF);
208  GenericValue executeTruncInst(Value *SrcVal, const Type *DstTy,
209                                ExecutionContext &SF);
210  GenericValue executeSExtInst(Value *SrcVal, const Type *DstTy,
211                               ExecutionContext &SF);
212  GenericValue executeZExtInst(Value *SrcVal, const Type *DstTy,
213                               ExecutionContext &SF);
214  GenericValue executeFPTruncInst(Value *SrcVal, const Type *DstTy,
215                                  ExecutionContext &SF);
216  GenericValue executeFPExtInst(Value *SrcVal, const Type *DstTy,
217                                ExecutionContext &SF);
218  GenericValue executeFPToUIInst(Value *SrcVal, const Type *DstTy,
219                                 ExecutionContext &SF);
220  GenericValue executeFPToSIInst(Value *SrcVal, const Type *DstTy,
221                                 ExecutionContext &SF);
222  GenericValue executeUIToFPInst(Value *SrcVal, const Type *DstTy,
223                                 ExecutionContext &SF);
224  GenericValue executeSIToFPInst(Value *SrcVal, const Type *DstTy,
225                                 ExecutionContext &SF);
226  GenericValue executePtrToIntInst(Value *SrcVal, const Type *DstTy,
227                                   ExecutionContext &SF);
228  GenericValue executeIntToPtrInst(Value *SrcVal, const Type *DstTy,
229                                   ExecutionContext &SF);
230  GenericValue executeBitCastInst(Value *SrcVal, const Type *DstTy,
231                                  ExecutionContext &SF);
232  GenericValue executeCastOperation(Instruction::CastOps opcode, Value *SrcVal,
233                                    const Type *Ty, ExecutionContext &SF);
234  void popStackAndReturnValueToCaller(const Type *RetTy, GenericValue Result);
235
236};
237
238inline void maskToBitWidth(GenericValue& GV, unsigned BitWidth) {
239  uint64_t BitMask = (1ull << BitWidth) - 1;
240  if (BitWidth <= 8)
241    GV.Int8Val &= BitMask;
242  else if (BitWidth <= 16)
243    GV.Int16Val &= BitMask;
244  else if (BitWidth <= 32)
245    GV.Int32Val &= BitMask;
246  else
247    GV.Int64Val &= BitMask;
248}
249} // End llvm namespace
250
251#endif
252