3 #include "interpreter.h"
10 int32_t regs[16] = {0};
11 bool zero_flag = false;
12 bool negative_flag = false;
13 uint8_t *pc = nullptr;
14 uint32_t cycle_count = 0;
18 struct ReturnException
22 void op_return(CpuState *state)
24 throw ReturnException();
27 void op_add(CpuState *state)
29 uint8_t reg = *state->pc++;
30 uint8_t dest = reg>>4, src = reg & 0xf;
32 int32_t v = state->regs[dest];
33 v += state->regs[src];
35 state->zero_flag = (v == 0);
36 state->negative_flag = (v < 0);
37 state->regs[dest] = v;
41 void op_sub(CpuState *state)
43 uint8_t reg = *state->pc++;
44 uint8_t dest = reg>>4, src = reg & 0xf;
46 int32_t v = state->regs[dest];
47 v -= state->regs[src];
49 state->zero_flag = (v == 0);
50 state->negative_flag = (v < 0);
51 state->regs[dest] = v;
54 void op_mov(CpuState *state)
56 uint8_t reg = *state->pc++;
57 uint8_t dest = reg>>4, src = reg & 0xf;
59 state->regs[dest] = state->regs[src];
63 void op_movi(CpuState *state)
65 uint8_t reg = *state->pc++;
66 uint8_t dest = reg>>4;
68 int32_t imm = *(int32_t *)state->pc;
71 state->regs[dest] = imm;
75 void op_b(CpuState *state)
77 int8_t rel = *state->pc++;
81 void op_bnz(CpuState *state)
83 int8_t rel = *state->pc++;
90 void (*dispatch_table[])(CpuState *) =
101 std::pair<int32_t, uint32_t> interpreter_run(uint8_t *program, int32_t param)
103 CpuState local_state;
104 CpuState *state = &local_state;
106 state->regs[X0] = param;
107 state->cycle_count = 0;
112 uint8_t opcode = *state->pc++;
113 state->cycle_count += cycle_table[opcode];
114 dispatch_table[opcode](state);
120 } catch(ReturnException ex)
122 return std::make_pair(state->regs[X0], state->cycle_count);