Skip to main content

hir_ty/next_solver/consts/
int.rs

1use std::{fmt, hash::Hash, num::NonZero};
2
3use rustc_abi::{Size, TargetDataLayout};
4use rustc_apfloat::Float;
5use rustc_apfloat::ieee::{Double, Half, Quad, Single};
6
7/// The raw bytes of a simple value.
8///
9/// This is a packed struct in order to allow this type to be optimally embedded in enums
10/// (like Scalar).
11#[derive(Clone, Copy, Eq, PartialEq, Hash)]
12#[repr(Rust, packed)]
13pub struct ScalarInt {
14    /// The first `size` bytes of `data` are the value.
15    /// Do not try to read less or more bytes than that. The remaining bytes must be 0.
16    data: u128,
17    size: NonZero<u8>,
18}
19
20impl ScalarInt {
21    pub const TRUE: ScalarInt = ScalarInt { data: 1_u128, size: NonZero::new(1).unwrap() };
22    pub const FALSE: ScalarInt = ScalarInt { data: 0_u128, size: NonZero::new(1).unwrap() };
23
24    fn raw(data: u128, size: Size) -> Self {
25        Self { data, size: NonZero::new(size.bytes() as u8).unwrap() }
26    }
27
28    #[inline]
29    pub fn size(self) -> Size {
30        Size::from_bytes(self.size.get())
31    }
32
33    /// Make sure the `data` fits in `size`.
34    /// This is guaranteed by all constructors here, but having had this check saved us from
35    /// bugs many times in the past, so keeping it around is definitely worth it.
36    #[inline(always)]
37    fn check_data(self) {
38        // Using a block `{self.data}` here to force a copy instead of using `self.data`
39        // directly, because `debug_assert_eq` takes references to its arguments and formatting
40        // arguments and would thus borrow `self.data`. Since `Self`
41        // is a packed struct, that would create a possibly unaligned reference, which
42        // is UB.
43        debug_assert_eq!(
44            self.size().truncate(self.data),
45            { self.data },
46            "Scalar value {:#x} exceeds size of {} bytes",
47            { self.data },
48            self.size
49        );
50    }
51
52    #[inline]
53    pub fn null(size: Size) -> Self {
54        Self::raw(0, size)
55    }
56
57    #[inline]
58    pub fn is_null(self) -> bool {
59        self.data == 0
60    }
61
62    #[inline]
63    pub fn try_from_uint(i: impl Into<u128>, size: Size) -> Option<Self> {
64        let (r, overflow) = Self::truncate_from_uint(i, size);
65        if overflow { None } else { Some(r) }
66    }
67
68    /// Returns the truncated result, and whether truncation changed the value.
69    #[inline]
70    pub fn truncate_from_uint(i: impl Into<u128>, size: Size) -> (Self, bool) {
71        let data = i.into();
72        let r = Self::raw(size.truncate(data), size);
73        (r, r.data != data)
74    }
75
76    #[inline]
77    pub fn try_from_int(i: impl Into<i128>, size: Size) -> Option<Self> {
78        let (r, overflow) = Self::truncate_from_int(i, size);
79        if overflow { None } else { Some(r) }
80    }
81
82    /// Returns the truncated result, and whether truncation changed the value.
83    #[inline]
84    pub fn truncate_from_int(i: impl Into<i128>, size: Size) -> (Self, bool) {
85        let data = i.into();
86        // `into` performed sign extension, we have to truncate
87        let r = Self::raw(size.truncate(data as u128), size);
88        (r, size.sign_extend(r.data) != data)
89    }
90
91    #[inline]
92    pub fn try_from_target_usize(
93        i: impl Into<u128>,
94        data_layout: &TargetDataLayout,
95    ) -> Option<Self> {
96        Self::try_from_uint(i, data_layout.pointer_size())
97    }
98
99    /// Try to convert this ScalarInt to the raw underlying bits.
100    /// Fails if the size is wrong. Generally a wrong size should lead to a panic,
101    /// but Miri sometimes wants to be resilient to size mismatches,
102    /// so the interpreter will generally use this `try` method.
103    #[inline]
104    pub fn try_to_bits(self, target_size: Size) -> Result<u128, Size> {
105        assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST");
106        if target_size.bytes() == u64::from(self.size.get()) {
107            self.check_data();
108            Ok(self.data)
109        } else {
110            Err(self.size())
111        }
112    }
113
114    #[inline]
115    pub fn to_bits(self, target_size: Size) -> u128 {
116        self.try_to_bits(target_size).unwrap_or_else(|size| {
117            panic!("expected int of size {}, but got size {}", target_size.bytes(), size.bytes())
118        })
119    }
120
121    /// Extracts the bits from the scalar without checking the size.
122    #[inline]
123    pub fn to_bits_unchecked(self) -> u128 {
124        self.check_data();
125        self.data
126    }
127
128    /// Converts the `ScalarInt` to an unsigned integer of the given size.
129    /// Panics if the size of the `ScalarInt` is not equal to `size`.
130    #[inline]
131    pub fn to_uint(self, size: Size) -> u128 {
132        self.to_bits(size)
133    }
134
135    #[inline]
136    // FIXME: delete this, it has been removed on the rustc side
137    pub fn to_uint_unchecked(self) -> u128 {
138        self.data
139    }
140
141    /// Converts the `ScalarInt` to `u8`.
142    /// Panics if the `size` of the `ScalarInt`in not equal to 1 byte.
143    #[inline]
144    pub fn to_u8(self) -> u8 {
145        self.to_uint(Size::from_bits(8)).try_into().unwrap()
146    }
147
148    /// Converts the `ScalarInt` to `u16`.
149    /// Panics if the size of the `ScalarInt` in not equal to 2 bytes.
150    #[inline]
151    pub fn to_u16(self) -> u16 {
152        self.to_uint(Size::from_bits(16)).try_into().unwrap()
153    }
154
155    /// Converts the `ScalarInt` to `u32`.
156    /// Panics if the `size` of the `ScalarInt` in not equal to 4 bytes.
157    #[inline]
158    pub fn to_u32(self) -> u32 {
159        self.to_uint(Size::from_bits(32)).try_into().unwrap()
160    }
161
162    /// Converts the `ScalarInt` to `u64`.
163    /// Panics if the `size` of the `ScalarInt` in not equal to 8 bytes.
164    #[inline]
165    pub fn to_u64(self) -> u64 {
166        self.to_uint(Size::from_bits(64)).try_into().unwrap()
167    }
168
169    /// Converts the `ScalarInt` to `u128`.
170    /// Panics if the `size` of the `ScalarInt` in not equal to 16 bytes.
171    #[inline]
172    pub fn to_u128(self) -> u128 {
173        self.to_uint(Size::from_bits(128))
174    }
175
176    #[inline]
177    pub fn to_target_usize(&self, data_layout: &TargetDataLayout) -> u64 {
178        self.to_uint(data_layout.pointer_size()).try_into().unwrap()
179    }
180
181    /// Converts the `ScalarInt` to `bool`.
182    /// Panics if the `size` of the `ScalarInt` is not equal to 1 byte.
183    /// Errors if it is not a valid `bool`.
184    #[inline]
185    pub fn try_to_bool(self) -> Result<bool, ()> {
186        match self.to_u8() {
187            0 => Ok(false),
188            1 => Ok(true),
189            _ => Err(()),
190        }
191    }
192
193    /// Converts the `ScalarInt` to a signed integer of the given size.
194    /// Panics if the size of the `ScalarInt` is not equal to `size`.
195    #[inline]
196    pub fn to_int(self, size: Size) -> i128 {
197        let b = self.to_bits(size);
198        size.sign_extend(b)
199    }
200
201    #[inline]
202    // FIXME: delete this, it has been removed on the rustc side
203    pub fn to_int_unchecked(self) -> i128 {
204        self.size().sign_extend(self.data)
205    }
206
207    /// Converts the `ScalarInt` to i8.
208    /// Panics if the size of the `ScalarInt` is not equal to 1 byte.
209    pub fn to_i8(self) -> i8 {
210        self.to_int(Size::from_bits(8)).try_into().unwrap()
211    }
212
213    /// Converts the `ScalarInt` to i16.
214    /// Panics if the size of the `ScalarInt` is not equal to 2 bytes.
215    pub fn to_i16(self) -> i16 {
216        self.to_int(Size::from_bits(16)).try_into().unwrap()
217    }
218
219    /// Converts the `ScalarInt` to i32.
220    /// Panics if the size of the `ScalarInt` is not equal to 4 bytes.
221    pub fn to_i32(self) -> i32 {
222        self.to_int(Size::from_bits(32)).try_into().unwrap()
223    }
224
225    /// Converts the `ScalarInt` to i64.
226    /// Panics if the size of the `ScalarInt` is not equal to 8 bytes.
227    pub fn to_i64(self) -> i64 {
228        self.to_int(Size::from_bits(64)).try_into().unwrap()
229    }
230
231    /// Converts the `ScalarInt` to i128.
232    /// Panics if the size of the `ScalarInt` is not equal to 16 bytes.
233    pub fn to_i128(self) -> i128 {
234        self.to_int(Size::from_bits(128))
235    }
236
237    #[inline]
238    pub fn to_target_isize(&self, data_layout: &TargetDataLayout) -> i64 {
239        self.to_int(data_layout.pointer_size()).try_into().unwrap()
240    }
241
242    #[inline]
243    pub fn to_float<F: Float>(self) -> F {
244        // Going through `to_uint` to check size and truncation.
245        F::from_bits(self.to_bits(Size::from_bits(F::BITS)))
246    }
247
248    #[inline]
249    pub fn to_f16(self) -> Half {
250        self.to_float()
251    }
252
253    #[inline]
254    pub fn to_f32(self) -> Single {
255        self.to_float()
256    }
257
258    #[inline]
259    pub fn to_f64(self) -> Double {
260        self.to_float()
261    }
262
263    #[inline]
264    pub fn to_f128(self) -> Quad {
265        self.to_float()
266    }
267}
268
269macro_rules! from_x_for_scalar_int {
270    ($($ty:ty),*) => {
271        $(
272            impl From<$ty> for ScalarInt {
273                #[inline]
274                fn from(u: $ty) -> Self {
275                    Self {
276                        data: u128::from(u),
277                        size: NonZero::new(size_of::<$ty>() as u8).unwrap(),
278                    }
279                }
280            }
281        )*
282    }
283}
284
285macro_rules! from_scalar_int_for_x {
286    ($($ty:ty),*) => {
287        $(
288            impl From<ScalarInt> for $ty {
289                #[inline]
290                fn from(int: ScalarInt) -> Self {
291                    // The `unwrap` cannot fail because to_uint (if it succeeds)
292                    // is guaranteed to return a value that fits into the size.
293                    int.to_uint(Size::from_bytes(size_of::<$ty>()))
294                       .try_into().unwrap()
295                }
296            }
297        )*
298    }
299}
300
301from_x_for_scalar_int!(u8, u16, u32, u64, u128, bool);
302from_scalar_int_for_x!(u8, u16, u32, u64, u128);
303
304impl TryFrom<ScalarInt> for bool {
305    type Error = ();
306    #[inline]
307    fn try_from(int: ScalarInt) -> Result<Self, ()> {
308        int.try_to_bool()
309    }
310}
311
312impl From<char> for ScalarInt {
313    #[inline]
314    fn from(c: char) -> Self {
315        (c as u32).into()
316    }
317}
318
319macro_rules! from_x_for_scalar_int_signed {
320    ($($ty:ty),*) => {
321        $(
322            impl From<$ty> for ScalarInt {
323                #[inline]
324                fn from(u: $ty) -> Self {
325                    Self {
326                        data: u128::from(u.cast_unsigned()), // go via the unsigned type of the same size
327                        size: NonZero::new(size_of::<$ty>() as u8).unwrap(),
328                    }
329                }
330            }
331        )*
332    }
333}
334
335macro_rules! from_scalar_int_for_x_signed {
336    ($($ty:ty),*) => {
337        $(
338            impl From<ScalarInt> for $ty {
339                #[inline]
340                fn from(int: ScalarInt) -> Self {
341                    // The `unwrap` cannot fail because to_int (if it succeeds)
342                    // is guaranteed to return a value that fits into the size.
343                    int.to_int(Size::from_bytes(size_of::<$ty>()))
344                       .try_into().unwrap()
345                }
346            }
347        )*
348    }
349}
350
351from_x_for_scalar_int_signed!(i8, i16, i32, i64, i128);
352from_scalar_int_for_x_signed!(i8, i16, i32, i64, i128);
353
354impl From<std::cmp::Ordering> for ScalarInt {
355    #[inline]
356    fn from(c: std::cmp::Ordering) -> Self {
357        // Here we rely on `cmp::Ordering` having the same values in host and target!
358        ScalarInt::from(c as i8)
359    }
360}
361
362/// Error returned when a conversion from ScalarInt to char fails.
363#[derive(Debug)]
364pub struct CharTryFromScalarInt;
365
366impl TryFrom<ScalarInt> for char {
367    type Error = CharTryFromScalarInt;
368
369    #[inline]
370    fn try_from(int: ScalarInt) -> Result<Self, Self::Error> {
371        match char::from_u32(int.to_u32()) {
372            Some(c) => Ok(c),
373            None => Err(CharTryFromScalarInt),
374        }
375    }
376}
377
378impl From<Half> for ScalarInt {
379    #[inline]
380    fn from(f: Half) -> Self {
381        // We trust apfloat to give us properly truncated data.
382        Self { data: f.to_bits(), size: NonZero::new((Half::BITS / 8) as u8).unwrap() }
383    }
384}
385
386impl From<ScalarInt> for Half {
387    #[inline]
388    fn from(int: ScalarInt) -> Self {
389        Self::from_bits(int.to_bits(Size::from_bytes(2)))
390    }
391}
392
393impl From<Single> for ScalarInt {
394    #[inline]
395    fn from(f: Single) -> Self {
396        // We trust apfloat to give us properly truncated data.
397        Self { data: f.to_bits(), size: NonZero::new((Single::BITS / 8) as u8).unwrap() }
398    }
399}
400
401impl From<ScalarInt> for Single {
402    #[inline]
403    fn from(int: ScalarInt) -> Self {
404        Self::from_bits(int.to_bits(Size::from_bytes(4)))
405    }
406}
407
408impl From<Double> for ScalarInt {
409    #[inline]
410    fn from(f: Double) -> Self {
411        // We trust apfloat to give us properly truncated data.
412        Self { data: f.to_bits(), size: NonZero::new((Double::BITS / 8) as u8).unwrap() }
413    }
414}
415
416impl From<ScalarInt> for Double {
417    #[inline]
418    fn from(int: ScalarInt) -> Self {
419        Self::from_bits(int.to_bits(Size::from_bytes(8)))
420    }
421}
422
423impl From<Quad> for ScalarInt {
424    #[inline]
425    fn from(f: Quad) -> Self {
426        // We trust apfloat to give us properly truncated data.
427        Self { data: f.to_bits(), size: NonZero::new((Quad::BITS / 8) as u8).unwrap() }
428    }
429}
430
431impl From<ScalarInt> for Quad {
432    #[inline]
433    fn from(int: ScalarInt) -> Self {
434        Self::from_bits(int.to_bits(Size::from_bytes(16)))
435    }
436}
437
438impl fmt::Debug for ScalarInt {
439    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
440        // Dispatch to LowerHex below.
441        write!(f, "0x{self:x}")
442    }
443}
444
445impl fmt::LowerHex for ScalarInt {
446    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
447        self.check_data();
448        if f.alternate() {
449            // Like regular ints, alternate flag adds leading `0x`.
450            write!(f, "0x")?;
451        }
452        // Format as hex number wide enough to fit any value of the given `size`.
453        // So data=20, size=1 will be "0x14", but with size=4 it'll be "0x00000014".
454        // Using a block `{self.data}` here to force a copy instead of using `self.data`
455        // directly, because `write!` takes references to its formatting arguments and
456        // would thus borrow `self.data`. Since `Self`
457        // is a packed struct, that would create a possibly unaligned reference, which
458        // is UB.
459        write!(f, "{:01$x}", { self.data }, self.size.get() as usize * 2)
460    }
461}
462
463impl fmt::UpperHex for ScalarInt {
464    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465        self.check_data();
466        // Format as hex number wide enough to fit any value of the given `size`.
467        // So data=20, size=1 will be "0x14", but with size=4 it'll be "0x00000014".
468        // Using a block `{self.data}` here to force a copy instead of using `self.data`
469        // directly, because `write!` takes references to its formatting arguments and
470        // would thus borrow `self.data`. Since `Self`
471        // is a packed struct, that would create a possibly unaligned reference, which
472        // is UB.
473        write!(f, "{:01$X}", { self.data }, self.size.get() as usize * 2)
474    }
475}
476
477impl fmt::Display for ScalarInt {
478    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
479        self.check_data();
480        write!(f, "{}", { self.data })
481    }
482}