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
use crate::addr::Addr;
use std::convert::From;
use std::fmt;

////////////////////////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////////////////////////

/// A struct for representing a general purpose register (eg, `x0`, `x1`, ..., `x32`).
/// This is used in the [`Instruction`](crate::decode::Instruction) enum to distinguish
/// the source and destination registers from other numeric data contained in an instruction.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct Reg(pub(crate) u8);

/// A struct for representing a value that can be held inside of a general purpose register
/// (eg, `x0`, `x1`, ..., `x32`).
///
/// While all general purpose registers are 32-bits wide in rv32i, the *interpretation*
/// of those bits depends on the operation in question. For example, some instructions
/// (such as `lw`) treat registers values as signed integers, while other instructions
/// (such as `lwu`) treat them as unsigned integers.
///
/// Therefore, [`riscy`](crate) uses this type to prevent programmers from assuming
/// one interpretation or the other, and instead, it forces them to explicitly cast any
/// `RegVal` to the representation they need.
///
/// All immediate values used by the [`decode`](crate::decode) module
/// (such as [`ImmS`](crate::decode::ImmS)) can also be cast to `RegVal`.
///
/// ```
/// // get the value of the first argument register, `a0` (also known as `x10`)
/// let value = riscv.reg(10);
/// println!("a0 = {} (as an unsigned integer)", u32::from(value));
/// println!("a0 = {} (as an   signed integer)", i32::from(value));
/// ```
///
/// Several operations which correspond to register-register instructions (eg, `add`, `xor`),
/// are provided as either methods or as traits.
///
/// ```
/// let value1 = RegVal::from_u32(2);
/// let value2 = RegVal::from_u32(3);
///
/// // addition
/// println!("value1 + value2 = {}", u32::from(value1 + value2));
///
/// // bitwise exclusive or
/// println!("value1 ^ value2 = {}", u32::from(value1 ^ value2));
///
/// // left logical shift
/// println!("value1 << value2 = {}", u32::from(value1.shift_left_logical(value2));
/// ```
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub struct RegVal(pub(crate) u32);

////////////////////////////////////////////////////////////////////////////////
// RegVal
////////////////////////////////////////////////////////////////////////////////

impl RegVal {
    /// Compares two `RegVal`s, interpreting them both as signed integers.
    pub fn less_than_signed(&self, other: RegVal) -> bool {
        self.to_i32() < other.to_i32()
    }

    /// Compares two `RegVal`s, interpreting them both as unsigned integers.
    pub fn less_than_unsigned(&self, other: RegVal) -> bool {
        self.to_u32() < other.to_u32()
    }

    /// Compares two `RegVal`s, interpreting them both as signed integers.
    pub fn greater_than_equal_to_signed(&self, other: RegVal) -> bool {
        self.to_i32() >= other.to_i32()
    }

    /// Compares two `RegVal`s, interpreting them both as unsigned integers.
    pub fn greater_than_equal_to_unsigned(&self, other: RegVal) -> bool {
        self.to_u32() >= other.to_u32()
    }

    /// Does a logical left shift of this register by the value in another register.
    ///
    /// A logical left shift is one where the vacant bits are all set to `0`.
    ///
    /// The value in `other` is interpreted as an unsigned integer.
    ///
    /// The `sll` instruction (shift left logical) will only ever supply small values
    /// for `other`. The behavior of this function is only guaranteed for values that
    /// could come from that instruction.
    pub fn shift_left_logical(&self, other: RegVal) -> RegVal {
        let RegVal(x) = *self;
        let RegVal(y) = other;
        RegVal(x << y)
    }

    /// Does a logical right shift of this register by the value in another register.
    ///
    /// A logical right shift is one where the vacant bits are all set to `0`. This is
    /// most common when the register value is interpreted as an unsigned integer, since
    /// it has the effect of dividing by `2` to the power of `other`.

    ///
    /// The value in `other` is interpreted as an unsigned integer.
    ///
    /// The `srl` instruction (shift right logical) will only ever supply small values
    /// for `other`. The behavior of this function is only guaranteed for values that
    /// could come from that instruction.
    pub fn shift_right_logical(&self, other: RegVal) -> RegVal {
        let RegVal(x) = *self;
        let RegVal(y) = other;
        RegVal(x >> y)
    }

