aboutsummaryrefslogtreecommitdiff
path: root/vm/src/vm.c
blob: 559ad5efe8e998e418766266dcf79a5421143105 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
#include "vm.h"

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// TODO: Make all these arguments of vm_new().

// Program's main memory stack size.
#define PROGRAM_STACK_SIZE (64 * 1024)

// Locals stack size.
#define LOCALS_STACK_SIZE 1024

// Frame stack size.
#define FRAME_STACK_SIZE (16 * 1024)

// Block stack size.
#define BLOCK_STACK_SIZE 1024

#define IMPLICIT_LABEL -1

// Locals index.
typedef size_t Index;

// Bools are internally I32s. 0 = false, non-zero = true.
static Type     Bool = I32;
typedef int32_t bool_t;

/// Function frame.
///
/// Every Frame implicitly starts a Block. The function's locals are inside this
/// implicit block.
typedef struct Frame {
  Label label;
} Frame;

/// A block of code, used for control flow.
///
/// Blocks have a label that the machine can jump to. Jumps are constrained to
/// the block labels that are in scope.
///
/// Block termination automatically frees the block's locals.
typedef struct Block {
  Label  label;
  size_t addr;         // Address (saved program counter) of the block.
  size_t locals_start; // Offset into the locals stack.
  size_t locals_size;  // Total size in bytes of local variables.
} Block;

typedef struct Vm {
  struct {
    bool exit : 1;
  } flags;
  int32_t  exit_code;
  size_t   pc;     // Program instruction counter.
  size_t   sp;     // Program stack pointer. Points to next available slot.
  size_t   lsp;    // Locals stack pointer. Points to next available slot.
  size_t   fsp;    // Frame stack pointer.
  size_t   bsp;    // Block stack pointer. Points to current Block.
  uint8_t* stack;  // Program stack. Program's main memory.
  uint8_t* locals; // Locals stack. Stores locals for each Block.
  Frame*   frames; // Frame stack for function calls.
  Block*   blocks; // Block stack for control flow.
} Vm;

Vm* vm_new() {
  Vm* vm = calloc(1, sizeof(Vm));
  if (!vm) {
    goto cleanup;
  }
  if (!(vm->stack = calloc(1, PROGRAM_STACK_SIZE))) {
    goto cleanup;
  }
  if (!(vm->locals = calloc(1, LOCALS_STACK_SIZE))) {
    goto cleanup;
  }
  if (!(vm->frames = calloc(FRAME_STACK_SIZE, sizeof(Frame)))) {
    goto cleanup;
  }
  if (!(vm->blocks = calloc(BLOCK_STACK_SIZE, sizeof(Block)))) {
    goto cleanup;
  }
  return vm;

cleanup:
  vm_del(&vm);
  return 0;
}

void vm_del(Vm** pVm) {
  if (pVm && *pVm) {
    Vm* vm = *pVm;
    if (vm->stack) {
      free(vm->stack);
    }
    if (vm->locals) {
      free(vm->locals);
    }
    if (vm->frames) {
      free(vm->frames);
    }
    if (vm->blocks) {
      free(vm->blocks);
    }
    free(vm);
    *pVm = 0;
  }
}

// static size_t get_size(Type type) {
//   switch (type) {
//   case I32:
//     return sizeof(int32_t);
//   }
//   assert(false);
//   return 0;
// }

// TODO: Not used?
#define VM_ASSERT(expr) \
  {}

#define TOP(vm, type)              \
  (assert(vm->sp >= sizeof(type)), \
   *((const type*)&vm->stack[vm->sp - sizeof(type)]))

#define PUSH(vm, value, type)                          \
  assert(vm->sp + sizeof(type) <= PROGRAM_STACK_SIZE); \
  *((type*)(&vm->stack[vm->sp])) = value;              \
  vm->sp += sizeof(type);

#define POP(vm, type)                                      \
  (assert(vm->sp >= sizeof(type)), vm->sp -= sizeof(type), \
   *((type*)(&vm->stack[vm->sp])))

