1 use std::convert::{TryFrom, TryInto};
5 ieee::{Double, Single},
8 use rustc_macros::HashStable;
9 use rustc_target::abi::{HasDataLayout, Size};
11 use crate::ty::{Lift, ParamEnv, ScalarInt, Ty, TyCtxt};
14 AllocId, AllocRange, ConstAllocation, InterpResult, Pointer, PointerArithmetic, Provenance,
18 /// Represents the result of const evaluation via the `eval_to_allocation` query.
19 #[derive(Copy, Clone, HashStable, TyEncodable, TyDecodable, Debug, Hash, Eq, PartialEq)]
20 pub struct ConstAlloc<'tcx> {
21 // the value lives here, at offset 0, and that allocation definitely is an `AllocKind::Memory`
22 // (so you can use `AllocMap::unwrap_memory`).
23 pub alloc_id: AllocId,
27 /// Represents a constant value in Rust. `Scalar` and `Slice` are optimizations for
28 /// array length computations, enum discriminants and the pattern matching logic.
29 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Hash)]
31 pub enum ConstValue<'tcx> {
32 /// Used only for types with `layout::abi::Scalar` ABI and ZSTs.
34 /// Not using the enum `Value` to encode that this must not be `Uninit`.
37 /// Used only for `&[u8]` and `&str`
38 Slice { data: ConstAllocation<'tcx>, start: usize, end: usize },
40 /// A value not represented/representable by `Scalar` or `Slice`
42 /// The backing memory of the value, may contain more memory than needed for just the value
43 /// in order to share `ConstAllocation`s between values
44 alloc: ConstAllocation<'tcx>,
45 /// Offset into `alloc`
50 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
51 static_assert_size!(ConstValue<'_>, 32);
53 impl<'a, 'tcx> Lift<'tcx> for ConstValue<'a> {
54 type Lifted = ConstValue<'tcx>;
55 fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<ConstValue<'tcx>> {
57 ConstValue::Scalar(s) => ConstValue::Scalar(s),
58 ConstValue::Slice { data, start, end } => {
59 ConstValue::Slice { data: tcx.lift(data)?, start, end }
61 ConstValue::ByRef { alloc, offset } => {
62 ConstValue::ByRef { alloc: tcx.lift(alloc)?, offset }
68 impl<'tcx> ConstValue<'tcx> {
70 pub fn try_to_scalar(&self) -> Option<Scalar<AllocId>> {
72 ConstValue::ByRef { .. } | ConstValue::Slice { .. } => None,
73 ConstValue::Scalar(val) => Some(val),
77 pub fn try_to_scalar_int(&self) -> Option<ScalarInt> {
78 Some(self.try_to_scalar()?.assert_int())
82 pub fn try_to_bits(&self, size: Size) -> Option<u128> {
83 self.try_to_scalar_int()?.to_bits(size).ok()
86 pub fn try_to_bool(&self) -> Option<bool> {
87 self.try_to_scalar_int()?.try_into().ok()
90 pub fn try_to_machine_usize(&self, tcx: TyCtxt<'tcx>) -> Option<u64> {
91 self.try_to_scalar_int()?.try_to_machine_usize(tcx).ok()
94 pub fn try_to_bits_for_ty(
97 param_env: ParamEnv<'tcx>,
100 let size = tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size;
101 self.try_to_bits(size)
104 pub fn from_bool(b: bool) -> Self {
105 ConstValue::Scalar(Scalar::from_bool(b))
108 pub fn from_u64(i: u64) -> Self {
109 ConstValue::Scalar(Scalar::from_u64(i))
112 pub fn from_machine_usize(i: u64, cx: &impl HasDataLayout) -> Self {
113 ConstValue::Scalar(Scalar::from_machine_usize(i, cx))
117 /// A `Scalar` represents an immediate, primitive value existing outside of a
118 /// `memory::Allocation`. It is in many ways like a small chunk of an `Allocation`, up to 16 bytes in
119 /// size. Like a range of bytes in an `Allocation`, a `Scalar` can either represent the raw bytes
120 /// of a simple value or a pointer into another `Allocation`
122 /// These variants would be private if there was a convenient way to achieve that in Rust.
123 /// Do *not* match on a `Scalar`! Use the various `to_*` methods instead.
124 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, TyEncodable, TyDecodable, Hash)]
125 #[derive(HashStable)]
126 pub enum Scalar<Tag = AllocId> {
127 /// The raw bytes of a simple value.
130 /// A pointer into an `Allocation`. An `Allocation` in the `memory` module has a list of
131 /// relocations, but a `Scalar` is only large enough to contain one, so we just represent the
132 /// relocation and its associated offset together as a `Pointer` here.
134 /// We also store the size of the pointer, such that a `Scalar` always knows how big it is.
135 /// The size is always the pointer size of the current target, but this is not information
136 /// that we always have readily available.
137 Ptr(Pointer<Tag>, u8),
140 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
141 static_assert_size!(Scalar, 24);
143 // We want the `Debug` output to be readable as it is used by `derive(Debug)` for
144 // all the Miri types.
145 impl<Tag: Provenance> fmt::Debug for Scalar<Tag> {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 Scalar::Ptr(ptr, _size) => write!(f, "{:?}", ptr),
149 Scalar::Int(int) => write!(f, "{:?}", int),
154 impl<Tag: Provenance> fmt::Display for Scalar<Tag> {
155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 Scalar::Ptr(ptr, _size) => write!(f, "pointer to {:?}", ptr),
158 Scalar::Int(int) => write!(f, "{}", int),
163 impl<Tag: Provenance> fmt::LowerHex for Scalar<Tag> {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 Scalar::Ptr(ptr, _size) => write!(f, "pointer to {:?}", ptr),
167 Scalar::Int(int) => write!(f, "0x{:x}", int),
172 impl<Tag> From<Single> for Scalar<Tag> {
174 fn from(f: Single) -> Self {
179 impl<Tag> From<Double> for Scalar<Tag> {
181 fn from(f: Double) -> Self {
186 impl<Tag> From<ScalarInt> for Scalar<Tag> {
188 fn from(ptr: ScalarInt) -> Self {
193 impl<Tag> Scalar<Tag> {
194 pub const ZST: Self = Scalar::Int(ScalarInt::ZST);
197 pub fn from_pointer(ptr: Pointer<Tag>, cx: &impl HasDataLayout) -> Self {
198 Scalar::Ptr(ptr, u8::try_from(cx.pointer_size().bytes()).unwrap())
201 /// Create a Scalar from a pointer with an `Option<_>` tag (where `None` represents a plain integer).
202 pub fn from_maybe_pointer(ptr: Pointer<Option<Tag>>, cx: &impl HasDataLayout) -> Self {
203 match ptr.into_parts() {
204 (Some(tag), offset) => Scalar::from_pointer(Pointer::new(tag, offset), cx),
206 Scalar::Int(ScalarInt::try_from_uint(offset.bytes(), cx.pointer_size()).unwrap())
212 pub fn null_ptr(cx: &impl HasDataLayout) -> Self {
213 Scalar::Int(ScalarInt::null(cx.pointer_size()))
217 pub fn from_bool(b: bool) -> Self {
218 Scalar::Int(b.into())
222 pub fn from_char(c: char) -> Self {
223 Scalar::Int(c.into())
227 pub fn try_from_uint(i: impl Into<u128>, size: Size) -> Option<Self> {
228 ScalarInt::try_from_uint(i, size).map(Scalar::Int)
232 pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
234 Self::try_from_uint(i, size)
235 .unwrap_or_else(|| bug!("Unsigned value {:#x} does not fit in {} bits", i, size.bits()))
239 pub fn from_u8(i: u8) -> Self {
240 Scalar::Int(i.into())
244 pub fn from_u16(i: u16) -> Self {
245 Scalar::Int(i.into())
249 pub fn from_u32(i: u32) -> Self {
250 Scalar::Int(i.into())
254 pub fn from_u64(i: u64) -> Self {
255 Scalar::Int(i.into())
259 pub fn from_machine_usize(i: u64, cx: &impl HasDataLayout) -> Self {
260 Self::from_uint(i, cx.data_layout().pointer_size)
264 pub fn try_from_int(i: impl Into<i128>, size: Size) -> Option<Self> {
265 ScalarInt::try_from_int(i, size).map(Scalar::Int)
269 pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
271 Self::try_from_int(i, size)
272 .unwrap_or_else(|| bug!("Signed value {:#x} does not fit in {} bits", i, size.bits()))
276 pub fn from_i32(i: i32) -> Self {
277 Self::from_int(i, Size::from_bits(32))
281 pub fn from_i64(i: i64) -> Self {
282 Self::from_int(i, Size::from_bits(64))
286 pub fn from_machine_isize(i: i64, cx: &impl HasDataLayout) -> Self {
287 Self::from_int(i, cx.data_layout().pointer_size)
291 pub fn from_f32(f: Single) -> Self {
292 Scalar::Int(f.into())
296 pub fn from_f64(f: Double) -> Self {
297 Scalar::Int(f.into())
300 /// This is almost certainly not the method you want! You should dispatch on the type
301 /// and use `to_{u8,u16,...}`/`scalar_to_ptr` to perform ptr-to-int / int-to-ptr casts as needed.
303 /// This method only exists for the benefit of low-level operations that truly need to treat the
304 /// scalar in whatever form it is.
306 /// This throws UB (instead of ICEing) on a size mismatch since size mismatches can arise in
307 /// Miri when someone declares a function that we shim (such as `malloc`) with a wrong type.
309 pub fn to_bits_or_ptr_internal(
312 ) -> Result<Result<u128, Pointer<Tag>>, ScalarSizeMismatch> {
313 assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST");
315 Scalar::Int(int) => Ok(int.to_bits(target_size).map_err(|size| {
316 ScalarSizeMismatch { target_size: target_size.bytes(), data_size: size.bytes() }
318 Scalar::Ptr(ptr, sz) => {
319 if target_size.bytes() != u64::from(sz) {
320 return Err(ScalarSizeMismatch {
321 target_size: target_size.bytes(),
322 data_size: sz.into(),
331 impl<'tcx, Tag: Provenance> Scalar<Tag> {
332 /// Fundamental scalar-to-int (cast) operation. Many convenience wrappers exist below, that you
333 /// likely want to use instead.
335 /// Will perform ptr-to-int casts if needed and possible.
336 /// If that fails, we know the offset is relative, so we return an "erased" Scalar
337 /// (which is useful for error messages but not much else).
339 pub fn try_to_int(self) -> Result<ScalarInt, Scalar<AllocId>> {
341 Scalar::Int(int) => Ok(int),
342 Scalar::Ptr(ptr, sz) => {
343 if Tag::OFFSET_IS_ADDR {
344 Ok(ScalarInt::try_from_uint(ptr.offset.bytes(), Size::from_bytes(sz)).unwrap())
346 // We know `offset` is relative, since `OFFSET_IS_ADDR == false`.
347 let (tag, offset) = ptr.into_parts();
348 // Because `OFFSET_IS_ADDR == false`, this unwrap can never fail.
349 Err(Scalar::Ptr(Pointer::new(tag.get_alloc_id().unwrap(), offset), sz))
356 pub fn assert_int(self) -> ScalarInt {
357 self.try_to_int().unwrap()
360 /// This throws UB (instead of ICEing) on a size mismatch since size mismatches can arise in
361 /// Miri when someone declares a function that we shim (such as `malloc`) with a wrong type.
363 pub fn to_bits(self, target_size: Size) -> InterpResult<'tcx, u128> {
364 assert_ne!(target_size.bytes(), 0, "you should never look at the bits of a ZST");
365 self.try_to_int().map_err(|_| err_unsup!(ReadPointerAsBytes))?.to_bits(target_size).map_err(
367 err_ub!(ScalarSizeMismatch(ScalarSizeMismatch {
368 target_size: target_size.bytes(),
369 data_size: size.bytes(),
377 pub fn assert_bits(self, target_size: Size) -> u128 {
378 self.to_bits(target_size).unwrap()
381 pub fn to_bool(self) -> InterpResult<'tcx, bool> {
382 let val = self.to_u8()?;
386 _ => throw_ub!(InvalidBool(val)),
390 pub fn to_char(self) -> InterpResult<'tcx, char> {
391 let val = self.to_u32()?;
392 match std::char::from_u32(val) {
394 None => throw_ub!(InvalidChar(val)),
398 /// Converts the scalar to produce an unsigned integer of the given size.
399 /// Fails if the scalar is a pointer.
401 pub fn to_uint(self, size: Size) -> InterpResult<'tcx, u128> {
405 /// Converts the scalar to produce a `u8`. Fails if the scalar is a pointer.
406 pub fn to_u8(self) -> InterpResult<'tcx, u8> {
407 self.to_uint(Size::from_bits(8)).map(|v| u8::try_from(v).unwrap())
410 /// Converts the scalar to produce a `u16`. Fails if the scalar is a pointer.
411 pub fn to_u16(self) -> InterpResult<'tcx, u16> {
412 self.to_uint(Size::from_bits(16)).map(|v| u16::try_from(v).unwrap())
415 /// Converts the scalar to produce a `u32`. Fails if the scalar is a pointer.
416 pub fn to_u32(self) -> InterpResult<'tcx, u32> {
417 self.to_uint(Size::from_bits(32)).map(|v| u32::try_from(v).unwrap())
420 /// Converts the scalar to produce a `u64`. Fails if the scalar is a pointer.
421 pub fn to_u64(self) -> InterpResult<'tcx, u64> {
422 self.to_uint(Size::from_bits(64)).map(|v| u64::try_from(v).unwrap())
425 /// Converts the scalar to produce a `u128`. Fails if the scalar is a pointer.
426 pub fn to_u128(self) -> InterpResult<'tcx, u128> {
427 self.to_uint(Size::from_bits(128))
430 /// Converts the scalar to produce a machine-pointer-sized unsigned integer.
431 /// Fails if the scalar is a pointer.
432 pub fn to_machine_usize(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
433 let b = self.to_uint(cx.data_layout().pointer_size)?;
434 Ok(u64::try_from(b).unwrap())
437 /// Converts the scalar to produce a signed integer of the given size.
438 /// Fails if the scalar is a pointer.
440 pub fn to_int(self, size: Size) -> InterpResult<'tcx, i128> {
441 let b = self.to_bits(size)?;
442 Ok(size.sign_extend(b) as i128)
445 /// Converts the scalar to produce an `i8`. Fails if the scalar is a pointer.
446 pub fn to_i8(self) -> InterpResult<'tcx, i8> {
447 self.to_int(Size::from_bits(8)).map(|v| i8::try_from(v).unwrap())
450 /// Converts the scalar to produce an `i16`. Fails if the scalar is a pointer.
451 pub fn to_i16(self) -> InterpResult<'tcx, i16> {
452 self.to_int(Size::from_bits(16)).map(|v| i16::try_from(v).unwrap())
455 /// Converts the scalar to produce an `i32`. Fails if the scalar is a pointer.
456 pub fn to_i32(self) -> InterpResult<'tcx, i32> {
457 self.to_int(Size::from_bits(32)).map(|v| i32::try_from(v).unwrap())
460 /// Converts the scalar to produce an `i64`. Fails if the scalar is a pointer.
461 pub fn to_i64(self) -> InterpResult<'tcx, i64> {
462 self.to_int(Size::from_bits(64)).map(|v| i64::try_from(v).unwrap())
465 /// Converts the scalar to produce an `i128`. Fails if the scalar is a pointer.
466 pub fn to_i128(self) -> InterpResult<'tcx, i128> {
467 self.to_int(Size::from_bits(128))
470 /// Converts the scalar to produce a machine-pointer-sized signed integer.
471 /// Fails if the scalar is a pointer.
472 pub fn to_machine_isize(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, i64> {
473 let b = self.to_int(cx.data_layout().pointer_size)?;
474 Ok(i64::try_from(b).unwrap())
478 pub fn to_f32(self) -> InterpResult<'tcx, Single> {
479 // Going through `u32` to check size and truncation.
480 Ok(Single::from_bits(self.to_u32()?.into()))
484 pub fn to_f64(self) -> InterpResult<'tcx, Double> {
485 // Going through `u64` to check size and truncation.
486 Ok(Double::from_bits(self.to_u64()?.into()))
490 #[derive(Clone, Copy, Eq, PartialEq, TyEncodable, TyDecodable, HashStable, Hash)]
491 pub enum ScalarMaybeUninit<Tag = AllocId> {
496 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
497 static_assert_size!(ScalarMaybeUninit, 24);
499 impl<Tag> From<Scalar<Tag>> for ScalarMaybeUninit<Tag> {
501 fn from(s: Scalar<Tag>) -> Self {
502 ScalarMaybeUninit::Scalar(s)
506 // We want the `Debug` output to be readable as it is used by `derive(Debug)` for
507 // all the Miri types.
508 impl<Tag: Provenance> fmt::Debug for ScalarMaybeUninit<Tag> {
509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511 ScalarMaybeUninit::Uninit => write!(f, "<uninitialized>"),
512 ScalarMaybeUninit::Scalar(s) => write!(f, "{:?}", s),
517 impl<Tag: Provenance> fmt::LowerHex for ScalarMaybeUninit<Tag> {
518 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520 ScalarMaybeUninit::Uninit => write!(f, "uninitialized bytes"),
521 ScalarMaybeUninit::Scalar(s) => write!(f, "{:x}", s),
526 impl<Tag> ScalarMaybeUninit<Tag> {
528 pub fn from_pointer(ptr: Pointer<Tag>, cx: &impl HasDataLayout) -> Self {
529 ScalarMaybeUninit::Scalar(Scalar::from_pointer(ptr, cx))
533 pub fn from_maybe_pointer(ptr: Pointer<Option<Tag>>, cx: &impl HasDataLayout) -> Self {
534 ScalarMaybeUninit::Scalar(Scalar::from_maybe_pointer(ptr, cx))
538 pub fn check_init<'tcx>(self) -> InterpResult<'tcx, Scalar<Tag>> {
540 ScalarMaybeUninit::Scalar(scalar) => Ok(scalar),
541 ScalarMaybeUninit::Uninit => throw_ub!(InvalidUninitBytes(None)),
546 impl<'tcx, Tag: Provenance> ScalarMaybeUninit<Tag> {
548 pub fn to_bool(self) -> InterpResult<'tcx, bool> {
549 self.check_init()?.to_bool()
553 pub fn to_char(self) -> InterpResult<'tcx, char> {
554 self.check_init()?.to_char()
558 pub fn to_f32(self) -> InterpResult<'tcx, Single> {
559 self.check_init()?.to_f32()
563 pub fn to_f64(self) -> InterpResult<'tcx, Double> {
564 self.check_init()?.to_f64()
568 pub fn to_u8(self) -> InterpResult<'tcx, u8> {
569 self.check_init()?.to_u8()
573 pub fn to_u16(self) -> InterpResult<'tcx, u16> {
574 self.check_init()?.to_u16()
578 pub fn to_u32(self) -> InterpResult<'tcx, u32> {
579 self.check_init()?.to_u32()
583 pub fn to_u64(self) -> InterpResult<'tcx, u64> {
584 self.check_init()?.to_u64()
588 pub fn to_machine_usize(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
589 self.check_init()?.to_machine_usize(cx)
593 pub fn to_i8(self) -> InterpResult<'tcx, i8> {
594 self.check_init()?.to_i8()
598 pub fn to_i16(self) -> InterpResult<'tcx, i16> {
599 self.check_init()?.to_i16()
603 pub fn to_i32(self) -> InterpResult<'tcx, i32> {
604 self.check_init()?.to_i32()
608 pub fn to_i64(self) -> InterpResult<'tcx, i64> {
609 self.check_init()?.to_i64()
613 pub fn to_machine_isize(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, i64> {
614 self.check_init()?.to_machine_isize(cx)
618 /// Gets the bytes of a constant slice value.
619 pub fn get_slice_bytes<'tcx>(cx: &impl HasDataLayout, val: ConstValue<'tcx>) -> &'tcx [u8] {
620 if let ConstValue::Slice { data, start, end } = val {
621 let len = end - start;
625 AllocRange { start: Size::from_bytes(start), size: Size::from_bytes(len) },
627 .unwrap_or_else(|err| bug!("const slice is invalid: {:?}", err))
629 bug!("expected const slice, but found another const value");