]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/interpret/value.rs
no longer assume that there is a default tag: give the machine the chance to tag...
[rust.git] / src / librustc / mir / interpret / value.rs
1 use std::fmt;
2 use rustc_macros::HashStable;
3
4 use crate::ty::{Ty, InferConst, ParamConst, layout::{HasDataLayout, Size}, subst::SubstsRef};
5 use crate::ty::PlaceholderConst;
6 use crate::hir::def_id::DefId;
7
8 use super::{EvalResult, Pointer, PointerArithmetic, Allocation, AllocId, sign_extend, truncate};
9
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,
16     pub ty: Ty<'tcx>,
17 }
18
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.
25     Param(ParamConst),
26
27     /// Infer the value of the const.
28     Infer(InferConst<'tcx>),
29
30     /// A placeholder const - universally quantified higher-ranked const.
31     Placeholder(PlaceholderConst),
32
33     /// Used only for types with `layout::abi::Scalar` ABI and ZSTs.
34     ///
35     /// Not using the enum `Value` to encode that this must not be `Undef`.
36     Scalar(Scalar),
37
38     /// Used only for `&[u8]` and `&str`
39     Slice {
40         data: &'tcx Allocation,
41         start: usize,
42         end: usize,
43     },
44
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),
48
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>),
52 }
53
54 #[cfg(target_arch = "x86_64")]
55 static_assert_size!(ConstValue<'_>, 32);
56
57 impl<'tcx> ConstValue<'tcx> {
58     #[inline]
59     pub fn try_to_scalar(&self) -> Option<Scalar> {
60         match *self {
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),
68         }
69     }
70
71     #[inline]
72     pub fn try_to_bits(&self, size: Size) -> Option<u128> {
73         self.try_to_scalar()?.to_bits(size).ok()
74     }
75
76     #[inline]
77     pub fn try_to_ptr(&self) -> Option<Pointer> {
78         self.try_to_scalar()?.to_ptr().ok()
79     }
80 }
81
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.
90     Raw {
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.
93         data: u128,
94         size: u8,
95     },
96
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>),
101 }
102
103 #[cfg(target_arch = "x86_64")]
104 static_assert_size!(Scalar, 24);
105
106 impl<Tag: fmt::Debug, Id: fmt::Debug> fmt::Debug for Scalar<Tag, Id> {
107     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108         match self {
109             Scalar::Ptr(ptr) =>
110                 write!(f, "{:?}", ptr),
111             &Scalar::Raw { data, size } => {
112                 Scalar::check_data(data, size);
113                 if size == 0 {
114                     write!(f, "<ZST>")
115                 } else {
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)
119                 }
120             }
121         }
122     }
123 }
124
125 impl<Tag> fmt::Display for Scalar<Tag> {
126     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127         match self {
128             Scalar::Ptr(_) => write!(f, "a pointer"),
129             Scalar::Raw { data, .. } => write!(f, "{}", data),
130         }
131     }
132 }
133
134 impl<'tcx> Scalar<()> {
135     #[inline(always)]
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);
139     }
140
141     #[inline]
142     pub fn with_tag<Tag>(self, new_tag: Tag) -> Scalar<Tag> {
143         // Used by `MemPlace::replace_tag`
144         match self {
145             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.with_tag(new_tag)),
146             Scalar::Raw { data, size } => Scalar::Raw { data, size },
147         }
148     }
149 }
150
151 impl<'tcx, Tag> Scalar<Tag> {
152     #[inline]
153     pub fn erase_tag(self) -> Scalar {
154         // Used by error reporting code to avoid having the error type depend on `Tag`
155         match self {
156             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.erase_tag()),
157             Scalar::Raw { data, size } => Scalar::Raw { data, size },
158         }
159     }
160
161     #[inline]
162     pub fn ptr_null(cx: &impl HasDataLayout) -> Self {
163         Scalar::Raw {
164             data: 0,
165             size: cx.data_layout().pointer_size.bytes() as u8,
166         }
167     }
168
169     #[inline]
170     pub fn zst() -> Self {
171         Scalar::Raw { data: 0, size: 0 }
172     }
173
174     #[inline]
175     pub fn ptr_offset(self, i: Size, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
176         let dl = cx.data_layout();
177         match self {
178             Scalar::Raw { data, size } => {
179                 assert_eq!(size as u64, dl.pointer_size.bytes());
180                 Ok(Scalar::Raw {
181                     data: dl.offset(data as u64, i.bytes())? as u128,
182                     size,
183                 })
184             }
185             Scalar::Ptr(ptr) => ptr.offset(i, dl).map(Scalar::Ptr),
186         }
187     }
188
189     #[inline]
190     pub fn ptr_wrapping_offset(self, i: Size, cx: &impl HasDataLayout) -> Self {
191         let dl = cx.data_layout();
192         match self {
193             Scalar::Raw { data, size } => {
194                 assert_eq!(size as u64, dl.pointer_size.bytes());
195                 Scalar::Raw {
196                     data: dl.overflowing_offset(data as u64, i.bytes()).0 as u128,
197                     size,
198                 }
199             }
200             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_offset(i, dl)),
201         }
202     }
203
204     #[inline]
205     pub fn ptr_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> EvalResult<'tcx, Self> {
206         let dl = cx.data_layout();
207         match self {
208             Scalar::Raw { data, size } => {
209                 assert_eq!(size as u64, dl.pointer_size().bytes());
210                 Ok(Scalar::Raw {
211                     data: dl.signed_offset(data as u64, i)? as u128,
212                     size,
213                 })
214             }
215             Scalar::Ptr(ptr) => ptr.signed_offset(i, dl).map(Scalar::Ptr),
216         }
217     }
218
219     #[inline]
220     pub fn ptr_wrapping_signed_offset(self, i: i64, cx: &impl HasDataLayout) -> Self {
221         let dl = cx.data_layout();
222         match self {
223             Scalar::Raw { data, size } => {
224                 assert_eq!(size as u64, dl.pointer_size.bytes());
225                 Scalar::Raw {
226                     data: dl.overflowing_signed_offset(data as u64, i128::from(i)).0 as u128,
227                     size,
228                 }
229             }
230             Scalar::Ptr(ptr) => Scalar::Ptr(ptr.wrapping_signed_offset(i, dl)),
231         }
232     }
233
234     /// Returns this pointer's offset from the allocation base, or from NULL (for
235     /// integer pointers).
236     #[inline]
237     pub fn get_ptr_offset(self, cx: &impl HasDataLayout) -> Size {
238         match self {
239             Scalar::Raw { data, size } => {
240                 assert_eq!(size as u64, cx.pointer_size().bytes());
241                 Size::from_bytes(data as u64)
242             }
243             Scalar::Ptr(ptr) => ptr.offset,
244         }
245     }
246
247     #[inline]
248     pub fn is_null_ptr(self, cx: &impl HasDataLayout) -> bool {
249         match self {
250             Scalar::Raw { data, size } => {
251                 assert_eq!(size as u64, cx.data_layout().pointer_size.bytes());
252                 data == 0
253             },
254             Scalar::Ptr(_) => false,
255         }
256     }
257
258     #[inline]
259     pub fn from_bool(b: bool) -> Self {
260         Scalar::Raw { data: b as u128, size: 1 }
261     }
262
263     #[inline]
264     pub fn from_char(c: char) -> Self {
265         Scalar::Raw { data: c as u128, size: 4 }
266     }
267
268     #[inline]
269     pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
270         let i = i.into();
271         assert_eq!(
272             truncate(i, size), i,
273             "Unsigned value {:#x} does not fit in {} bits", i, size.bits()
274         );
275         Scalar::Raw { data: i, size: size.bytes() as u8 }
276     }
277
278     #[inline]
279     pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
280         let i = i.into();
281         // `into` performed sign extension, we have to truncate
282         let truncated = truncate(i as u128, size);
283         assert_eq!(
284             sign_extend(truncated, size) as i128, i,
285             "Signed value {:#x} does not fit in {} bits", i, size.bits()
286         );
287         Scalar::Raw { data: truncated, size: size.bytes() as u8 }
288     }
289
290     #[inline]
291     pub fn from_f32(f: f32) -> Self {
292         Scalar::Raw { data: f.to_bits() as u128, size: 4 }
293     }
294
295     #[inline]
296     pub fn from_f64(f: f64) -> Self {
297         Scalar::Raw { data: f.to_bits() as u128, size: 8 }
298     }
299
300     #[inline]
301     pub fn to_bits_or_ptr(
302         self,
303         target_size: Size,
304         cx: &impl HasDataLayout,
305     ) -> Result<u128, Pointer<Tag>> {
306         match self {
307             Scalar::Raw { data, size } => {
308                 assert_eq!(target_size.bytes(), size as u64);
309                 assert_ne!(size, 0, "you should never look at the bits of a ZST");
310                 Scalar::check_data(data, size);
311                 Ok(data)
312             }
313             Scalar::Ptr(ptr) => {
314                 assert_eq!(target_size, cx.data_layout().pointer_size);
315                 Err(ptr)
316             }
317         }
318     }
319
320     #[inline]
321     pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
322         match self {
323             Scalar::Raw { data, size } => {
324                 assert_eq!(target_size.bytes(), size as u64);
325                 assert_ne!(size, 0, "you should never look at the bits of a ZST");
326                 Scalar::check_data(data, size);
327                 Ok(data)
328             }
329             Scalar::Ptr(_) => err!(ReadPointerAsBytes),
330         }
331     }
332
333     #[inline]
334     pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
335         match self {
336             Scalar::Raw { data: 0, .. } => err!(InvalidNullPointerUsage),
337             Scalar::Raw { .. } => err!(ReadBytesAsPointer),
338             Scalar::Ptr(p) => Ok(p),
339         }
340     }
341
342     #[inline]
343     pub fn is_bits(self) -> bool {
344         match self {
345             Scalar::Raw { .. } => true,
346             _ => false,
347         }
348     }
349
350     #[inline]
351     pub fn is_ptr(self) -> bool {
352         match self {
353             Scalar::Ptr(_) => true,
354             _ => false,
355         }
356     }
357
358     pub fn to_bool(self) -> EvalResult<'tcx, bool> {
359         match self {
360             Scalar::Raw { data: 0, size: 1 } => Ok(false),
361             Scalar::Raw { data: 1, size: 1 } => Ok(true),
362             _ => err!(InvalidBool),
363         }
364     }
365
366     pub fn to_char(self) -> EvalResult<'tcx, char> {
367         let val = self.to_u32()?;
368         match ::std::char::from_u32(val) {
369             Some(c) => Ok(c),
370             None => err!(InvalidChar(val as u128)),
371         }
372     }
373
374     pub fn to_u8(self) -> EvalResult<'static, u8> {
375         let sz = Size::from_bits(8);
376         let b = self.to_bits(sz)?;
377         Ok(b as u8)
378     }
379
380     pub fn to_u32(self) -> EvalResult<'static, u32> {
381         let sz = Size::from_bits(32);
382         let b = self.to_bits(sz)?;
383         Ok(b as u32)
384     }
385
386     pub fn to_u64(self) -> EvalResult<'static, u64> {
387         let sz = Size::from_bits(64);
388         let b = self.to_bits(sz)?;
389         Ok(b as u64)
390     }
391
392     pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'static, u64> {
393         let b = self.to_bits(cx.data_layout().pointer_size)?;
394         Ok(b as u64)
395     }
396
397     pub fn to_i8(self) -> EvalResult<'static, i8> {
398         let sz = Size::from_bits(8);
399         let b = self.to_bits(sz)?;
400         let b = sign_extend(b, sz) as i128;
401         Ok(b as i8)
402     }
403
404     pub fn to_i32(self) -> EvalResult<'static, i32> {
405         let sz = Size::from_bits(32);
406         let b = self.to_bits(sz)?;
407         let b = sign_extend(b, sz) as i128;
408         Ok(b as i32)
409     }
410
411     pub fn to_i64(self) -> EvalResult<'static, i64> {
412         let sz = Size::from_bits(64);
413         let b = self.to_bits(sz)?;
414         let b = sign_extend(b, sz) as i128;
415         Ok(b as i64)
416     }
417
418     pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'static, i64> {
419         let sz = cx.data_layout().pointer_size;
420         let b = self.to_bits(sz)?;
421         let b = sign_extend(b, sz) as i128;
422         Ok(b as i64)
423     }
424
425     #[inline]
426     pub fn to_f32(self) -> EvalResult<'static, f32> {
427         Ok(f32::from_bits(self.to_u32()?))
428     }
429
430     #[inline]
431     pub fn to_f64(self) -> EvalResult<'static, f64> {
432         Ok(f64::from_bits(self.to_u64()?))
433     }
434 }
435
436 impl<Tag> From<Pointer<Tag>> for Scalar<Tag> {
437     #[inline(always)]
438     fn from(ptr: Pointer<Tag>) -> Self {
439         Scalar::Ptr(ptr)
440     }
441 }
442
443 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, RustcEncodable, RustcDecodable, Hash)]
444 pub enum ScalarMaybeUndef<Tag=(), Id=AllocId> {
445     Scalar(Scalar<Tag, Id>),
446     Undef,
447 }
448
449 impl<Tag> From<Scalar<Tag>> for ScalarMaybeUndef<Tag> {
450     #[inline(always)]
451     fn from(s: Scalar<Tag>) -> Self {
452         ScalarMaybeUndef::Scalar(s)
453     }
454 }
455
456 impl<Tag: fmt::Debug, Id: fmt::Debug> fmt::Debug for ScalarMaybeUndef<Tag, Id> {
457     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458         match self {
459             ScalarMaybeUndef::Undef => write!(f, "Undef"),
460             ScalarMaybeUndef::Scalar(s) => write!(f, "{:?}", s),
461         }
462     }
463 }
464
465 impl<Tag> fmt::Display for ScalarMaybeUndef<Tag> {
466     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
467         match self {
468             ScalarMaybeUndef::Undef => write!(f, "uninitialized bytes"),
469             ScalarMaybeUndef::Scalar(s) => write!(f, "{}", s),
470         }
471     }
472 }
473
474 impl<'tcx, Tag> ScalarMaybeUndef<Tag> {
475     #[inline]
476     pub fn erase_tag(self) -> ScalarMaybeUndef
477     {
478         // Used by error reporting code to avoid having the error type depend on `Tag`
479         match self {
480             ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.erase_tag()),
481             ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
482         }
483     }
484
485     #[inline]
486     pub fn not_undef(self) -> EvalResult<'static, Scalar<Tag>> {
487         match self {
488             ScalarMaybeUndef::Scalar(scalar) => Ok(scalar),
489             ScalarMaybeUndef::Undef => err!(ReadUndefBytes(Size::from_bytes(0))),
490         }
491     }
492
493     #[inline(always)]
494     pub fn to_ptr(self) -> EvalResult<'tcx, Pointer<Tag>> {
495         self.not_undef()?.to_ptr()
496     }
497
498     #[inline(always)]
499     pub fn to_bits(self, target_size: Size) -> EvalResult<'tcx, u128> {
500         self.not_undef()?.to_bits(target_size)
501     }
502
503     #[inline(always)]
504     pub fn to_bool(self) -> EvalResult<'tcx, bool> {
505         self.not_undef()?.to_bool()
506     }
507
508     #[inline(always)]
509     pub fn to_char(self) -> EvalResult<'tcx, char> {
510         self.not_undef()?.to_char()
511     }
512
513     #[inline(always)]
514     pub fn to_f32(self) -> EvalResult<'tcx, f32> {
515         self.not_undef()?.to_f32()
516     }
517
518     #[inline(always)]
519     pub fn to_f64(self) -> EvalResult<'tcx, f64> {
520         self.not_undef()?.to_f64()
521     }
522
523     #[inline(always)]
524     pub fn to_u8(self) -> EvalResult<'tcx, u8> {
525         self.not_undef()?.to_u8()
526     }
527
528     #[inline(always)]
529     pub fn to_u32(self) -> EvalResult<'tcx, u32> {
530         self.not_undef()?.to_u32()
531     }
532
533     #[inline(always)]
534     pub fn to_u64(self) -> EvalResult<'tcx, u64> {
535         self.not_undef()?.to_u64()
536     }
537
538     #[inline(always)]
539     pub fn to_usize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, u64> {
540         self.not_undef()?.to_usize(cx)
541     }
542
543     #[inline(always)]
544     pub fn to_i8(self) -> EvalResult<'tcx, i8> {
545         self.not_undef()?.to_i8()
546     }
547
548     #[inline(always)]
549     pub fn to_i32(self) -> EvalResult<'tcx, i32> {
550         self.not_undef()?.to_i32()
551     }
552
553     #[inline(always)]
554     pub fn to_i64(self) -> EvalResult<'tcx, i64> {
555         self.not_undef()?.to_i64()
556     }
557
558     #[inline(always)]
559     pub fn to_isize(self, cx: &impl HasDataLayout) -> EvalResult<'tcx, i64> {
560         self.not_undef()?.to_isize(cx)
561     }
562 }
563
564 impl_stable_hash_for!(enum crate::mir::interpret::ScalarMaybeUndef {
565     Scalar(v),
566     Undef
567 });