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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
use super::*;

/// A bitvector is a fixed-length vector of bits
/// with the semantics of a CPU register,
/// i.e. it supports two's complement modulo arithmetic.
///
/// Bitvector is just an alias for the [`apint::ApInt`] type.
pub type Bitvector = apint::ApInt;

/// A trait to extend the bitvector type with useful helper functions
/// that are not contained in the [`apint`] crate.
pub trait BitvectorExtended: Sized {
    /// Resize `self` to the target byte size by either zero extending or truncating `self`.
    fn into_resize_unsigned(self, size: ByteSize) -> Self;

    /// Resize `self` to the target byte size by either sign extending or truncating `self`.
    fn into_resize_signed(self, size: ByteSize) -> Self;

    /// Perform a cast operation on the bitvector.
    /// Returns an error for non-implemented cast operations (currently all float-related casts).
    fn cast(&self, kind: CastOpType, width: ByteSize) -> Result<Self, Error>;

    /// Extract a subpiece from the given bitvector.
    fn subpiece(&self, low_byte: ByteSize, size: ByteSize) -> Self;

    /// Perform a unary operation on the given bitvector.
    /// Returns an error for non-implemented operations (currently all float-related operations).
    fn un_op(&self, op: UnOpType) -> Result<Self, Error>;

    /// Perform a binary operation on the given bitvectors.
    /// Returns an error for non-implemented operations (currently all float-related operations).
    fn bin_op(&self, op: BinOpType, rhs: &Self) -> Result<Self, Error>;

    /// Returns the result of `self + rhs` if the computation does not result in a signed integer overflow or underflow.
    fn signed_add_overflow_checked(&self, rhs: &Self) -> Option<Self>;

    /// Returns the result of `self - rhs` if the computation does not result in a signed integer overflow or underflow.
    fn signed_sub_overflow_checked(&self, rhs: &Self) -> Option<Self>;

    /// Return the result of multiplying `self` with `rhs`
    /// and a flag that is set to `true` if the multiplication resulted in a signed integer overflow or underflow.
    ///
    /// Returns an error for bitvectors larger than 8 bytes,
    /// since multiplication for them is not yet implemented in the [`apint`] crate.
    fn signed_mult_with_overflow_flag(&self, rhs: &Self) -> Result<(Self, bool), Error>;

    /// Return the size in bytes of the bitvector.
    fn bytesize(&self) -> ByteSize;
}

impl BitvectorExtended for Bitvector {
    /// Perform a cast operation on the bitvector.
    /// Returns an error for non-implemented cast operations (currently all float-related casts).
    fn cast(&self, kind: CastOpType, width: ByteSize) -> Result<Self, Error> {
        match kind {
            CastOpType::IntZExt => Ok(self.clone().into_zero_extend(width).unwrap()),
            CastOpType::IntSExt => Ok(self.clone().into_sign_extend(width).unwrap()),
            CastOpType::Int2Float | CastOpType::Float2Float | CastOpType::Trunc => {
                Err(anyhow!("Float operations not yet implemented"))
            }
            CastOpType::PopCount => {
                Ok(Bitvector::from_u64(self.count_ones() as u64).into_resize_unsigned(width))
            }
            CastOpType::LzCount => {
                Ok(Bitvector::from_u64(self.leading_zeros() as u64).into_resize_unsigned(width))
            }
        }
    }

    /// Extract a subpiece from the given bitvector.
    fn subpiece(&self, low_byte: ByteSize, size: ByteSize) -> Self {
        self.clone()
            .into_checked_lshr(low_byte.as_bit_length())
            .unwrap()
            .into_truncate(size.as_bit_length())
            .unwrap()
    }

    /// Perform a unary operation on the given bitvector.
    /// Returns an error for non-implemented operations (currently all float-related operations).
    fn un_op(&self, op: UnOpType) -> Result<Self, Error> {
        use UnOpType::*;
        match op {
            Int2Comp => Ok(-self.clone()),
            IntNegate => Ok(self.clone().into_bitnot()),
            BoolNegate => {
                if self.is_zero() {
                    Ok(Bitvector::from_u8(1))
                } else {
                    assert_eq!(self, &Bitvector::from_u8(1)); // Any other value would indicate a bug.
                    Ok(Bitvector::from_u8(0))
                }
            }
            FloatNegate | FloatAbs | FloatSqrt | FloatCeil | FloatFloor | FloatRound | FloatNaN => {
                Err(anyhow!("Float operations not yet implemented"))
            }
        }
    }

