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

use crate::consts::{DWord, RegId, Word};

const MASK_REGISTER: Word = 0x1f;

#[derive(Debug, Clone, Copy)]
pub struct Instruction(pub Word);

#[allow(dead_code)]
impl Instruction {
    #[inline]
    pub fn opcode(self) -> u8 {
        (self.0 & 0x7f) as u8
    }

    /// Returns the opcode of the instruction, with the last 2 bits stripped away, as they are always 0b11 in a non-compressed instruction
    #[inline]
    pub fn opcode_noncompressed(self) -> u8 {
        debug_assert_eq!(self.0 & 0b11, 0b11, "Compressed (or invalid) opcode");
        (self.0 >> 2 & 0x1f) as u8
    }

    #[inline]
    pub fn rd(self) -> RegId {
        (self.0 >> 7 & MASK_REGISTER) as RegId
    }

    #[inline]
    pub fn funct3(self) -> u8 {
        (self.0 >> 12 & 0x7) as u8
    }

    #[inline]
    pub fn rs1(self) -> RegId {
        (self.0 >> 15 & MASK_REGISTER) as RegId
    }

    #[inline]
    pub fn rs2(self) -> RegId {
        (self.0 >> 20 & MASK_REGISTER) as RegId
    }

    #[inline]
    pub fn funct7(self) -> u8 {
        (self.0 >> 25 & 0x7f) as u8
    }

    #[inline]
    pub fn imm_i(self) -> DWord {
        (self.0 as i64 >> 20) as DWord
    }

    #[inline]
    pub fn imm_s(self) -> DWord {
        (self.0 as i64 >> (25 - 5) & (0x7f << 5)) as DWord | (self.0 >> 7 & 0b1111) as DWord
    }

    #[inline]
    pub fn imm_b(self) -> DWord {
        let imm_12 = ((self.0 & 0x8000_0000) as i32 as i64 >> (31 - 12)) as DWord;
        let imm_10_5 = ((self.0 >> 25 & 0x3f) << 5) as DWord;
        let imm_4_1 = ((self.0 >> 8 & 0xf) << 1) as DWord;
        let imm_11 = ((self.0 >> 7 & 1) << 11) as DWord;

        imm_12 | imm_10_5 | imm_4_1 | imm_11
    }

    #[inline]
    pub fn imm_u(self) -> DWord {
        (self.0 & 0xffff_f000) as i32 as i64 as DWord
    }

    #[inline]
    pub fn imm_j(self) -> DWord {
        let imm_20 = ((self.0 & 0x8000_0000) as i32 as i64 >> (31 - 20)) as DWord;
        let imm_10_1 = ((self.0 >> 21 & 0x3ff) << 1) as DWord;
        let imm_11 = ((self.0 >> 20 & 1) << 11) as DWord;
        let imm_19_12 = ((self.0 >> 12 & 0xff) << 12) as DWord;

        imm_20 | imm_10_1 | imm_11 | imm_19_12
    }

    // The following are AFAIK only used for shift by immediate operations

    #[inline]
    fn funct6(self) -> u8 {
        (self.0 >> 26 & 0x3f) as u8
    }

    #[inline]
    fn imm_shamt(self) -> usize {
        (self.0 >> 20 & 0x3f) as usize
    }
}