Skip to main content

rustc_codegen_ssa/mir/
rvalue.rs

1use itertools::Itertools as _;
2use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT};
3use rustc_index::IndexVec;
4use rustc_middle::ty::adjustment::PointerCoercion;
5use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
6use rustc_middle::ty::{self, Instance, Mutability, Ty, TyCtxt};
7use rustc_middle::{bug, mir, span_bug};
8use rustc_session::config::OptLevel;
9use tracing::{debug, instrument};
10
11use super::FunctionCx;
12use super::operand::{OperandRef, OperandRefBuilder, OperandValue};
13use super::place::{PlaceRef, PlaceValue, codegen_tag_value};
14use crate::common::{IntPredicate, TypeKind};
15use crate::traits::*;
16use crate::{MemFlags, base};
17
18impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
19    fn try_codegen_const_aggregate_as_immediate(
20        &mut self,
21        bx: &mut Bx,
22        dest: PlaceRef<'tcx, Bx::Value>,
23        kind: &mir::AggregateKind<'tcx>,
24        operands: &IndexVec<abi::FieldIdx, mir::Operand<'tcx>>,
25    ) -> bool {
26        // Keep this allowlist limited to aggregate kinds with direct codegen coverage.
27        // Extract the variant index at the same time so we can verify it against
28        // the layout below. Tuples always use `FIRST_VARIANT` (index 0); the
29        // `None` in the `Adt` arm excludes unions (which carry an active field).
30        let variant_index = match kind {
31            mir::AggregateKind::Tuple => FIRST_VARIANT,
32            mir::AggregateKind::Adt(_, variant_index, _, _, None) => *variant_index,
33            _ => return false,
34        };
35        if !#[allow(non_exhaustive_omitted_patterns)] match dest.layout.fields {
    abi::FieldsShape::Arbitrary { .. } => true,
    _ => false,
}matches!(dest.layout.fields, abi::FieldsShape::Arbitrary { .. }) {
36            return false;
37        }
38        // `dest.layout` is the layout of the *overall* type, not a specific
39        // variant. When the layout is `Variants::Single { index: M }`, the
40        // field offsets and counts below all refer to variant M. If the MIR
41        // aggregate is constructing a different variant N (e.g. because N is
42        // uninhabited and the layout collapsed to M), using `dest.layout`
43        // directly would read the wrong field metadata. Bail out and let the
44        // normal codegen path handle it via `project_downcast`.
45        if !#[allow(non_exhaustive_omitted_patterns)] match dest.layout.variants {
    abi::Variants::Single { index } if index == variant_index => true,
    _ => false,
}matches!(dest.layout.variants, abi::Variants::Single { index } if index == variant_index)
46        {
47            return false;
48        }
49        // Now that the variant indices are known to match, the operand count
50        // and the layout field count must agree.
51        if true {
    {
        match (&operands.len(), &dest.layout.fields.count()) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(operands.len(), dest.layout.fields.count());
52
53        let size = dest.layout.size.bytes();
54        let llty = match size {
55            1 => bx.cx().type_i8(),
56            2 => bx.cx().type_i16(),
57            4 => bx.cx().type_i32(),
58            8 => bx.cx().type_i64(),
59            16 => bx.cx().type_i128(),
60            _ => return false,
61        };
62
63        let mut value = 0u128;
64        for (field_idx, operand) in operands.iter_enumerated() {
65            let field_layout = dest.layout.field(bx.cx(), field_idx.as_usize());
66            if field_layout.is_zst() {
67                continue;
68            }
69            let mir::Operand::Constant(constant) = operand else {
70                return false;
71            };
72            let Some(field_value) = self.eval_mir_constant(constant).try_to_bits(field_layout.size)
73            else {
74                return false;
75            };
76
77            let field_size = field_layout.size.bytes();
78            let field_offset = dest.layout.fields.offset(field_idx.as_usize()).bytes();
79            if true {
    if !(field_offset + field_size <= size) {
        ::core::panicking::panic("assertion failed: field_offset + field_size <= size")
    };
};debug_assert!(field_offset + field_size <= size);
80            let shift = match bx.tcx().data_layout.endian {
81                abi::Endian::Little => field_offset * 8,
82                abi::Endian::Big => (size - field_offset - field_size) * 8,
83            };
84            value |= field_value << shift;
85        }
86
87        let value = bx.cx().const_uint_big(llty, value);
88        bx.store_to_place(value, dest.val);
89        true
90    }
91
92    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("codegen_rvalue",
                                    "rustc_codegen_ssa::mir::rvalue", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
                                    ::tracing_core::__macro_support::Option::Some(92u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
                                    ::tracing_core::field::FieldSet::new(&["dest", "rvalue"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dest)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rvalue)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match *rvalue {
                mir::Rvalue::Use(ref operand, with_retag) => {
                    if let mir::Operand::Constant(const_op) = operand {
                        let val = self.eval_mir_constant(&const_op);
                        if val.all_bytes_uninit(self.cx.tcx()) { return; }
                    }
                    let cg_operand = self.codegen_operand(bx, operand);
                    if #[allow(non_exhaustive_omitted_patterns)] match cg_operand.layout.backend_repr
                            {
                            BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. } =>
                                true,
                            _ => false,
                        } {
                        if true {
                            if !!#[allow(non_exhaustive_omitted_patterns)] match cg_operand.val
                                            {
                                            OperandValue::Ref(..) => true,
                                            _ => false,
                                        } {
                                ::core::panicking::panic("assertion failed: !matches!(cg_operand.val, OperandValue::Ref(..))")
                            };
                        };
                    }
                    let flags =
                        if let ty::Ref(_, pointee_ty, Mutability::Not) =
                                        cg_operand.layout.ty.kind() && with_retag.yes() &&
                                pointee_ty.is_freeze(self.cx.tcx(), self.cx.typing_env()) {
                            MemFlags::CAPTURES_READ_ONLY
                        } else { MemFlags::empty() };
                    cg_operand.store_with_annotation_and_flags(bx, dest, flags);
                }
                mir::Rvalue::Cast(mir::CastKind::PointerCoercion(PointerCoercion::Unsize,
                    _), ref source, _) => {
                    if bx.cx().is_backend_scalar_pair(dest.layout) {
                        let temp = self.codegen_rvalue_operand(bx, rvalue);
                        temp.store_with_annotation(bx, dest);
                        return;
                    }
                    let operand = self.codegen_operand(bx, source);
                    match operand.val {
                        OperandValue::Pair(..) | OperandValue::Immediate(_) => {
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/rvalue.rs:161",
                                                    "rustc_codegen_ssa::mir::rvalue", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(161u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
                                                    ::tracing_core::field::FieldSet::new(&["message"],
                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::EVENT)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let enabled =
                                    ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                            ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::LevelFilter::current() &&
                                        {
                                            let interest = __CALLSITE.interest();
                                            !interest.is_never() &&
                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                    interest)
                                        };
                                if enabled {
                                    (|value_set: ::tracing::field::ValueSet|
                                                {
                                                    let meta = __CALLSITE.metadata();
                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                    ;
                                                })({
                                            #[allow(unused_imports)]
                                            use ::tracing::field::{debug, display, Value};
                                            let mut iter = __CALLSITE.metadata().fields().iter();
                                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                ::tracing::__macro_support::Option::Some(&format_args!("codegen_rvalue: creating ugly alloca")
                                                                        as &dyn Value))])
                                        });
                                } else { ; }
                            };
                            let scratch = PlaceRef::alloca(bx, operand.layout);
                            scratch.storage_live(bx);
                            operand.store_with_annotation(bx, scratch);
                            base::coerce_unsized_into(bx, scratch, dest);
                            scratch.storage_dead(bx);
                        }
                        OperandValue::Ref(val) => {
                            if val.llextra.is_some() {
                                ::rustc_middle::util::bug::bug_fmt(format_args!("unsized coercion on an unsized rvalue"));
                            }
                            base::coerce_unsized_into(bx, val.with_type(operand.layout),
                                dest);
                        }
                        OperandValue::ZeroSized => {
                            ::rustc_middle::util::bug::bug_fmt(format_args!("unsized coercion on a ZST rvalue"));
                        }
                    }
                }
                mir::Rvalue::Cast(mir::CastKind::Transmute |
                    mir::CastKind::Subtype, ref operand, _ty) => {
                    let src = self.codegen_operand(bx, operand);
                    self.codegen_transmute(bx, src, dest);
                }
                mir::Rvalue::Repeat(ref elem, count) => {
                    if dest.layout.is_zst() { return; }
                    if let mir::Operand::Constant(const_op) = elem {
                        let val = self.eval_mir_constant(const_op);
                        if val.all_bytes_uninit(self.cx.tcx()) {
                            let size = bx.const_usize(dest.layout.size.bytes());
                            bx.memset(dest.val.llval, bx.const_undef(bx.type_i8()),
                                size, dest.val.align, MemFlags::empty());
                            return;
                        }
                    }
                    let cg_elem = self.codegen_operand(bx, elem);
                    let try_init_all_same =
                        |bx: &mut Bx, v|
                            {
                                let start = dest.val.llval;
                                let size = bx.const_usize(dest.layout.size.bytes());
                                if let Some(int) = bx.cx().const_to_opt_u128(v, false) &&
                                            let bytes =
                                                &int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()] &&
                                        let Ok(&byte) = bytes.iter().all_equal_value() {
                                    let fill = bx.cx().const_u8(byte);
                                    bx.memset(start, fill, size, dest.val.align,
                                        MemFlags::empty());
                                    return true;
                                }
                                let v = bx.from_immediate(v);
                                if bx.cx().val_ty(v) == bx.cx().type_i8() {
                                    bx.memset(start, v, size, dest.val.align,
                                        MemFlags::empty());
                                    return true;
                                }
                                false
                            };
                    if let OperandValue::Immediate(v) = cg_elem.val &&
                            try_init_all_same(bx, v) {
                        return;
                    }
                    let count =
                        self.monomorphize(count).try_to_target_usize(bx.tcx()).expect("expected monomorphic const in codegen");
                    bx.write_operand_repeatedly(cg_elem, count, dest);
                }
                mir::Rvalue::Aggregate(ref kind, ref operands) if
                    !#[allow(non_exhaustive_omitted_patterns)] match **kind {
                            mir::AggregateKind::RawPtr(..) => true,
                            _ => false,
                        } => {
                    if self.try_codegen_const_aggregate_as_immediate(bx, dest,
                            kind, operands) {
                        return;
                    }
                    let (variant_index, variant_dest, active_field_index) =
                        match **kind {
                            mir::AggregateKind::Adt(_, variant_index, _, _,
                                active_field_index) => {
                                let variant_dest = dest.project_downcast(bx, variant_index);
                                (variant_index, variant_dest, active_field_index)
                            }
                            _ => (FIRST_VARIANT, dest, None),
                        };
                    if active_field_index.is_some() {
                        {
                            match (&operands.len(), &1) {
                                (left_val, right_val) => {
                                    if !(*left_val == *right_val) {
                                        let kind = ::core::panicking::AssertKind::Eq;
                                        ::core::panicking::assert_failed(kind, &*left_val,
                                            &*right_val, ::core::option::Option::None);
                                    }
                                }
                            }
                        };
                    }
                    for (i, operand) in operands.iter_enumerated() {
                        let op = self.codegen_operand(bx, operand);
                        if !op.layout.is_zst() {
                            let field_index = active_field_index.unwrap_or(i);
                            let field =
                                if let mir::AggregateKind::Array(_) = **kind {
                                    let llindex =
                                        bx.cx().const_usize(field_index.as_u32().into());
                                    variant_dest.project_index(bx, llindex)
                                } else {
                                    variant_dest.project_field(bx, field_index.as_usize())
                                };
                            op.store_with_annotation(bx, field);
                        }
                    }
                    dest.codegen_set_discr(bx, variant_index);
                }
                _ => {
                    let temp = self.codegen_rvalue_operand(bx, rvalue);
                    temp.store_with_annotation(bx, dest);
                }
            }
        }
    }
}#[instrument(level = "trace", skip(self, bx))]
93    pub(crate) fn codegen_rvalue(
94        &mut self,
95        bx: &mut Bx,
96        dest: PlaceRef<'tcx, Bx::Value>,
97        rvalue: &mir::Rvalue<'tcx>,
98    ) {
99        match *rvalue {
100            mir::Rvalue::Use(ref operand, with_retag) => {
101                if let mir::Operand::Constant(const_op) = operand {
102                    let val = self.eval_mir_constant(&const_op);
103                    if val.all_bytes_uninit(self.cx.tcx()) {
104                        return;
105                    }
106                }
107                let cg_operand = self.codegen_operand(bx, operand);
108                // Crucially, we do *not* use `OperandValue::Ref` for types with
109                // `BackendRepr::Scalar | BackendRepr::ScalarPair`. This ensures we match the MIR
110                // semantics regarding when assignment operators allow overlap of LHS and RHS.
111                if matches!(
112                    cg_operand.layout.backend_repr,
113                    BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. },
114                ) {
115                    debug_assert!(!matches!(cg_operand.val, OperandValue::Ref(..)));
116                }
117                // If this is storing a &Freeze reference with a retag, record that it's not
118                // possible to perform writes through the stored pointer.
119                let flags = if let ty::Ref(_, pointee_ty, Mutability::Not) =
120                    cg_operand.layout.ty.kind()
121                    && with_retag.yes()
122                    && pointee_ty.is_freeze(self.cx.tcx(), self.cx.typing_env())
123                {
124                    MemFlags::CAPTURES_READ_ONLY
125                } else {
126                    MemFlags::empty()
127                };
128                // FIXME: consider not copying constants through stack. (Fixable by codegen'ing
129                // constants into `OperandValue::Ref`; why don’t we do that yet if we don’t?)
130                cg_operand.store_with_annotation_and_flags(bx, dest, flags);
131            }
132
133            mir::Rvalue::Cast(
134                mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
135                ref source,
136                _,
137            ) => {
138                // The destination necessarily contains a wide pointer, so if
139                // it's a scalar pair, it's a wide pointer or newtype thereof.
140                if bx.cx().is_backend_scalar_pair(dest.layout) {
141                    // Into-coerce of a thin pointer to a wide pointer -- just
142                    // use the operand path.
143                    let temp = self.codegen_rvalue_operand(bx, rvalue);
144                    temp.store_with_annotation(bx, dest);
145                    return;
146                }
147
148                // Unsize of a nontrivial struct. I would prefer for
149                // this to be eliminated by MIR building, but
150                // `CoerceUnsized` can be passed by a where-clause,
151                // so the (generic) MIR may not be able to expand it.
152                let operand = self.codegen_operand(bx, source);
153                match operand.val {
154                    OperandValue::Pair(..) | OperandValue::Immediate(_) => {
155                        // Unsize from an immediate structure. We don't
156                        // really need a temporary alloca here, but
157                        // avoiding it would require us to have
158                        // `coerce_unsized_into` use `extractvalue` to
159                        // index into the struct, and this case isn't
160                        // important enough for it.
161                        debug!("codegen_rvalue: creating ugly alloca");
162                        let scratch = PlaceRef::alloca(bx, operand.layout);
163                        scratch.storage_live(bx);
164                        operand.store_with_annotation(bx, scratch);
165                        base::coerce_unsized_into(bx, scratch, dest);
166                        scratch.storage_dead(bx);
167                    }
168                    OperandValue::Ref(val) => {
169                        if val.llextra.is_some() {
170                            bug!("unsized coercion on an unsized rvalue");
171                        }
172                        base::coerce_unsized_into(bx, val.with_type(operand.layout), dest);
173                    }
174                    OperandValue::ZeroSized => {
175                        bug!("unsized coercion on a ZST rvalue");
176                    }
177                }
178            }
179
180            mir::Rvalue::Cast(
181                mir::CastKind::Transmute | mir::CastKind::Subtype,
182                ref operand,
183                _ty,
184            ) => {
185                let src = self.codegen_operand(bx, operand);
186                self.codegen_transmute(bx, src, dest);
187            }
188
189            mir::Rvalue::Repeat(ref elem, count) => {
190                // Do not generate the loop for zero-sized elements or empty arrays.
191                if dest.layout.is_zst() {
192                    return;
193                }
194
195                // When the element is a const with all bytes uninit, emit a single memset that
196                // writes undef to the entire destination.
197                if let mir::Operand::Constant(const_op) = elem {
198                    let val = self.eval_mir_constant(const_op);
199                    if val.all_bytes_uninit(self.cx.tcx()) {
200                        let size = bx.const_usize(dest.layout.size.bytes());
201                        bx.memset(
202                            dest.val.llval,
203                            bx.const_undef(bx.type_i8()),
204                            size,
205                            dest.val.align,
206                            MemFlags::empty(),
207                        );
208                        return;
209                    }
210                }
211
212                let cg_elem = self.codegen_operand(bx, elem);
213
214                let try_init_all_same = |bx: &mut Bx, v| {
215                    let start = dest.val.llval;
216                    let size = bx.const_usize(dest.layout.size.bytes());
217
218                    // Use llvm.memset.p0i8.* to initialize all same byte arrays
219                    if let Some(int) = bx.cx().const_to_opt_u128(v, false)
220                        && let bytes = &int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()]
221                        && let Ok(&byte) = bytes.iter().all_equal_value()
222                    {
223                        let fill = bx.cx().const_u8(byte);
224                        bx.memset(start, fill, size, dest.val.align, MemFlags::empty());
225                        return true;
226                    }
227
228                    // Use llvm.memset.p0i8.* to initialize byte arrays
229                    let v = bx.from_immediate(v);
230                    if bx.cx().val_ty(v) == bx.cx().type_i8() {
231                        bx.memset(start, v, size, dest.val.align, MemFlags::empty());
232                        return true;
233                    }
234                    false
235                };
236
237                if let OperandValue::Immediate(v) = cg_elem.val
238                    && try_init_all_same(bx, v)
239                {
240                    return;
241                }
242
243                let count = self
244                    .monomorphize(count)
245                    .try_to_target_usize(bx.tcx())
246                    .expect("expected monomorphic const in codegen");
247
248                bx.write_operand_repeatedly(cg_elem, count, dest);
249            }
250
251            // This implementation does field projection, so never use it for `RawPtr`,
252            // which will always be fine with the `codegen_rvalue_operand` path below.
253            mir::Rvalue::Aggregate(ref kind, ref operands)
254                if !matches!(**kind, mir::AggregateKind::RawPtr(..)) =>
255            {
256                if self.try_codegen_const_aggregate_as_immediate(bx, dest, kind, operands) {
257                    return;
258                }
259
260                let (variant_index, variant_dest, active_field_index) = match **kind {
261                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
262                        let variant_dest = dest.project_downcast(bx, variant_index);
263                        (variant_index, variant_dest, active_field_index)
264                    }
265                    _ => (FIRST_VARIANT, dest, None),
266                };
267                if active_field_index.is_some() {
268                    assert_eq!(operands.len(), 1);
269                }
270                for (i, operand) in operands.iter_enumerated() {
271                    let op = self.codegen_operand(bx, operand);
272                    // Do not generate stores and GEPis for zero-sized fields.
273                    if !op.layout.is_zst() {
274                        let field_index = active_field_index.unwrap_or(i);
275                        let field = if let mir::AggregateKind::Array(_) = **kind {
276                            let llindex = bx.cx().const_usize(field_index.as_u32().into());
277                            variant_dest.project_index(bx, llindex)
278                        } else {
279                            variant_dest.project_field(bx, field_index.as_usize())
280                        };
281                        op.store_with_annotation(bx, field);
282                    }
283                }
284                dest.codegen_set_discr(bx, variant_index);
285            }
286
287            _ => {
288                let temp = self.codegen_rvalue_operand(bx, rvalue);
289                temp.store_with_annotation(bx, dest);
290            }
291        }
292    }
293
294    /// Transmutes the `src` value to the destination type by writing it to `dst`.
295    ///
296    /// See also [`Self::codegen_transmute_operand`] for cases that can be done
297    /// without needing a pre-allocated place for the destination.
298    fn codegen_transmute(
299        &mut self,
300        bx: &mut Bx,
301        src: OperandRef<'tcx, Bx::Value>,
302        dst: PlaceRef<'tcx, Bx::Value>,
303    ) {
304        // The MIR validator enforces no unsized transmutes.
305        if !src.layout.is_sized() {
    ::core::panicking::panic("assertion failed: src.layout.is_sized()")
};assert!(src.layout.is_sized());
306        if !dst.layout.is_sized() {
    ::core::panicking::panic("assertion failed: dst.layout.is_sized()")
};assert!(dst.layout.is_sized());
307
308        if src.layout.size != dst.layout.size
309            || src.layout.is_uninhabited()
310            || dst.layout.is_uninhabited()
311        {
312            // These cases are all UB to actually hit, so don't emit code for them.
313            // (The size mismatches are reachable via `transmute_unchecked`.)
314            bx.unreachable_nonterminator();
315        } else {
316            // Since in this path we have a place anyway, we can store or copy to it,
317            // making sure we use the destination place's alignment even if the
318            // source would normally have a higher one.
319            src.store_with_annotation(bx, dst.val.with_type(src.layout));
320        }
321    }
322
323    /// Transmutes an `OperandValue` to another `OperandValue`.
324    ///
325    /// This is supported for all cases where the `cast` type is SSA,
326    /// but for non-ZSTs with [`abi::BackendRepr::Memory`] it ICEs.
327    pub(crate) fn codegen_transmute_operand(
328        &mut self,
329        bx: &mut Bx,
330        operand: OperandRef<'tcx, Bx::Value>,
331        cast: TyAndLayout<'tcx>,
332    ) -> OperandValue<Bx::Value> {
333        if let abi::BackendRepr::Memory { .. } = cast.backend_repr
334            && !cast.is_zst()
335        {
336            ::rustc_middle::util::bug::span_bug_fmt(self.mir.span,
    format_args!("Use `codegen_transmute` to transmute to {0:?}", cast));span_bug!(self.mir.span, "Use `codegen_transmute` to transmute to {cast:?}");
337        }
338
339        // `Layout` is interned, so we can do a cheap check for things that are
340        // exactly the same and thus don't need any handling.
341        if abi::Layout::eq(&operand.layout.layout, &cast.layout) {
342            return operand.val;
343        }
344
345        // Check for transmutes that are always UB.
346        if operand.layout.size != cast.size
347            || operand.layout.is_uninhabited()
348            || cast.is_uninhabited()
349        {
350            bx.unreachable_nonterminator();
351
352            // We still need to return a value of the appropriate type, but
353            // it's already UB so do the easiest thing available.
354            return OperandValue::poison(bx, cast);
355        }
356
357        // To or from pointers takes different methods, so we use this to restrict
358        // the SimdVector case to types which can be `bitcast` between each other.
359        #[inline]
360        fn vector_can_bitcast(x: abi::Scalar) -> bool {
361            #[allow(non_exhaustive_omitted_patterns)] match x {
    abi::Scalar::Initialized {
        value: abi::Primitive::Int(..) | abi::Primitive::Float(..), .. } =>
        true,
    _ => false,
}matches!(
362                x,
363                abi::Scalar::Initialized {
364                    value: abi::Primitive::Int(..) | abi::Primitive::Float(..),
365                    ..
366                }
367            )
368        }
369
370        let cx = bx.cx();
371        match (operand.val, operand.layout.backend_repr, cast.backend_repr) {
372            _ if cast.is_zst() => OperandValue::ZeroSized,
373            (OperandValue::Ref(source_place_val), abi::BackendRepr::Memory { .. }, _) => {
374                {
    match (&source_place_val.llextra, &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(source_place_val.llextra, None);
375                // The existing alignment is part of `source_place_val`,
376                // so that alignment will be used, not `cast`'s.
377                bx.load_operand(source_place_val.with_type(cast)).val
378            }
379            (
380                OperandValue::Immediate(imm),
381                abi::BackendRepr::Scalar(from_scalar),
382                abi::BackendRepr::Scalar(to_scalar),
383            ) if from_scalar.size(cx) == to_scalar.size(cx) => {
384                OperandValue::Immediate(transmute_scalar(bx, imm, from_scalar, to_scalar))
385            }
386            (
387                OperandValue::Immediate(imm),
388                abi::BackendRepr::SimdVector { element: from_scalar, .. },
389                abi::BackendRepr::SimdVector { element: to_scalar, .. },
390            ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
391                let to_backend_ty = bx.cx().immediate_backend_type(cast);
392                OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
393            }
394            (
395                OperandValue::Immediate(imm),
396                abi::BackendRepr::SimdScalableVector { element: from_scalar, .. },
397                abi::BackendRepr::SimdScalableVector { element: to_scalar, .. },
398            ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
399                let to_backend_ty = bx.cx().immediate_backend_type(cast);
400                OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
401            }
402            (
403                OperandValue::Pair(imm_a, imm_b),
404                abi::BackendRepr::ScalarPair { a: in_a, b: in_b, b_offset: in_offset },
405                abi::BackendRepr::ScalarPair { a: out_a, b: out_b, b_offset: out_offset },
406            ) if in_a.size(cx) == out_a.size(cx)
407                && in_b.size(cx) == out_b.size(cx)
408                && in_offset == out_offset =>
409            {
410                OperandValue::Pair(
411                    transmute_scalar(bx, imm_a, in_a, out_a),
412                    transmute_scalar(bx, imm_b, in_b, out_b),
413                )
414            }
415            _ => {
416                // For any other potentially-tricky cases, make a temporary instead.
417                // If anything else wants the target local to be in memory this won't
418                // be hit, as `codegen_transmute` will get called directly. Thus this
419                // is only for places where everything else wants the operand form,
420                // and thus it's not worth making those places get it from memory.
421                //
422                // Notably, Scalar ⇌ ScalarPair cases go here to avoid padding
423                // and endianness issues, as do SimdVector ones to avoid worrying
424                // about things like f32x8 ⇌ ptrx4 that would need multiple steps.
425                let align = Ord::max(operand.layout.align.abi, cast.align.abi);
426                let size = Ord::max(operand.layout.size, cast.size);
427                let temp = PlaceValue::alloca(bx, size, align);
428                bx.lifetime_start(temp.llval, size);
429                operand.store_with_annotation(bx, temp.with_type(operand.layout));
430                let val = bx.load_operand(temp.with_type(cast)).val;
431                bx.lifetime_end(temp.llval, size);
432                val
433            }
434        }
435    }
436
437    /// Cast one of the immediates from an [`OperandValue::Immediate`]
438    /// or an [`OperandValue::Pair`] to an immediate of the target type.
439    ///
440    /// Returns `None` if the cast is not possible.
441    fn cast_immediate(
442        &self,
443        bx: &mut Bx,
444        mut imm: Bx::Value,
445        from_scalar: abi::Scalar,
446        from_backend_ty: Bx::Type,
447        to_scalar: abi::Scalar,
448        to_backend_ty: Bx::Type,
449    ) -> Option<Bx::Value> {
450        use abi::Primitive::*;
451
452        // When scalars are passed by value, there's no metadata recording their
453        // valid ranges. For example, `char`s are passed as just `i32`, with no
454        // way for LLVM to know that they're 0x10FFFF at most. Thus we assume
455        // the range of the input value too, not just the output range.
456        assume_scalar_range(bx, imm, from_scalar, from_backend_ty, None);
457
458        imm = match (from_scalar.primitive(), to_scalar.primitive()) {
459            (Int(_, is_signed), Int(..)) => bx.intcast(imm, to_backend_ty, is_signed),
460            (Float(_), Float(_)) => {
461                let srcsz = bx.cx().float_width(from_backend_ty);
462                let dstsz = bx.cx().float_width(to_backend_ty);
463                if dstsz > srcsz {
464                    bx.fpext(imm, to_backend_ty)
465                } else if srcsz > dstsz {
466                    bx.fptrunc(imm, to_backend_ty)
467                } else {
468                    imm
469                }
470            }
471            (Int(_, is_signed), Float(_)) => {
472                if is_signed {
473                    bx.sitofp(imm, to_backend_ty)
474                } else {
475                    bx.uitofp(imm, to_backend_ty)
476                }
477            }
478            (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
479            (Int(_, is_signed), Pointer(..)) => {
480                let usize_imm = bx.intcast(imm, bx.cx().type_isize(), is_signed);
481                bx.inttoptr(usize_imm, to_backend_ty)
482            }
483            (Float(_), Int(_, is_signed)) => bx.cast_float_to_int(is_signed, imm, to_backend_ty),
484            _ => return None,
485        };
486        Some(imm)
487    }
488
489    pub(crate) fn codegen_rvalue_operand(
490        &mut self,
491        bx: &mut Bx,
492        rvalue: &mir::Rvalue<'tcx>,
493    ) -> OperandRef<'tcx, Bx::Value> {
494        match *rvalue {
495            mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
496                let operand = self.codegen_operand(bx, source);
497                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/rvalue.rs:497",
                        "rustc_codegen_ssa::mir::rvalue", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
                        ::tracing_core::__macro_support::Option::Some(497u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("cast operand is {0:?}",
                                                    operand) as &dyn Value))])
            });
    } else { ; }
};debug!("cast operand is {:?}", operand);
498                let cast = bx.cx().layout_of(self.monomorphize(mir_cast_ty));
499
500                let val = match *kind {
501                    mir::CastKind::PointerExposeProvenance => {
502                        if !bx.cx().is_backend_immediate(cast) {
    ::core::panicking::panic("assertion failed: bx.cx().is_backend_immediate(cast)")
};assert!(bx.cx().is_backend_immediate(cast));
503                        let llptr = operand.immediate();
504                        let llcast_ty = bx.cx().immediate_backend_type(cast);
505                        let lladdr = bx.ptrtoint(llptr, llcast_ty);
506                        OperandValue::Immediate(lladdr)
507                    }
508                    mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _) => {
509                        match *operand.layout.ty.kind() {
510                            ty::FnDef(def_id, args) => {
511                                let instance = ty::Instance::resolve_for_fn_ptr(
512                                    bx.tcx(),
513                                    bx.typing_env(),
514                                    def_id,
515                                    args,
516                                )
517                                .unwrap();
518                                OperandValue::Immediate(
519                                    bx.get_fn_addr(
520                                        instance,
521                                        Some(PacMetadata::default()),
522                                    ),
523                                )
524                            }
525                            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} cannot be reified to a fn ptr",
        operand.layout.ty))bug!("{} cannot be reified to a fn ptr", operand.layout.ty),