    /// Perform a binary operation on the given bitvectors.
    /// Returns an error for non-implemented operations (currently all float-related operations)
    /// or for divisions-by-zero.
    fn bin_op(&self, op: BinOpType, rhs: &Self) -> Result<Self, Error> {
        use BinOpType::*;
        match op {
            Piece => {
                let new_bitwidth = self.width().to_usize() + rhs.width().to_usize();
                let upper_bits = self
                    .clone()
                    .into_zero_extend(new_bitwidth)
                    .unwrap()
                    .into_checked_shl(rhs.width().to_usize())
                    .unwrap();
                let lower_bits = rhs.clone().into_zero_extend(new_bitwidth).unwrap();
                Ok(upper_bits | &lower_bits)
            }
            IntAdd => Ok(self + rhs),
            IntSub => Ok(self - rhs),
            IntCarry => {
                let result = self + rhs;
                if result.checked_ult(self).unwrap() || result.checked_ult(rhs).unwrap() {
                    Ok(Bitvector::from_u8(1))
                } else {
                    Ok(Bitvector::from_u8(0))
                }
            }
            IntSCarry => {
                let result = apint::Int::from(self + rhs);
                let signed_self = apint::Int::from(self.clone());
                let signed_rhs = apint::Int::from(rhs.clone());
                if (result.is_negative() && signed_self.is_positive() && signed_rhs.is_positive())
                    || (!result.is_negative()
                        && signed_self.is_negative()
                        && signed_rhs.is_negative())
                {
                    Ok(Bitvector::from_u8(1))
                } else {
                    Ok(Bitvector::from_u8(0))
                }
            }
            IntSBorrow => {
                let result = apint::Int::from(self - rhs);
                let signed_self = apint::Int::from(self.clone());
                let signed_rhs = apint::Int::from(rhs.clone());
                if (result.is_negative() && !signed_self.is_positive() && signed_rhs.is_negative())
                    || (result.is_positive()
                        && signed_self.is_negative()
                        && signed_rhs.is_positive())
                {
                    Ok(Bitvector::from_u8(1))
                } else {
                    Ok(Bitvector::from_u8(0))
                }
            }
            IntMult => {
                // FIXME: Multiplication for bitvectors larger than 8 bytes is not yet implemented in the `apint` crate (version 0.2).
                if self.width().to_usize() > 64 {
                    Err(anyhow!("Multiplication and division of integers larger than 8 bytes not yet implemented."))
                } else {
                    Ok(self * rhs)
                }
            }
            IntDiv => {
                // FIXME: Division for bitvectors larger than 8 bytes is not yet implemented in the `apint` crate (version 0.2).
                if self.width().to_usize() > 64 {
                    Err(anyhow!("Multiplication and division of integers larger than 8 bytes not yet implemented."))
                } else {
                    Ok(self.clone().into_checked_udiv(rhs)?)
                }
            }
            IntSDiv => {
                // FIXME: Division for bitvectors larger than 8 bytes is not yet implemented in the `apint` crate (version 0.2).
                if self.width().to_usize() > 64 {
                    Err(anyhow!("Multiplication and division of integers larger than 8 bytes not yet implemented."))
                } else {
                    Ok(self.clone().into_checked_sdiv(rhs)?)
                }
            }
            IntRem => {
                // FIXME: Division for bitvectors larger than 8 bytes is not yet implemented in the `apint` crate (version 0.2).
                if self.width().to_usize() > 64 {
                    Err(anyhow!("Multiplication and division of integers larger than 8 bytes not yet implemented."))
                } else {
                    Ok(self.clone().into_checked_urem(rhs)?)
                }
            }
            IntSRem => {
                // FIXME: Division for bitvectors larger than 8 bytes is not yet implemented in the `apint` crate (version 0.2).
                if self.width().to_usize() > 64 {
                    Err(anyhow!("Multiplication and division of integers larger than 8 bytes not yet implemented."))
                } else {
                    Ok(self.clone().into_checked_srem(rhs)?)
                }
            }
            IntLeft => {
                let shift_amount = rhs.try_to_u64().unwrap() as usize;
                if shift_amount < self.width().to_usize() {
                    Ok(self.clone().into_checked_shl(shift_amount).unwrap())
                } else {
                    Ok(Bitvector::zero(self.width()))
                }
            }
            IntRight => {
                let shift_amount = rhs.try_to_u64().unwrap() as usize;
                if shift_amount < self.width().to_usize() {
                    Ok(self.clone().into_checked_lshr(shift_amount).unwrap())
                } else {
                    Ok(Bitvector::zero(self.width()))
                }
            }
            IntSRight => {
                let shift_amount = rhs.try_to_u64().unwrap() as usize;
                if shift_amount < self.width().to_usize() {
                    Ok(self.clone().into_checked_ashr(shift_amount).unwrap())
                } else {
                    let signed_bitvec = apint::Int::from(self.clone());
                    if signed_bitvec.is_negative() {
                        let minus_one =
                            Bitvector::zero(self.width()) - &Bitvector::one(self.width());
                        Ok(minus_one)
                    } else {
                        Ok(Bitvector::zero(self.width()))
                    }
                }
            }
            IntAnd | BoolAnd => Ok(self & rhs),
            IntOr | BoolOr => Ok(self | rhs),
            IntXOr | BoolXOr => Ok(self ^ rhs),
            IntEqual => {
                assert_eq!(self.width(), rhs.width());
                Ok(Bitvector::from((self == rhs) as u8))
            }
            IntNotEqual => {
                assert_eq!(self.width(), rhs.width());
                Ok(Bitvector::from((self != rhs) as u8))
            }
            IntLess => Ok(Bitvector::from(self.checked_ult(rhs).unwrap() as u8)),
            IntLessEqual => Ok(Bitvector::from(self.checked_ule(rhs).unwrap() as u8)),
            IntSLess => Ok(Bitvector::from(self.checked_slt(rhs).unwrap() as u8)),
            IntSLessEqual => Ok(Bitvector::from(self.checked_sle(rhs).unwrap() as u8)),
            FloatEqual | FloatNotEqual | FloatLess | FloatLessEqual => {
                // TODO: Implement floating point comparison operators!
                Err(anyhow!("Float operations not yet implemented"))
            }
            FloatAdd | FloatSub | FloatMult | FloatDiv => {
                // TODO: Implement floating point arithmetic operators!
                Err(anyhow!("Float operations not yet implemented"))
            }
        }
    }

