1 //! Functions concerning immediate values and operands, and reading from operands.
2 //! All high-level functions to read from memory work on operands as sources.
4 use either::{Either, Left, Right};
6 use rustc_hir::def::Namespace;
7 use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
8 use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter};
9 use rustc_middle::ty::{ConstInt, Ty, ValTree};
10 use rustc_middle::{mir, ty};
12 use rustc_target::abi::{self, Abi, Align, HasDataLayout, Size};
15 alloc_range, from_known_layout, mir_assign_valid_types, AllocId, ConstValue, Frame, GlobalId,
16 InterpCx, InterpResult, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Place, PlaceTy, Pointer,
20 /// An `Immediate` represents a single immediate self-contained Rust value.
22 /// For optimization of a few very common cases, there is also a representation for a pair of
23 /// primitive values (`ScalarPair`). It allows Miri to avoid making allocations for checked binary
24 /// operations and wide pointers. This idea was taken from rustc's codegen.
25 /// In particular, thanks to `ScalarPair`, arithmetic operations and casts can be entirely
26 /// defined on `Immediate`, and do not have to work with a `Place`.
27 #[derive(Copy, Clone, Debug)]
28 pub enum Immediate<Prov: Provenance = AllocId> {
29 /// A single scalar value (must have *initialized* `Scalar` ABI).
31 /// A pair of two scalar value (must have `ScalarPair` ABI where both fields are
32 /// `Scalar::Initialized`).
33 ScalarPair(Scalar<Prov>, Scalar<Prov>),
34 /// A value of fully uninitialized memory. Can have and size and layout.
38 impl<Prov: Provenance> From<Scalar<Prov>> for Immediate<Prov> {
40 fn from(val: Scalar<Prov>) -> Self {
41 Immediate::Scalar(val)
45 impl<Prov: Provenance> Immediate<Prov> {
46 pub fn from_pointer(p: Pointer<Prov>, cx: &impl HasDataLayout) -> Self {
47 Immediate::Scalar(Scalar::from_pointer(p, cx))
50 pub fn from_maybe_pointer(p: Pointer<Option<Prov>>, cx: &impl HasDataLayout) -> Self {
51 Immediate::Scalar(Scalar::from_maybe_pointer(p, cx))
54 pub fn new_slice(val: Scalar<Prov>, len: u64, cx: &impl HasDataLayout) -> Self {
55 Immediate::ScalarPair(val, Scalar::from_machine_usize(len, cx))
60 vtable: Pointer<Option<Prov>>,
61 cx: &impl HasDataLayout,
63 Immediate::ScalarPair(val, Scalar::from_maybe_pointer(vtable, cx))
67 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
68 pub fn to_scalar(self) -> Scalar<Prov> {
70 Immediate::Scalar(val) => val,
71 Immediate::ScalarPair(..) => bug!("Got a scalar pair where a scalar was expected"),
72 Immediate::Uninit => bug!("Got uninit where a scalar was expected"),
77 #[cfg_attr(debug_assertions, track_caller)] // only in debug builds due to perf (see #98980)
78 pub fn to_scalar_pair(self) -> (Scalar<Prov>, Scalar<Prov>) {
80 Immediate::ScalarPair(val1, val2) => (val1, val2),
81 Immediate::Scalar(..) => bug!("Got a scalar where a scalar pair was expected"),
82 Immediate::Uninit => bug!("Got uninit where a scalar pair was expected"),
87 // ScalarPair needs a type to interpret, so we often have an immediate and a type together
88 // as input for binary and cast operations.
89 #[derive(Clone, Debug)]
90 pub struct ImmTy<'tcx, Prov: Provenance = AllocId> {
92 pub layout: TyAndLayout<'tcx>,
95 impl<Prov: Provenance> std::fmt::Display for ImmTy<'_, Prov> {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 /// Helper function for printing a scalar to a FmtPrinter
98 fn p<'a, 'tcx, Prov: Provenance>(
99 cx: FmtPrinter<'a, 'tcx>,
102 ) -> Result<FmtPrinter<'a, 'tcx>, std::fmt::Error> {
104 Scalar::Int(int) => cx.pretty_print_const_scalar_int(int, ty, true),
105 Scalar::Ptr(ptr, _sz) => {
106 // Just print the ptr value. `pretty_print_const_scalar_ptr` would also try to
107 // print what is points to, which would fail since it has no access to the local
109 cx.pretty_print_const_pointer(ptr, ty, true)
113 ty::tls::with(|tcx| {
115 Immediate::Scalar(s) => {
116 if let Some(ty) = tcx.lift(self.layout.ty) {
117 let cx = FmtPrinter::new(tcx, Namespace::ValueNS);
118 f.write_str(&p(cx, s, ty)?.into_buffer())?;
121 write!(f, "{:x}: {}", s, self.layout.ty)
123 Immediate::ScalarPair(a, b) => {
124 // FIXME(oli-obk): at least print tuples and slices nicely
125 write!(f, "({:x}, {:x}): {}", a, b, self.layout.ty)
127 Immediate::Uninit => {
128 write!(f, "uninit: {}", self.layout.ty)
135 impl<'tcx, Prov: Provenance> std::ops::Deref for ImmTy<'tcx, Prov> {
136 type Target = Immediate<Prov>;
138 fn deref(&self) -> &Immediate<Prov> {
143 /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate,
144 /// or still in memory. The latter is an optimization, to delay reading that chunk of
145 /// memory and to avoid having to store arbitrary-sized data here.
146 #[derive(Copy, Clone, Debug)]
147 pub enum Operand<Prov: Provenance = AllocId> {
148 Immediate(Immediate<Prov>),
149 Indirect(MemPlace<Prov>),
152 #[derive(Clone, Debug)]
153 pub struct OpTy<'tcx, Prov: Provenance = AllocId> {
154 op: Operand<Prov>, // Keep this private; it helps enforce invariants.
155 pub layout: TyAndLayout<'tcx>,
156 /// rustc does not have a proper way to represent the type of a field of a `repr(packed)` struct:
157 /// it needs to have a different alignment than the field type would usually have.
158 /// So we represent this here with a separate field that "overwrites" `layout.align`.
159 /// This means `layout.align` should never be used for an `OpTy`!
160 /// `None` means "alignment does not matter since this is a by-value operand"
161 /// (`Operand::Immediate`); this field is only relevant for `Operand::Indirect`.
162 /// Also CTFE ignores alignment anyway, so this is for Miri only.
163 pub align: Option<Align>,
166 impl<'tcx, Prov: Provenance> std::ops::Deref for OpTy<'tcx, Prov> {
167 type Target = Operand<Prov>;
169 fn deref(&self) -> &Operand<Prov> {
174 impl<'tcx, Prov: Provenance> From<MPlaceTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
176 fn from(mplace: MPlaceTy<'tcx, Prov>) -> Self {
177 OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout, align: Some(mplace.align) }
181 impl<'tcx, Prov: Provenance> From<&'_ MPlaceTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
183 fn from(mplace: &MPlaceTy<'tcx, Prov>) -> Self {
184 OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout, align: Some(mplace.align) }
188 impl<'tcx, Prov: Provenance> From<&'_ mut MPlaceTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
190 fn from(mplace: &mut MPlaceTy<'tcx, Prov>) -> Self {
191 OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout, align: Some(mplace.align) }
195 impl<'tcx, Prov: Provenance> From<ImmTy<'tcx, Prov>> for OpTy<'tcx, Prov> {
197 fn from(val: ImmTy<'tcx, Prov>) -> Self {
198 OpTy { op: Operand::Immediate(val.imm), layout: val.layout, align: None }
202 impl<'tcx, Prov: Provenance> ImmTy<'tcx, Prov> {
204 pub fn from_scalar(val: Scalar<Prov>, layout: TyAndLayout<'tcx>) -> Self {
205 ImmTy { imm: val.into(), layout }
209 pub fn from_immediate(imm: Immediate<Prov>, layout: TyAndLayout<'tcx>) -> Self {
210 ImmTy { imm, layout }
214 pub fn uninit(layout: TyAndLayout<'tcx>) -> Self {
215 ImmTy { imm: Immediate::Uninit, layout }
219 pub fn try_from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
220 Some(Self::from_scalar(Scalar::try_from_uint(i, layout.size)?, layout))
223 pub fn from_uint(i: impl Into<u128>, layout: TyAndLayout<'tcx>) -> Self {
224 Self::from_scalar(Scalar::from_uint(i, layout.size), layout)
228 pub fn try_from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Option<Self> {
229 Some(Self::from_scalar(Scalar::try_from_int(i, layout.size)?, layout))
233 pub fn from_int(i: impl Into<i128>, layout: TyAndLayout<'tcx>) -> Self {
234 Self::from_scalar(Scalar::from_int(i, layout.size), layout)
238 pub fn to_const_int(self) -> ConstInt {
239 assert!(self.layout.ty.is_integral());
240 let int = self.to_scalar().assert_int();
241 ConstInt::new(int, self.layout.ty.is_signed(), self.layout.ty.is_ptr_sized_integral())
245 impl<'tcx, Prov: Provenance> OpTy<'tcx, Prov> {
246 pub fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> {
247 if self.layout.is_unsized() {
248 // There are no unsized immediates.
249 self.assert_mem_place().len(cx)
251 match self.layout.fields {
252 abi::FieldsShape::Array { count, .. } => Ok(count),
253 _ => bug!("len not supported on sized type {:?}", self.layout.ty),
258 pub fn offset_with_meta(
261 meta: MemPlaceMeta<Prov>,
262 layout: TyAndLayout<'tcx>,
263 cx: &impl HasDataLayout,
264 ) -> InterpResult<'tcx, Self> {
265 match self.as_mplace_or_imm() {
266 Left(mplace) => Ok(mplace.offset_with_meta(offset, meta, layout, cx)?.into()),
269 matches!(*imm, Immediate::Uninit),
270 "Scalar/ScalarPair cannot be offset into"
272 assert!(!meta.has_meta()); // no place to store metadata here
273 // Every part of an uninit is uninit.
274 Ok(ImmTy::uninit(layout).into())
282 layout: TyAndLayout<'tcx>,
283 cx: &impl HasDataLayout,
284 ) -> InterpResult<'tcx, Self> {
285 assert!(layout.is_sized());
286 self.offset_with_meta(offset, MemPlaceMeta::None, layout, cx)
290 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
291 /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
292 /// Returns `None` if the layout does not permit loading this as a value.
294 /// This is an internal function; call `read_immediate` instead.
295 fn read_immediate_from_mplace_raw(
297 mplace: &MPlaceTy<'tcx, M::Provenance>,
298 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, M::Provenance>>> {
299 if mplace.layout.is_unsized() {
300 // Don't touch unsized
304 let Some(alloc) = self.get_place_alloc(mplace)? else {
305 // zero-sized type can be left uninit
306 return Ok(Some(ImmTy::uninit(mplace.layout)));
309 // It may seem like all types with `Scalar` or `ScalarPair` ABI are fair game at this point.
310 // However, `MaybeUninit<u64>` is considered a `Scalar` as far as its layout is concerned --
311 // and yet cannot be represented by an interpreter `Scalar`, since we have to handle the
312 // case where some of the bytes are initialized and others are not. So, we need an extra
313 // check that walks over the type of `mplace` to make sure it is truly correct to treat this
314 // like a `Scalar` (or `ScalarPair`).
315 Ok(match mplace.layout.abi {
316 Abi::Scalar(abi::Scalar::Initialized { value: s, .. }) => {
317 let size = s.size(self);
318 assert_eq!(size, mplace.layout.size, "abi::Scalar size does not match layout size");
319 let scalar = alloc.read_scalar(
320 alloc_range(Size::ZERO, size),
321 /*read_provenance*/ matches!(s, abi::Pointer(_)),
323 Some(ImmTy { imm: scalar.into(), layout: mplace.layout })
326 abi::Scalar::Initialized { value: a, .. },
327 abi::Scalar::Initialized { value: b, .. },
329 // We checked `ptr_align` above, so all fields will have the alignment they need.
330 // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`,
331 // which `ptr.offset(b_offset)` cannot possibly fail to satisfy.
332 let (a_size, b_size) = (a.size(self), b.size(self));
333 let b_offset = a_size.align_to(b.align(self).abi);
334 assert!(b_offset.bytes() > 0); // in `operand_field` we use the offset to tell apart the fields
335 let a_val = alloc.read_scalar(
336 alloc_range(Size::ZERO, a_size),
337 /*read_provenance*/ matches!(a, abi::Pointer(_)),
339 let b_val = alloc.read_scalar(
340 alloc_range(b_offset, b_size),
341 /*read_provenance*/ matches!(b, abi::Pointer(_)),
343 Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout })
346 // Neither a scalar nor scalar pair.
352 /// Try returning an immediate for the operand. If the layout does not permit loading this as an
353 /// immediate, return where in memory we can find the data.
354 /// Note that for a given layout, this operation will either always return Left or Right!
355 /// succeed! Whether it returns Left depends on whether the layout can be represented
356 /// in an `Immediate`, not on which data is stored there currently.
358 /// This is an internal function that should not usually be used; call `read_immediate` instead.
359 /// ConstProp needs it, though.
360 pub fn read_immediate_raw(
362 src: &OpTy<'tcx, M::Provenance>,
363 ) -> InterpResult<'tcx, Either<MPlaceTy<'tcx, M::Provenance>, ImmTy<'tcx, M::Provenance>>> {
364 Ok(match src.as_mplace_or_imm() {
365 Left(ref mplace) => {
366 if let Some(val) = self.read_immediate_from_mplace_raw(mplace)? {
372 Right(val) => Right(val),
376 /// Read an immediate from a place, asserting that that is possible with the given layout.
378 /// If this succeeds, the `ImmTy` is never `Uninit`.
380 pub fn read_immediate(
382 op: &OpTy<'tcx, M::Provenance>,
383 ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
386 Abi::Scalar(abi::Scalar::Initialized { .. })
387 | Abi::ScalarPair(abi::Scalar::Initialized { .. }, abi::Scalar::Initialized { .. })
389 span_bug!(self.cur_span(), "primitive read not possible for type: {:?}", op.layout.ty);
391 let imm = self.read_immediate_raw(op)?.right().unwrap();
392 if matches!(*imm, Immediate::Uninit) {
393 throw_ub!(InvalidUninitBytes(None));
398 /// Read a scalar from a place
401 op: &OpTy<'tcx, M::Provenance>,
402 ) -> InterpResult<'tcx, Scalar<M::Provenance>> {
403 Ok(self.read_immediate(op)?.to_scalar())
406 // Pointer-sized reads are fairly common and need target layout access, so we wrap them in
407 // convenience functions.
409 /// Read a pointer from a place.
412 op: &OpTy<'tcx, M::Provenance>,
413 ) -> InterpResult<'tcx, Pointer<Option<M::Provenance>>> {
414 self.read_scalar(op)?.to_pointer(self)
416 /// Read a pointer-sized unsigned integer from a place.
417 pub fn read_machine_usize(&self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx, u64> {
418 self.read_scalar(op)?.to_machine_usize(self)
420 /// Read a pointer-sized signed integer from a place.
421 pub fn read_machine_isize(&self, op: &OpTy<'tcx, M::Provenance>) -> InterpResult<'tcx, i64> {
422 self.read_scalar(op)?.to_machine_isize(self)
425 /// Turn the wide MPlace into a string (must already be dereferenced!)
426 pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx, &str> {
427 let len = mplace.len(self)?;
428 let bytes = self.read_bytes_ptr_strip_provenance(mplace.ptr, Size::from_bytes(len))?;
429 let str = std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?;
433 /// Converts a repr(simd) operand into an operand where `place_index` accesses the SIMD elements.
434 /// Also returns the number of elements.
436 /// Can (but does not always) trigger UB if `op` is uninitialized.
437 pub fn operand_to_simd(
439 op: &OpTy<'tcx, M::Provenance>,
440 ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::Provenance>, u64)> {
441 // Basically we just transmute this place into an array following simd_size_and_type.
442 // This only works in memory, but repr(simd) types should never be immediates anyway.
443 assert!(op.layout.ty.is_simd());
444 match op.as_mplace_or_imm() {
445 Left(mplace) => self.mplace_to_simd(&mplace),
446 Right(imm) => match *imm {
447 Immediate::Uninit => {
448 throw_ub!(InvalidUninitBytes(None))
450 Immediate::Scalar(..) | Immediate::ScalarPair(..) => {
451 bug!("arrays/slices can never have Scalar/ScalarPair layout")
457 /// Read from a local.
458 /// Will not access memory, instead an indirect `Operand` is returned.
460 /// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an
461 /// OpTy from a local.
464 frame: &Frame<'mir, 'tcx, M::Provenance, M::FrameExtra>,
466 layout: Option<TyAndLayout<'tcx>>,
467 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
468 let layout = self.layout_of_local(frame, local, layout)?;
469 let op = *frame.locals[local].access()?;
470 Ok(OpTy { op, layout, align: Some(layout.align.abi) })
473 /// Every place can be read from, so we can turn them into an operand.
474 /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this
475 /// will never actually read from memory.
479 place: &PlaceTy<'tcx, M::Provenance>,
480 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
481 let op = match **place {
482 Place::Ptr(mplace) => Operand::Indirect(mplace),
483 Place::Local { frame, local } => {
484 *self.local_to_op(&self.stack()[frame], local, None)?
487 Ok(OpTy { op, layout: place.layout, align: Some(place.align) })
490 /// Evaluate a place with the goal of reading from it. This lets us sometimes
491 /// avoid allocations.
492 pub fn eval_place_to_op(
494 mir_place: mir::Place<'tcx>,
495 layout: Option<TyAndLayout<'tcx>>,
496 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
497 // Do not use the layout passed in as argument if the base we are looking at
498 // here is not the entire place.
499 let layout = if mir_place.projection.is_empty() { layout } else { None };
501 let mut op = self.local_to_op(self.frame(), mir_place.local, layout)?;
502 // Using `try_fold` turned out to be bad for performance, hence the loop.
503 for elem in mir_place.projection.iter() {
504 op = self.operand_projection(&op, elem)?
507 trace!("eval_place_to_op: got {:?}", *op);
508 // Sanity-check the type we ended up with.
510 mir_assign_valid_types(
513 self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions(
514 mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty
518 "eval_place of a MIR place with type {:?} produced an interpreter operand with type {:?}",
519 mir_place.ty(&self.frame().body.local_decls, *self.tcx).ty,
525 /// Evaluate the operand, returning a place where you can then find the data.
526 /// If you already know the layout, you can save two table lookups
527 /// by passing it in here.
531 mir_op: &mir::Operand<'tcx>,
532 layout: Option<TyAndLayout<'tcx>>,
533 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
534 use rustc_middle::mir::Operand::*;
535 let op = match mir_op {
536 // FIXME: do some more logic on `move` to invalidate the old location
537 &Copy(place) | &Move(place) => self.eval_place_to_op(place, layout)?,
539 Constant(constant) => {
541 self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal)?;
543 // This can still fail:
544 // * During ConstProp, with `TooGeneric` or since the `required_consts` were not all
546 // * During CTFE, since promoteds in `const`/`static` initializer bodies can fail.
547 self.eval_mir_constant(&c, Some(constant.span), layout)?
550 trace!("{:?}: {:?}", mir_op, *op);
554 /// Evaluate a bunch of operands at once
555 pub(super) fn eval_operands(
557 ops: &[mir::Operand<'tcx>],
558 ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::Provenance>>> {
559 ops.iter().map(|op| self.eval_operand(op, None)).collect()
564 val: ty::Const<'tcx>,
566 ) -> InterpResult<'tcx, ValTree<'tcx>> {
567 Ok(match val.kind() {
568 ty::ConstKind::Param(_) | ty::ConstKind::Placeholder(..) => {
569 throw_inval!(TooGeneric)
571 // FIXME(generic_const_exprs): `ConstKind::Expr` should be able to be evaluated
572 ty::ConstKind::Expr(_) => throw_inval!(TooGeneric),
573 ty::ConstKind::Error(reported) => {
574 throw_inval!(AlreadyReported(reported))
576 ty::ConstKind::Unevaluated(uv) => {
577 let instance = self.resolve(uv.def, uv.substs)?;
578 let cid = GlobalId { instance, promoted: None };
579 self.ctfe_query(span, |tcx| {
580 tcx.eval_to_valtree(self.param_env.with_const().and(cid))
582 .unwrap_or_else(|| bug!("unable to create ValTree for {uv:?}"))
584 ty::ConstKind::Bound(..) | ty::ConstKind::Infer(..) => {
585 span_bug!(self.cur_span(), "unexpected ConstKind in ctfe: {val:?}")
587 ty::ConstKind::Value(valtree) => valtree,
591 pub fn eval_mir_constant(
593 val: &mir::ConstantKind<'tcx>,
595 layout: Option<TyAndLayout<'tcx>>,
596 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
597 // FIXME(const_prop): normalization needed b/c const prop lint in
598 // `mir_drops_elaborated_and_const_checked`, which happens before
599 // optimized MIR. Only after optimizing the MIR can we guarantee
600 // that the `RevealAll` pass has happened and that the body's consts
601 // are normalized, so any call to resolve before that needs to be
602 // manually normalized.
603 let val = self.tcx.normalize_erasing_regions(self.param_env, *val);
605 mir::ConstantKind::Ty(ct) => {
607 let valtree = self.eval_ty_constant(ct, span)?;
608 let const_val = self.tcx.valtree_to_const_val((ty, valtree));
609 self.const_val_to_op(const_val, ty, layout)
611 mir::ConstantKind::Val(val, ty) => self.const_val_to_op(val, ty, layout),
612 mir::ConstantKind::Unevaluated(uv, _) => {
613 let instance = self.resolve(uv.def, uv.substs)?;
614 Ok(self.eval_global(GlobalId { instance, promoted: uv.promoted }, span)?.into())
619 pub(super) fn const_val_to_op(
621 val_val: ConstValue<'tcx>,
623 layout: Option<TyAndLayout<'tcx>>,
624 ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
625 // Other cases need layout.
626 let adjust_scalar = |scalar| -> InterpResult<'tcx, _> {
628 Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size),
629 Scalar::Int(int) => Scalar::Int(int),
632 let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?;
633 let op = match val_val {
634 ConstValue::ByRef { alloc, offset } => {
635 let id = self.tcx.create_memory_alloc(alloc);
636 // We rely on mutability being set correctly in that allocation to prevent writes
637 // where none should happen.
638 let ptr = self.global_base_pointer(Pointer::new(id, offset))?;
639 Operand::Indirect(MemPlace::from_ptr(ptr.into()))
641 ConstValue::Scalar(x) => Operand::Immediate(adjust_scalar(x)?.into()),
642 ConstValue::ZeroSized => Operand::Immediate(Immediate::Uninit),
643 ConstValue::Slice { data, start, end } => {
644 // We rely on mutability being set correctly in `data` to prevent writes
645 // where none should happen.
646 let ptr = Pointer::new(
647 self.tcx.create_memory_alloc(data),
648 Size::from_bytes(start), // offset: `start`
650 Operand::Immediate(Immediate::new_slice(
651 Scalar::from_pointer(self.global_base_pointer(ptr)?, &*self.tcx),
652 u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start`
657 Ok(OpTy { op, layout, align: Some(layout.align.abi) })
661 // Some nodes are used a lot. Make sure they don't unintentionally get bigger.
662 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
665 use rustc_data_structures::static_assert_size;
666 // tidy-alphabetical-start
667 static_assert_size!(Immediate, 48);
668 static_assert_size!(ImmTy<'_>, 64);
669 static_assert_size!(Operand, 56);
670 static_assert_size!(OpTy<'_>, 80);
671 // tidy-alphabetical-end