Skip to main content

rustc_codegen_ssa/mir/
rvalue.rs

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