1 use std::convert::TryFrom;
5 ieee::{Double, Single},
8 use rustc_macros::HashStable;
9 use rustc_target::abi::{HasDataLayout, Size, TargetDataLayout};
11 use crate::ty::{ParamEnv, Ty, TyCtxt};
13 use super::{sign_extend, truncate, AllocId, Allocation, InterpResult, Pointer, PointerArithmetic};
15 /// Represents the result of a raw const operation, pre-validation.
16 #[derive(Clone, HashStable)]
17 pub struct RawConst<'tcx> {
18 // the value lives here, at offset 0, and that allocation definitely is a `AllocKind::Memory`
19 // (so you can use `AllocMap::unwrap_memory`).
20 pub alloc_id: AllocId,
24 /// Represents a constant value in Rust. `Scalar` and `Slice` are optimizations for
25 /// array length computations, enum discriminants and the pattern matching logic.
26 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash)]
28 pub enum ConstValue<'tcx> {
29 /// Used only for types with `layout::abi::Scalar` ABI and ZSTs.
31 /// Not using the enum `Value` to encode that this must not be `Uninit`.
34 /// Used only for `&[u8]` and `&str`
35 Slice { data: &'tcx Allocation, start: usize, end: usize },
37 /// A value not represented/representable by `Scalar` or `Slice`
39 /// The backing memory of the value, may contain more memory than needed for just the value
40 /// in order to share `Allocation`s between values
41 alloc: &'tcx Allocation,
42 /// Offset into `alloc`
47 #[cfg(target_arch = "x86_64")]
48 static_assert_size!(ConstValue<'_>, 32);
50 impl<'tcx> ConstValue<'tcx> {
52 pub fn try_to_scalar(&self) -> Option<Scalar> {
54 ConstValue::ByRef { .. } | ConstValue::Slice { .. } => None,
55 ConstValue::Scalar(val) => Some(val),
59 pub fn try_to_bits(&self, size: Size) -> Option<u128> {
60 self.try_to_scalar()?.to_bits(size).ok()
63 pub fn try_to_bool(&self) -> Option<bool> {
64 match self.try_to_bits(Size::from_bytes(1))? {
71 pub fn try_to_machine_usize(&self, tcx: TyCtxt<'tcx>) -> Option<u64> {
72 Some(self.try_to_bits(tcx.data_layout.pointer_size)? as u64)
75 pub fn try_to_bits_for_ty(
78 param_env: ParamEnv<'tcx>,
81 let size = tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
82 self.try_to_bits(size)
85 pub fn from_bool(b: bool) -> Self {
86 ConstValue::Scalar(Scalar::from_bool(b))
89 pub fn from_u64(i: u64) -> Self {
90 ConstValue::Scalar(Scalar::from_u64(i))
93 pub fn from_machine_usize(i: u64, cx: &impl HasDataLayout) -> Self {
94 ConstValue::Scalar(Scalar::from_machine_usize(i, cx))
98 /// A `Scalar` represents an immediate, primitive value existing outside of a
99 /// `memory::Allocation`. It is in many ways like a small chunk of a `Allocation`, up to 8 bytes in
100 /// size. Like a range of bytes in an `Allocation`, a `Scalar` can either represent the raw bytes
101 /// of a simple value or a pointer into another `Allocation`
102 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, RustcEncodable, RustcDecodable, Hash)]
103 #[derive(HashStable)]
104 pub enum Scalar<Tag = ()> {
105 /// The raw bytes of a simple value.
107 /// The first `size` bytes of `data` are the value.
108 /// Do not try to read less or more bytes than that. The remaining bytes must be 0.
113 /// A pointer into an `Allocation`. An `Allocation` in the `memory` module has a list of
114 /// relocations, but a `Scalar` is only large enough to contain one, so we just represent the
115 /// relocation and its associated offset together as a `Pointer` here.
119 #[cfg(target_arch = "x86_64")]
120 static_assert_size!(Scalar, 24);
122 // We want the `Debug` output to be readable as it is used by `derive(Debug)` for
123 // all the Miri types.
124 impl<Tag: fmt::Debug> fmt::Debug for Scalar<Tag> {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 Scalar::Ptr(ptr) => write!(f, "{:?}", ptr),
128 &Scalar::Raw { data, size } => {
129 Scalar::check_data(data, size);
133 // Format as hex number wide enough to fit any value of the given `size`.
134 // So data=20, size=1 will be "0x14", but with size=4 it'll be "0x00000014".
135 write!(f, "0x{:>0width$x}", data, width = (size * 2) as usize)
142 impl<Tag: fmt::Debug> fmt::Display for Scalar<Tag> {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 Scalar::Ptr(ptr) => write!(f, "pointer to {}", ptr),
146 Scalar::Raw { .. } => fmt::Debug::fmt(self, f),
151 impl<Tag> From<Single> for Scalar<Tag> {
153 fn from(f: Single) -> Self {
158 impl<Tag> From<Double> for Scalar<Tag> {
160 fn from(f: Double) -> Self {
166 /// Make sure the `data` fits in `size`.
167 /// This is guaranteed by all constructors here, but since the enum variants are public,
168 /// it could still be violated (even though no code outside this file should
169 /// construct `Scalar`s).
171 fn check_data(data: u128, size: u8) {
173 truncate(data, Size::from_bytes(u64::from(size))),
175 "Scalar value {:#x} exceeds size of {} bytes",
181 /// Tag this scalar with `new_tag` if it is a pointer, leave it unchanged otherwise.
183 /// Used by `MemPlace::replace_tag`.
185 pub fn with_tag<Tag>(self, new_tag: Tag) -> Scalar<Tag> {
187 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.with_tag(new_tag)),
188 Scalar::Raw { data, size } => Scalar::Raw { data, size },
193 impl<'tcx, Tag> Scalar<Tag> {
194 /// Erase the tag from the scalar, if any.
196 /// Used by error reporting code to avoid having the error type depend on `Tag`.
198 pub fn erase_tag(self) -> Scalar {
200 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.erase_tag()),
201 Scalar::Raw { data, size } => Scalar::Raw { data, size },
206 pub fn null_ptr(cx: &impl HasDataLayout) -> Self {
207 Scalar::Raw { data: 0, size: cx.data_layout().pointer_size.bytes() as u8 }
211 pub fn zst() -> Self {
212 Scalar::Raw { data: 0, size: 0 }
218 dl: &TargetDataLayout,
219 f_int: impl FnOnce(u64) -> InterpResult<'tcx, u64>,
220 f_ptr: impl FnOnce(Pointer<Tag>) -> InterpResult<'tcx, Pointer<Tag>>,
221 ) -> InterpResult<'tcx, Self> {
223 Scalar::Raw { data, size } => {
224 assert_eq!(u64::from(size), dl.pointer_size.bytes());
225 Ok(Scalar::Raw { data: u128::from(f_int(u64::try_from(data).unwrap())?), size })
227 Scalar::Ptr(ptr) => Ok(Scalar::Ptr(f_ptr(ptr)?)),
232 pub fn ptr_offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
233 let dl = cx.data_layout();
234 self.ptr_op(dl, |int| dl.offset(int, i.bytes()), |ptr| ptr.offset(i, dl))
238 pub fn ptr_wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
239 let dl = cx.data_layout();
242 |int| Ok(dl.overflowing_offset(int, i.bytes()).0),
243 |ptr| Ok(ptr.wrapping_offset(i, dl)),
249 pub fn ptr_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
250 let dl = cx.data_layout();
251 self.ptr_op(dl, |int| dl.signed_offset(int, i), |ptr| ptr.signed_offset(i, dl))
255 pub fn ptr_wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
256 let dl = cx.data_layout();
259 |int| Ok(dl.overflowing_signed_offset(int, i).0),
260 |ptr| Ok(ptr.wrapping_signed_offset(i, dl)),
266 pub fn from_bool(b: bool) -> Self {
267 // Guaranteed to be truncated and does not need sign extension.
268 Scalar::Raw { data: b as u128, size: 1 }
272 pub fn from_char(c: char) -> Self {
273 // Guaranteed to be truncated and does not need sign extension.
274 Scalar::Raw { data: c as u128, size: 4 }
278 pub fn try_from_uint(i: impl Into<u128>, size: Size) -> Option<Self> {
280 if truncate(i, size) == i {
281 Some(Scalar::Raw { data: i, size: size.bytes() as u8 })
288 pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
290 Self::try_from_uint(i, size)
291 .unwrap_or_else(|| bug!("Unsigned value {:#x} does not fit in {} bits", i, size.bits()))
295 pub fn from_u8(i: u8) -> Self {
296 // Guaranteed to be truncated and does not need sign extension.
297 Scalar::Raw { data: i.into(), size: 1 }
301 pub fn from_u16(i: u16) -> Self {
302 // Guaranteed to be truncated and does not need sign extension.
303 Scalar::Raw { data: i.into(), size: 2 }
307 pub fn from_u32(i: u32) -> Self {
308 // Guaranteed to be truncated and does not need sign extension.
309 Scalar::Raw { data: i.into(), size: 4 }
313 pub fn from_u64(i: u64) -> Self {
314 // Guaranteed to be truncated and does not need sign extension.
315 Scalar::Raw { data: i.into(), size: 8 }
319 pub fn from_machine_usize(i: u64, cx: &impl HasDataLayout) -> Self {
320 Self::from_uint(i, cx.data_layout().pointer_size)
324 pub fn try_from_int(i: impl Into<i128>, size: Size) -> Option<Self> {
326 // `into` performed sign extension, we have to truncate
327 let truncated = truncate(i as u128, size);
328 if sign_extend(truncated, size) as i128 == i {
329 Some(Scalar::Raw { data: truncated, size: size.bytes() as u8 })
336 pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
338 Self::try_from_int(i, size)
339 .unwrap_or_else(|| bug!("Signed value {:#x} does not fit in {} bits", i, size.bits()))
343 pub fn from_i8(i: i8) -> Self {
344 Self::from_int(i, Size::from_bits(8))
348 pub fn from_i16(i: i16) -> Self {
349 Self::from_int(i, Size::from_bits(16))
353 pub fn from_i32(i: i32) -> Self {
354 Self::from_int(i, Size::from_bits(32))
358 pub fn from_i64(i: i64) -> Self {
359 Self::from_int(i, Size::from_bits(64))
363 pub fn from_machine_isize(i: i64, cx: &impl HasDataLayout) -> Self {
364 Self::from_int(i, cx.data_layout().pointer_size)
368 pub fn from_f32(f: Single) -> Self {
369 // We trust apfloat to give us properly truncated data.
370 Scalar::Raw { data: f.to_bits(), size: 4 }
374 pub fn from_f64(f: Double) -> Self {
375 // We trust apfloat to give us properly truncated data.
376 Scalar::Raw { data: f.to_bits(), size: 8 }
379 /// This is very rarely the method you want! You should dispatch on the type
380 /// and use `force_bits`/`assert_bits`/`force_ptr`/`assert_ptr`.
381 /// This method only exists for the benefit of low-level memory operations
382 /// as well as the implementation of the `force_*` methods.
384 pub fn to_bits_or_ptr(
387 cx: &impl HasDataLayout,
388 ) -> Result<u128, Pointer<Tag>> {
389 assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST");
391 Scalar::Raw { data, size } => {
392 assert_eq!(target_size.bytes(), u64::from(size));
393 Scalar::check_data(data, size);
396 Scalar::Ptr(ptr) => {
397 assert_eq!(target_size, cx.data_layout().pointer_size);
403 /// This method is intentionally private!
404 /// It is just a helper for other methods in this file.
406 fn to_bits(self, target_size: Size) -> InterpResult<'tcx, u128> {
407 assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST");
409 Scalar::Raw { data, size } => {
410 if target_size.bytes() != u64::from(size) {
411 throw_ub!(ScalarSizeMismatch {
412 target_size: target_size.bytes(),
413 data_size: u64::from(size),
416 Scalar::check_data(data, size);
419 Scalar::Ptr(_) => throw_unsup!(ReadPointerAsBytes),
424 pub fn assert_bits(self, target_size: Size) -> u128 {
425 self.to_bits(target_size).expect("expected Raw bits but got a Pointer")
429 pub fn assert_ptr(self) -> Pointer<Tag> {
432 Scalar::Raw { .. } => bug!("expected a Pointer but got Raw bits"),
436 /// Do not call this method! Dispatch based on the type instead.
438 pub fn is_bits(self) -> bool {
440 Scalar::Raw { .. } => true,
445 /// Do not call this method! Dispatch based on the type instead.
447 pub fn is_ptr(self) -> bool {
449 Scalar::Ptr(_) => true,
454 pub fn to_bool(self) -> InterpResult<'tcx, bool> {
455 let val = self.to_u8()?;
459 _ => throw_ub!(InvalidBool(val)),
463 pub fn to_char(self) -> InterpResult<'tcx, char> {
464 let val = self.to_u32()?;
465 match ::std::char::from_u32(val) {
467 None => throw_ub!(InvalidChar(val)),
472 fn to_unsigned_with_bit_width(self, bits: u64) -> InterpResult<'static, u128> {
473 let sz = Size::from_bits(bits);
477 /// Converts the scalar to produce an `u8`. Fails if the scalar is a pointer.
478 pub fn to_u8(self) -> InterpResult<'static, u8> {
479 self.to_unsigned_with_bit_width(8).map(|v| u8::try_from(v).unwrap())
482 /// Converts the scalar to produce an `u16`. Fails if the scalar is a pointer.
483 pub fn to_u16(self) -> InterpResult<'static, u16> {
484 self.to_unsigned_with_bit_width(16).map(|v| u16::try_from(v).unwrap())
487 /// Converts the scalar to produce an `u32`. Fails if the scalar is a pointer.
488 pub fn to_u32(self) -> InterpResult<'static, u32> {
489 self.to_unsigned_with_bit_width(32).map(|v| u32::try_from(v).unwrap())
492 /// Converts the scalar to produce an `u64`. Fails if the scalar is a pointer.
493 pub fn to_u64(self) -> InterpResult<'static, u64> {
494 self.to_unsigned_with_bit_width(64).map(|v| u64::try_from(v).unwrap())
497 pub fn to_machine_usize(self, cx: &impl HasDataLayout) -> InterpResult<'static, u64> {
498 let b = self.to_bits(cx.data_layout().pointer_size)?;
499 Ok(u64::try_from(b).unwrap())
503 fn to_signed_with_bit_width(self, bits: u64) -> InterpResult<'static, i128> {
504 let sz = Size::from_bits(bits);
505 let b = self.to_bits(sz)?;
506 Ok(sign_extend(b, sz) as i128)
509 /// Converts the scalar to produce an `i8`. Fails if the scalar is a pointer.
510 pub fn to_i8(self) -> InterpResult<'static, i8> {
511 self.to_signed_with_bit_width(8).map(|v| i8::try_from(v).unwrap())
514 /// Converts the scalar to produce an `i16`. Fails if the scalar is a pointer.
515 pub fn to_i16(self) -> InterpResult<'static, i16> {
516 self.to_signed_with_bit_width(16).map(|v| i16::try_from(v).unwrap())
519 /// Converts the scalar to produce an `i32`. Fails if the scalar is a pointer.
520 pub fn to_i32(self) -> InterpResult<'static, i32> {
521 self.to_signed_with_bit_width(32).map(|v| i32::try_from(v).unwrap())
524 /// Converts the scalar to produce an `i64`. Fails if the scalar is a pointer.
525 pub fn to_i64(self) -> InterpResult<'static, i64> {
526 self.to_signed_with_bit_width(64).map(|v| i64::try_from(v).unwrap())
529 pub fn to_machine_isize(self, cx: &impl HasDataLayout) -> InterpResult<'static, i64> {
530 let sz = cx.data_layout().pointer_size;
531 let b = self.to_bits(sz)?;
532 let b = sign_extend(b, sz) as i128;
533 Ok(i64::try_from(b).unwrap())
537 pub fn to_f32(self) -> InterpResult<'static, Single> {
538 // Going through `u32` to check size and truncation.
539 Ok(Single::from_bits(self.to_u32()?.into()))
543 pub fn to_f64(self) -> InterpResult<'static, Double> {
544 // Going through `u64` to check size and truncation.
545 Ok(Double::from_bits(self.to_u64()?.into()))
549 impl<Tag> From<Pointer<Tag>> for Scalar<Tag> {
551 fn from(ptr: Pointer<Tag>) -> Self {
556 #[derive(Clone, Copy, Eq, PartialEq, RustcEncodable, RustcDecodable, HashStable, Hash)]
557 pub enum ScalarMaybeUninit<Tag = ()> {
562 impl<Tag> From<Scalar<Tag>> for ScalarMaybeUninit<Tag> {
564 fn from(s: Scalar<Tag>) -> Self {
565 ScalarMaybeUninit::Scalar(s)
569 impl<Tag> From<Pointer<Tag>> for ScalarMaybeUninit<Tag> {
571 fn from(s: Pointer<Tag>) -> Self {
572 ScalarMaybeUninit::Scalar(s.into())
576 // We want the `Debug` output to be readable as it is used by `derive(Debug)` for
577 // all the Miri types.
578 impl<Tag: fmt::Debug> fmt::Debug for ScalarMaybeUninit<Tag> {
579 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
581 ScalarMaybeUninit::Uninit => write!(f, "<uninitialized>"),
582 ScalarMaybeUninit::Scalar(s) => write!(f, "{:?}", s),
587 impl<Tag: fmt::Debug> fmt::Display for ScalarMaybeUninit<Tag> {
588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
590 ScalarMaybeUninit::Uninit => write!(f, "uninitialized bytes"),
591 ScalarMaybeUninit::Scalar(s) => write!(f, "{}", s),
596 impl<'tcx, Tag> ScalarMaybeUninit<Tag> {
597 /// Erase the tag from the scalar, if any.
599 /// Used by error reporting code to avoid having the error type depend on `Tag`.
601 pub fn erase_tag(self) -> ScalarMaybeUninit {
603 ScalarMaybeUninit::Scalar(s) => ScalarMaybeUninit::Scalar(s.erase_tag()),
604 ScalarMaybeUninit::Uninit => ScalarMaybeUninit::Uninit,
609 pub fn check_init(self) -> InterpResult<'static, Scalar<Tag>> {
611 ScalarMaybeUninit::Scalar(scalar) => Ok(scalar),
612 ScalarMaybeUninit::Uninit => throw_ub!(InvalidUninitBytes(None)),
617 pub fn to_bool(self) -> InterpResult<'tcx, bool> {
618 self.check_init()?.to_bool()
622 pub fn to_char(self) -> InterpResult<'tcx, char> {
623 self.check_init()?.to_char()
627 pub fn to_f32(self) -> InterpResult<'tcx, Single> {
628 self.check_init()?.to_f32()
632 pub fn to_f64(self) -> InterpResult<'tcx, Double> {
633 self.check_init()?.to_f64()
637 pub fn to_u8(self) -> InterpResult<'tcx, u8> {
638 self.check_init()?.to_u8()
642 pub fn to_u16(self) -> InterpResult<'tcx, u16> {
643 self.check_init()?.to_u16()
647 pub fn to_u32(self) -> InterpResult<'tcx, u32> {
648 self.check_init()?.to_u32()
652 pub fn to_u64(self) -> InterpResult<'tcx, u64> {
653 self.check_init()?.to_u64()
657 pub fn to_machine_usize(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
658 self.check_init()?.to_machine_usize(cx)
662 pub fn to_i8(self) -> InterpResult<'tcx, i8> {
663 self.check_init()?.to_i8()
667 pub fn to_i16(self) -> InterpResult<'tcx, i16> {
668 self.check_init()?.to_i16()
672 pub fn to_i32(self) -> InterpResult<'tcx, i32> {
673 self.check_init()?.to_i32()
677 pub fn to_i64(self) -> InterpResult<'tcx, i64> {
678 self.check_init()?.to_i64()
682 pub fn to_machine_isize(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, i64> {
683 self.check_init()?.to_machine_isize(cx)
687 /// Gets the bytes of a constant slice value.
688 pub fn get_slice_bytes<'tcx>(cx: &impl HasDataLayout, val: ConstValue<'tcx>) -> &'tcx [u8] {
689 if let ConstValue::Slice { data, start, end } = val {
690 let len = end - start;
693 // invent a pointer, only the offset is relevant anyway
694 Pointer::new(AllocId(0), Size::from_bytes(start)),
695 Size::from_bytes(len),
697 .unwrap_or_else(|err| bug!("const slice is invalid: {:?}", err))
699 bug!("expected const slice, but found another const value");