The JIT now passes the environment pointer to the main() function when it
[oota-llvm.git] / lib / ExecutionEngine / Interpreter / Interpreter.h
1 //===-- Interpreter.h ------------------------------------------*- C++ -*--===//
2 //
3 // This header file defines the interpreter structure
4 //
5 //===----------------------------------------------------------------------===//
6
7 #ifndef LLI_INTERPRETER_H
8 #define LLI_INTERPRETER_H
9
10 // Uncomment this line to enable profiling of structure field accesses.
11 //#define PROFILE_STRUCTURE_FIELDS 1
12
13 #include "../ExecutionEngine.h"
14 #include "../GenericValue.h"
15 #include "Support/DataTypes.h"
16 #include "llvm/Assembly/CachedWriter.h"
17 #include "llvm/Target/TargetData.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/Support/InstVisitor.h"
20
21 extern CachedWriter CW;     // Object to accelerate printing of LLVM
22
23 struct FunctionInfo;        // Defined in ExecutionAnnotations.h
24
25 // AllocaHolder - Object to track all of the blocks of memory allocated by
26 // alloca.  When the function returns, this object is poped off the execution
27 // stack, which causes the dtor to be run, which frees all the alloca'd memory.
28 //
29 class AllocaHolder {
30   friend class AllocaHolderHandle;
31   std::vector<void*> Allocations;
32   unsigned RefCnt;
33 public:
34   AllocaHolder() : RefCnt(0) {}
35   void add(void *mem) { Allocations.push_back(mem); }
36   ~AllocaHolder() {
37     for (unsigned i = 0; i < Allocations.size(); ++i)
38       free(Allocations[i]);
39   }
40 };
41
42 // AllocaHolderHandle gives AllocaHolder value semantics so we can stick it into
43 // a vector...
44 //
45 class AllocaHolderHandle {
46   AllocaHolder *H;
47 public:
48   AllocaHolderHandle() : H(new AllocaHolder()) { H->RefCnt++; }
49   AllocaHolderHandle(const AllocaHolderHandle &AH) : H(AH.H) { H->RefCnt++; }
50   ~AllocaHolderHandle() { if (--H->RefCnt == 0) delete H; }
51
52   void add(void *mem) { H->add(mem); }
53 };
54
55 typedef std::vector<GenericValue> ValuePlaneTy;
56
57 // ExecutionContext struct - This struct represents one stack frame currently
58 // executing.
59 //
60 struct ExecutionContext {
61   Function             *CurFunction;// The currently executing function
62   BasicBlock           *CurBB;      // The currently executing BB
63   BasicBlock::iterator  CurInst;    // The next instruction to execute
64   FunctionInfo         *FuncInfo;   // The FuncInfo annotation for the function
65   std::vector<ValuePlaneTy>  Values;// ValuePlanes for each type
66   std::vector<GenericValue>  VarArgs; // Values passed through an ellipsis
67
68   CallInst             *Caller;     // Holds the call that called subframes.
69                                     // NULL if main func or debugger invoked fn
70   AllocaHolderHandle    Allocas;    // Track memory allocated by alloca
71 };
72
73 // Interpreter - This class represents the entirety of the interpreter.
74 //
75 class Interpreter : public ExecutionEngine, public InstVisitor<Interpreter> {
76   int ExitCode;                // The exit code to be returned by the lli util
77   bool Debug;                  // Debug mode enabled?
78   bool Profile;                // Profiling enabled?
79   bool Trace;                  // Tracing enabled?
80   int CurFrame;                // The current stack frame being inspected
81   TargetData TD;
82
83   // The runtime stack of executing code.  The top of the stack is the current
84   // function record.
85   std::vector<ExecutionContext> ECStack;
86
87   // AtExitHandlers - List of functions to call when the program exits.
88   std::vector<Function*> AtExitHandlers;
89 public:
90   Interpreter(Module *M, unsigned Config, bool DebugMode, bool TraceMode);
91   inline ~Interpreter() { CW.setModule(0); }
92
93   // getExitCode - return the code that should be the exit code for the lli
94   // utility.
95   inline int getExitCode() const { return ExitCode; }
96
97   /// run - Start execution with the specified function and arguments.
98   ///
99   virtual int run(const std::string &FnName,
100                   const std::vector<std::string> &Args,
101                   const char ** envp);
102  
103
104   // enableProfiling() - Turn profiling on, clear stats?
105   void enableProfiling() { Profile = true; }
106   void enableTracing() { Trace = true; }
107
108   void handleUserInput();
109
110   // User Interation Methods...
111   bool callFunction(const std::string &Name);      // return true on failure
112   void setBreakpoint(const std::string &Name);
113   void infoValue(const std::string &Name);
114   void print(const std::string &Name);
115   static void print(const Type *Ty, GenericValue V);
116   static void printValue(const Type *Ty, GenericValue V);
117
118   bool callMainFunction(const std::string &MainName,
119                         const std::vector<std::string> &InputFilename);
120
121   void list();             // Do the 'list' command
122   void printStackTrace();  // Do the 'backtrace' command
123
124   // Code execution methods...
125   void callFunction(Function *F, const std::vector<GenericValue> &ArgVals);
126   bool executeInstruction(); // Execute one instruction...
127
128   void stepInstruction();  // Do the 'step' command
129   void nextInstruction();  // Do the 'next' command
130   void run();              // Do the 'run' command
131   void finish();           // Do the 'finish' command
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 visitAllocationInst(AllocationInst &I);
140   void visitFreeInst(FreeInst &I);
141   void visitLoadInst(LoadInst &I);
142   void visitStoreInst(StoreInst &I);
143   void visitGetElementPtrInst(GetElementPtrInst &I);
144
145   void visitPHINode(PHINode &PN) { assert(0 && "PHI nodes already handled!"); }
146   void visitCastInst(CastInst &I);
147   void visitCallInst(CallInst &I);
148   void visitShl(ShiftInst &I);
149   void visitShr(ShiftInst &I);
150   void visitVarArgInst(VarArgInst &I);
151   void visitInstruction(Instruction &I) {
152     std::cerr << I;
153     assert(0 && "Instruction not interpretable yet!");
154   }
155
156   GenericValue callExternalFunction(Function *F, 
157                                     const std::vector<GenericValue> &ArgVals);
158   void exitCalled(GenericValue GV);
159
160   // getCurrentFunction - Return the currently executing function
161   inline Function *getCurrentFunction() const {
162     return CurFrame < 0 ? 0 : ECStack[CurFrame].CurFunction;
163   }
164
165   // isStopped - Return true if a program is stopped.  Return false if no
166   // program is running.
167   //
168   inline bool isStopped() const { return !ECStack.empty(); }
169
170   void addAtExitHandler(Function *F) {
171     AtExitHandlers.push_back(F);
172   }
173
174   //FIXME: private:
175 public:
176   GenericValue executeGEPOperation(Value *Ptr, User::op_iterator I,
177                                    User::op_iterator E, ExecutionContext &SF);
178
179 private:  // Helper functions
180   // SwitchToNewBasicBlock - Start execution in a new basic block and run any
181   // PHI nodes in the top of the block.  This is used for intraprocedural
182   // control flow.
183   // 
184   void SwitchToNewBasicBlock(BasicBlock *Dest, ExecutionContext &SF);
185
186   void *getPointerToFunction(Function *F) { return (void*)F; }
187
188   // getCurrentExecutablePath() - Return the directory that the lli executable
189   // lives in.
190   //
191   std::string getCurrentExecutablePath() const;
192
193   // printCurrentInstruction - Print out the instruction that the virtual PC is
194   // at, or fail silently if no program is running.
195   //
196   void printCurrentInstruction();
197
198   // printStackFrame - Print information about the specified stack frame, or -1
199   // for the default one.
200   //
201   void printStackFrame(int FrameNo = -1);
202
203   // LookupMatchingNames - Search the current function namespace, then the
204   // global namespace looking for values that match the specified name.  Return
205   // ALL matches to that name.  This is obviously slow, and should only be used
206   // for user interaction.
207   //
208   std::vector<Value*> LookupMatchingNames(const std::string &Name);
209
210   // ChooseOneOption - Prompt the user to choose among the specified options to
211   // pick one value.  If no options are provided, emit an error.  If a single 
212   // option is provided, just return that option.
213   //
214   Value *ChooseOneOption(const std::string &Name,
215                          const std::vector<Value*> &Opts);
216
217   // PerformExitStuff - Print out counters and profiling information if
218   // applicable...
219   void PerformExitStuff();
220
221   void initializeExecutionEngine();
222   void initializeExternalFunctions();
223 };
224
225 #endif