1// See LICENSE for license details.
2
3#ifndef _RISCV_EMULATION_H
4#define _RISCV_EMULATION_H
5
6#include "encoding.h"
7#include "bits.h"
8#include <stdint.h>
9
10typedef uintptr_t insn_t;
11typedef void (*emulation_func)(uintptr_t*, uintptr_t, uintptr_t, uintptr_t, insn_t);
12#define DECLARE_EMULATION_FUNC(name) void name(uintptr_t* regs, uintptr_t mcause, uintptr_t mepc, uintptr_t mstatus, insn_t insn)
13
14void misaligned_load_trap(uintptr_t* regs, uintptr_t mcause, uintptr_t mepc);
15void misaligned_store_trap(uintptr_t* regs, uintptr_t mcause, uintptr_t mepc);
16void redirect_trap(uintptr_t epc, uintptr_t mstatus, uintptr_t badaddr);
17DECLARE_EMULATION_FUNC(truly_illegal_insn);
18DECLARE_EMULATION_FUNC(emulate_rvc_0);
19DECLARE_EMULATION_FUNC(emulate_rvc_2);
20
21#define SH_RD 7
22#define SH_RS1 15
23#define SH_RS2 20
24#define SH_RS2C 2
25
26#define RV_X(x, s, n) (((x) >> (s)) & ((1 << (n)) - 1))
27#define RVC_LW_IMM(x) ((RV_X(x, 6, 1) << 2) | (RV_X(x, 10, 3) << 3) | (RV_X(x, 5, 1) << 6))
28#define RVC_LD_IMM(x) ((RV_X(x, 10, 3) << 3) | (RV_X(x, 5, 2) << 6))
29#define RVC_LWSP_IMM(x) ((RV_X(x, 4, 3) << 2) | (RV_X(x, 12, 1) << 5) | (RV_X(x, 2, 2) << 6))
30#define RVC_LDSP_IMM(x) ((RV_X(x, 5, 2) << 3) | (RV_X(x, 12, 1) << 5) | (RV_X(x, 2, 3) << 6))
31#define RVC_SWSP_IMM(x) ((RV_X(x, 9, 4) << 2) | (RV_X(x, 7, 2) << 6))
32#define RVC_SDSP_IMM(x) ((RV_X(x, 10, 3) << 3) | (RV_X(x, 7, 3) << 6))
33#define RVC_RS1S(insn) (8 + RV_X(insn, SH_RD, 3))
34#define RVC_RS2S(insn) (8 + RV_X(insn, SH_RS2C, 3))
35#define RVC_RS2(insn) RV_X(insn, SH_RS2C, 5)
36
37#define SHIFT_RIGHT(x, y) ((y) < 0 ? ((x) << -(y)) : ((x) >> (y)))
38#define GET_REG(insn, pos, regs) ({ \
39  int mask = (1 << (5+LOG_REGBYTES)) - (1 << LOG_REGBYTES); \
40  (uintptr_t*)((uintptr_t)regs + (SHIFT_RIGHT(insn, (pos) - LOG_REGBYTES) & (mask))); \
41})
42#define GET_RS1(insn, regs) (*GET_REG(insn, SH_RS1, regs))
43#define GET_RS2(insn, regs) (*GET_REG(insn, SH_RS2, regs))
44#define GET_RS1S(insn, regs) (*GET_REG(RVC_RS1S(insn), 0, regs))
45#define GET_RS2S(insn, regs) (*GET_REG(RVC_RS2S(insn), 0, regs))
46#define GET_RS2C(insn, regs) (*GET_REG(insn, SH_RS2C, regs))
47#define GET_SP(regs) (*GET_REG(2, 0, regs))
48#define SET_RD(insn, regs, val) (*GET_REG(insn, SH_RD, regs) = (val))
49#define IMM_I(insn) ((int32_t)(insn) >> 20)
50#define IMM_S(insn) (((int32_t)(insn) >> 25 << 5) | (int32_t)(((insn) >> 7) & 0x1f))
51#define MASK_FUNCT3 0x7000
52
53#endif
54