summaryrefslogtreecommitdiff
path: root/src/instructions/macros.rs
blob: 98cf63d79e78db5405bc95b29c3f18376b5f2f57 (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
// Copyright (c) 2025 taitep
// SPDX-License-Identifier: BSD-2-Clause
//
// This file is part of TRVE (https://gitea.taitep.se/taitep/trve)
// See LICENSE file in the project root for full license text.

#[macro_export]
macro_rules! instr_branch {
    ($name:ident, $cond:expr) => {
        pub fn $name(core: &mut Core, instr: Instruction) -> Result<(), ExceptionType> {
            let a = core.reg_read(instr.rs1());
            let b = core.reg_read(instr.rs2());
            if $cond(a, b) {
                core.pc = core.pc.wrapping_add(instr.imm_b());
            } else {
                core.advance_pc();
            }
            Ok(())
        }
    };
}

#[macro_export]
macro_rules! instr_branch_signed {
    ($name:ident, $cond:expr) => {
        instr_branch!($name, |a, b| $cond((a as i64), (b as i64)));
    };
}

#[macro_export]
macro_rules! instr_op_r {
    ($name:ident, $op:expr) => {
        pub fn $name(core: &mut Core, instr: Instruction) -> Result<(), ExceptionType> {
            let a = core.reg_read(instr.rs1());
            let b = core.reg_read(instr.rs2());
            let res = $op(a, b);
            core.reg_write(instr.rd(), res);
            core.advance_pc();
            Ok(())
        }
    };
}

#[macro_export]
macro_rules! instr_op_i {
    ($name:ident, $op:expr) => {
        pub fn $name(core: &mut Core, instr: Instruction) -> Result<(), ExceptionType> {
            let a = core.reg_read(instr.rs1());
            let b = instr.imm_i();
            let res = $op(a, b);
            core.reg_write(instr.rd(), res);
            core.advance_pc();
            Ok(())
        }
    };
}

#[macro_export]
macro_rules! instr_op {
    ($name:ident, $name_imm:ident, $op:expr) => {
        instr_op_r!($name, $op);
        instr_op_i!($name_imm, $op);
    };
}