526                        }
527                    }
528                    mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => {
529                        match *operand.layout.ty.kind() {
530                            ty::Closure(def_id, args) => {
531                                let instance = Instance::resolve_closure(
532                                    bx.cx().tcx(),
533                                    def_id,
534                                    args,
535                                    ty::ClosureKind::FnOnce,
536                                );
537                                OperandValue::Immediate(
538                                    bx.cx().get_fn_addr(
539                                        instance,
540                                        Some(PacMetadata::default()),
541                                    ),
542                                )
543                            }
544                            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} cannot be cast to a fn ptr",
        operand.layout.ty))bug!("{} cannot be cast to a fn ptr", operand.layout.ty),
545                        }
546                    }
547                    mir::CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
548                        // This is a no-op at the LLVM level.
549                        operand.val
550                    }
551                    mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
552                        if !bx.cx().is_backend_scalar_pair(cast) {
    ::core::panicking::panic("assertion failed: bx.cx().is_backend_scalar_pair(cast)")
};assert!(bx.cx().is_backend_scalar_pair(cast));
553                        let (lldata, llextra) = operand.val.pointer_parts();
554                        let (lldata, llextra) =
555                            base::unsize_ptr(bx, lldata, operand.layout.ty, cast.ty, llextra);
556                        OperandValue::Pair(lldata, llextra)
557                    }
558                    mir::CastKind::PointerCoercion(
559                        PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer,
560                        _,
561                    ) => {
562                        ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} is for borrowck, and should never appear in codegen",
        kind));bug!("{kind:?} is for borrowck, and should never appear in codegen");