    /// Returns the result of `self + rhs` if the computation does not result in a signed integer overflow or underflow.
    fn signed_add_overflow_checked(&self, rhs: &Self) -> Option<Self> {
        let result = self.clone().into_checked_add(rhs).unwrap();
        match (rhs.sign_bit().to_bool(), self.checked_sle(&result).unwrap()) {
            (true, true) | (false, false) => None,
            _ => Some(result),
        }
    }

    /// Returns the result of `self - rhs` if the computation does not result in a signed integer overflow or underflow.
    fn signed_sub_overflow_checked(&self, rhs: &Self) -> Option<Self> {
        let result = self.clone().into_checked_sub(rhs).unwrap();
        match (rhs.sign_bit().to_bool(), self.checked_sge(&result).unwrap()) {
            (true, true) | (false, false) => None,
            _ => Some(result),
        }
    }

    /// Return the result of multiplying `self` with `rhs`
    /// and a flag that is set to `true` if the multiplication resulted in a signed integer overflow or underflow.
    ///
    /// Returns an error for bitvectors larger than 8 bytes,
    /// since multiplication for them is not yet implemented in the [`apint`] crate.
    fn signed_mult_with_overflow_flag(&self, rhs: &Self) -> Result<(Self, bool), Error> {
        if self.is_zero() {
            Ok((Bitvector::zero(self.width()), false))
        } else if self.width().to_usize() > 64 {
            // FIXME: Multiplication for bitvectors larger than 8 bytes is not yet implemented in the `apint` crate (version 0.2).
            Err(anyhow!(
                "Multiplication and division of integers larger than 8 bytes not yet implemented."
            ))
        } else {
            let result = self.clone().into_checked_mul(rhs).unwrap();
            if result.clone().into_checked_sdiv(self).unwrap() != *rhs {
                Ok((result, true))
            } else {
                Ok((result, false))
            }
        }
    }

    /// Return the size in bytes of the bitvector.
    fn bytesize(&self) -> ByteSize {
        self.width().into()
    }

    /// Resize `self` to the target byte size by either zero extending or truncating `self`.
    fn into_resize_unsigned(self, size: ByteSize) -> Self {
        if self.width() < size.into() {
            self.into_zero_extend(size).unwrap()
        } else {
            self.into_truncate(size).unwrap()
        }
    }

    /// Resize `self` to the target byte size by either sign extending or truncating `self`.
    fn into_resize_signed(self, size: ByteSize) -> Self {
        if self.width() < size.into() {
            self.into_sign_extend(size).unwrap()
        } else {
            self.into_truncate(size).unwrap()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn overflow_checked_add_and_sub() {
        let max = Bitvector::signed_max_value(ByteSize::new(8).into());
        let min = Bitvector::signed_min_value(ByteSize::new(8).into());

        assert_eq!(min.signed_add_overflow_checked(&min), None);
        assert_eq!(
            min.signed_add_overflow_checked(&max),
            Some(-Bitvector::one(ByteSize::new(8).into()))
        );
        assert_eq!(
            max.signed_add_overflow_checked(&min),
            Some(-Bitvector::one(ByteSize::new(8).into()))
        );
        assert_eq!(max.signed_add_overflow_checked(&max), None);

        assert_eq!(
            min.signed_sub_overflow_checked(&min),
            Some(Bitvector::zero(ByteSize::new(8).into()))
        );
        assert_eq!(min.signed_sub_overflow_checked(&max), None);
        assert_eq!(max.signed_sub_overflow_checked(&min), None);
        assert_eq!(
            max.signed_sub_overflow_checked(&max),
            Some(Bitvector::zero(ByteSize::new(8).into()))
        );
    }
}