#include "isa.h" #include #include #include #include size_t op_encode( uint16_t program[], size_t program_size, size_t i, const Op *op) { assert(program_size >= i + 1); uint16_t *l = &program[i]; *l = 0; *l |= op->ty & 0b11111; *l |= (op->op1_reg & 0b111) << 5; if (!op->use_imm) { *l |= (op->op2_reg_or_imm & 0b111) << 9; return 1; } *l |= 1 << 8; // imm assert(program_size >= i + 2); program[i + 1] = op->op2_reg_or_imm; return 2; } size_t op_decode( Op *op, const uint16_t program[], size_t program_size, size_t i) { *op = (Op) { }; assert(program_size >= i + 1); uint16_t line = program[i]; uint16_t opcode = line & 0b11111; if (opcode >= Opcode_size) { printf("error: invalid opcode\n"); return 0; } op->ty = (Opcode)opcode; op->op1_reg = line >> 5 & 0b111; op->use_imm = line >> 8 & 1; if (!op->use_imm) { op->op2_reg_or_imm = line >> 9 & 0b111; return 1; } assert(program_size >= i + 2); op->op2_reg_or_imm = program[i + 1]; return 2; } static const char *opty_str(Opcode ty); const char *op_reg_str(uint16_t reg) { assert(reg <= 7); const char *strs[] = { "r0", "r1", "r2", "r3", "sp", "bp", "fl", "ip" }; return strs[reg]; } static void op_print_op1(const Op *op) { printf(" \033[1;36m%s", op_reg_str(op->op1_reg)); } static void op_print_op2(const Op *op) { if (op->use_imm) { printf("\033[0;35m0x%x", op->op2_reg_or_imm); } else { printf("\033[1;36m%s", op_reg_str(op->op2_reg_or_imm)); } } static void op_print(const Op *op) { printf("\033[1;31m%s", opty_str(op->ty)); switch (op->ty) { case Op_Hlt: break; case Op_Load: op_print_op1(op); printf("\033[37m, ["); op_print_op2(op); printf("\033[37m]"); break; case Op_Store: printf(" \033[37m["); op_print_op2(op); printf("\033[37m],"); op_print_op1(op); break; default: op_print_op1(op); printf("\033[37m, "); op_print_op2(op); break; } printf("\033[0m\n"); } void op_print_line(const Op *op, uint16_t ip) { printf("\033[37m[\033[35m%04x\033[37m] ", ip); op_print(op); } const char *opty_str(Opcode ty) { switch (ty) { #define X(A, B) \ case Op_##A: \ return #B; OP_LIST #undef X } assert(false); }