rustc_codegen_ssa/mir/
rvalue.rs

1use itertools::Itertools as _;
2use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT};
3use rustc_middle::ty::adjustment::PointerCoercion;
4use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
5use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
6use rustc_middle::{bug, mir, span_bug};
7use rustc_session::config::OptLevel;
8use tracing::{debug, instrument};
9
10use super::FunctionCx;
11use super::operand::{OperandRef, OperandRefBuilder, OperandValue};
12use super::place::{PlaceRef, PlaceValue, codegen_tag_value};
13use crate::common::{IntPredicate, TypeKind};
14use crate::traits::*;
15use crate::{MemFlags, base};
16
17impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
18    #[instrument(level = "trace", skip(self, bx))]
19    pub(crate) fn codegen_rvalue(
20        &mut self,
21        bx: &mut Bx,
22        dest: PlaceRef<'tcx, Bx::Value>,
23        rvalue: &mir::Rvalue<'tcx>,
24    ) {
25        match *rvalue {
26            mir::Rvalue::Use(ref operand) => {
27                let cg_operand = self.codegen_operand(bx, operand);
28                // Crucially, we do *not* use `OperandValue::Ref` for types with
29                // `BackendRepr::Scalar | BackendRepr::ScalarPair`. This ensures we match the MIR
30                // semantics regarding when assignment operators allow overlap of LHS and RHS.
31                if matches!(
32                    cg_operand.layout.backend_repr,
33                    BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..),
34                ) {
35                    debug_assert!(!matches!(cg_operand.val, OperandValue::Ref(..)));
36                }
37                // FIXME: consider not copying constants through stack. (Fixable by codegen'ing
38                // constants into `OperandValue::Ref`; why don’t we do that yet if we don’t?)
39                cg_operand.store_with_annotation(bx, dest);
40            }
41
42            mir::Rvalue::Cast(
43                mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
44                ref source,
45                _,
46            ) => {
47                // The destination necessarily contains a wide pointer, so if
48                // it's a scalar pair, it's a wide pointer or newtype thereof.
49                if bx.cx().is_backend_scalar_pair(dest.layout) {
50                    // Into-coerce of a thin pointer to a wide pointer -- just
51                    // use the operand path.
52                    let temp = self.codegen_rvalue_operand(bx, rvalue);
53                    temp.store_with_annotation(bx, dest);
54                    return;
55                }
56
57                // Unsize of a nontrivial struct. I would prefer for
58                // this to be eliminated by MIR building, but
59                // `CoerceUnsized` can be passed by a where-clause,
60                // so the (generic) MIR may not be able to expand it.
61                let operand = self.codegen_operand(bx, source);
62                match operand.val {
63                    OperandValue::Pair(..) | OperandValue::Immediate(_) => {
64                        // Unsize from an immediate structure. We don't
65                        // really need a temporary alloca here, but
66                        // avoiding it would require us to have
67                        // `coerce_unsized_into` use `extractvalue` to
68                        // index into the struct, and this case isn't
69                        // important enough for it.
70                        debug!("codegen_rvalue: creating ugly alloca");
71                        let scratch = PlaceRef::alloca(bx, operand.layout);
72                        scratch.storage_live(bx);
73                        operand.store_with_annotation(bx, scratch);
74                        base::coerce_unsized_into(bx, scratch, dest);
75                        scratch.storage_dead(bx);
76                    }
77                    OperandValue::Ref(val) => {
78                        if val.llextra.is_some() {
79                            bug!("unsized coercion on an unsized rvalue");
80                        }
81                        base::coerce_unsized_into(bx, val.with_type(operand.layout), dest);
82                    }
83                    OperandValue::ZeroSized => {
84                        bug!("unsized coercion on a ZST rvalue");
85                    }
86                }
87            }
88
89            mir::Rvalue::Cast(
90                mir::CastKind::Transmute | mir::CastKind::Subtype,
91                ref operand,
92                _ty,
93            ) => {
94                let src = self.codegen_operand(bx, operand);
95                self.codegen_transmute(bx, src, dest);
96            }
97
98            mir::Rvalue::Repeat(ref elem, count) => {
99                // Do not generate the loop for zero-sized elements or empty arrays.
100                if dest.layout.is_zst() {
101                    return;
102                }
103
104                // When the element is a const with all bytes uninit, emit a single memset that
105                // writes undef to the entire destination.
106                if let mir::Operand::Constant(const_op) = elem {
107                    let val = self.eval_mir_constant(const_op);
108                    if val.all_bytes_uninit(self.cx.tcx()) {
109                        let size = bx.const_usize(dest.layout.size.bytes());
110                        bx.memset(
111                            dest.val.llval,
112                            bx.const_undef(bx.type_i8()),
113                            size,
114                            dest.val.align,
115                            MemFlags::empty(),
116                        );
117                        return;
118                    }
119                }
120
121                let cg_elem = self.codegen_operand(bx, elem);
122
123                let try_init_all_same = |bx: &mut Bx, v| {
124                    let start = dest.val.llval;
125                    let size = bx.const_usize(dest.layout.size.bytes());
126
127                    // Use llvm.memset.p0i8.* to initialize all same byte arrays
128                    if let Some(int) = bx.cx().const_to_opt_u128(v, false)
129                        && let bytes = &int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()]
130                        && let Ok(&byte) = bytes.iter().all_equal_value()
131                    {
132                        let fill = bx.cx().const_u8(byte);
133                        bx.memset(start, fill, size, dest.val.align, MemFlags::empty());
134                        return true;
135                    }
136
137                    // Use llvm.memset.p0i8.* to initialize byte arrays
138                    let v = bx.from_immediate(v);
139                    if bx.cx().val_ty(v) == bx.cx().type_i8() {
140                        bx.memset(start, v, size, dest.val.align, MemFlags::empty());
141                        return true;
142                    }
143                    false
144                };
145
146                if let OperandValue::Immediate(v) = cg_elem.val
147                    && try_init_all_same(bx, v)
148                {
149                    return;
150                }
151
152                let count = self
153                    .monomorphize(count)
154                    .try_to_target_usize(bx.tcx())
155                    .expect("expected monomorphic const in codegen");
156
157                bx.write_operand_repeatedly(cg_elem, count, dest);
158            }
159
160            // This implementation does field projection, so never use it for `RawPtr`,
161            // which will always be fine with the `codegen_rvalue_operand` path below.
162            mir::Rvalue::Aggregate(ref kind, ref operands)
163                if !matches!(**kind, mir::AggregateKind::RawPtr(..)) =>
164            {
165                let (variant_index, variant_dest, active_field_index) = match **kind {
166                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
167                        let variant_dest = dest.project_downcast(bx, variant_index);
168                        (variant_index, variant_dest, active_field_index)
169                    }
170                    _ => (FIRST_VARIANT, dest, None),
171                };
172                if active_field_index.is_some() {
173                    assert_eq!(operands.len(), 1);
174                }
175                for (i, operand) in operands.iter_enumerated() {
176                    let op = self.codegen_operand(bx, operand);
177                    // Do not generate stores and GEPis for zero-sized fields.
178                    if !op.layout.is_zst() {
179                        let field_index = active_field_index.unwrap_or(i);
180                        let field = if let mir::AggregateKind::Array(_) = **kind {
181                            let llindex = bx.cx().const_usize(field_index.as_u32().into());
182                            variant_dest.project_index(bx, llindex)
183                        } else {
184                            variant_dest.project_field(bx, field_index.as_usize())
185                        };
186                        op.store_with_annotation(bx, field);
187                    }
188                }
189                dest.codegen_set_discr(bx, variant_index);
190            }
191
192            _ => {
193                let temp = self.codegen_rvalue_operand(bx, rvalue);
194                temp.store_with_annotation(bx, dest);
195            }
196        }
197    }
198
199    /// Transmutes the `src` value to the destination type by writing it to `dst`.
200    ///
201    /// See also [`Self::codegen_transmute_operand`] for cases that can be done
202    /// without needing a pre-allocated place for the destination.
203    fn codegen_transmute(
204        &mut self,
205        bx: &mut Bx,
206        src: OperandRef<'tcx, Bx::Value>,
207        dst: PlaceRef<'tcx, Bx::Value>,
208    ) {
209        // The MIR validator enforces no unsized transmutes.
210        assert!(src.layout.is_sized());
211        assert!(dst.layout.is_sized());
212
213        if src.layout.size != dst.layout.size
214            || src.layout.is_uninhabited()
215            || dst.layout.is_uninhabited()
216        {
217            // These cases are all UB to actually hit, so don't emit code for them.
218            // (The size mismatches are reachable via `transmute_unchecked`.)
219            bx.unreachable_nonterminator();
220        } else {
221            // Since in this path we have a place anyway, we can store or copy to it,
222            // making sure we use the destination place's alignment even if the
223            // source would normally have a higher one.
224            src.store_with_annotation(bx, dst.val.with_type(src.layout));
225        }
226    }
227
228    /// Transmutes an `OperandValue` to another `OperandValue`.
229    ///
230    /// This is supported for all cases where the `cast` type is SSA,
231    /// but for non-ZSTs with [`abi::BackendRepr::Memory`] it ICEs.
232    pub(crate) fn codegen_transmute_operand(
233        &mut self,
234        bx: &mut Bx,
235        operand: OperandRef<'tcx, Bx::Value>,
236        cast: TyAndLayout<'tcx>,
237    ) -> OperandValue<Bx::Value> {
238        if let abi::BackendRepr::Memory { .. } = cast.backend_repr
239            && !cast.is_zst()
240        {
241            span_bug!(self.mir.span, "Use `codegen_transmute` to transmute to {cast:?}");
242        }
243
244        // `Layout` is interned, so we can do a cheap check for things that are
245        // exactly the same and thus don't need any handling.
246        if abi::Layout::eq(&operand.layout.layout, &cast.layout) {
247            return operand.val;
248        }
249
250        // Check for transmutes that are always UB.
251        if operand.layout.size != cast.size
252            || operand.layout.is_uninhabited()
253            || cast.is_uninhabited()
254        {
255            bx.unreachable_nonterminator();
256
257            // We still need to return a value of the appropriate type, but
258            // it's already UB so do the easiest thing available.
259            return OperandValue::poison(bx, cast);
260        }
261
262        // To or from pointers takes different methods, so we use this to restrict
263        // the SimdVector case to types which can be `bitcast` between each other.
264        #[inline]
265        fn vector_can_bitcast(x: abi::Scalar) -> bool {
266            matches!(
267                x,
268                abi::Scalar::Initialized {
269                    value: abi::Primitive::Int(..) | abi::Primitive::Float(..),
270                    ..
271                }
272            )
273        }
274
275        let cx = bx.cx();
276        match (operand.val, operand.layout.backend_repr, cast.backend_repr) {
277            _ if cast.is_zst() => OperandValue::ZeroSized,
278            (OperandValue::Ref(source_place_val), abi::BackendRepr::Memory { .. }, _) => {
279                assert_eq!(source_place_val.llextra, None);
280                // The existing alignment is part of `source_place_val`,
281                // so that alignment will be used, not `cast`'s.
282                bx.load_operand(source_place_val.with_type(cast)).val
283            }
284            (
285                OperandValue::Immediate(imm),
286                abi::BackendRepr::Scalar(from_scalar),
287                abi::BackendRepr::Scalar(to_scalar),
288            ) if from_scalar.size(cx) == to_scalar.size(cx) => {
289                OperandValue::Immediate(transmute_scalar(bx, imm, from_scalar, to_scalar))
290            }
291            (
292                OperandValue::Immediate(imm),
293                abi::BackendRepr::SimdVector { element: from_scalar, .. },
294                abi::BackendRepr::SimdVector { element: to_scalar, .. },
295            ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
296                let to_backend_ty = bx.cx().immediate_backend_type(cast);
297                OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
298            }
299            (
300                OperandValue::Pair(imm_a, imm_b),
301                abi::BackendRepr::ScalarPair(in_a, in_b),
302                abi::BackendRepr::ScalarPair(out_a, out_b),
303            ) if in_a.size(cx) == out_a.size(cx) && in_b.size(cx) == out_b.size(cx) => {
304                OperandValue::Pair(
305                    transmute_scalar(bx, imm_a, in_a, out_a),
306                    transmute_scalar(bx, imm_b, in_b, out_b),
307                )
308            }
309            _ => {
310                // For any other potentially-tricky cases, make a temporary instead.
311                // If anything else wants the target local to be in memory this won't
312                // be hit, as `codegen_transmute` will get called directly. Thus this
313                // is only for places where everything else wants the operand form,
314                // and thus it's not worth making those places get it from memory.
315                //
316                // Notably, Scalar ⇌ ScalarPair cases go here to avoid padding
317                // and endianness issues, as do SimdVector ones to avoid worrying
318                // about things like f32x8 ⇌ ptrx4 that would need multiple steps.
319                let align = Ord::max(operand.layout.align.abi, cast.align.abi);
320                let size = Ord::max(operand.layout.size, cast.size);
321                let temp = PlaceValue::alloca(bx, size, align);
322                bx.lifetime_start(temp.llval, size);
323                operand.store_with_annotation(bx, temp.with_type(operand.layout));
324                let val = bx.load_operand(temp.with_type(cast)).val;
325                bx.lifetime_end(temp.llval, size);
326                val
327            }
328        }
329    }
330
331    /// Cast one of the immediates from an [`OperandValue::Immediate`]
332    /// or an [`OperandValue::Pair`] to an immediate of the target type.
333    ///
334    /// Returns `None` if the cast is not possible.
335    fn cast_immediate(
336        &self,
337        bx: &mut Bx,
338        mut imm: Bx::Value,
339        from_scalar: abi::Scalar,
340        from_backend_ty: Bx::Type,
341        to_scalar: abi::Scalar,
342        to_backend_ty: Bx::Type,
343    ) -> Option<Bx::Value> {
344        use abi::Primitive::*;
345
346        // When scalars are passed by value, there's no metadata recording their
347        // valid ranges. For example, `char`s are passed as just `i32`, with no
348        // way for LLVM to know that they're 0x10FFFF at most. Thus we assume
349        // the range of the input value too, not just the output range.
350        assume_scalar_range(bx, imm, from_scalar, from_backend_ty, None);
351
352        imm = match (from_scalar.primitive(), to_scalar.primitive()) {
353            (Int(_, is_signed), Int(..)) => bx.intcast(imm, to_backend_ty, is_signed),
354            (Float(_), Float(_)) => {
355                let srcsz = bx.cx().float_width(from_backend_ty);
356                let dstsz = bx.cx().float_width(to_backend_ty);
357                if dstsz > srcsz {
358                    bx.fpext(imm, to_backend_ty)
359                } else if srcsz > dstsz {
360                    bx.fptrunc(imm, to_backend_ty)
361                } else {
362                    imm
363                }
364            }
365            (Int(_, is_signed), Float(_)) => {
366                if is_signed {
367                    bx.sitofp(imm, to_backend_ty)
368                } else {
369                    bx.uitofp(imm, to_backend_ty)
370                }
371            }
372            (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
373            (Int(_, is_signed), Pointer(..)) => {
374                let usize_imm = bx.intcast(imm, bx.cx().type_isize(), is_signed);
375                bx.inttoptr(usize_imm, to_backend_ty)
376            }
377            (Float(_), Int(_, is_signed)) => bx.cast_float_to_int(is_signed, imm, to_backend_ty),
378            _ => return None,
379        };
380        Some(imm)
381    }
382
383    pub(crate) fn codegen_rvalue_operand(
384        &mut self,
385        bx: &mut Bx,
386        rvalue: &mir::Rvalue<'tcx>,
387    ) -> OperandRef<'tcx, Bx::Value> {
388        match *rvalue {
389            mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
390                let operand = self.codegen_operand(bx, source);
391                debug!("cast operand is {:?}", operand);
392                let cast = bx.cx().layout_of(self.monomorphize(mir_cast_ty));
393
394                let val = match *kind {
395                    mir::CastKind::PointerExposeProvenance => {
396                        assert!(bx.cx().is_backend_immediate(cast));
397                        let llptr = operand.immediate();
398                        let llcast_ty = bx.cx().immediate_backend_type(cast);
399                        let lladdr = bx.ptrtoint(llptr, llcast_ty);
400                        OperandValue::Immediate(lladdr)
401                    }
402                    mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, _) => {
403                        match *operand.layout.ty.kind() {
404                            ty::FnDef(def_id, args) => {
405                                let instance = ty::Instance::resolve_for_fn_ptr(
406                                    bx.tcx(),
407                                    bx.typing_env(),
408                                    def_id,
409                                    args,
410                                )
411                                .unwrap();
412                                OperandValue::Immediate(bx.get_fn_addr(instance))
413                            }
414                            _ => bug!("{} cannot be reified to a fn ptr", operand.layout.ty),
415                        }
416                    }
417                    mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => {
418                        match *operand.layout.ty.kind() {
419                            ty::Closure(def_id, args) => {
420                                let instance = Instance::resolve_closure(
421                                    bx.cx().tcx(),
422                                    def_id,
423                                    args,
424                                    ty::ClosureKind::FnOnce,
425                                );
426                                OperandValue::Immediate(bx.cx().get_fn_addr(instance))
427                            }
428                            _ => bug!("{} cannot be cast to a fn ptr", operand.layout.ty),
429                        }
430                    }
431                    mir::CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
432                        // This is a no-op at the LLVM level.
433                        operand.val
434                    }
435                    mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
436                        assert!(bx.cx().is_backend_scalar_pair(cast));
437                        let (lldata, llextra) = operand.val.pointer_parts();
438                        let (lldata, llextra) =
439                            base::unsize_ptr(bx, lldata, operand.layout.ty, cast.ty, llextra);
440                        OperandValue::Pair(lldata, llextra)
441                    }
442                    mir::CastKind::PointerCoercion(
443                        PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, _
444                    ) => {
445                        bug!("{kind:?} is for borrowck, and should never appear in codegen");
446                    }
447                    mir::CastKind::PtrToPtr
448                        if bx.cx().is_backend_scalar_pair(operand.layout) =>
449                    {
450                        if let OperandValue::Pair(data_ptr, meta) = operand.val {
451                            if bx.cx().is_backend_scalar_pair(cast) {
452                                OperandValue::Pair(data_ptr, meta)
453                            } else {
454                                // Cast of wide-ptr to thin-ptr is an extraction of data-ptr.
455                                OperandValue::Immediate(data_ptr)
456                            }
457                        } else {
458                            bug!("unexpected non-pair operand");
459                        }
460                    }
461                    | mir::CastKind::IntToInt
462                    | mir::CastKind::FloatToInt
463                    | mir::CastKind::FloatToFloat
464                    | mir::CastKind::IntToFloat
465                    | mir::CastKind::PtrToPtr
466                    | mir::CastKind::FnPtrToPtr
467                    // Since int2ptr can have arbitrary integer types as input (so we have to do
468                    // sign extension and all that), it is currently best handled in the same code
469                    // path as the other integer-to-X casts.
470                    | mir::CastKind::PointerWithExposedProvenance => {
471                        let imm = operand.immediate();
472                        let abi::BackendRepr::Scalar(from_scalar) = operand.layout.backend_repr else {
473                            bug!("Found non-scalar for operand {operand:?}");
474                        };
475                        let from_backend_ty = bx.cx().immediate_backend_type(operand.layout);
476
477                        assert!(bx.cx().is_backend_immediate(cast));
478                        let to_backend_ty = bx.cx().immediate_backend_type(cast);
479                        if operand.layout.is_uninhabited() {
480                            let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty));
481                            return OperandRef { val, layout: cast, move_annotation: None };
482                        }
483                        let abi::BackendRepr::Scalar(to_scalar) = cast.layout.backend_repr else {
484                            bug!("Found non-scalar for cast {cast:?}");
485                        };
486
487                        self.cast_immediate(bx, imm, from_scalar, from_backend_ty, to_scalar, to_backend_ty)
488                            .map(OperandValue::Immediate)
489                            .unwrap_or_else(|| {
490                                bug!("Unsupported cast of {operand:?} to {cast:?}");
491                            })
492                    }
493                    mir::CastKind::Transmute | mir::CastKind::Subtype => {
494                        self.codegen_transmute_operand(bx, operand, cast)
495                    }
496                };
497                OperandRef { val, layout: cast, move_annotation: None }
498            }
499
500            mir::Rvalue::Ref(_, bk, place) => {
501                let mk_ref = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
502                    Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, bk.to_mutbl_lossy())
503                };
504                self.codegen_place_to_pointer(bx, place, mk_ref)
505            }
506
507            mir::Rvalue::RawPtr(kind, place) => {
508                let mk_ptr = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
509                    Ty::new_ptr(tcx, ty, kind.to_mutbl_lossy())
510                };
511                self.codegen_place_to_pointer(bx, place, mk_ptr)
512            }
513
514            mir::Rvalue::BinaryOp(op_with_overflow, box (ref lhs, ref rhs))
515                if let Some(op) = op_with_overflow.overflowing_to_wrapping() =>
516            {
517                let lhs = self.codegen_operand(bx, lhs);
518                let rhs = self.codegen_operand(bx, rhs);
519                let result = self.codegen_scalar_checked_binop(
520                    bx,
521                    op,
522                    lhs.immediate(),
523                    rhs.immediate(),
524                    lhs.layout.ty,
525                );
526                let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
527                let operand_ty = Ty::new_tup(bx.tcx(), &[val_ty, bx.tcx().types.bool]);
528                OperandRef {
529                    val: result,
530                    layout: bx.cx().layout_of(operand_ty),
531                    move_annotation: None,
532                }
533            }
534            mir::Rvalue::BinaryOp(op, box (ref lhs, ref rhs)) => {
535                let lhs = self.codegen_operand(bx, lhs);
536                let rhs = self.codegen_operand(bx, rhs);
537                let llresult = match (lhs.val, rhs.val) {
538                    (
539                        OperandValue::Pair(lhs_addr, lhs_extra),
540                        OperandValue::Pair(rhs_addr, rhs_extra),
541                    ) => self.codegen_wide_ptr_binop(
542                        bx,
543                        op,
544                        lhs_addr,
545                        lhs_extra,
546                        rhs_addr,
547                        rhs_extra,
548                        lhs.layout.ty,
549                    ),
550
551                    (OperandValue::Immediate(lhs_val), OperandValue::Immediate(rhs_val)) => self
552                        .codegen_scalar_binop(
553                            bx,
554                            op,
555                            lhs_val,
556                            rhs_val,
557                            lhs.layout.ty,
558                            rhs.layout.ty,
559                        ),
560
561                    _ => bug!(),
562                };
563                OperandRef {
564                    val: OperandValue::Immediate(llresult),
565                    layout: bx.cx().layout_of(op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
566                    move_annotation: None,
567                }
568            }
569
570            mir::Rvalue::UnaryOp(op, ref operand) => {
571                let operand = self.codegen_operand(bx, operand);
572                let is_float = operand.layout.ty.is_floating_point();
573                let (val, layout) = match op {
574                    mir::UnOp::Not => {
575                        let llval = bx.not(operand.immediate());
576                        (OperandValue::Immediate(llval), operand.layout)
577                    }
578                    mir::UnOp::Neg => {
579                        let llval = if is_float {
580                            bx.fneg(operand.immediate())
581                        } else {
582                            bx.neg(operand.immediate())
583                        };
584                        (OperandValue::Immediate(llval), operand.layout)
585                    }
586                    mir::UnOp::PtrMetadata => {
587                        assert!(operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref(),);
588                        let (_, meta) = operand.val.pointer_parts();
589                        assert_eq!(operand.layout.fields.count() > 1, meta.is_some());
590                        if let Some(meta) = meta {
591                            (OperandValue::Immediate(meta), operand.layout.field(self.cx, 1))
592                        } else {
593                            (OperandValue::ZeroSized, bx.cx().layout_of(bx.tcx().types.unit))
594                        }
595                    }
596                };
597                assert!(
598                    val.is_expected_variant_for_type(self.cx, layout),
599                    "Made wrong variant {val:?} for type {layout:?}",
600                );
601                OperandRef { val, layout, move_annotation: None }
602            }
603
604            mir::Rvalue::Discriminant(ref place) => {
605                let discr_ty = rvalue.ty(self.mir, bx.tcx());
606                let discr_ty = self.monomorphize(discr_ty);
607                let operand = self.codegen_consume(bx, place.as_ref());
608                let discr = operand.codegen_get_discr(self, bx, discr_ty);
609                OperandRef {
610                    val: OperandValue::Immediate(discr),
611                    layout: self.cx.layout_of(discr_ty),
612                    move_annotation: None,
613                }
614            }
615
616            mir::Rvalue::NullaryOp(ref null_op, ty) => {
617                let ty = self.monomorphize(ty);
618                let layout = bx.cx().layout_of(ty);
619                let val = match null_op {
620                    mir::NullOp::OffsetOf(fields) => {
621                        let val = bx
622                            .tcx()
623                            .offset_of_subfield(bx.typing_env(), layout, fields.iter())
624                            .bytes();
625                        bx.cx().const_usize(val)
626                    }
627                    mir::NullOp::RuntimeChecks(kind) => {
628                        let val = kind.value(bx.tcx().sess);
629                        bx.cx().const_bool(val)
630                    }
631                };
632                let tcx = self.cx.tcx();
633                OperandRef {
634                    val: OperandValue::Immediate(val),
635                    layout: self.cx.layout_of(null_op.ty(tcx)),
636                    move_annotation: None,
637                }
638            }
639
640            mir::Rvalue::ThreadLocalRef(def_id) => {
641                assert!(bx.cx().tcx().is_static(def_id));
642                let layout = bx.layout_of(bx.cx().tcx().static_ptr_ty(def_id, bx.typing_env()));
643                let static_ = if !def_id.is_local() && bx.cx().tcx().needs_thread_local_shim(def_id)
644                {
645                    let instance = ty::Instance {
646                        def: ty::InstanceKind::ThreadLocalShim(def_id),
647                        args: ty::GenericArgs::empty(),
648                    };
649                    let fn_ptr = bx.get_fn_addr(instance);
650                    let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty());
651                    let fn_ty = bx.fn_decl_backend_type(fn_abi);
652                    let fn_attrs = if bx.tcx().def_kind(instance.def_id()).has_codegen_attrs() {
653                        Some(bx.tcx().codegen_instance_attrs(instance.def))
654                    } else {
655                        None
656                    };
657                    bx.call(
658                        fn_ty,
659                        fn_attrs.as_deref(),
660                        Some(fn_abi),
661                        fn_ptr,
662                        &[],
663                        None,
664                        Some(instance),
665                    )
666                } else {
667                    bx.get_static(def_id)
668                };
669                OperandRef { val: OperandValue::Immediate(static_), layout, move_annotation: None }
670            }
671            mir::Rvalue::Use(ref operand) => self.codegen_operand(bx, operand),
672            mir::Rvalue::Repeat(ref elem, len_const) => {
673                // All arrays have `BackendRepr::Memory`, so only the ZST cases
674                // end up here. Anything else forces the destination local to be
675                // `Memory`, and thus ends up handled in `codegen_rvalue` instead.
676                let operand = self.codegen_operand(bx, elem);
677                let array_ty = Ty::new_array_with_const_len(bx.tcx(), operand.layout.ty, len_const);
678                let array_ty = self.monomorphize(array_ty);
679                let array_layout = bx.layout_of(array_ty);
680                assert!(array_layout.is_zst());
681                OperandRef {
682                    val: OperandValue::ZeroSized,
683                    layout: array_layout,
684                    move_annotation: None,
685                }
686            }
687            mir::Rvalue::Aggregate(ref kind, ref fields) => {
688                let (variant_index, active_field_index) = match **kind {
689                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
690                        (variant_index, active_field_index)
691                    }
692                    _ => (FIRST_VARIANT, None),
693                };
694
695                let ty = rvalue.ty(self.mir, self.cx.tcx());
696                let ty = self.monomorphize(ty);
697                let layout = self.cx.layout_of(ty);
698
699                let mut builder = OperandRefBuilder::new(layout);
700                for (field_idx, field) in fields.iter_enumerated() {
701                    let op = self.codegen_operand(bx, field);
702                    let fi = active_field_index.unwrap_or(field_idx);
703                    builder.insert_field(bx, variant_index, fi, op);
704                }
705
706                let tag_result = codegen_tag_value(self.cx, variant_index, layout);
707                match tag_result {
708                    Err(super::place::UninhabitedVariantError) => {
709                        // Like codegen_set_discr we use a sound abort, but could
710                        // potentially `unreachable` or just return the poison for
711                        // more optimizability, if that turns out to be helpful.
712                        bx.abort();
713                        let val = OperandValue::poison(bx, layout);
714                        OperandRef { val, layout, move_annotation: None }
715                    }
716                    Ok(maybe_tag_value) => {
717                        if let Some((tag_field, tag_imm)) = maybe_tag_value {
718                            builder.insert_imm(tag_field, tag_imm);
719                        }
720                        builder.build(bx.cx())
721                    }
722                }
723            }
724            mir::Rvalue::WrapUnsafeBinder(ref operand, binder_ty) => {
725                let operand = self.codegen_operand(bx, operand);
726                let binder_ty = self.monomorphize(binder_ty);
727                let layout = bx.cx().layout_of(binder_ty);
728                OperandRef { val: operand.val, layout, move_annotation: None }
729            }
730            mir::Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in codegen"),
731            mir::Rvalue::ShallowInitBox(..) => bug!("`ShallowInitBox` in codegen"),
732        }
733    }
734
735    /// Codegen an `Rvalue::RawPtr` or `Rvalue::Ref`
736    fn codegen_place_to_pointer(
737        &mut self,
738        bx: &mut Bx,
739        place: mir::Place<'tcx>,
740        mk_ptr_ty: impl FnOnce(TyCtxt<'tcx>, Ty<'tcx>) -> Ty<'tcx>,
741    ) -> OperandRef<'tcx, Bx::Value> {
742        let cg_place = self.codegen_place(bx, place.as_ref());
743        let val = cg_place.val.address();
744
745        let ty = cg_place.layout.ty;
746        assert!(
747            if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {
748                matches!(val, OperandValue::Pair(..))
749            } else {
750                matches!(val, OperandValue::Immediate(..))
751            },
752            "Address of place was unexpectedly {val:?} for pointee type {ty:?}",
753        );
754
755        OperandRef {
756            val,
757            layout: self.cx.layout_of(mk_ptr_ty(self.cx.tcx(), ty)),
758            move_annotation: None,
759        }
760    }
761
762    fn codegen_scalar_binop(
763        &mut self,
764        bx: &mut Bx,
765        op: mir::BinOp,
766        lhs: Bx::Value,
767        rhs: Bx::Value,
768        lhs_ty: Ty<'tcx>,
769        rhs_ty: Ty<'tcx>,
770    ) -> Bx::Value {
771        let is_float = lhs_ty.is_floating_point();
772        let is_signed = lhs_ty.is_signed();
773        match op {
774            mir::BinOp::Add => {
775                if is_float {
776                    bx.fadd(lhs, rhs)
777                } else {
778                    bx.add(lhs, rhs)
779                }
780            }
781            mir::BinOp::AddUnchecked => {
782                if is_signed {
783                    bx.unchecked_sadd(lhs, rhs)
784                } else {
785                    bx.unchecked_uadd(lhs, rhs)
786                }
787            }
788            mir::BinOp::Sub => {
789                if is_float {
790                    bx.fsub(lhs, rhs)
791                } else {
792                    bx.sub(lhs, rhs)
793                }
794            }
795            mir::BinOp::SubUnchecked => {
796                if is_signed {
797                    bx.unchecked_ssub(lhs, rhs)
798                } else {
799                    bx.unchecked_usub(lhs, rhs)
800                }
801            }
802            mir::BinOp::Mul => {
803                if is_float {
804                    bx.fmul(lhs, rhs)
805                } else {
806                    bx.mul(lhs, rhs)
807                }
808            }
809            mir::BinOp::MulUnchecked => {
810                if is_signed {
811                    bx.unchecked_smul(lhs, rhs)
812                } else {
813                    bx.unchecked_umul(lhs, rhs)
814                }
815            }
816            mir::BinOp::Div => {
817                if is_float {
818                    bx.fdiv(lhs, rhs)
819                } else if is_signed {
820                    bx.sdiv(lhs, rhs)
821                } else {
822                    bx.udiv(lhs, rhs)
823                }
824            }
825            mir::BinOp::Rem => {
826                if is_float {
827                    bx.frem(lhs, rhs)
828                } else if is_signed {
829                    bx.srem(lhs, rhs)
830                } else {
831                    bx.urem(lhs, rhs)
832                }
833            }
834            mir::BinOp::BitOr => bx.or(lhs, rhs),
835            mir::BinOp::BitAnd => bx.and(lhs, rhs),
836            mir::BinOp::BitXor => bx.xor(lhs, rhs),
837            mir::BinOp::Offset => {
838                let pointee_type = lhs_ty
839                    .builtin_deref(true)
840                    .unwrap_or_else(|| bug!("deref of non-pointer {:?}", lhs_ty));
841                let pointee_layout = bx.cx().layout_of(pointee_type);
842                if pointee_layout.is_zst() {
843                    // `Offset` works in terms of the size of pointee,
844                    // so offsetting a pointer to ZST is a noop.
845                    lhs
846                } else {
847                    let llty = bx.cx().backend_type(pointee_layout);
848                    if !rhs_ty.is_signed() {
849                        bx.inbounds_nuw_gep(llty, lhs, &[rhs])
850                    } else {
851                        bx.inbounds_gep(llty, lhs, &[rhs])
852                    }
853                }
854            }
855            mir::BinOp::Shl | mir::BinOp::ShlUnchecked => {
856                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShlUnchecked);
857                bx.shl(lhs, rhs)
858            }
859            mir::BinOp::Shr | mir::BinOp::ShrUnchecked => {
860                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShrUnchecked);
861                if is_signed { bx.ashr(lhs, rhs) } else { bx.lshr(lhs, rhs) }
862            }
863            mir::BinOp::Ne
864            | mir::BinOp::Lt
865            | mir::BinOp::Gt
866            | mir::BinOp::Eq
867            | mir::BinOp::Le
868            | mir::BinOp::Ge => {
869                if is_float {
870                    bx.fcmp(base::bin_op_to_fcmp_predicate(op), lhs, rhs)
871                } else {
872                    bx.icmp(base::bin_op_to_icmp_predicate(op, is_signed), lhs, rhs)
873                }
874            }
875            mir::BinOp::Cmp => {
876                assert!(!is_float);
877                bx.three_way_compare(lhs_ty, lhs, rhs)
878            }
879            mir::BinOp::AddWithOverflow
880            | mir::BinOp::SubWithOverflow
881            | mir::BinOp::MulWithOverflow => {
882                bug!("{op:?} needs to return a pair, so call codegen_scalar_checked_binop instead")
883            }
884        }
885    }
886
887    fn codegen_wide_ptr_binop(
888        &mut self,
889        bx: &mut Bx,
890        op: mir::BinOp,
891        lhs_addr: Bx::Value,
892        lhs_extra: Bx::Value,
893        rhs_addr: Bx::Value,
894        rhs_extra: Bx::Value,
895        _input_ty: Ty<'tcx>,
896    ) -> Bx::Value {
897        match op {
898            mir::BinOp::Eq => {
899                let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
900                let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
901                bx.and(lhs, rhs)
902            }
903            mir::BinOp::Ne => {
904                let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
905                let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
906                bx.or(lhs, rhs)
907            }
908            mir::BinOp::Le | mir::BinOp::Lt | mir::BinOp::Ge | mir::BinOp::Gt => {
909                // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
910                let (op, strict_op) = match op {
911                    mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
912                    mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
913                    mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
914                    mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
915                    _ => bug!(),
916                };
917                let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
918                let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
919                let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
920                let rhs = bx.and(and_lhs, and_rhs);
921                bx.or(lhs, rhs)
922            }
923            _ => {
924                bug!("unexpected wide ptr binop");
925            }
926        }
927    }
928
929    fn codegen_scalar_checked_binop(
930        &mut self,
931        bx: &mut Bx,
932        op: mir::BinOp,
933        lhs: Bx::Value,
934        rhs: Bx::Value,
935        input_ty: Ty<'tcx>,
936    ) -> OperandValue<Bx::Value> {
937        let (val, of) = match op {
938            // These are checked using intrinsics
939            mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
940                let oop = match op {
941                    mir::BinOp::Add => OverflowOp::Add,
942                    mir::BinOp::Sub => OverflowOp::Sub,
943                    mir::BinOp::Mul => OverflowOp::Mul,
944                    _ => unreachable!(),
945                };
946                bx.checked_binop(oop, input_ty, lhs, rhs)
947            }
948            _ => bug!("Operator `{:?}` is not a checkable operator", op),
949        };
950
951        OperandValue::Pair(val, of)
952    }
953}
954
955/// Transmutes a single scalar value `imm` from `from_scalar` to `to_scalar`.
956///
957/// This is expected to be in *immediate* form, as seen in [`OperandValue::Immediate`]
958/// or [`OperandValue::Pair`] (so `i1` for bools, not `i8`, for example).
959///
960/// ICEs if the passed-in `imm` is not a value of the expected type for
961/// `from_scalar`, such as if it's a vector or a pair.
962pub(super) fn transmute_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
963    bx: &mut Bx,
964    mut imm: Bx::Value,
965    from_scalar: abi::Scalar,
966    to_scalar: abi::Scalar,
967) -> Bx::Value {
968    assert_eq!(from_scalar.size(bx.cx()), to_scalar.size(bx.cx()));
969    let imm_ty = bx.cx().val_ty(imm);
970    assert_ne!(
971        bx.cx().type_kind(imm_ty),
972        TypeKind::Vector,
973        "Vector type {imm_ty:?} not allowed in transmute_scalar {from_scalar:?} -> {to_scalar:?}"
974    );
975
976    // While optimizations will remove no-op transmutes, they might still be
977    // there in debug or things that aren't no-op in MIR because they change
978    // the Rust type but not the underlying layout/niche.
979    if from_scalar == to_scalar {
980        return imm;
981    }
982
983    use abi::Primitive::*;
984    imm = bx.from_immediate(imm);
985
986    let from_backend_ty = bx.cx().type_from_scalar(from_scalar);
987    debug_assert_eq!(bx.cx().val_ty(imm), from_backend_ty);
988    let to_backend_ty = bx.cx().type_from_scalar(to_scalar);
989
990    // If we have a scalar, we must already know its range. Either
991    //
992    // 1) It's a parameter with `range` parameter metadata,
993    // 2) It's something we `load`ed with `!range` metadata, or
994    // 3) After a transmute we `assume`d the range (see below).
995    //
996    // That said, last time we tried removing this, it didn't actually help
997    // the rustc-perf results, so might as well keep doing it
998    // <https://github.com/rust-lang/rust/pull/135610#issuecomment-2599275182>
999    assume_scalar_range(bx, imm, from_scalar, from_backend_ty, Some(&to_scalar));
1000
1001    imm = match (from_scalar.primitive(), to_scalar.primitive()) {
1002        (Int(..) | Float(_), Int(..) | Float(_)) => bx.bitcast(imm, to_backend_ty),
1003        (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
1004        (Int(..), Pointer(..)) => bx.inttoptr(imm, to_backend_ty),
1005        (Pointer(..), Int(..)) => {
1006            // FIXME: this exposes the provenance, which shouldn't be necessary.
1007            bx.ptrtoint(imm, to_backend_ty)
1008        }
1009        (Float(_), Pointer(..)) => {
1010            let int_imm = bx.bitcast(imm, bx.cx().type_isize());
1011            bx.inttoptr(int_imm, to_backend_ty)
1012        }
1013        (Pointer(..), Float(_)) => {
1014            // FIXME: this exposes the provenance, which shouldn't be necessary.
1015            let int_imm = bx.ptrtoint(imm, bx.cx().type_isize());
1016            bx.bitcast(int_imm, to_backend_ty)
1017        }
1018    };
1019
1020    debug_assert_eq!(bx.cx().val_ty(imm), to_backend_ty);
1021
1022    // This `assume` remains important for cases like (a conceptual)
1023    //    transmute::<u32, NonZeroU32>(x) == 0
1024    // since it's never passed to something with parameter metadata (especially
1025    // after MIR inlining) so the only way to tell the backend about the
1026    // constraint that the `transmute` introduced is to `assume` it.
1027    assume_scalar_range(bx, imm, to_scalar, to_backend_ty, Some(&from_scalar));
1028
1029    imm = bx.to_immediate_scalar(imm, to_scalar);
1030    imm
1031}
1032
1033/// Emits an `assume` call that `imm`'s value is within the known range of `scalar`.
1034///
1035/// If `known` is `Some`, only emits the assume if it's more specific than
1036/// whatever is already known from the range of *that* scalar.
1037fn assume_scalar_range<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1038    bx: &mut Bx,
1039    imm: Bx::Value,
1040    scalar: abi::Scalar,
1041    backend_ty: Bx::Type,
1042    known: Option<&abi::Scalar>,
1043) {
1044    if matches!(bx.cx().sess().opts.optimize, OptLevel::No) {
1045        return;
1046    }
1047
1048    match (scalar, known) {
1049        (abi::Scalar::Union { .. }, _) => return,
1050        (_, None) => {
1051            if scalar.is_always_valid(bx.cx()) {
1052                return;
1053            }
1054        }
1055        (abi::Scalar::Initialized { valid_range, .. }, Some(known)) => {
1056            let known_range = known.valid_range(bx.cx());
1057            if valid_range.contains_range(known_range, scalar.size(bx.cx())) {
1058                return;
1059            }
1060        }
1061    }
1062
1063    match scalar.primitive() {
1064        abi::Primitive::Int(..) => {
1065            let range = scalar.valid_range(bx.cx());
1066            bx.assume_integer_range(imm, backend_ty, range);
1067        }
1068        abi::Primitive::Pointer(abi::AddressSpace::ZERO)
1069            if !scalar.valid_range(bx.cx()).contains(0) =>
1070        {
1071            bx.assume_nonnull(imm);
1072        }
1073        abi::Primitive::Pointer(..) | abi::Primitive::Float(..) => {}
1074    }
1075}