2 use rustc_macros::HashStable;
4 use crate::ty::{Ty, InferConst, ParamConst, layout::{HasDataLayout, Size}, subst::SubstsRef};
5 use crate::ty::PlaceholderConst;
6 use crate::hir::def_id::DefId;
8 use super::{InterpResult, Pointer, PointerArithmetic, Allocation, AllocId, sign_extend, truncate};
10 /// Represents the result of a raw const operation, pre-validation.
11 #[derive(Copy, Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable, Hash, HashStable)]
12 pub struct RawConst<'tcx> {
13 // the value lives here, at offset 0, and that allocation definitely is a `AllocKind::Memory`
14 // (so you can use `AllocMap::unwrap_memory`).
15 pub alloc_id: AllocId,
19 /// Represents a constant value in Rust. `Scalar` and `ScalarPair` are optimizations that
20 /// match the `LocalState` optimizations for easy conversions between `Value` and `ConstValue`.
21 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord,
22 RustcEncodable, RustcDecodable, Hash, HashStable)]
23 pub enum ConstValue<'tcx> {
24 /// A const generic parameter.
27 /// Infer the value of the const.
28 Infer(InferConst<'tcx>),
30 /// A placeholder const - universally quantified higher-ranked const.
31 Placeholder(PlaceholderConst),
33 /// Used only for types with `layout::abi::Scalar` ABI and ZSTs.
35 /// Not using the enum `Value` to encode that this must not be `Undef`.
38 /// Used only for `&[u8]` and `&str`
40 data: &'tcx Allocation,
45 /// An allocation together with a pointer into the allocation.
46 /// Invariant: the pointer's `AllocId` resolves to the allocation.
47 ByRef(Pointer, &'tcx Allocation),
49 /// Used in the HIR by using `Unevaluated` everywhere and later normalizing to one of the other
50 /// variants when the code is monomorphic enough for that.
51 Unevaluated(DefId, SubstsRef<'tcx>),
54 #[cfg(target_arch = "x86_64")]
55 static_assert_size!(ConstValue<'_>, 32);
57 impl<'tcx> ConstValue<'tcx> {
59 pub fn try_to_scalar(&self) -> Option<Scalar> {
61 ConstValue::Param(_) |
62 ConstValue::Infer(_) |
63 ConstValue::Placeholder(_) |
64 ConstValue::ByRef(..) |
65 ConstValue::Unevaluated(..) |
66 ConstValue::Slice { .. } => None,
67 ConstValue::Scalar(val) => Some(val),
72 pub fn try_to_bits(&self, size: Size) -> Option<u128> {
73 self.try_to_scalar()?.to_bits(size).ok()
77 pub fn try_to_ptr(&self) -> Option<Pointer> {
78 self.try_to_scalar()?.to_ptr().ok()
82 /// A `Scalar` represents an immediate, primitive value existing outside of a
83 /// `memory::Allocation`. It is in many ways like a small chunk of a `Allocation`, up to 8 bytes in
84 /// size. Like a range of bytes in an `Allocation`, a `Scalar` can either represent the raw bytes
85 /// of a simple value or a pointer into another `Allocation`
86 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd,
87 RustcEncodable, RustcDecodable, Hash, HashStable)]
88 pub enum Scalar<Tag=(), Id=AllocId> {
89 /// The raw bytes of a simple value.
91 /// The first `size` bytes of `data` are the value.
92 /// Do not try to read less or more bytes than that. The remaining bytes must be 0.
97 /// A pointer into an `Allocation`. An `Allocation` in the `memory` module has a list of
98 /// relocations, but a `Scalar` is only large enough to contain one, so we just represent the
99 /// relocation and its associated offset together as a `Pointer` here.
100 Ptr(Pointer<Tag, Id>),
103 #[cfg(target_arch = "x86_64")]
104 static_assert_size!(Scalar, 24);
106 impl<Tag: fmt::Debug, Id: fmt::Debug> fmt::Debug for Scalar<Tag, Id> {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 write!(f, "{:?}", ptr),
111 &Scalar::Raw { data, size } => {
112 Scalar::check_data(data, size);
116 // Format as hex number wide enough to fit any value of the given `size`.
117 // So data=20, size=1 will be "0x14", but with size=4 it'll be "0x00000014".
118 write!(f, "0x{:>0width$x}", data, width=(size*2) as usize)
125 impl<Tag> fmt::Display for Scalar<Tag> {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 Scalar::Ptr(_) => write!(f, "a pointer"),
129 Scalar::Raw { data, .. } => write!(f, "{}", data),
134 impl<'tcx> Scalar<()> {
136 fn check_data(data: u128, size: u8) {
137 debug_assert_eq!(truncate(data, Size::from_bytes(size as u64)), data,
138 "Scalar value {:#x} exceeds size of {} bytes", data, size);
141 /// Tag this scalar with `new_tag` if it is a pointer, leave it unchanged otherwise.
143 /// Used by `MemPlace::replace_tag`.
145 pub fn with_tag<Tag>(self, new_tag: Tag) -> Scalar<Tag> {
147 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.with_tag(new_tag)),
148 Scalar::Raw { data, size } => Scalar::Raw { data, size },
153 impl<'tcx, Tag> Scalar<Tag> {
154 /// Erase the tag from the scalar, if any.
156 /// Used by error reporting code to avoid having the error type depend on `Tag`.
158 pub fn erase_tag(self) -> Scalar {
160 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.erase_tag()),
161 Scalar::Raw { data, size } => Scalar::Raw { data, size },
166 pub fn ptr_null(cx: &impl HasDataLayout) -> Self {
169 size: cx.data_layout().pointer_size.bytes() as u8,
174 pub fn zst() -> Self {
175 Scalar::Raw { data: 0, size: 0 }
179 pub fn ptr_offset(self, i: Size, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
180 let dl = cx.data_layout();
182 Scalar::Raw { data, size } => {
183 assert_eq!(size as u64, dl.pointer_size.bytes());
185 data: dl.offset(data as u64, i.bytes())? as u128,
189 Scalar::Ptr(ptr) => ptr.offset(i, dl).map(Scalar::Ptr),
194 pub fn ptr_wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
195 let dl = cx.data_layout();
197 Scalar::Raw { data, size } => {
198 assert_eq!(size as u64, dl.pointer_size.bytes());
200 data: dl.overflowing_offset(data as u64, i.bytes()).0 as u128,
204 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_offset(i, dl)),
209 pub fn ptr_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> InterpResult<'tcx, Self> {
210 let dl = cx.data_layout();
212 Scalar::Raw { data, size } => {
213 assert_eq!(size as u64, dl.pointer_size().bytes());
215 data: dl.signed_offset(data as u64, i)? as u128,
219 Scalar::Ptr(ptr) => ptr.signed_offset(i, dl).map(Scalar::Ptr),
224 pub fn ptr_wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
225 let dl = cx.data_layout();
227 Scalar::Raw { data, size } => {
228 assert_eq!(size as u64, dl.pointer_size.bytes());
230 data: dl.overflowing_signed_offset(data as u64, i128::from(i)).0 as u128,
234 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_signed_offset(i, dl)),
238 /// Returns this pointer's offset from the allocation base, or from NULL (for
239 /// integer pointers).
241 pub fn get_ptr_offset(self, cx: &impl HasDataLayout) -> Size {
243 Scalar::Raw { data, size } => {
244 assert_eq!(size as u64, cx.pointer_size().bytes());
245 Size::from_bytes(data as u64)
247 Scalar::Ptr(ptr) => ptr.offset,
252 pub fn is_null_ptr(self, cx: &impl HasDataLayout) -> bool {
254 Scalar::Raw { data, size } => {
255 assert_eq!(size as u64, cx.data_layout().pointer_size.bytes());
258 Scalar::Ptr(_) => false,
263 pub fn from_bool(b: bool) -> Self {
264 Scalar::Raw { data: b as u128, size: 1 }
268 pub fn from_char(c: char) -> Self {
269 Scalar::Raw { data: c as u128, size: 4 }
273 pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
276 truncate(i, size), i,
277 "Unsigned value {:#x} does not fit in {} bits", i, size.bits()
279 Scalar::Raw { data: i, size: size.bytes() as u8 }
283 pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
285 // `into` performed sign extension, we have to truncate
286 let truncated = truncate(i as u128, size);
288 sign_extend(truncated, size) as i128, i,
289 "Signed value {:#x} does not fit in {} bits", i, size.bits()
291 Scalar::Raw { data: truncated, size: size.bytes() as u8 }
295 pub fn from_f32(f: f32) -> Self {
296 Scalar::Raw { data: f.to_bits() as u128, size: 4 }
300 pub fn from_f64(f: f64) -> Self {
301 Scalar::Raw { data: f.to_bits() as u128, size: 8 }
305 pub fn to_bits_or_ptr(
308 cx: &impl HasDataLayout,
309 ) -> Result<u128, Pointer<Tag>> {
311 Scalar::Raw { data, size } => {
312 assert_eq!(target_size.bytes(), size as u64);
313 assert_ne!(size, 0, "you should never look at the bits of a ZST");
314 Scalar::check_data(data, size);
317 Scalar::Ptr(ptr) => {
318 assert_eq!(target_size, cx.data_layout().pointer_size);
325 pub fn to_bits(self, target_size: Size) -> InterpResult<'tcx, u128> {
327 Scalar::Raw { data, size } => {
328 assert_eq!(target_size.bytes(), size as u64);
329 assert_ne!(size, 0, "you should never look at the bits of a ZST");
330 Scalar::check_data(data, size);
333 Scalar::Ptr(_) => err!(ReadPointerAsBytes),
338 pub fn to_ptr(self) -> InterpResult<'tcx, Pointer<Tag>> {
340 Scalar::Raw { data: 0, .. } => err!(InvalidNullPointerUsage),
341 Scalar::Raw { .. } => err!(ReadBytesAsPointer),
342 Scalar::Ptr(p) => Ok(p),
347 pub fn is_bits(self) -> bool {
349 Scalar::Raw { .. } => true,
355 pub fn is_ptr(self) -> bool {
357 Scalar::Ptr(_) => true,
362 pub fn to_bool(self) -> InterpResult<'tcx, bool> {
364 Scalar::Raw { data: 0, size: 1 } => Ok(false),
365 Scalar::Raw { data: 1, size: 1 } => Ok(true),
366 _ => err!(InvalidBool),
370 pub fn to_char(self) -> InterpResult<'tcx, char> {
371 let val = self.to_u32()?;
372 match ::std::char::from_u32(val) {
374 None => err!(InvalidChar(val as u128)),
378 pub fn to_u8(self) -> InterpResult<'static, u8> {
379 let sz = Size::from_bits(8);
380 let b = self.to_bits(sz)?;
384 pub fn to_u32(self) -> InterpResult<'static, u32> {
385 let sz = Size::from_bits(32);
386 let b = self.to_bits(sz)?;
390 pub fn to_u64(self) -> InterpResult<'static, u64> {
391 let sz = Size::from_bits(64);
392 let b = self.to_bits(sz)?;
396 pub fn to_usize(self, cx: &impl HasDataLayout) -> InterpResult<'static, u64> {
397 let b = self.to_bits(cx.data_layout().pointer_size)?;
401 pub fn to_i8(self) -> InterpResult<'static, i8> {
402 let sz = Size::from_bits(8);
403 let b = self.to_bits(sz)?;
404 let b = sign_extend(b, sz) as i128;
408 pub fn to_i32(self) -> InterpResult<'static, i32> {
409 let sz = Size::from_bits(32);
410 let b = self.to_bits(sz)?;
411 let b = sign_extend(b, sz) as i128;
415 pub fn to_i64(self) -> InterpResult<'static, i64> {
416 let sz = Size::from_bits(64);
417 let b = self.to_bits(sz)?;
418 let b = sign_extend(b, sz) as i128;
422 pub fn to_isize(self, cx: &impl HasDataLayout) -> InterpResult<'static, i64> {
423 let sz = cx.data_layout().pointer_size;
424 let b = self.to_bits(sz)?;
425 let b = sign_extend(b, sz) as i128;
430 pub fn to_f32(self) -> InterpResult<'static, f32> {
431 Ok(f32::from_bits(self.to_u32()?))
435 pub fn to_f64(self) -> InterpResult<'static, f64> {
436 Ok(f64::from_bits(self.to_u64()?))
440 impl<Tag> From<Pointer<Tag>> for Scalar<Tag> {
442 fn from(ptr: Pointer<Tag>) -> Self {
447 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, RustcEncodable, RustcDecodable, Hash)]
448 pub enum ScalarMaybeUndef<Tag=(), Id=AllocId> {
449 Scalar(Scalar<Tag, Id>),
453 impl<Tag> From<Scalar<Tag>> for ScalarMaybeUndef<Tag> {
455 fn from(s: Scalar<Tag>) -> Self {
456 ScalarMaybeUndef::Scalar(s)
460 impl<Tag: fmt::Debug, Id: fmt::Debug> fmt::Debug for ScalarMaybeUndef<Tag, Id> {
461 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463 ScalarMaybeUndef::Undef => write!(f, "Undef"),
464 ScalarMaybeUndef::Scalar(s) => write!(f, "{:?}", s),
469 impl<Tag> fmt::Display for ScalarMaybeUndef<Tag> {
470 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 ScalarMaybeUndef::Undef => write!(f, "uninitialized bytes"),
473 ScalarMaybeUndef::Scalar(s) => write!(f, "{}", s),
478 impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
479 /// Erase the tag from the scalar, if any.
481 /// Used by error reporting code to avoid having the error type depend on `Tag`.
483 pub fn erase_tag(self) -> ScalarMaybeUndef
486 ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.erase_tag()),
487 ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
492 pub fn not_undef(self) -> InterpResult<'static, Scalar<Tag>> {
494 ScalarMaybeUndef::Scalar(scalar) => Ok(scalar),
495 ScalarMaybeUndef::Undef => err!(ReadUndefBytes(Size::from_bytes(0))),
500 pub fn to_ptr(self) -> InterpResult<'tcx, Pointer<Tag>> {
501 self.not_undef()?.to_ptr()
505 pub fn to_bits(self, target_size: Size) -> InterpResult<'tcx, u128> {
506 self.not_undef()?.to_bits(target_size)
510 pub fn to_bool(self) -> InterpResult<'tcx, bool> {
511 self.not_undef()?.to_bool()
515 pub fn to_char(self) -> InterpResult<'tcx, char> {
516 self.not_undef()?.to_char()
520 pub fn to_f32(self) -> InterpResult<'tcx, f32> {
521 self.not_undef()?.to_f32()
525 pub fn to_f64(self) -> InterpResult<'tcx, f64> {
526 self.not_undef()?.to_f64()
530 pub fn to_u8(self) -> InterpResult<'tcx, u8> {
531 self.not_undef()?.to_u8()
535 pub fn to_u32(self) -> InterpResult<'tcx, u32> {
536 self.not_undef()?.to_u32()
540 pub fn to_u64(self) -> InterpResult<'tcx, u64> {
541 self.not_undef()?.to_u64()
545 pub fn to_usize(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
546 self.not_undef()?.to_usize(cx)
550 pub fn to_i8(self) -> InterpResult<'tcx, i8> {
551 self.not_undef()?.to_i8()
555 pub fn to_i32(self) -> InterpResult<'tcx, i32> {
556 self.not_undef()?.to_i32()
560 pub fn to_i64(self) -> InterpResult<'tcx, i64> {
561 self.not_undef()?.to_i64()
565 pub fn to_isize(self, cx: &impl HasDataLayout) -> InterpResult<'tcx, i64> {
566 self.not_undef()?.to_isize(cx)
570 impl_stable_hash_for!(enum crate::mir::interpret::ScalarMaybeUndef {