563                    }
564                    mir::CastKind::PtrToPtr if bx.cx().is_backend_scalar_pair(operand.layout) => {
565                        if let OperandValue::Pair(data_ptr, meta) = operand.val {
566                            if bx.cx().is_backend_scalar_pair(cast) {
567                                OperandValue::Pair(data_ptr, meta)
568                            } else {
569                                // Cast of wide-ptr to thin-ptr is an extraction of data-ptr.
570                                OperandValue::Immediate(data_ptr)
571                            }
572                        } else {
573                            ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected non-pair operand"));bug!("unexpected non-pair operand");
574                        }
575                    }
576                    | mir::CastKind::IntToInt
577                    | mir::CastKind::FloatToInt
578                    | mir::CastKind::FloatToFloat
579                    | mir::CastKind::IntToFloat
580                    | mir::CastKind::PtrToPtr
581                    | mir::CastKind::FnPtrToPtr
582                    // Since int2ptr can have arbitrary integer types as input (so we have to do
583                    // sign extension and all that), it is currently best handled in the same code
584                    // path as the other integer-to-X casts.
585                    | mir::CastKind::PointerWithExposedProvenance => {
586                        let imm = operand.immediate();
587                        let abi::BackendRepr::Scalar(from_scalar) = operand.layout.backend_repr
588                        else {
589                            ::rustc_middle::util::bug::bug_fmt(format_args!("Found non-scalar for operand {0:?}",
        operand));bug!("Found non-scalar for operand {operand:?}");
590                        };
591                        let from_backend_ty = bx.cx().immediate_backend_type(operand.layout);
592
593                        if !bx.cx().is_backend_immediate(cast) {
    ::core::panicking::panic("assertion failed: bx.cx().is_backend_immediate(cast)")
};assert!(bx.cx().is_backend_immediate(cast));
594                        let to_backend_ty = bx.cx().immediate_backend_type(cast);
595                        if operand.layout.is_uninhabited() {
596                            let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty));
597                            return OperandRef { val, layout: cast, move_annotation: None };
598                        }
599                        let abi::BackendRepr::Scalar(to_scalar) = cast.layout.backend_repr else {
600                            ::rustc_middle::util::bug::bug_fmt(format_args!("Found non-scalar for cast {0:?}",
        cast));bug!("Found non-scalar for cast {cast:?}");
601                        };
602
603                        self.cast_immediate(
604                            bx,
605                            imm,
606                            from_scalar,
607                            from_backend_ty,
608                            to_scalar,
609                            to_backend_ty,
610                        )
611                        .map(OperandValue::Immediate)
612                        .unwrap_or_else(|| {
613                            ::rustc_middle::util::bug::bug_fmt(format_args!("Unsupported cast of {0:?} to {1:?}",
        operand, cast));bug!("Unsupported cast of {operand:?} to {cast:?}");
614                        })
615                    }
616                    mir::CastKind::Transmute | mir::CastKind::Subtype => {
617                        self.codegen_transmute_operand(bx, operand, cast)
618                    }
619                };
620                OperandRef { val, layout: cast, move_annotation: None }
621            }
622
623            mir::Rvalue::Ref(_, bk, place) => {
624                let mk_ref = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
625                    Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, bk.to_mutbl_lossy())
626                };
627                let op = self.codegen_place_to_pointer(bx, place, mk_ref);
628                if self.cx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some() {
629                    self.codegen_retag_operand(bx, op, false)
630                } else {
631                    op
632                }
633            }
634
635            // Note: Exclusive reborrowing is always equal to a memcpy, as the types do not change.
636            // Generic shared reborrowing is not (necessarily) a simple memcpy, but currently the
637            // coherence check places such restrictions on the CoerceShared trait as to guarantee
638            // that it is.
639            mir::Rvalue::Reborrow(_, _, place) => {
640                self.codegen_operand(bx, &mir::Operand::Copy(place))
641            }
642
643            mir::Rvalue::RawPtr(kind, place) => {
644                let mk_ptr = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
645                    Ty::new_ptr(tcx, ty, kind.to_mutbl_lossy())
646                };
647                self.codegen_place_to_pointer(bx, place, mk_ptr)
648            }
649
650            mir::Rvalue::BinaryOp(op_with_overflow, (ref lhs, ref rhs))
651                if let Some(op) = op_with_overflow.overflowing_to_wrapping() =>
652            {
653                let lhs = self.codegen_operand(bx, lhs);
654                let rhs = self.codegen_operand(bx, rhs);
655                let result = self.codegen_scalar_checked_binop(
656                    bx,
657                    op,
658                    lhs.immediate(),
659                    rhs.immediate(),
660                    lhs.layout.ty,
661                );
662                let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
663                let operand_ty = Ty::new_tup(bx.tcx(), &[val_ty, bx.tcx().types.bool]);
664                OperandRef {
665                    val: result,
666                    layout: bx.cx().layout_of(operand_ty),
667                    move_annotation: None,
668                }
669            }
670
671            mir::Rvalue::BinaryOp(op, (ref lhs, ref rhs)) => {
672                let lhs = self.codegen_operand(bx, lhs);
673                let rhs = self.codegen_operand(bx, rhs);
674                let llresult = match (lhs.val, rhs.val) {
675                    (
676                        OperandValue::Pair(lhs_addr, lhs_extra),
677                        OperandValue::Pair(rhs_addr, rhs_extra),
678                    ) => self.codegen_wide_ptr_binop(
679                        bx,
680                        op,
681                        lhs_addr,
682                        lhs_extra,
683                        rhs_addr,
684                        rhs_extra,
685                        lhs.layout.ty,
686                    ),
687
688                    (OperandValue::Immediate(lhs_val), OperandValue::Immediate(rhs_val)) => self
689                        .codegen_scalar_binop(
690                            bx,
691                            op,
692                            lhs_val,
693                            rhs_val,
694                            lhs.layout.ty,
695                            rhs.layout.ty,
696                        ),
697
698                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
699                };
700                OperandRef {
701                    val: OperandValue::Immediate(llresult),
702                    layout: bx.cx().layout_of(op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
703                    move_annotation: None,
704                }
705            }
706
707            mir::Rvalue::UnaryOp(op, ref operand) => {
708                let operand = self.codegen_operand(bx, operand);
709                let is_float = operand.layout.ty.is_floating_point();
710                let (val, layout) = match op {
711                    mir::UnOp::Not => {
712                        let llval = bx.not(operand.immediate());
713                        (OperandValue::Immediate(llval), operand.layout)
714                    }
715                    mir::UnOp::Neg => {
716                        let llval = if is_float {
717                            bx.fneg(operand.immediate())
718                        } else {
719                            bx.neg(operand.immediate())
720                        };
721                        (OperandValue::Immediate(llval), operand.layout)
722                    }
723                    mir::UnOp::PtrMetadata => {
724                        if !(operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref()) {
    ::core::panicking::panic("assertion failed: operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref()")
};assert!(operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref(),);
725                        let (_, meta) = operand.val.pointer_parts();
726                        {
    match (&(operand.layout.fields.count() > 1), &meta.is_some()) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(operand.layout.fields.count() > 1, meta.is_some());
727                        if let Some(meta) = meta {
728                            (OperandValue::Immediate(meta), operand.layout.field(self.cx, 1))
729                        } else {
730                            (OperandValue::ZeroSized, bx.cx().layout_of(bx.tcx().types.unit))
731                        }
732                    }
733                };
734                if !val.is_expected_variant_for_type(self.cx, layout) {
    {
        ::core::panicking::panic_fmt(format_args!("Made wrong variant {0:?} for type {1:?}",
                val, layout));
    }
};assert!(
735                    val.is_expected_variant_for_type(self.cx, layout),
736                    "Made wrong variant {val:?} for type {layout:?}",
737                );
738                OperandRef { val, layout, move_annotation: None }
739            }
740
741            mir::Rvalue::Discriminant(ref place) => {
742                let discr_ty = rvalue.ty(self.mir, bx.tcx());
743                let discr_ty = self.monomorphize(discr_ty);
744                let operand = self.codegen_consume(bx, place.as_ref());
745                let discr = operand.codegen_get_discr(self, bx, discr_ty);
746                OperandRef {
747                    val: OperandValue::Immediate(discr),
748                    layout: self.cx.layout_of(discr_ty),
749                    move_annotation: None,
750                }
751            }
752
753            mir::Rvalue::ThreadLocalRef(def_id) => {
754                if !bx.cx().tcx().is_static(def_id) {
    ::core::panicking::panic("assertion failed: bx.cx().tcx().is_static(def_id)")
};assert!(bx.cx().tcx().is_static(def_id));
755                let layout = bx.layout_of(bx.cx().tcx().static_ptr_ty(def_id, bx.typing_env()));
756                let static_ = if !def_id.is_local() && bx.cx().tcx().needs_thread_local_shim(def_id)
757                {
758                    let instance = ty::Instance {
759                        def: ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(def_id)),
760                        args: ty::GenericArgs::empty(),
761                    };
762                    let fn_ptr = bx.get_fn_addr(instance, Some(PacMetadata::default()));
763                    let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty());
764                    let fn_ty = bx.fn_decl_backend_type(fn_abi);
765                    let fn_attrs = if bx.tcx().def_kind(instance.def_id()).has_codegen_attrs() {
766                        Some(bx.tcx().codegen_instance_attrs(instance.def))
767                    } else {
768                        None
769                    };
770                    bx.call(
771                        fn_ty,
772                        fn_attrs.as_deref(),
773                        Some(fn_abi),
774                        fn_ptr,
775                        &[],
776                        None,
777                        Some(instance),
778                    )
779                } else {
780                    bx.get_static(def_id)
781                };
782                OperandRef { val: OperandValue::Immediate(static_), layout, move_annotation: None }
783            }
784
785            mir::Rvalue::Use(ref operand, _) => self.codegen_operand(bx, operand),
786
787            mir::Rvalue::Repeat(ref elem, len_const) => {
788                // All arrays have `BackendRepr::Memory`, so only the ZST cases
789                // end up here. Anything else forces the destination local to be
790                // `Memory`, and thus ends up handled in `codegen_rvalue` instead.
791                let operand = self.codegen_operand(bx, elem);
792                let array_ty = Ty::new_array_with_const_len(bx.tcx(), operand.layout.ty, len_const);
793                let array_ty = self.monomorphize(array_ty);
794                let array_layout = bx.layout_of(array_ty);
795                if !array_layout.is_zst() {
    ::core::panicking::panic("assertion failed: array_layout.is_zst()")
};assert!(array_layout.is_zst());
796                OperandRef {
797                    val: OperandValue::ZeroSized,
798                    layout: array_layout,
799                    move_annotation: None,
800                }
801            }
802
803            mir::Rvalue::Aggregate(ref kind, ref fields) => {
804                let (variant_index, active_field_index) = match **kind {
805                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
806                        (variant_index, active_field_index)
807                    }
808                    _ => (FIRST_VARIANT, None),
809                };
810
811                let ty = rvalue.ty(self.mir, self.cx.tcx());
812                let ty = self.monomorphize(ty);
813                let layout = self.cx.layout_of(ty);
814
815                let mut builder = OperandRefBuilder::new(layout);
816                for (field_idx, field) in fields.iter_enumerated() {
817                    let op = self.codegen_operand(bx, field);
818                    let fi = active_field_index.unwrap_or(field_idx);
819                    builder.insert_field(bx, variant_index, fi, op);
820                }
821
822                let tag_result = codegen_tag_value(self.cx, variant_index, layout);
823                match tag_result {
824                    Err(super::place::UninhabitedVariantError) => {
825                        // Like codegen_set_discr we use a sound abort, but could
826                        // potentially `unreachable` or just return the poison for
827                        // more optimizability, if that turns out to be helpful.
828                        bx.abort();
829                        let val = OperandValue::poison(bx, layout);
830                        OperandRef { val, layout, move_annotation: None }
831                    }
832                    Ok(maybe_tag_value) => {
833                        if let Some((tag_field, tag_imm)) = maybe_tag_value {
834                            builder.insert_imm(tag_field, tag_imm);
835                        }
836                        builder.build(bx.cx())
837                    }
838                }
839            }
840
841            mir::Rvalue::WrapUnsafeBinder(ref operand, binder_ty) => {
842                let operand = self.codegen_operand(bx, operand);
843                let binder_ty = self.monomorphize(binder_ty);
844                let layout = bx.cx().layout_of(binder_ty);
845                OperandRef { val: operand.val, layout, move_annotation: None }
846            }
847
848            mir::Rvalue::CopyForDeref(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("`CopyForDeref` in codegen"))bug!("`CopyForDeref` in codegen"),
849        }
850    }
851
852    /// Codegen an `Rvalue::RawPtr` or `Rvalue::Ref`
853    fn codegen_place_to_pointer(
854        &mut self,
855        bx: &mut Bx,
856        place: mir::Place<'tcx>,
857        mk_ptr_ty: impl FnOnce(TyCtxt<'tcx>, Ty<'tcx>) -> Ty<'tcx>,
858    ) -> OperandRef<'tcx, Bx::Value> {
859        let cg_place = self.codegen_place(bx, place.as_ref());
860        let val = cg_place.val.address();
861
862        let ty = cg_place.layout.ty;
863        if !if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {

            #[allow(non_exhaustive_omitted_patterns)]
            match val { OperandValue::Pair(..) => true, _ => false, }
        } else {

            #[allow(non_exhaustive_omitted_patterns)]
            match val { OperandValue::Immediate(..) => true, _ => false, }
        } {
    {
        ::core::panicking::panic_fmt(format_args!("Address of place was unexpectedly {0:?} for pointee type {1:?}",
                val, ty));
    }
};assert!(
864            if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {
865                matches!(val, OperandValue::Pair(..))
866            } else {
867                matches!(val, OperandValue::Immediate(..))
868            },
869            "Address of place was unexpectedly {val:?} for pointee type {ty:?}",
870        );
871
872        OperandRef {
873            val,
874            layout: self.cx.layout_of(mk_ptr_ty(self.cx.tcx(), ty)),
875            move_annotation: None,
876        }
877    }
878
879    fn codegen_scalar_binop(
880        &mut self,
881        bx: &mut Bx,
882        op: mir::BinOp,
883        lhs: Bx::Value,
884        rhs: Bx::Value,
885        lhs_ty: Ty<'tcx>,
886        rhs_ty: Ty<'tcx>,
887    ) -> Bx::Value {
888        let is_float = lhs_ty.is_floating_point();
889        let is_signed = lhs_ty.is_signed();
890        match op {
891            mir::BinOp::Add => {
892                if is_float {
893                    bx.fadd(lhs, rhs)
894                } else {
895                    bx.add(lhs, rhs)
896                }
897            }
898            mir::BinOp::AddUnchecked => {
899                if is_signed {
900                    bx.unchecked_sadd(lhs, rhs)
901                } else {
902                    bx.unchecked_uadd(lhs, rhs)
903                }
904            }
905            mir::BinOp::Sub => {
906                if is_float {
907                    bx.fsub(lhs, rhs)
908                } else {
909                    bx.sub(lhs, rhs)
910                }
911            }
912            mir::BinOp::SubUnchecked => {
913                if is_signed {
914                    bx.unchecked_ssub(lhs, rhs)
915                } else {
916                    bx.unchecked_usub(lhs, rhs)
917                }
918            }
919            mir::BinOp::Mul => {
920                if is_float {
921                    bx.fmul(lhs, rhs)
922                } else {
923                    bx.mul(lhs, rhs)
924                }
925            }
926            mir::BinOp::MulUnchecked => {
927                if is_signed {
928                    bx.unchecked_smul(lhs, rhs)
929                } else {
930                    bx.unchecked_umul(lhs, rhs)
931                }
932            }
933            mir::BinOp::Div => {
934                if is_float {
935                    bx.fdiv(lhs, rhs)
936                } else if is_signed {
937                    bx.sdiv(lhs, rhs)
938                } else {
939                    bx.udiv(lhs, rhs)
940                }
941            }
942            mir::BinOp::Rem => {
943                if is_float {
944                    bx.frem(lhs, rhs)
945                } else if is_signed {
946                    bx.srem(lhs, rhs)
947                } else {
948                    bx.urem(lhs, rhs)
949                }
950            }
951            mir::BinOp::BitOr => bx.or(lhs, rhs),
952            mir::BinOp::BitAnd => bx.and(lhs, rhs),
953            mir::BinOp::BitXor => bx.xor(lhs, rhs),
954            mir::BinOp::Offset => {
955                let pointee_type = lhs_ty
956                    .builtin_deref(true)
957                    .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("deref of non-pointer {0:?}",
        lhs_ty))bug!("deref of non-pointer {:?}", lhs_ty));
958                let pointee_layout = bx.cx().layout_of(pointee_type);
959                if pointee_layout.is_zst() {
960                    // `Offset` works in terms of the size of pointee,
961                    // so offsetting a pointer to ZST is a noop.
962                    lhs
963                } else {
964                    let llty = bx.cx().backend_type(pointee_layout);
965                    if !rhs_ty.is_signed() {
966                        bx.inbounds_nuw_gep(llty, lhs, &[rhs])
967                    } else {
968                        bx.inbounds_gep(llty, lhs, &[rhs])
969                    }
970                }
971            }
972            mir::BinOp::Shl | mir::BinOp::ShlUnchecked => {
973                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShlUnchecked);
974                bx.shl(lhs, rhs)
975            }
976            mir::BinOp::Shr | mir::BinOp::ShrUnchecked => {
977                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShrUnchecked);
978                if is_signed { bx.ashr(lhs, rhs) } else { bx.lshr(lhs, rhs) }
979            }
980            mir::BinOp::Ne
981            | mir::BinOp::Lt
982            | mir::BinOp::Gt
983            | mir::BinOp::Eq
984            | mir::BinOp::Le
985            | mir::BinOp::Ge => {
986                if is_float {
987                    bx.fcmp(base::bin_op_to_fcmp_predicate(op), lhs, rhs)
988                } else {
989                    bx.icmp(base::bin_op_to_icmp_predicate(op, is_signed), lhs, rhs)
990                }
991            }
992            mir::BinOp::Cmp => {
993                if !!is_float { ::core::panicking::panic("assertion failed: !is_float") };assert!(!is_float);
994                bx.three_way_compare(lhs_ty, lhs, rhs)
995            }
996            mir::BinOp::AddWithOverflow
997            | mir::BinOp::SubWithOverflow
998            | mir::BinOp::MulWithOverflow => {
999                ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} needs to return a pair, so call codegen_scalar_checked_binop instead",
        op))bug!("{op:?} needs to return a pair, so call codegen_scalar_checked_binop instead")