#define BLOCK_PUSH(vm, block)         \
  assert(vm->bsp < BLOCK_STACK_SIZE); \
  vm->blocks[++vm->bsp] = block;

#define BLOCK_POP(vm)                            \
  assert(vm->bsp > 0);                           \
  vm->locals -= vm->blocks[vm->bsp].locals_size; \
  vm->bsp--;

#define PUSH_LOCAL(vm, type)                           \
  assert(vm->lsp + sizeof(type) <= LOCALS_STACK_SIZE); \
  /* Auto-initialize locals to 0. */                   \
  *((type*)(&vm->locals[vm->lsp])) = 0;                \
  vm->lsp += sizeof(type);                             \
  vm->blocks[vm->bsp].locals_size += sizeof(type);

#define POP_LOCAL(vm, type)                                  \
  (assert(vm->lsp >= sizeof(type)), vm->lsp -= sizeof(type), \
   vm->blocks[vm->bsp].locals -= sizeof(type),               \
   *((type*)(&vm->locals[vm->lsp])))

// TODO: Should be an offset from the current frame, not block.
#define GET_LOCAL_PTR(vm, idx, type) \
  ((const type*)(&vm->locals[vm->blocks[vm->bsp].locals_start + idx]))
// TODO: Same here.
#define GET_LOCAL_PTR_MUT(vm, idx, type) \
  ((type*)(&vm->locals[vm->blocks[vm->bsp].locals_start + idx]))

#define LOCAL_RD(vm, idx, type) (*GET_LOCAL_PTR(vm, idx, type))

#define LOCAL_WR(vm, idx, val, type) (*GET_LOCAL_PTR_MUT(vm, idx, type) = val)

static void push(Vm* vm, Inst inst) {
  switch (inst.type) {
  case I32:
    PUSH(vm, inst.payload.i32, int32_t);
    break;
  case F32:
    PUSH(vm, inst.payload.f32, float);
    break;
  }
}

static Value pop(Vm* vm, Type type) {
  Value val;
  switch (type) {
  case I32:
    val.i32 = POP(vm, int32_t);
    break;
  case F32:
    val.f32 = POP(vm, float);
    break;
  }
  return val;
}

static void vm_exit(Vm* vm, Inst inst) {
  vm->exit_code  = vm->sp == 0 ? 0 : POP(vm, int32_t);
  vm->flags.exit = true;
}

#define ADD(vm, a, b, field, type)         \
  {                                        \
    type result = ((a.field) + (b.field)); \
    PUSH(vm, result, type);                \
  }

static void add(Vm* vm, Type type) {
  Value opr1 = pop(vm, type);
  Value opr2 = pop(vm, type);
  switch (type) {
  case I32:
    ADD(vm, opr1, opr2, i32, int32_t);
    break;

  case F32:
    ADD(vm, opr1, opr2, f32, float);
    break;
  }
}

static void dec(Vm* vm, Type type) {
  Value top = pop(vm, type);
  switch (type) {
  case I32:
    PUSH(vm, top.i32 - 1, int32_t);
    break;
  case F32:
    PUSH(vm, top.f32 - 1.0f, float);
    break;
  }
}

static void empty(Vm* vm) { PUSH(vm, vm->sp == 0, bool_t); }

#define CMP(vm, val, type) (POP(vm, type) == val)

static void cmp(Vm* vm, Inst inst) {
  switch (inst.type) {
  case I32:
    PUSH(vm, CMP(vm, inst.payload.i32, int32_t), bool_t);
    break;
  case F32:
    PUSH(vm, CMP(vm, inst.payload.f32, float), bool_t);
    break;
  }
}

static void end(Vm* vm) { BLOCK_POP(vm); }

static void loop(Vm* vm, Inst inst) {
  const Block block = (Block){.label = inst.payload.i32, .addr = vm->pc};
  BLOCK_PUSH(vm, block);
}