    /// Does an arithmetic right shift of this register by the value in another register.
    ///
    /// An arithmetic right shift is one where the vacant bits are all set to a copy of
    /// the most signfint bit. This is most common when the register value is interpreted
    /// as a signed integer, since it has the effect of dividing by `2` to the power of `other`,
    /// while preserving the sign.
    ///
    /// The value in `other` is interpreted as an unsigned integer.
    ///
    /// The `srl` instruction (shift right logical) will only ever supply small values
    /// for `other`. The behavior of this function is only guaranteed for values that
    /// could come from that instruction.
    pub fn shift_right_arithmetic(&self, other: RegVal) -> RegVal {
        let x = self.to_i32();
        let y = other.to_i32();
        RegVal::from_i32(x >> y)
    }

    pub fn from_u32(val: u32) -> RegVal {
        val.into()
    }

    pub fn from_i32(val: i32) -> RegVal {
        val.into()
    }

    pub fn from_addr(addr: Addr) -> RegVal {
        let Addr(val) = addr;
        val.into()
    }

    pub fn to_u32(self) -> u32 {
        self.into()
    }

    pub fn to_i32(self) -> i32 {
        self.into()
    }

    pub fn to_addr(self) -> Addr {
        self.into()
    }
}

////////////////////////////////////////////////////////////////////////////////
// Reg
////////////////////////////////////////////////////////////////////////////////

impl Reg {
    fn friendly(&self) -> String {
        let xi = self.0;
        match xi {
            0 => return "zero".to_owned(),
            1 => return "ra".to_owned(),
            2 => return "sp".to_owned(),
            3 => return "gp".to_owned(),
            4 => return "tp".to_owned(),
            _ => (),
        };

        if xi >= 5 && xi <= 7 {
            return format!("a{}", xi - 5);
        }

        if xi >= 8 && xi <= 9 {
            return format!("s{}", xi - 8);
        }

        if xi >= 10 && xi <= 17 {
            return format!("a{}", xi - 10);
        }

        if xi >= 18 && xi <= 27 {
            return format!("s{}", xi - 16);
        }

        if xi >= 28 && xi <= 31 {
            return format!("s{}", xi - 25);
        }

        unreachable!()
    }
}

////////////////////////////////////////////////////////////////////////////////
// Display
////////////////////////////////////////////////////////////////////////////////

impl fmt::Display for Reg {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.friendly())
    }
}

////////////////////////////////////////////////////////////////////////////////
// Convert
////////////////////////////////////////////////////////////////////////////////

impl From<u32> for RegVal {
    fn from(val: u32) -> RegVal {
        RegVal(val)
    }
}

impl From<i32> for RegVal {
    fn from(val: i32) -> RegVal {
        RegVal(val as u32)
    }
}

impl From<Addr> for RegVal {
    fn from(addr: Addr) -> RegVal {
        let Addr(val) = addr;
        RegVal(val)
    }
}

impl From<RegVal> for u32 {
    fn from(val: RegVal) -> u32 {
        val.0
    }
}

impl From<RegVal> for i32 {
    fn from(val: RegVal) -> i32 {
        val.0 as i32
    }
}

impl From<RegVal> for Addr {
    fn from(val: RegVal) -> Addr {
        Addr(val.0)
    }
}

impl From<u8> for Reg {
    fn from(val: u8) -> Reg {
        assert!(val < 32, "{} is not a valid register number", val);
        Reg(val)
    }
}

////////////////////////////////////////////////////////////////////////////////
// RegVal Arithmetic
////////////////////////////////////////////////////////////////////////////////

impl std::ops::Add for RegVal {
    type Output = RegVal;

    fn add(self, other: RegVal) -> Self {
        let RegVal(x) = self;
        let RegVal(y) = other;
        let (result, _did_overflow) = x.overflowing_add(y);
        RegVal(result)
    }
}

impl std::ops::Sub for RegVal {
    type Output = RegVal;

    fn sub(self, other: RegVal) -> Self {
        let RegVal(x) = self;
        let RegVal(y) = other;
        let (result, _did_overflow) = x.overflowing_sub(y);
        RegVal(result)
    }
}

impl std::ops::BitAnd for RegVal {
    type Output = RegVal;

    fn bitand(self, other: RegVal) -> Self {
        let RegVal(x) = self;
        let RegVal(y) = other;
        RegVal(x & y)
    }
}

impl std::ops::BitOr for RegVal {
    type Output = RegVal;

    fn bitor(self, other: RegVal) -> Self {
        let RegVal(x) = self;
        let RegVal(y) = other;
        RegVal(x | y)
    }
}

impl std::ops::BitXor for RegVal {
    type Output = RegVal;

    fn bitxor(self, other: RegVal) -> Self {
        let RegVal(x) = self;
        let RegVal(y) = other;
        RegVal(x ^ y)
    }
}