1000            }
1001        }
1002    }
1003
1004    fn codegen_wide_ptr_binop(
1005        &mut self,
1006        bx: &mut Bx,
1007        op: mir::BinOp,
1008        lhs_addr: Bx::Value,
1009        lhs_extra: Bx::Value,
1010        rhs_addr: Bx::Value,
1011        rhs_extra: Bx::Value,
1012        _input_ty: Ty<'tcx>,
1013    ) -> Bx::Value {
1014        match op {
1015            mir::BinOp::Eq => {
1016                let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1017                let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
1018                bx.and(lhs, rhs)
1019            }
1020            mir::BinOp::Ne => {
1021                let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
1022                let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
1023                bx.or(lhs, rhs)
1024            }
1025            mir::BinOp::Le | mir::BinOp::Lt | mir::BinOp::Ge | mir::BinOp::Gt => {
1026                // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
1027                let (op, strict_op) = match op {
1028                    mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
1029                    mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
1030                    mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
1031                    mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
1032                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1033                };
1034                let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
1035                let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1036                let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
1037                let rhs = bx.and(and_lhs, and_rhs);
1038                bx.or(lhs, rhs)
1039            }
1040            _ => {
1041                ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected wide ptr binop"));bug!("unexpected wide ptr binop");
1042            }
1043        }
1044    }
1045
1046    fn codegen_scalar_checked_binop(
1047        &mut self,
1048        bx: &mut Bx,
1049        op: mir::BinOp,
1050        lhs: Bx::Value,
1051        rhs: Bx::Value,
1052        input_ty: Ty<'tcx>,
1053    ) -> OperandValue<Bx::Value> {
1054        let (val, of) = match op {
1055            // These are checked using intrinsics
1056            mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
1057                let oop = match op {
1058                    mir::BinOp::Add => OverflowOp::Add,
1059                    mir::BinOp::Sub => OverflowOp::Sub,
1060                    mir::BinOp::Mul => OverflowOp::Mul,
1061                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1062                };
1063                bx.checked_binop(oop, input_ty, lhs, rhs)
1064            }
1065            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Operator `{0:?}` is not a checkable operator",
        op))bug!("Operator `{:?}` is not a checkable operator", op),
