rustc_const_eval/interpret/
cast.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
use std::assert_matches::assert_matches;

use rustc_abi::Integer;
use rustc_apfloat::ieee::{Double, Half, Quad, Single};
use rustc_apfloat::{Float, FloatConvert};
use rustc_middle::mir::CastKind;
use rustc_middle::mir::interpret::{InterpResult, PointerArithmetic, Scalar};
use rustc_middle::ty::adjustment::PointerCoercion;
use rustc_middle::ty::layout::{IntegerExt, LayoutOf, TyAndLayout};
use rustc_middle::ty::{self, FloatTy, Ty};
use rustc_middle::{bug, span_bug};
use rustc_type_ir::TyKind::*;
use tracing::trace;

use super::util::ensure_monomorphic_enough;
use super::{
    FnVal, ImmTy, Immediate, InterpCx, Machine, OpTy, PlaceTy, err_inval, interp_ok, throw_ub,
    throw_ub_custom,
};
use crate::fluent_generated as fluent;

impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
    pub fn cast(
        &mut self,
        src: &OpTy<'tcx, M::Provenance>,
        cast_kind: CastKind,
        cast_ty: Ty<'tcx>,
        dest: &PlaceTy<'tcx, M::Provenance>,
    ) -> InterpResult<'tcx> {
        // `cast_ty` will often be the same as `dest.ty`, but not always, since subtyping is still
        // possible.
        let cast_layout =
            if cast_ty == dest.layout.ty { dest.layout } else { self.layout_of(cast_ty)? };
        // FIXME: In which cases should we trigger UB when the source is uninit?
        match cast_kind {
            CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
                self.unsize_into(src, cast_layout, dest)?;
            }

            CastKind::PointerExposeProvenance => {
                let src = self.read_immediate(src)?;
                let res = self.pointer_expose_provenance_cast(&src, cast_layout)?;
                self.write_immediate(*res, dest)?;
            }

            CastKind::PointerWithExposedProvenance => {
                let src = self.read_immediate(src)?;
                let res = self.pointer_with_exposed_provenance_cast(&src, cast_layout)?;
                self.write_immediate(*res, dest)?;
            }

            CastKind::IntToInt | CastKind::IntToFloat => {
                let src = self.read_immediate(src)?;
                let res = self.int_to_int_or_float(&src, cast_layout)?;
                self.write_immediate(*res, dest)?;
            }

            CastKind::FloatToFloat | CastKind::FloatToInt => {
                let src = self.read_immediate(src)?;
                let res = self.float_to_float_or_int(&src, cast_layout)?;
                self.write_immediate(*res, dest)?;
            }

            CastKind::FnPtrToPtr | CastKind::PtrToPtr => {
                let src = self.read_immediate(src)?;
                let res = self.ptr_to_ptr(&src, cast_layout)?;
                self.write_immediate(*res, dest)?;
            }

            CastKind::PointerCoercion(
                PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer,
                _,
            ) => {
                bug!("{cast_kind:?} casts are for borrowck only, not runtime MIR");
            }

            CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, _) => {
                // All reifications must be monomorphic, bail out otherwise.
                ensure_monomorphic_enough(*self.tcx, src.layout.ty)?;

                // The src operand does not matter, just its type
                match *src.layout.ty.kind() {
                    ty::FnDef(def_id, args) => {
                        let instance = ty::Instance::resolve_for_fn_ptr(
                            *self.tcx,
                            self.typing_env,
                            def_id,
                            args,
                        )
                        .ok_or_else(|| err_inval!(TooGeneric))?;

                        let fn_ptr = self.fn_ptr(FnVal::Instance(instance));
                        self.write_pointer(fn_ptr, dest)?;
                    }
                    _ => span_bug!(self.cur_span(), "reify fn pointer on {}", src.layout.ty),
                }
            }

            CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
                let src = self.read_immediate(src)?;
                match cast_ty.kind() {
                    ty::FnPtr(..) => {
                        // No change to value
                        self.write_immediate(*src, dest)?;
                    }
                    _ => span_bug!(self.cur_span(), "fn to unsafe fn cast on {}", cast_ty),
                }
            }

            CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => {
                // All reifications must be monomorphic, bail out otherwise.
                ensure_monomorphic_enough(*self.tcx, src.layout.ty)?;

                // The src operand does not matter, just its type
                match *src.layout.ty.kind() {
                    ty::Closure(def_id, args) => {
                        let instance = ty::Instance::resolve_closure(
                            *self.tcx,
                            def_id,
                            args,
                            ty::ClosureKind::FnOnce,
                        );
                        let fn_ptr = self.fn_ptr(FnVal::Instance(instance));
                        self.write_pointer(fn_ptr, dest)?;
                    }
                    _ => span_bug!(self.cur_span(), "closure fn pointer on {}", src.layout.ty),
                }
            }

            CastKind::PointerCoercion(PointerCoercion::DynStar, _) => {
                if let ty::Dynamic(data, _, ty::DynStar) = cast_ty.kind() {
                    // Initial cast from sized to dyn trait
                    let vtable = self.get_vtable_ptr(src.layout.ty, data)?;
                    let vtable = Scalar::from_maybe_pointer(vtable, self);
                    let data = self.read_immediate(src)?.to_scalar();
                    let _assert_pointer_like = data.to_pointer(self)?;
                    let val = Immediate::ScalarPair(data, vtable);
                    self.write_immediate(val, dest)?;
                } else {
                    bug!()
                }
            }

            CastKind::Transmute => {
                assert!(src.layout.is_sized());
                assert!(dest.layout.is_sized());
                assert_eq!(cast_ty, dest.layout.ty); // we otherwise ignore `cast_ty` enirely...
                if src.layout.size != dest.layout.size {
                    throw_ub_custom!(
                        fluent::const_eval_invalid_transmute,
                        src_bytes = src.layout.size.bytes(),
                        dest_bytes = dest.layout.size.bytes(),
                        src = src.layout.ty,
                        dest = dest.layout.ty,
                    );
                }

                self.copy_op_allow_transmute(src, dest)?;
            }
        }
        interp_ok(())
    }

    /// Handles 'IntToInt' and 'IntToFloat' casts.
    pub fn int_to_int_or_float(
        &self,
        src: &ImmTy<'tcx, M::Provenance>,
        cast_to: TyAndLayout<'tcx>,
    ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
        assert!(src.layout.ty.is_integral() || src.layout.ty.is_char() || src.layout.ty.is_bool());
        assert!(cast_to.ty.is_floating_point() || cast_to.ty.is_integral() || cast_to.ty.is_char());

        interp_ok(ImmTy::from_scalar(
            self.cast_from_int_like(src.to_scalar(), src.layout, cast_to.ty)?,
            cast_to,
        ))
    }

    /// Handles 'FloatToFloat' and 'FloatToInt' casts.
    pub fn float_to_float_or_int(
        &self,
        src: &ImmTy<'tcx, M::Provenance>,
        cast_to: TyAndLayout<'tcx>,
    ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
        use rustc_type_ir::TyKind::*;

        let Float(fty) = src.layout.ty.kind() else {
            bug!("FloatToFloat/FloatToInt cast: source type {} is not a float type", src.layout.ty)
        };
        let val = match fty {
            FloatTy::F16 => self.cast_from_float(src.to_scalar().to_f16()?, cast_to.ty),
            FloatTy::F32 => self.cast_from_float(src.to_scalar().to_f32()?, cast_to.ty),
            FloatTy::F64 => self.cast_from_float(src.to_scalar().to_f64()?, cast_to.ty),
            FloatTy::F128 => self.cast_from_float(src.to_scalar().to_f128()?, cast_to.ty),
        };
        interp_ok(ImmTy::from_scalar(val, cast_to))
    }

    /// Handles 'FnPtrToPtr' and 'PtrToPtr' casts.
    pub fn ptr_to_ptr(
        &self,
        src: &ImmTy<'tcx, M::Provenance>,
        cast_to: TyAndLayout<'tcx>,
    ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
        assert!(src.layout.ty.is_any_ptr());
        assert!(cast_to.ty.is_unsafe_ptr());
        // Handle casting any ptr to raw ptr (might be a wide ptr).
        if cast_to.size == src.layout.size {
            // Thin or wide pointer that just has the ptr kind of target type changed.
            return interp_ok(ImmTy::from_immediate(**src, cast_to));
        } else {
            // Casting the metadata away from a wide ptr.
            assert_eq!(src.layout.size, 2 * self.pointer_size());
            assert_eq!(cast_to.size, self.pointer_size());
            assert!(src.layout.ty.is_unsafe_ptr());
            return match **src {
                Immediate::ScalarPair(data, _) => interp_ok(ImmTy::from_scalar(data, cast_to)),
                Immediate::Scalar(..) => span_bug!(
                    self.cur_span(),
                    "{:?} input to a fat-to-thin cast ({} -> {})",
                    *src,
                    src.layout.ty,
                    cast_to.ty
                ),
                Immediate::Uninit => throw_ub!(InvalidUninitBytes(None)),
            };
        }
    }

    pub fn pointer_expose_provenance_cast(
        &mut self,
        src: &ImmTy<'tcx, M::Provenance>,
        cast_to: TyAndLayout<'tcx>,
    ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
        assert_matches!(src.layout.ty.kind(), ty::RawPtr(_, _) | ty::FnPtr(..));
        assert!(cast_to.ty.is_integral());

        let scalar = src.to_scalar();
        let ptr = scalar.to_pointer(self)?;
        match ptr.into_pointer_or_addr() {
            Ok(ptr) => M::expose_provenance(self, ptr.provenance)?,
            Err(_) => {} // Do nothing, exposing an invalid pointer (`None` provenance) is a NOP.
        };
        interp_ok(ImmTy::from_scalar(
            self.cast_from_int_like(scalar, src.layout, cast_to.ty)?,
            cast_to,
        ))
    }

    pub fn pointer_with_exposed_provenance_cast(
        &self,
        src: &ImmTy<'tcx, M::Provenance>,
        cast_to: TyAndLayout<'tcx>,
    ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
        assert!(src.layout.ty.is_integral());
        assert_matches!(cast_to.ty.kind(), ty::RawPtr(_, _));

        // First cast to usize.
        let scalar = src.to_scalar();
        let addr = self.cast_from_int_like(scalar, src.layout, self.tcx.types.usize)?;
        let addr = addr.to_target_usize(self)?;

        // Then turn address into pointer.
        let ptr = M::ptr_from_addr_cast(self, addr)?;
        interp_ok(ImmTy::from_scalar(Scalar::from_maybe_pointer(ptr, self), cast_to))
    }

    /// Low-level cast helper function. This works directly on scalars and can take 'int-like' input
    /// type (basically everything with a scalar layout) to int/float/char types.
    fn cast_from_int_like(
        &self,
        scalar: Scalar<M::Provenance>, // input value (there is no ScalarTy so we separate data+layout)
        src_layout: TyAndLayout<'tcx>,
        cast_ty: Ty<'tcx>,
    ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
        // Let's make sure v is sign-extended *if* it has a signed type.
        let signed = src_layout.backend_repr.is_signed(); // Also asserts that abi is `Scalar`.

        let v = match src_layout.ty.kind() {
            Uint(_) | RawPtr(..) | FnPtr(..) => scalar.to_uint(src_layout.size)?,
            Int(_) => scalar.to_int(src_layout.size)? as u128, // we will cast back to `i128` below if the sign matters
            Bool => scalar.to_bool()?.into(),
            Char => scalar.to_char()?.into(),
            _ => span_bug!(self.cur_span(), "invalid int-like cast from {}", src_layout.ty),
        };

        interp_ok(match *cast_ty.kind() {
            // int -> int
            Int(_) | Uint(_) => {
                let size = match *cast_ty.kind() {
                    Int(t) => Integer::from_int_ty(self, t).size(),
                    Uint(t) => Integer::from_uint_ty(self, t).size(),
                    _ => bug!(),
                };
                let v = size.truncate(v);
                Scalar::from_uint(v, size)
            }

            // signed int -> float
            Float(fty) if signed => {
                let v = v as i128;
                match fty {
                    FloatTy::F16 => Scalar::from_f16(Half::from_i128(v).value),
                    FloatTy::F32 => Scalar::from_f32(Single::from_i128(v).value),
                    FloatTy::F64 => Scalar::from_f64(Double::from_i128(v).value),
                    FloatTy::F128 => Scalar::from_f128(Quad::from_i128(v).value),
                }
            }
            // unsigned int -> float
            Float(fty) => match fty {
                FloatTy::F16 => Scalar::from_f16(Half::from_u128(v).value),
                FloatTy::F32 => Scalar::from_f32(Single::from_u128(v).value),
                FloatTy::F64 => Scalar::from_f64(Double::from_u128(v).value),
                FloatTy::F128 => Scalar::from_f128(Quad::from_u128(v).value),
            },

            // u8 -> char
            Char => Scalar::from_u32(u8::try_from(v).unwrap().into()),

            // Casts to bool are not permitted by rustc, no need to handle them here.
            _ => span_bug!(self.cur_span(), "invalid int to {} cast", cast_ty),
        })
    }

    /// Low-level cast helper function. Converts an apfloat `f` into int or float types.
    fn cast_from_float<F>(&self, f: F, dest_ty: Ty<'tcx>) -> Scalar<M::Provenance>
    where
        F: Float
            + Into<Scalar<M::Provenance>>
            + FloatConvert<Half>
            + FloatConvert<Single>
            + FloatConvert<Double>
            + FloatConvert<Quad>,
    {
        use rustc_type_ir::TyKind::*;

        match *dest_ty.kind() {
            // float -> uint
            Uint(t) => {
                let size = Integer::from_uint_ty(self, t).size();
                // `to_u128` is a saturating cast, which is what we need
                // (https://doc.rust-lang.org/nightly/nightly-rustc/rustc_apfloat/trait.Float.html#method.to_i128_r).
                let v = f.to_u128(size.bits_usize()).value;
                // This should already fit the bit width
                Scalar::from_uint(v, size)
            }
            // float -> int
            Int(t) => {
                let size = Integer::from_int_ty(self, t).size();
                // `to_i128` is a saturating cast, which is what we need
                // (https://doc.rust-lang.org/nightly/nightly-rustc/rustc_apfloat/trait.Float.html#method.to_i128_r).
                let v = f.to_i128(size.bits_usize()).value;
                Scalar::from_int(v, size)
            }
            // float -> float
            Float(fty) => match fty {
                FloatTy::F16 => {
                    Scalar::from_f16(self.adjust_nan(f.convert(&mut false).value, &[f]))
                }
                FloatTy::F32 => {
                    Scalar::from_f32(self.adjust_nan(f.convert(&mut false).value, &[f]))
                }
                FloatTy::F64 => {
                    Scalar::from_f64(self.adjust_nan(f.convert(&mut false).value, &[f]))
                }
                FloatTy::F128 => {
                    Scalar::from_f128(self.adjust_nan(f.convert(&mut false).value, &[f]))
                }
            },
            // That's it.
            _ => span_bug!(self.cur_span(), "invalid float to {} cast", dest_ty),
        }
    }

    /// `src` is a *pointer to* a `source_ty`, and in `dest` we should store a pointer to th same
    /// data at type `cast_ty`.
    fn unsize_into_ptr(
        &mut self,
        src: &OpTy<'tcx, M::Provenance>,
        dest: &PlaceTy<'tcx, M::Provenance>,
        // The pointee types
        source_ty: Ty<'tcx>,
        cast_ty: Ty<'tcx>,
    ) -> InterpResult<'tcx> {
        // A<Struct> -> A<Trait> conversion
        let (src_pointee_ty, dest_pointee_ty) =
            self.tcx.struct_lockstep_tails_for_codegen(source_ty, cast_ty, self.typing_env);

        match (src_pointee_ty.kind(), dest_pointee_ty.kind()) {
            (&ty::Array(_, length), &ty::Slice(_)) => {
                let ptr = self.read_pointer(src)?;
                let val = Immediate::new_slice(
                    ptr,
                    length
                        .try_to_target_usize(*self.tcx)
                        .expect("expected monomorphic const in const eval"),
                    self,
                );
                self.write_immediate(val, dest)
            }
            (ty::Dynamic(data_a, _, ty::Dyn), ty::Dynamic(data_b, _, ty::Dyn)) => {
                let val = self.read_immediate(src)?;
                // MIR building generates odd NOP casts, prevent them from causing unexpected trouble.
                // See <https://github.com/rust-lang/rust/issues/128880>.
                // FIXME: ideally we wouldn't have to do this.
                if data_a == data_b {
                    return self.write_immediate(*val, dest);
                }
                // Take apart the old pointer, and find the dynamic type.
                let (old_data, old_vptr) = val.to_scalar_pair();
                let old_data = old_data.to_pointer(self)?;
                let old_vptr = old_vptr.to_pointer(self)?;
                let ty = self.get_ptr_vtable_ty(old_vptr, Some(data_a))?;

                // Sanity-check that `supertrait_vtable_slot` in this type's vtable indeed produces
                // our destination trait.
                if cfg!(debug_assertions) {
                    let vptr_entry_idx =
                        self.tcx.supertrait_vtable_slot((src_pointee_ty, dest_pointee_ty));
                    let vtable_entries = self.vtable_entries(data_a.principal(), ty);
                    if let Some(entry_idx) = vptr_entry_idx {
                        let Some(&ty::VtblEntry::TraitVPtr(upcast_trait_ref)) =
                            vtable_entries.get(entry_idx)
                        else {
                            span_bug!(
                                self.cur_span(),
                                "invalid vtable entry index in {} -> {} upcast",
                                src_pointee_ty,
                                dest_pointee_ty
                            );
                        };
                        let erased_trait_ref = upcast_trait_ref
                            .map_bound(|r| ty::ExistentialTraitRef::erase_self_ty(*self.tcx, r));
                        assert!(
                            data_b
                                .principal()
                                .is_some_and(|b| self.eq_in_param_env(erased_trait_ref, b))
                        );
                    } else {
                        // In this case codegen would keep using the old vtable. We don't want to do
                        // that as it has the wrong trait. The reason codegen can do this is that
                        // one vtable is a prefix of the other, so we double-check that.
                        let vtable_entries_b = self.vtable_entries(data_b.principal(), ty);
                        assert!(&vtable_entries[..vtable_entries_b.len()] == vtable_entries_b);
                    };
                }

                // Get the destination trait vtable and return that.
                let new_vptr = self.get_vtable_ptr(ty, data_b)?;
                self.write_immediate(Immediate::new_dyn_trait(old_data, new_vptr, self), dest)
            }
            (_, &ty::Dynamic(data, _, ty::Dyn)) => {
                // Initial cast from sized to dyn trait
                let vtable = self.get_vtable_ptr(src_pointee_ty, data)?;
                let ptr = self.read_pointer(src)?;
                let val = Immediate::new_dyn_trait(ptr, vtable, &*self.tcx);
                self.write_immediate(val, dest)
            }
            _ => {
                // Do not ICE if we are not monomorphic enough.
                ensure_monomorphic_enough(*self.tcx, src.layout.ty)?;
                ensure_monomorphic_enough(*self.tcx, cast_ty)?;

                span_bug!(
                    self.cur_span(),
                    "invalid pointer unsizing {} -> {}",
                    src.layout.ty,
                    cast_ty
                )
            }
        }
    }

    pub fn unsize_into(
        &mut self,
        src: &OpTy<'tcx, M::Provenance>,
        cast_ty: TyAndLayout<'tcx>,
        dest: &PlaceTy<'tcx, M::Provenance>,
    ) -> InterpResult<'tcx> {
        trace!("Unsizing {:?} of type {} into {}", *src, src.layout.ty, cast_ty.ty);
        match (src.layout.ty.kind(), cast_ty.ty.kind()) {
            (&ty::Ref(_, s, _), &ty::Ref(_, c, _) | &ty::RawPtr(c, _))
            | (&ty::RawPtr(s, _), &ty::RawPtr(c, _)) => self.unsize_into_ptr(src, dest, s, c),
            (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
                assert_eq!(def_a, def_b); // implies same number of fields

                // Unsizing of generic struct with pointer fields, like `Arc<T>` -> `Arc<Trait>`.
                // There can be extra fields as long as they don't change their type or are 1-ZST.
                // There might also be no field that actually needs unsizing.
                let mut found_cast_field = false;
                for i in 0..src.layout.fields.count() {
                    let cast_ty_field = cast_ty.field(self, i);
                    let src_field = self.project_field(src, i)?;
                    let dst_field = self.project_field(dest, i)?;
                    if src_field.layout.is_1zst() && cast_ty_field.is_1zst() {
                        // Skip 1-ZST fields.
                    } else if src_field.layout.ty == cast_ty_field.ty {
                        self.copy_op(&src_field, &dst_field)?;
                    } else {
                        if found_cast_field {
                            span_bug!(self.cur_span(), "unsize_into: more than one field to cast");
                        }
                        found_cast_field = true;
                        self.unsize_into(&src_field, cast_ty_field, &dst_field)?;
                    }
                }
                interp_ok(())
            }
            _ => {
                // Do not ICE if we are not monomorphic enough.
                ensure_monomorphic_enough(*self.tcx, src.layout.ty)?;
                ensure_monomorphic_enough(*self.tcx, cast_ty.ty)?;

                span_bug!(
                    self.cur_span(),
                    "unsize_into: invalid conversion: {:?} -> {:?}",
                    src.layout,
                    dest.layout
                )
            }
        }
    }
}