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::{EvalResult, 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 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::Bits { bits, size } => {
113 assert_eq!(bits, 0, "ZST value must be 0");
116 assert_eq!(truncate(bits, Size::from_bytes(size as u64)), bits,
117 "Scalar value {:#x} exceeds size of {} bytes", bits, size);
118 // Format as hex number wide enough to fit any value of the given `size`.
119 // So bits=20, size=1 will be "0x14", but with size=4 it'll be "0x00000014".
120 write!(f, "0x{:>0width$x}", bits, width=(size*2) as usize)
127 impl<Tag> fmt::Display for Scalar<Tag> {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 Scalar::Ptr(_) => write!(f, "a pointer"),
131 Scalar::Bits { bits, .. } => write!(f, "{}", bits),
136 impl<'tcx> Scalar<()> {
138 pub fn with_tag<Tag>(self, new_tag: Tag) -> Scalar<Tag> {
140 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.with_tag(new_tag)),
141 Scalar::Bits { bits, size } => Scalar::Bits { bits, size },
146 pub fn with_default_tag<Tag>(self) -> Scalar<Tag>
149 self.with_tag(Tag::default())
153 impl<'tcx, Tag> Scalar<Tag> {
155 pub fn erase_tag(self) -> Scalar {
157 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.erase_tag()),
158 Scalar::Bits { bits, size } => Scalar::Bits { bits, size },
163 pub fn ptr_null(cx: &impl HasDataLayout) -> Self {
166 size: cx.data_layout().pointer_size.bytes() as u8,
171 pub fn zst() -> Self {
172 Scalar::Bits { bits: 0, size: 0 }
176 pub fn ptr_offset(self, i: Size, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
177 let dl = cx.data_layout();
179 Scalar::Bits { bits, size } => {
180 assert_eq!(size as u64, dl.pointer_size.bytes());
182 bits: dl.offset(bits as u64, i.bytes())? as u128,
186 Scalar::Ptr(ptr) => ptr.offset(i, dl).map(Scalar::Ptr),
191 pub fn ptr_wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
192 let dl = cx.data_layout();
194 Scalar::Bits { bits, size } => {
195 assert_eq!(size as u64, dl.pointer_size.bytes());
197 bits: dl.overflowing_offset(bits as u64, i.bytes()).0 as u128,
201 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_offset(i, dl)),
206 pub fn ptr_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
207 let dl = cx.data_layout();
209 Scalar::Bits { bits, size } => {
210 assert_eq!(size as u64, dl.pointer_size().bytes());
212 bits: dl.signed_offset(bits as u64, i)? as u128,
216 Scalar::Ptr(ptr) => ptr.signed_offset(i, dl).map(Scalar::Ptr),
221 pub fn ptr_wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
222 let dl = cx.data_layout();
224 Scalar::Bits { bits, size } => {
225 assert_eq!(size as u64, dl.pointer_size.bytes());
227 bits: dl.overflowing_signed_offset(bits as u64, i128::from(i)).0 as u128,
231 Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_signed_offset(i, dl)),
235 /// Returns this pointers offset from the allocation base, or from NULL (for
236 /// integer pointers).
238 pub fn get_ptr_offset(self, cx: &impl HasDataLayout) -> Size {
240 Scalar::Bits { bits, size } => {
241 assert_eq!(size as u64, cx.pointer_size().bytes());
242 Size::from_bytes(bits as u64)
244 Scalar::Ptr(ptr) => ptr.offset,
249 pub fn is_null_ptr(self, cx: &impl HasDataLayout) -> bool {
251 Scalar::Bits { bits, size } => {
252 assert_eq!(size as u64, cx.data_layout().pointer_size.bytes());
255 Scalar::Ptr(_) => false,
260 pub fn from_bool(b: bool) -> Self {
261 Scalar::Bits { bits: b as u128, size: 1 }
265 pub fn from_char(c: char) -> Self {
266 Scalar::Bits { bits: c as u128, size: 4 }
270 pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
272 debug_assert_eq!(truncate(i, size), i,
273 "Unsigned value {} does not fit in {} bits", i, size.bits());
274 Scalar::Bits { bits: i, size: size.bytes() as u8 }
278 pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
280 // `into` performed sign extension, we have to truncate
281 let truncated = truncate(i as u128, size);
282 debug_assert_eq!(sign_extend(truncated, size) as i128, i,
283 "Signed value {} does not fit in {} bits", i, size.bits());
284 Scalar::Bits { bits: truncated, size: size.bytes() as u8 }
288 pub fn from_f32(f: f32) -> Self {
289 Scalar::Bits { bits: f.to_bits() as u128, size: 4 }
293 pub fn from_f64(f: f64) -> Self {
294 Scalar::Bits { bits: f.to_bits() as u128, size: 8 }
298 pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
300 Scalar::Bits { bits, size } => {
301 assert_eq!(target_size.bytes(), size as u64);
302 assert_ne!(size, 0, "to_bits cannot be used with zsts");
305 Scalar::Ptr(_) => err!(ReadPointerAsBytes),
310 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
312 Scalar::Bits { bits: 0, .. } => err!(InvalidNullPointerUsage),
313 Scalar::Bits { .. } => err!(ReadBytesAsPointer),
314 Scalar::Ptr(p) => Ok(p),
319 pub fn is_bits(self) -> bool {
321 Scalar::Bits { .. } => true,
327 pub fn is_ptr(self) -> bool {
329 Scalar::Ptr(_) => true,
334 pub fn to_bool(self) -> EvalResult<'tcx, bool> {
336 Scalar::Bits { bits: 0, size: 1 } => Ok(false),
337 Scalar::Bits { bits: 1, size: 1 } => Ok(true),
338 _ => err!(InvalidBool),
342 pub fn to_char(self) -> EvalResult<'tcx, char> {
343 let val = self.to_u32()?;
344 match ::std::char::from_u32(val) {
346 None => err!(InvalidChar(val as u128)),
350 pub fn to_u8(self) -> EvalResult<'static, u8> {
351 let sz = Size::from_bits(8);
352 let b = self.to_bits(sz)?;
353 assert_eq!(b as u8 as u128, b);
357 pub fn to_u32(self) -> EvalResult<'static, u32> {
358 let sz = Size::from_bits(32);
359 let b = self.to_bits(sz)?;
360 assert_eq!(b as u32 as u128, b);
364 pub fn to_u64(self) -> EvalResult<'static, u64> {
365 let sz = Size::from_bits(64);
366 let b = self.to_bits(sz)?;
367 assert_eq!(b as u64 as u128, b);
371 pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'static, u64> {
372 let b = self.to_bits(cx.data_layout().pointer_size)?;
373 assert_eq!(b as u64 as u128, b);
377 pub fn to_i8(self) -> EvalResult<'static, i8> {
378 let sz = Size::from_bits(8);
379 let b = self.to_bits(sz)?;
380 let b = sign_extend(b, sz) as i128;
381 assert_eq!(b as i8 as i128, b);
385 pub fn to_i32(self) -> EvalResult<'static, i32> {
386 let sz = Size::from_bits(32);
387 let b = self.to_bits(sz)?;
388 let b = sign_extend(b, sz) as i128;
389 assert_eq!(b as i32 as i128, b);
393 pub fn to_i64(self) -> EvalResult<'static, i64> {
394 let sz = Size::from_bits(64);
395 let b = self.to_bits(sz)?;
396 let b = sign_extend(b, sz) as i128;
397 assert_eq!(b as i64 as i128, b);
401 pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'static, i64> {
402 let b = self.to_bits(cx.data_layout().pointer_size)?;
403 let b = sign_extend(b, cx.data_layout().pointer_size) as i128;
404 assert_eq!(b as i64 as i128, b);
409 pub fn to_f32(self) -> EvalResult<'static, f32> {
410 Ok(f32::from_bits(self.to_u32()?))
414 pub fn to_f64(self) -> EvalResult<'static, f64> {
415 Ok(f64::from_bits(self.to_u64()?))
419 impl<Tag> From<Pointer<Tag>> for Scalar<Tag> {
421 fn from(ptr: Pointer<Tag>) -> Self {
426 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, RustcEncodable, RustcDecodable, Hash)]
427 pub enum ScalarMaybeUndef<Tag=(), Id=AllocId> {
428 Scalar(Scalar<Tag, Id>),
432 impl<Tag> From<Scalar<Tag>> for ScalarMaybeUndef<Tag> {
434 fn from(s: Scalar<Tag>) -> Self {
435 ScalarMaybeUndef::Scalar(s)
439 impl<Tag: fmt::Debug, Id: fmt::Debug> fmt::Debug for ScalarMaybeUndef<Tag, Id> {
440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442 ScalarMaybeUndef::Undef => write!(f, "Undef"),
443 ScalarMaybeUndef::Scalar(s) => write!(f, "{:?}", s),
448 impl<Tag> fmt::Display for ScalarMaybeUndef<Tag> {
449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451 ScalarMaybeUndef::Undef => write!(f, "uninitialized bytes"),
452 ScalarMaybeUndef::Scalar(s) => write!(f, "{}", s),
457 impl<'tcx> ScalarMaybeUndef<()> {
459 pub fn with_tag<Tag>(self, new_tag: Tag) -> ScalarMaybeUndef<Tag> {
461 ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.with_tag(new_tag)),
462 ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
467 pub fn with_default_tag<Tag>(self) -> ScalarMaybeUndef<Tag>
470 self.with_tag(Tag::default())
474 impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
476 pub fn erase_tag(self) -> ScalarMaybeUndef
479 ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.erase_tag()),
480 ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
485 pub fn not_undef(self) -> EvalResult<'static, Scalar<Tag>> {
487 ScalarMaybeUndef::Scalar(scalar) => Ok(scalar),
488 ScalarMaybeUndef::Undef => err!(ReadUndefBytes(Size::from_bytes(0))),
493 pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
494 self.not_undef()?.to_ptr()
498 pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
499 self.not_undef()?.to_bits(target_size)
503 pub fn to_bool(self) -> EvalResult<'tcx, bool> {
504 self.not_undef()?.to_bool()
508 pub fn to_char(self) -> EvalResult<'tcx, char> {
509 self.not_undef()?.to_char()
513 pub fn to_f32(self) -> EvalResult<'tcx, f32> {
514 self.not_undef()?.to_f32()
518 pub fn to_f64(self) -> EvalResult<'tcx, f64> {
519 self.not_undef()?.to_f64()
523 pub fn to_u8(self) -> EvalResult<'tcx, u8> {
524 self.not_undef()?.to_u8()
528 pub fn to_u32(self) -> EvalResult<'tcx, u32> {
529 self.not_undef()?.to_u32()
533 pub fn to_u64(self) -> EvalResult<'tcx, u64> {
534 self.not_undef()?.to_u64()
538 pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, u64> {
539 self.not_undef()?.to_usize(cx)
543 pub fn to_i8(self) -> EvalResult<'tcx, i8> {
544 self.not_undef()?.to_i8()
548 pub fn to_i32(self) -> EvalResult<'tcx, i32> {
549 self.not_undef()?.to_i32()
553 pub fn to_i64(self) -> EvalResult<'tcx, i64> {
554 self.not_undef()?.to_i64()
558 pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, i64> {
559 self.not_undef()?.to_isize(cx)
563 impl_stable_hash_for!(enum crate::mir::interpret::ScalarMaybeUndef {