1066        };
1067
1068        OperandValue::Pair(val, of)
1069    }
1070}
1071
1072/// Transmutes a single scalar value `imm` from `from_scalar` to `to_scalar`.
1073///
1074/// This is expected to be in *immediate* form, as seen in [`OperandValue::Immediate`]
1075/// or [`OperandValue::Pair`] (so `i1` for bools, not `i8`, for example).
1076///
1077/// ICEs if the passed-in `imm` is not a value of the expected type for
1078/// `from_scalar`, such as if it's a vector or a pair.
1079pub(super) fn transmute_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1080    bx: &mut Bx,
1081    mut imm: Bx::Value,
1082    from_scalar: abi::Scalar,
1083    to_scalar: abi::Scalar,
1084) -> Bx::Value {
1085    {
    match (&from_scalar.size(bx.cx()), &to_scalar.size(bx.cx())) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(from_scalar.size(bx.cx()), to_scalar.size(bx.cx()));
1086    let imm_ty = bx.cx().val_ty(imm);
1087    {
    match (&(bx.cx().type_kind(imm_ty)), &(TypeKind::Vector)) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("Vector type {0:?} not allowed in transmute_scalar {1:?} -> {2:?}",
                            imm_ty, from_scalar, to_scalar)));
            }
        }
    }
};assert_ne!(
1088        bx.cx().type_kind(imm_ty),
1089        TypeKind::Vector,
1090        "Vector type {imm_ty:?} not allowed in transmute_scalar {from_scalar:?} -> {to_scalar:?}"
1091    );
1092
1093    // While optimizations will remove no-op transmutes, they might still be
1094    // there in debug or things that aren't no-op in MIR because they change
1095    // the Rust type but not the underlying layout/niche.
1096    if from_scalar == to_scalar {
1097        return imm;
1098    }
1099
1100    use abi::Primitive::*;
1101    imm = bx.from_immediate(imm);
1102
1103    let from_backend_ty = bx.cx().type_from_scalar(from_scalar);
1104    if true {
    {
        match (&bx.cx().val_ty(imm), &from_backend_ty) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(bx.cx().val_ty(imm), from_backend_ty);
1105    let to_backend_ty = bx.cx().type_from_scalar(to_scalar);
1106
1107    // If we have a scalar, we must already know its range. Either
1108    //
1109    // 1) It's a parameter with `range` parameter metadata,
1110    // 2) It's something we `load`ed with `!range` metadata, or
1111    // 3) After a transmute we `assume`d the range (see below).
1112    //
1113    // That said, last time we tried removing this, it didn't actually help
1114    // the rustc-perf results, so might as well keep doing it
1115    // <https://github.com/rust-lang/rust/pull/135610#issuecomment-2599275182>
1116    assume_scalar_range(bx, imm, from_scalar, from_backend_ty, Some(&to_scalar));
1117
1118    imm = match (from_scalar.primitive(), to_scalar.primitive()) {
1119        (Int(..) | Float(_), Int(..) | Float(_)) => bx.bitcast(imm, to_backend_ty),
1120        (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
1121        (Int(..), Pointer(..)) => bx.inttoptr(imm, to_backend_ty),
1122        (Pointer(..), Int(..)) => {
1123            // FIXME: this exposes the provenance, which shouldn't be necessary.
1124            bx.ptrtoint(imm, to_backend_ty)
1125        }
1126        (Float(_), Pointer(..)) => {
1127            let int_imm = bx.bitcast(imm, bx.cx().type_isize());
1128            bx.inttoptr(int_imm, to_backend_ty)
1129        }
1130        (Pointer(..), Float(_)) => {
1131            // FIXME: this exposes the provenance, which shouldn't be necessary.
1132            let int_imm = bx.ptrtoint(imm, bx.cx().type_isize());
1133            bx.bitcast(int_imm, to_backend_ty)
1134        }
1135    };
1136
1137    if true {
    {
        match (&bx.cx().val_ty(imm), &to_backend_ty) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(bx.cx().val_ty(imm), to_backend_ty);
1138
1139    // This `assume` remains important for cases like (a conceptual)
1140    //    transmute::<u32, NonZeroU32>(x) == 0
1141    // since it's never passed to something with parameter metadata (especially
1142    // after MIR inlining) so the only way to tell the backend about the
1143    // constraint that the `transmute` introduced is to `assume` it.
1144    assume_scalar_range(bx, imm, to_scalar, to_backend_ty, Some(&from_scalar));
1145
1146    imm = bx.to_immediate_scalar(imm, to_scalar);
1147    imm
1148}
1149
1150/// Emits an `assume` call that `imm`'s value is within the known range of `scalar`.
1151///
1152/// If `known` is `Some`, only emits the assume if it's more specific than
1153/// whatever is already known from the range of *that* scalar.
1154fn assume_scalar_range<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1155    bx: &mut Bx,
1156    imm: Bx::Value,
1157    scalar: abi::Scalar,
1158    backend_ty: Bx::Type,
1159    known: Option<&abi::Scalar>,
1160) {
1161    if #[allow(non_exhaustive_omitted_patterns)] match bx.cx().sess().opts.optimize {
    OptLevel::No => true,
    _ => false,
}matches!(bx.cx().sess().opts.optimize, OptLevel::No) {
1162        return;
1163    }
1164
1165    match (scalar, known) {
1166        (abi::Scalar::Union { .. }, _) => return,
1167        (_, None) => {
1168            if scalar.is_always_valid(bx.cx()) {
1169                return;
1170            }
1171        }
1172        (abi::Scalar::Initialized { valid_range, .. }, Some(known)) => {
1173            let known_range = known.valid_range(bx.cx());
1174            if valid_range.contains_range(known_range, scalar.size(bx.cx())) {
1175                return;
1176            }
1177        }
1178    }
1179
1180    match scalar.primitive() {
1181        abi::Primitive::Int(..) => {
1182            let range = scalar.valid_range(bx.cx());
1183            bx.assume_integer_range(imm, backend_ty, range);
1184        }
1185        abi::Primitive::Pointer(abi::AddressSpace::ZERO)
1186            if !scalar.valid_range(bx.cx()).contains(0) =>
1187        {
1188            bx.assume_nonnull(imm);
1189        }
1190        abi::Primitive::Pointer(..) | abi::Primitive::Float(..) => {}
1191    }
1192}