static void br(Vm* vm, Inst inst) {
  const Branch  branch         = inst.payload.branch;
  const int32_t label          = branch.label;
  const bool    value          = branch.expected;
  const bool    is_conditional = branch.conditional;
  bool should_branch = is_conditional ? POP(vm, bool_t) == value : true;
  // printf("is conditional: %d\n", is_conditional);
  // printf("value: %d\n", value);
  // printf("should branch: %d\n", should_branch);
  if (should_branch) {
    while (vm->bsp > 0) {
      const Block block = vm->blocks[vm->bsp];
      if (block.label == label) {
        vm->pc = block.addr;
        vm->pc--; // Account for increment at every step of the VM loop.
        return;
      }
      vm->bsp--;
    }
    // We should be able to find the label in the block stack.
    assert(false);
  }
}

static void vm_break(Vm* vm, Inst inst) {
  // TODO.
  // Step over instructions until an End instruction is found.
}

static void local(Vm* vm, Type type) {
  switch (type) {
  case I32:
    PUSH_LOCAL(vm, int32_t);
    break;
  case F32:
    PUSH_LOCAL(vm, float);
    break;
  }
}

static void local_rd(Vm* vm, Inst inst) {
  const Index idx = (Index)inst.payload.u64;
  switch (inst.type) {
  case I32:
    PUSH(vm, LOCAL_RD(vm, idx, int32_t), int32_t);
    break;
  case F32:
    PUSH(vm, LOCAL_RD(vm, idx, float), float);
    break;
  }
}

static void local_wr(Vm* vm, Inst inst) {
  const Index idx = (Index)inst.payload.u64;
  const Value top = pop(vm, inst.type);
  switch (inst.type) {
  case I32:
    LOCAL_WR(vm, idx, top.i32, int32_t);
    break;
  case F32:
    LOCAL_WR(vm, idx, top.f32, float);
    break;
  }
}

static void exec(Vm* vm, Inst inst) {
  switch (inst.op) {
  case Exit:
    vm_exit(vm, inst);
    break;
  case Push:
    push(vm, inst);
    break;
  case Pop:
    pop(vm, inst.type);
    break;
  case Add:
    add(vm, inst.type);
    break;
  case Sub:
    break;
  case Mul:
    break;
  case Div:
    break;
  case Dec:
    dec(vm, inst.type);
    break;
  case Empty:
    empty(vm);
    break;
  case Cmp:
    cmp(vm, inst);
    break;
  case End:
    end(vm);
    break;
  case Break:
    vm_break(vm, inst);
    break;
  case Loop:
    loop(vm, inst);
    break;
  case Br:
    br(vm, inst);
    break;
  case Func: // TODO
    break;
  case Arg: // TODO
    break;
  case Call: // TODO
    break;
  case Local:
    local(vm, inst.type);
    break;
  case LocalRd:
    local_rd(vm, inst);
    break;
  case LocalWr:
    local_wr(vm, inst);
    break;
  }
}

static void init(Vm* vm) {
  // Create an implicit frame for the start of the program.
  vm->frames[0] = (Frame){.label = IMPLICIT_LABEL};
  vm->blocks[0] = (Block){.label = IMPLICIT_LABEL};
  // TODO: Reset all Vm state.
}

int vm_run(Vm* vm, const Inst instructions[], size_t count) {
  assert(vm);
  init(vm);
  for (vm->pc = 0; !vm->flags.exit && vm->pc < count; vm->pc++) {
    const Inst inst = instructions[vm->pc];
    exec(vm, inst);
  }
  // printf("exit code: %d\n", vm->exit_code);
  return vm->exit_code;
}

void vm_print_stack(const Vm* vm) {
  printf("stack start\n");
  for (size_t i = 0; i < vm->sp; ++i) {
    const char sep = (i == vm->sp - 1) ? '\n' : ' ';
    printf("%x%c", vm->stack[i], sep);
  }
  printf("stack end\n");
}