Skip to main content

rustc_codegen_ssa/mir/
operand.rs

1use std::fmt;
2
3use itertools::Either;
4use rustc_abi as abi;
5use rustc_abi::{
6    Align, BackendRepr, FIRST_VARIANT, FieldIdx, Primitive, Size, TagEncoding, VariantIdx, Variants,
7};
8use rustc_hir::attrs::lang_items::LangItem;
9use rustc_middle::mir::interpret::{Pointer, Scalar, alloc_range};
10use rustc_middle::mir::{self, ConstValue};
11use rustc_middle::ty::consts::ConstExt;
12use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
13use rustc_middle::ty::{self, Ty};
14use rustc_session::config::{AnnotateMoves, DebugInfo, OptLevel};
15use rustc_span::{bug, span_bug};
16use tracing::{debug, instrument};
17
18use super::place::{PlaceRef, PlaceValue};
19use super::rvalue::transmute_scalar;
20use super::{FunctionCx, LocalRef};
21use crate::MemFlags;
22use crate::common::IntPredicate;
23use crate::traits::*;
24
25/// The representation of a Rust value. The enum variant is in fact
26/// uniquely determined by the value's type, but is kept as a
27/// safety check.
28#[derive(#[automatically_derived]
impl<V: ::core::marker::Copy> ::core::marker::Copy for OperandValue<V> { }Copy, #[automatically_derived]
impl<V: ::core::clone::Clone> ::core::clone::Clone for OperandValue<V> {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Ref(__self_0) =>
                Self::Ref(::core::clone::Clone::clone(__self_0)),
            Self::Immediate(__self_0) =>
                Self::Immediate(::core::clone::Clone::clone(__self_0)),
            Self::Pair(__self_0, __self_1) =>
                Self::Pair(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            Self::ZeroSized => Self::ZeroSized,
        }
    }
}Clone, #[automatically_derived]
impl<V: ::core::fmt::Debug> ::core::fmt::Debug for OperandValue<V> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Ref(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ref",
                    &__self_0),
            Self::Immediate(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Immediate", &__self_0),
            Self::Pair(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Pair",
                    __self_0, &__self_1),
            Self::ZeroSized =>
                ::core::fmt::Formatter::write_str(f, "ZeroSized"),
        }
    }
}Debug)]
29pub enum OperandValue<V> {
30    /// A reference to the actual operand. The data is guaranteed
31    /// to be valid for the operand's lifetime.
32    /// The [`PlaceValue::llextra`], if any, is the extra data (vtable or length)
33    /// which indicates that it refers to an unsized rvalue.
34    ///
35    /// An `OperandValue` *must* be this variant for any type for which
36    /// [`rustc_abi::LayoutData::is_ssa_standalone`] returns `false`.
37    /// (That basically amounts to "isn't one of the other variants".)
38    ///
39    /// This holds a [`PlaceValue`] (like a [`PlaceRef`] does) with a pointer
40    /// to the location holding the value. The type behind that pointer is the
41    /// one returned by [`LayoutTypeCodegenMethods::backend_type`].
42    ///
43    /// Note that a [`load_operand`] which produces this variant didn't actually
44    /// *load* anything; it just put the pointer-to-place into this variant.
45    ///
46    /// [`load_operand`]: BuilderMethods::load_operand
47    Ref(PlaceValue<V>),
48    /// A single LLVM immediate value.
49    ///
50    /// An `OperandValue` *must* be this variant for any type that's
51    /// [`BackendRepr::Scalar`], [`BackendRepr::SimdVector`], or
52    /// [`BackendRepr::SimdScalableVector`].
53    ///
54    /// The backend value in this variant must be the *immediate* backend type,
55    /// as returned by [`LayoutTypeCodegenMethods::immediate_backend_type`].
56    ///
57    /// Notably, that means that in LLVM a `bool` is `i1` here, even though we
58    /// load and store `bool`s as LLVM's `i8` type. Methods such as
59    /// [`BuilderMethods::load_operand`] and [`OperandRef::store_with_annotation`]
60    /// will handle that correctly, but if you're using the value directly or
61    /// implementing such methods, be sure to convert using
62    /// [`BuilderMethods::from_immediate`] and [`BuilderMethods::to_immediate_scalar`]
63    /// in the appropriate places.
64    Immediate(V),
65    /// A pair of immediate LLVM values.
66    ///
67    /// Notably this includes wide pointers, where the two values are the pointer
68    /// and the metadata (slice length, vtable pointer, etc).
69    ///
70    /// # Invariants
71    /// - For `Pair(a, b)`, `a` is always at offset 0, but may have `FieldIdx(1..)`
72    /// - `b` is not at offset 0, because `V` is not a 1ZST type.
73    /// - `a` and `b` will have a different FieldIdx, but otherwise `b`'s may be lower
74    ///   or they may not be adjacent, due to arbitrary numbers of 1ZST fields that
75    ///   will not affect the shape of the data which determines if `Pair` will be used.
76    /// - An `OperandValue` *must* be this variant for any type that's [`BackendRepr::ScalarPair`].
77    /// - The backend values in this variant must be the *immediate* backend types,
78    /// as returned by [`LayoutTypeCodegenMethods::scalar_pair_element_backend_type`]
79    /// with `immediate: true`. See the note in [`Self::Immediate`].
80    Pair(V, V),
81    /// A value taking no bytes, and which therefore needs no LLVM value at all.
82    ///
83    /// If you ever need a `V` to pass to something, get a fresh poison value
84    /// from [`ConstCodegenMethods::const_poison`].
85    ///
86    /// An `OperandValue` *must* be this variant for any type for which
87    /// `is_zst` on its `Layout` returns `true`. Note however that
88    /// these values can still require alignment.
89    ZeroSized,
90}
91
92impl<V: CodegenObject> OperandValue<V> {
93    /// Return the data pointer and optional metadata as backend values
94    /// if this value can be treat as a pointer.
95    pub(crate) fn try_pointer_parts(self) -> Option<(V, Option<V>)> {
96        match self {
97            OperandValue::Immediate(llptr) => Some((llptr, None)),
98            OperandValue::Pair(llptr, llextra) => Some((llptr, Some(llextra))),
99            OperandValue::Ref(_) | OperandValue::ZeroSized => None,
100        }
101    }
102
103    /// Treat this value as a pointer and return the data pointer and
104    /// optional metadata as backend values.
105    ///
106    /// If you're making a place, use [`Self::deref`] instead.
107    pub(crate) fn pointer_parts(self) -> (V, Option<V>) {
108        self.try_pointer_parts()
109            .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
    format_args!("OperandValue cannot be a pointer: {0:?}", self),
    Location::caller())bug!("OperandValue cannot be a pointer: {self:?}"))
110    }
111
112    /// Treat this value as a pointer and return the place to which it points.
113    ///
114    /// The pointer immediate doesn't inherently know its alignment,
115    /// so you need to pass it in. If you want to get it from a type's ABI
116    /// alignment, then maybe you want [`OperandRef::deref`] instead.
117    ///
118    /// This is the inverse of [`PlaceValue::address`].
119    pub(crate) fn deref(self, align: Align) -> PlaceValue<V> {
120        let (llval, llextra) = self.pointer_parts();
121        PlaceValue { llval, llextra, align }
122    }
123
124    #[must_use]
125    pub(crate) fn is_expected_variant_for_type<'tcx>(&self, ty: TyAndLayout<'tcx>) -> bool {
126        match (self, ty.backend_repr) {
127            (OperandValue::ZeroSized, BackendRepr::Memory { .. }) => ty.is_zst(),
128            (OperandValue::Ref(_), BackendRepr::Memory { .. }) => !ty.is_zst(),
129            (
130                OperandValue::Immediate(_),
131                BackendRepr::Scalar(..)
132                | BackendRepr::SimdVector { .. }
133                | BackendRepr::SimdScalableVector { .. },
134            ) => true,
135            (OperandValue::Pair(_, _), BackendRepr::ScalarPair { .. }) => true,
136            _ => false,
137        }
138    }
139}
140
141/// An `OperandRef` is an "SSA" reference to a Rust value, along with
142/// its type.
143///
144/// NOTE: unless you know a value's type exactly, you should not
145/// generate LLVM opcodes acting on it and instead act via methods,
146/// to avoid nasty edge cases. In particular, using `Builder::store`
147/// directly is sure to cause problems -- use `OperandRef::store`
148/// instead.
149#[derive(#[automatically_derived]
impl<'tcx, V: ::core::marker::Copy> ::core::marker::Copy for
    OperandRef<'tcx, V> {
}Copy, #[automatically_derived]
impl<'tcx, V: ::core::clone::Clone> ::core::clone::Clone for
    OperandRef<'tcx, V> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            val: ::core::clone::Clone::clone(&self.val),
            layout: ::core::clone::Clone::clone(&self.layout),
            move_annotation: ::core::clone::Clone::clone(&self.move_annotation),
        }
    }
}Clone)]
150pub struct OperandRef<'tcx, V> {
151    /// The value.
152    pub val: OperandValue<V>,
153
154    /// The layout of value, based on its Rust type.
155    pub layout: TyAndLayout<'tcx>,
156
157    /// Annotation for profiler visibility of move/copy operations.
158    /// When set, the store operation should appear as an inlined call to this function.
159    pub move_annotation: Option<ty::Instance<'tcx>>,
160}
161
162impl<V: CodegenObject> fmt::Debug for OperandRef<'_, V> {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        f.write_fmt(format_args!("OperandRef({0:?} @ {1:?})", self.val, self.layout))write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
165    }
166}
167
168impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
169    pub fn zero_sized(layout: TyAndLayout<'tcx>) -> OperandRef<'tcx, V> {
170        if !layout.is_zst() {
    ::core::panicking::panic("assertion failed: layout.is_zst()")
};assert!(layout.is_zst());
171        OperandRef { val: OperandValue::ZeroSized, layout, move_annotation: None }
172    }
173
174    pub(crate) fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
175        bx: &mut Bx,
176        val: mir::ConstValue,
177        ty: Ty<'tcx>,
178    ) -> Self {
179        let layout = bx.layout_of(ty);
180
181        let val = match val {
182            ConstValue::Scalar(x) => {
183                let BackendRepr::Scalar(scalar) = layout.backend_repr else {
184                    ::rustc_span::macros::bug_impl(None,
    format_args!("from_const: invalid ByVal layout: {0:#?}", layout),
    Location::caller());bug!("from_const: invalid ByVal layout: {:#?}", layout);
185                };
186                let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
187                OperandValue::Immediate(llval)
188            }
189            ConstValue::ZeroSized => return OperandRef::zero_sized(layout),
190            ConstValue::Slice { alloc_id, meta } => {
191                let BackendRepr::ScalarPair { a: a_scalar, b: _, b_offset: _ } =
192                    layout.backend_repr
193                else {
194                    ::rustc_span::macros::bug_impl(None,
    format_args!("from_const: invalid ScalarPair layout: {0:#?}", layout),
    Location::caller());bug!("from_const: invalid ScalarPair layout: {:#?}", layout);
195                };
196                let a = Scalar::from_pointer(Pointer::new(alloc_id.into(), Size::ZERO), &bx.tcx());
197                let a_llval = bx.scalar_to_backend(
198                    a,
199                    a_scalar,
200                    bx.scalar_pair_element_backend_type(layout, 0, true),
201                );
202                let b_llval = bx.const_usize(meta);
203                OperandValue::Pair(a_llval, b_llval)
204            }
205            ConstValue::Indirect { alloc_id, offset } => {
206                let alloc = bx.tcx().global_alloc(alloc_id).unwrap_memory();
207                return Self::from_const_alloc(bx, layout, alloc, offset);
208            }
209        };
210
211        OperandRef { val, layout, move_annotation: None }
212    }
213
214    fn from_const_alloc<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
215        bx: &mut Bx,
216        layout: TyAndLayout<'tcx>,
217        alloc: rustc_middle::mir::interpret::ConstAllocation<'tcx>,
218        offset: Size,
219    ) -> Self {
220        let alloc_align = alloc.inner().align;
221        if !(alloc_align >= layout.align.abi) {
    {
        ::core::panicking::panic_fmt(format_args!("{1:?} < {0:?}",
                layout.align.abi, alloc_align));
    }
};assert!(alloc_align >= layout.align.abi, "{alloc_align:?} < {:?}", layout.align.abi);
222
223        let read_scalar = |start, size, s: abi::Scalar, ty| {
224            match alloc.0.read_scalar(
225                bx,
226                alloc_range(start, size),
227                /*read_provenance*/ #[allow(non_exhaustive_omitted_patterns)] match s.primitive() {
    abi::Primitive::Pointer(_) => true,
    _ => false,
}matches!(s.primitive(), abi::Primitive::Pointer(_)),
228            ) {
229                Ok(val) => bx.scalar_to_backend(val, s, ty),
230                Err(_) => bx.const_poison(ty),
231            }
232        };
233
234        // It may seem like all types with `Scalar` or `ScalarPair` ABI are fair game at this point.
235        // However, `MaybeUninit<u64>` is considered a `Scalar` as far as its layout is concerned --
236        // and yet cannot be represented by an interpreter `Scalar`, since we have to handle the
237        // case where some of the bytes are initialized and others are not. So, we need an extra
238        // check that walks over the type of `mplace` to make sure it is truly correct to treat this
239        // like a `Scalar` (or `ScalarPair`).
240        match layout.backend_repr {
241            BackendRepr::Scalar(s @ abi::Scalar::Initialized { .. }) => {
242                let size = s.size(bx);
243                {
    match (&size, &layout.size) {
        (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::Some(format_args!("abi::Scalar size does not match layout size")));
            }
        }
    }
};assert_eq!(size, layout.size, "abi::Scalar size does not match layout size");
244                let val = read_scalar(offset, size, s, bx.immediate_backend_type(layout));
245                OperandRef { val: OperandValue::Immediate(val), layout, move_annotation: None }
246            }
247            BackendRepr::ScalarPair {
248                a: a @ abi::Scalar::Initialized { .. },
249                b: b @ abi::Scalar::Initialized { .. },
250                b_offset: local_b_offset,
251            } => {
252                let (a_size, b_size) = (a.size(bx), b.size(bx));
253                let alloc_b_offset = offset + local_b_offset;
254                if !(alloc_b_offset.bytes() > 0) {
    ::core::panicking::panic("assertion failed: alloc_b_offset.bytes() > 0")
};assert!(alloc_b_offset.bytes() > 0);
255                let a_val = read_scalar(
256                    offset,
257                    a_size,
258                    a,
259                    bx.scalar_pair_element_backend_type(layout, 0, true),
260                );
261                let b_val = read_scalar(
262                    alloc_b_offset,
263                    b_size,
264                    b,
265                    bx.scalar_pair_element_backend_type(layout, 1, true),
266                );
267                OperandRef { val: OperandValue::Pair(a_val, b_val), layout, move_annotation: None }
268            }
269            _ if layout.is_zst() => OperandRef::zero_sized(layout),
270            _ => {
271                // Neither a scalar nor scalar pair. Load from a place
272                let base_addr = bx.static_addr_of(alloc, None);
273
274                let llval = bx.const_ptr_byte_offset(base_addr, offset);
275                bx.load_operand(PlaceRef::new_sized(llval, layout))
276            }
277        }
278    }
279
280    /// Asserts that this operand refers to a scalar and returns
281    /// a reference to its value.
282    pub fn immediate(self) -> V {
283        match self.val {
284            OperandValue::Immediate(s) => s,
285            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("not immediate: {0:?}", self), Location::caller())bug!("not immediate: {:?}", self),
286        }
287    }
288
289    /// Asserts that this operand is a pointer (or reference) and returns
290    /// the place to which it points.  (This requires no code to be emitted
291    /// as we represent places using the pointer to the place.)
292    ///
293    /// This uses [`Ty::builtin_deref`] to include the type of the place and
294    /// assumes the place is aligned to the pointee's usual ABI alignment.
295    ///
296    /// If you don't need the type, see [`OperandValue::pointer_parts`]
297    /// or [`OperandValue::deref`].
298    pub fn deref<Cx: CodegenMethods<'tcx>>(self, cx: &Cx) -> PlaceRef<'tcx, V> {
299        if self.layout.ty.is_box() {
300            // Derefer should have removed all Box derefs
301            ::rustc_span::macros::bug_impl(None,
    format_args!("dereferencing {0:?} in codegen", self.layout.ty),
    Location::caller());bug!("dereferencing {:?} in codegen", self.layout.ty);
302        }
303
304        let projected_ty = self
305            .layout
306            .ty
307            .builtin_deref(true)
308            .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
    format_args!("deref of non-pointer {0:?}", self), Location::caller())bug!("deref of non-pointer {:?}", self));
309
310        let layout = cx.layout_of(projected_ty);
311        self.val.deref(layout.align.abi).with_type(layout)
312    }
313
314    /// Store this operand into a place, applying move/copy annotation if present.
315    ///
316    /// This is the preferred method for storing operands, as it automatically
317    /// applies profiler annotations for tracked move/copy operations.
318    pub fn store_with_annotation<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
319        self,
320        bx: &mut Bx,
321        dest: PlaceRef<'tcx, V>,
322    ) {
323        self.store_with_annotation_and_flags(bx, dest, MemFlags::empty())
324    }
325
326    /// Same as store_with_annotation(), but also specify flags for the store.
327    pub fn store_with_annotation_and_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
328        self,
329        bx: &mut Bx,
330        dest: PlaceRef<'tcx, V>,
331        flags: MemFlags,
332    ) {
333        if let Some(instance) = self.move_annotation {
334            bx.with_move_annotation(instance, |bx| self.val.store_with_flags(bx, dest, flags))
335        } else {
336            self.val.store_with_flags(bx, dest, flags)
337        }
338    }
339
340    /// If this operand is a `Pair`, we return an aggregate with the two values.
341    /// For other cases, see `immediate`.
342    ///
343    /// Note: The use of this is discouraged outside cg_llvm, as some other backends
344    /// don't natively support packing multiple things into one like this.
345    pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
346        self,
347        bx: &mut Bx,
348    ) -> V {
349        if let OperandValue::Pair(a, b) = self.val {
350            let llty = bx.cx().immediate_backend_type(self.layout);
351            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs:351",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(351u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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!("Operand::immediate_or_packed_pair: packing {0:?} into {1:?}",
                                                    self, llty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}", self, llty);
352            // Reconstruct the immediate aggregate.
353            let mut llpair = bx.cx().const_poison(llty);
354            llpair = bx.insert_value(llpair, a, 0);
355            llpair = bx.insert_value(llpair, b, 1);
356            llpair
357        } else {
358            self.immediate()
359        }
360    }
361
362    /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
363    ///
364    /// Note: The use of this is discouraged outside cg_llvm, as some other backends
365    /// don't natively support packing multiple things into one like this.
366    pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
367        bx: &mut Bx,
368        llval: V,
369        layout: TyAndLayout<'tcx>,
370    ) -> Self {
371        let val = if let BackendRepr::ScalarPair { .. } = layout.backend_repr {
372            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs:372",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(372u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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!("Operand::from_immediate_or_packed_pair: unpacking {0:?} @ {1:?}",
                                                    llval, layout) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}", llval, layout);
373
374            // Deconstruct the immediate aggregate.
375            let a_llval = bx.extract_value(llval, 0);
376            let b_llval = bx.extract_value(llval, 1);
377            OperandValue::Pair(a_llval, b_llval)
378        } else {
379            OperandValue::Immediate(llval)
380        };
381        OperandRef { val, layout, move_annotation: None }
382    }
383
384    pub(crate) fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
385        &self,
386        fx: &mut FunctionCx<'a, 'tcx, Bx>,
387        bx: &mut Bx,
388        i: usize,
389    ) -> Self {
390        let field = self.layout.field(bx.cx(), i);
391        let offset = self.layout.fields.offset(i);
392
393        if self.layout.is_ssa_standalone() && !field.is_ssa_standalone() {
394            // Part of https://github.com/rust-lang/compiler-team/issues/838
395            ::rustc_span::macros::bug_impl(Some(fx.mir.span),
    format_args!("Standalone type {0:?} cannot project to memory-dependent field type {1:?}",
        self, field), Location::caller());span_bug!(
396                fx.mir.span,
397                "Standalone type {self:?} cannot project to memory-dependent field type {field:?}",
398            );
399        }
400
401        let val = if field.is_zst() {
402            OperandValue::ZeroSized
403        } else if field.size == self.layout.size {
404            {
    match (&offset.bytes(), &0) {
        (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!(offset.bytes(), 0);
405            fx.codegen_transmute_operand(bx, *self, field)
406        } else {
407            let (in_scalar, imm) = match (self.val, self.layout.backend_repr) {
408                // Extract a scalar component from a pair.
409                (
410                    OperandValue::Pair(a_llval, b_llval),
411                    BackendRepr::ScalarPair { a, b, b_offset },
412                ) => {
413                    if offset.bytes() == 0 {
414                        {
    match (&field.size, &a.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!(field.size, a.size(bx.cx()));
415                        (Some(a), a_llval)
416                    } else {
417                        {
    match (&offset, &b_offset) {
        (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!(offset, b_offset);
418                        {
    match (&field.size, &b.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!(field.size, b.size(bx.cx()));
419                        (Some(b), b_llval)
420                    }
421                }
422
423                _ => {
424                    ::rustc_span::macros::bug_impl(Some(fx.mir.span),
    format_args!("OperandRef::extract_field({0:?}): not applicable", self),
    Location::caller())span_bug!(fx.mir.span, "OperandRef::extract_field({:?}): not applicable", self)
425                }
426            };
427            OperandValue::Immediate(match field.backend_repr {
428                BackendRepr::SimdVector { .. } => imm,
429                BackendRepr::Scalar(out_scalar) => {
430                    let Some(in_scalar) = in_scalar else {
431                        ::rustc_span::macros::bug_impl(Some(fx.mir.span),
    format_args!("OperandRef::extract_field({0:?}): missing input scalar for output scalar",
        self), Location::caller())span_bug!(
432                            fx.mir.span,
433                            "OperandRef::extract_field({:?}): missing input scalar for output scalar",
434                            self
435                        )
436                    };
437                    if in_scalar != out_scalar {
438                        // If the backend and backend_immediate types might differ,
439                        // flip back to the backend type then to the new immediate.
440                        // This avoids nop truncations, but still handles things like
441                        // Bools in union fields needs to be truncated.
442                        let backend = bx.from_immediate(imm);
443                        bx.to_immediate_scalar(backend, out_scalar)
444                    } else {
445                        imm
446                    }
447                }
448                BackendRepr::ScalarPair { a: _, b: _, b_offset: _ }
449                | BackendRepr::Memory { .. }
450                | BackendRepr::SimdScalableVector { .. } => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
451            })
452        };
453
454        OperandRef { val, layout: field, move_annotation: None }
455    }
456
457    /// Obtain the actual discriminant of a value.
458    {}
#[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_get_discr",
                                    "rustc_codegen_ssa::mir::operand", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                                    ::tracing_core::__macro_support::Option::Some(458u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cast_to")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cast_to");
                                                        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(&self)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cast_to)
                                                            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: V = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let dl = &bx.tcx().data_layout;
            let cast_to_layout = bx.cx().layout_of(cast_to);
            let cast_to = bx.cx().immediate_backend_type(cast_to_layout);
            if self.layout.is_uninhabited() {
                return bx.cx().const_poison(cast_to);
            }
            let (tag_scalar, tag_encoding, tag_field) =
                match self.layout.variants {
                    Variants::Empty => {
                        ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                format_args!("we already handled uninhabited types")));
                    }
                    Variants::Single { index } => {
                        let discr_val =
                            if let Some(discr) =
                                    self.layout.ty.discriminant_for_variant(bx.tcx(), index) {
                                discr.val
                            } else {
                                {
                                    match (&index, &FIRST_VARIANT) {
                                        (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);
                                            }
                                        }
                                    }
                                };
                                0
                            };
                        return bx.cx().const_uint_big(cast_to, discr_val);
                    }
                    Variants::Multiple { tag, ref tag_encoding, tag_field, .. }
                        => {
                        (tag, tag_encoding, tag_field)
                    }
                };
            let tag_op =
                match self.val {
                    OperandValue::ZeroSized =>
                        ::rustc_span::macros::bug_impl(None,
                            format_args!("impossible case reached"),
                            Location::caller()),
                    OperandValue::Immediate(_) | OperandValue::Pair(_, _) => {
                        self.extract_field(fx, bx, tag_field.as_usize())
                    }
                    OperandValue::Ref(place) => {
                        let tag =
                            place.with_type(self.layout).project_field(bx,
                                tag_field.as_usize());
                        bx.load_operand(tag)
                    }
                };
            let tag_imm = tag_op.immediate();
            match *tag_encoding {
                TagEncoding::Direct => {
                    let signed =
                        match tag_scalar.primitive() {
                            Primitive::Int(_, signed) =>
                                !tag_scalar.is_bool() && signed,
                            _ => false,
                        };
                    bx.intcast(tag_imm, cast_to, signed)
                }
                TagEncoding::Niche {
                    untagged_variant, ref niche_variants, niche_start } => {
                    let (tag, tag_llty) =
                        match tag_scalar.primitive() {
                            Primitive::Pointer(_) => {
                                let t = bx.type_from_integer(dl.ptr_sized_integer());
                                let tag = bx.ptrtoint(tag_imm, t);
                                (tag, t)
                            }
                            _ =>
                                (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)),
                        };
                    let relative_max =
                        niche_variants.last.as_u32() -
                            niche_variants.start.as_u32();
                    let niche_start_const =
                        bx.cx().const_uint_big(tag_llty, niche_start);
                    let (is_niche, tagged_discr, delta) =
                        if relative_max == 0 {
                            let is_niche =
                                bx.icmp(IntPredicate::IntEQ, tag, niche_start_const);
                            let tagged_discr =
                                bx.cx().const_uint(cast_to,
                                    niche_variants.start.as_u32() as u64);
                            (is_niche, tagged_discr, 0)
                        } else {
                            if niche_variants.contains(&untagged_variant) &&
                                    bx.cx().sess().opts.optimize != OptLevel::No {
                                let impossible =
                                    niche_start.wrapping_add(u128::from(untagged_variant.as_u32())).wrapping_sub(u128::from(niche_variants.start.as_u32()));
                                let impossible =
                                    bx.cx().const_uint_big(tag_llty, impossible);
                                let ne = bx.icmp(IntPredicate::IntNE, tag, impossible);
                                bx.assume(ne);
                            }
                            let tag_range = tag_scalar.valid_range(&dl);
                            let tag_size = tag_scalar.size(&dl);
                            let niche_end =
                                u128::from(relative_max).wrapping_add(niche_start);
                            let niche_end = tag_size.truncate(niche_end);
                            let relative_discr = bx.sub(tag, niche_start_const);
                            let cast_tag = bx.intcast(relative_discr, cast_to, false);
                            let is_niche =
                                if tag_range.no_unsigned_wraparound(tag_size) == Ok(true) {
                                    if niche_start == tag_range.start {
                                        let niche_end_const =
                                            bx.cx().const_uint_big(tag_llty, niche_end);
                                        bx.icmp(IntPredicate::IntULE, tag, niche_end_const)
                                    } else {
                                        {
                                            match (&niche_end, &tag_range.end) {
                                                (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);
                                                    }
                                                }
                                            }
                                        };
                                        bx.icmp(IntPredicate::IntUGE, tag, niche_start_const)
                                    }
                                } else if tag_range.no_signed_wraparound(tag_size) ==
                                        Ok(true) {
                                    if niche_start == tag_range.start {
                                        let niche_end_const =
                                            bx.cx().const_uint_big(tag_llty, niche_end);
                                        bx.icmp(IntPredicate::IntSLE, tag, niche_end_const)
                                    } else {
                                        {
                                            match (&niche_end, &tag_range.end) {
                                                (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);
                                                    }
                                                }
                                            }
                                        };
                                        bx.icmp(IntPredicate::IntSGE, tag, niche_start_const)
                                    }
                                } else {
                                    bx.icmp(IntPredicate::IntULE, relative_discr,
                                        bx.cx().const_uint(tag_llty, relative_max as u64))
                                };
                            (is_niche, cast_tag, niche_variants.start.as_u32() as u128)
                        };
                    let tagged_discr =
                        if delta == 0 {
                            tagged_discr
                        } else {
                            bx.add(tagged_discr, bx.cx().const_uint_big(cast_to, delta))
                        };
                    let untagged_variant_const =
                        bx.cx().const_uint(cast_to,
                            u64::from(untagged_variant.as_u32()));
                    let discr =
                        bx.select(is_niche, tagged_discr, untagged_variant_const);
                    discr
                }
            }
        }
    }
}#[instrument(level = "trace", skip(fx, bx))]
459    pub fn codegen_get_discr<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
460        self,
461        fx: &mut FunctionCx<'a, 'tcx, Bx>,
462        bx: &mut Bx,
463        cast_to: Ty<'tcx>,
464    ) -> V {
465        let dl = &bx.tcx().data_layout;
466        let cast_to_layout = bx.cx().layout_of(cast_to);
467        let cast_to = bx.cx().immediate_backend_type(cast_to_layout);
468
469        // We check uninhabitedness separately because a type like
470        // `enum Foo { Bar(i32, !) }` is still reported as `Variants::Single`,
471        // *not* as `Variants::Empty`.
472        if self.layout.is_uninhabited() {
473            return bx.cx().const_poison(cast_to);
474        }
475
476        let (tag_scalar, tag_encoding, tag_field) = match self.layout.variants {
477            Variants::Empty => unreachable!("we already handled uninhabited types"),
478            Variants::Single { index } => {
479                let discr_val =
480                    if let Some(discr) = self.layout.ty.discriminant_for_variant(bx.tcx(), index) {
481                        discr.val
482                    } else {
483                        // This arm is for types which are neither enums nor coroutines,
484                        // and thus for which the only possible "variant" should be the first one.
485                        assert_eq!(index, FIRST_VARIANT);
486                        // There's thus no actual discriminant to return, so we return
487                        // what it would have been if this was a single-variant enum.
488                        0
489                    };
490                return bx.cx().const_uint_big(cast_to, discr_val);
491            }
492            Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => {
493                (tag, tag_encoding, tag_field)
494            }
495        };
496
497        // Read the tag/niche-encoded discriminant from memory.
498        let tag_op = match self.val {
499            OperandValue::ZeroSized => bug!(),
500            OperandValue::Immediate(_) | OperandValue::Pair(_, _) => {
501                self.extract_field(fx, bx, tag_field.as_usize())
502            }
503            OperandValue::Ref(place) => {
504                let tag = place.with_type(self.layout).project_field(bx, tag_field.as_usize());
505                bx.load_operand(tag)
506            }
507        };
508        let tag_imm = tag_op.immediate();
509
510        // Decode the discriminant (specifically if it's niche-encoded).
511        match *tag_encoding {
512            TagEncoding::Direct => {
513                let signed = match tag_scalar.primitive() {
514                    // We use `i1` for bytes that are always `0` or `1`,
515                    // e.g., `#[repr(i8)] enum E { A, B }`, but we can't
516                    // let LLVM interpret the `i1` as signed, because
517                    // then `i1 1` (i.e., `E::B`) is effectively `i8 -1`.
518                    Primitive::Int(_, signed) => !tag_scalar.is_bool() && signed,
519                    _ => false,
520                };
521                bx.intcast(tag_imm, cast_to, signed)
522            }
523            TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => {
524                // Cast to an integer so we don't have to treat a pointer as a
525                // special case.
526                let (tag, tag_llty) = match tag_scalar.primitive() {
527                    // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
528                    Primitive::Pointer(_) => {
529                        let t = bx.type_from_integer(dl.ptr_sized_integer());
530                        let tag = bx.ptrtoint(tag_imm, t);
531                        (tag, t)
532                    }
533                    _ => (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)),
534                };
535
536                // `layout_sanity_check` ensures that we only get here for cases where the discriminant
537                // value and the variant index match, since that's all `Niche` can encode.
538
539                let relative_max = niche_variants.last.as_u32() - niche_variants.start.as_u32();
540                let niche_start_const = bx.cx().const_uint_big(tag_llty, niche_start);
541
542                // We have a subrange `niche_start..=niche_end` inside `range`.
543                // If the value of the tag is inside this subrange, it's a
544                // "niche value", an increment of the discriminant. Otherwise it
545                // indicates the untagged variant.
546                // A general algorithm to extract the discriminant from the tag
547                // is:
548                // relative_tag = tag - niche_start
549                // is_niche = relative_tag <= (ule) relative_max
550                // discr = if is_niche {
551                //     cast(relative_tag) + niche_variants.start()
552                // } else {
553                //     untagged_variant
554                // }
555                // However, we will likely be able to emit simpler code.
556                let (is_niche, tagged_discr, delta) = if relative_max == 0 {
557                    // Best case scenario: only one tagged variant. This will
558                    // likely become just a comparison and a jump.
559                    // The algorithm is:
560                    // is_niche = tag == niche_start
561                    // discr = if is_niche {
562                    //     niche_start
563                    // } else {
564                    //     untagged_variant
565                    // }
566                    let is_niche = bx.icmp(IntPredicate::IntEQ, tag, niche_start_const);
567                    let tagged_discr =
568                        bx.cx().const_uint(cast_to, niche_variants.start.as_u32() as u64);
569                    (is_niche, tagged_discr, 0)
570                } else {
571                    // Thanks to parameter attributes and load metadata, LLVM already knows
572                    // the general valid range of the tag. It's possible, though, for there
573                    // to be an impossible value *in the middle*, which those ranges don't
574                    // communicate, so it's worth an `assume` to let the optimizer know.
575                    // Most importantly, this means when optimizing a variant test like
576                    // `SELECT(is_niche, complex, CONST) == CONST` it's ok to simplify that
577                    // to `!is_niche` because the `complex` part can't possibly match.
578                    //
579                    // This was previously asserted on `tagged_discr` below, where the
580                    // impossible value is more obvious, but that caused an intermediate
581                    // value to become multi-use and thus not optimize, so instead this
582                    // assumes on the original input which is always multi-use. See
583                    // <https://github.com/llvm/llvm-project/issues/134024#issuecomment-3131782555>
584                    //
585                    // FIXME: If we ever get range assume operand bundles in LLVM (so we
586                    // don't need the `icmp`s in the instruction stream any more), it
587                    // might be worth moving this back to being on the switch argument
588                    // where it's more obviously applicable.
589                    if niche_variants.contains(&untagged_variant)
590                        && bx.cx().sess().opts.optimize != OptLevel::No
591                    {
592                        let impossible = niche_start
593                            .wrapping_add(u128::from(untagged_variant.as_u32()))
594                            .wrapping_sub(u128::from(niche_variants.start.as_u32()));
595                        let impossible = bx.cx().const_uint_big(tag_llty, impossible);
596                        let ne = bx.icmp(IntPredicate::IntNE, tag, impossible);
597                        bx.assume(ne);
598                    }
599
600                    // With multiple niched variants we'll have to actually compute
601                    // the variant index from the stored tag.
602                    //
603                    // However, there's still one small optimization we can often do for
604                    // determining *whether* a tag value is a natural value or a niched
605                    // variant. The general algorithm involves a subtraction that often
606                    // wraps in practice, making it tricky to analyse. However, in cases
607                    // where there are few enough possible values of the tag that it doesn't
608                    // need to wrap around, we can instead just look for the contiguous
609                    // tag values on the end of the range with a single comparison.
610                    //
611                    // For example, take the type `enum Demo { A, B, Untagged(bool) }`.
612                    // The `bool` is {0, 1}, and the two other variants are given the
613                    // tags {2, 3} respectively. That means the `tag_range` is
614                    // `[0, 3]`, which doesn't wrap as unsigned (nor as signed), so
615                    // we can test for the niched variants with just `>= 2`.
616                    //
617                    // That means we're looking either for the niche values *above*
618                    // the natural values of the untagged variant:
619                    //
620                    //             niche_start                  niche_end
621                    //                  |                           |
622                    //                  v                           v
623                    // MIN -------------+---------------------------+---------- MAX
624                    //         ^        |         is niche          |
625                    //         |        +---------------------------+
626                    //         |                                    |
627                    //   tag_range.start                      tag_range.end
628                    //
629                    // Or *below* the natural values:
630                    //
631                    //    niche_start              niche_end
632                    //         |                       |
633                    //         v                       v
634                    // MIN ----+-----------------------+---------------------- MAX
635                    //         |       is niche        |           ^
636                    //         +-----------------------+           |
637                    //         |                                   |
638                    //   tag_range.start                      tag_range.end
639                    //
640                    // With those two options and having the flexibility to choose
641                    // between a signed or unsigned comparison on the tag, that
642                    // covers most realistic scenarios. The tests have a (contrived)
643                    // example of a 1-byte enum with over 128 niched variants which
644                    // wraps both as signed as unsigned, though, and for something
645                    // like that we're stuck with the general algorithm.
646
647                    let tag_range = tag_scalar.valid_range(&dl);
648                    let tag_size = tag_scalar.size(&dl);
649                    let niche_end = u128::from(relative_max).wrapping_add(niche_start);
650                    let niche_end = tag_size.truncate(niche_end);
651
652                    let relative_discr = bx.sub(tag, niche_start_const);
653                    let cast_tag = bx.intcast(relative_discr, cast_to, false);
654                    let is_niche = if tag_range.no_unsigned_wraparound(tag_size) == Ok(true) {
655                        if niche_start == tag_range.start {
656                            let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end);
657                            bx.icmp(IntPredicate::IntULE, tag, niche_end_const)
658                        } else {
659                            assert_eq!(niche_end, tag_range.end);
660                            bx.icmp(IntPredicate::IntUGE, tag, niche_start_const)
661                        }
662                    } else if tag_range.no_signed_wraparound(tag_size) == Ok(true) {
663                        if niche_start == tag_range.start {
664                            let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end);
665                            bx.icmp(IntPredicate::IntSLE, tag, niche_end_const)
666                        } else {
667                            assert_eq!(niche_end, tag_range.end);
668                            bx.icmp(IntPredicate::IntSGE, tag, niche_start_const)
669                        }
670                    } else {
671                        bx.icmp(
672                            IntPredicate::IntULE,
673                            relative_discr,
674                            bx.cx().const_uint(tag_llty, relative_max as u64),
675                        )
676                    };
677
678                    (is_niche, cast_tag, niche_variants.start.as_u32() as u128)
679                };
680
681                let tagged_discr = if delta == 0 {
682                    tagged_discr
683                } else {
684                    bx.add(tagged_discr, bx.cx().const_uint_big(cast_to, delta))
685                };
686
687                let untagged_variant_const =
688                    bx.cx().const_uint(cast_to, u64::from(untagged_variant.as_u32()));
689
690                let discr = bx.select(is_niche, tagged_discr, untagged_variant_const);
691
692                // In principle we could insert assumes on the possible range of `discr`, but
693                // currently in LLVM this isn't worth it because the original `tag` will
694                // have either a `range` parameter attribute or `!range` metadata,
695                // or come from a `transmute` that already `assume`d it.
696
697                discr
698            }
699        }
700    }
701}
702
703/// Each of these variants starts out as `Either::Right` when it's uninitialized,
704/// then setting the field changes that to `Either::Left` with the backend value.
705#[derive(#[automatically_derived]
impl<V: ::core::fmt::Debug> ::core::fmt::Debug for OperandValueBuilder<V> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::ZeroSized =>
                ::core::fmt::Formatter::write_str(f, "ZeroSized"),
            Self::Immediate(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Immediate", &__self_0),
            Self::Pair(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Pair",
                    __self_0, &__self_1),
            Self::Vector(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Vector",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<V: ::core::marker::Copy> ::core::marker::Copy for OperandValueBuilder<V>
    {
}Copy, #[automatically_derived]
impl<V: ::core::clone::Clone> ::core::clone::Clone for OperandValueBuilder<V>
    {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::ZeroSized => Self::ZeroSized,
            Self::Immediate(__self_0) =>
                Self::Immediate(::core::clone::Clone::clone(__self_0)),
            Self::Pair(__self_0, __self_1) =>
                Self::Pair(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            Self::Vector(__self_0) =>
                Self::Vector(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
706enum OperandValueBuilder<V> {
707    ZeroSized,
708    Immediate(Either<V, abi::Scalar>),
709    Pair(Either<V, abi::Scalar>, Either<V, abi::Scalar>),
710    /// `repr(simd)` types need special handling because they each have a non-empty
711    /// array field (which uses [`OperandValue::Ref`]) despite the SIMD type itself
712    /// using [`OperandValue::Immediate`] which for any other kind of type would
713    /// mean that its one non-ZST field would also be [`OperandValue::Immediate`].
714    Vector(Either<V, ()>),
715}
716
717/// Allows building up an `OperandRef` by setting fields one at a time.
718#[derive(#[automatically_derived]
impl<'tcx, V: ::core::fmt::Debug> ::core::fmt::Debug for
    OperandRefBuilder<'tcx, V> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "OperandRefBuilder", "val", &self.val, "layout", &&self.layout)
    }
}Debug, #[automatically_derived]
impl<'tcx, V: ::core::marker::Copy> ::core::marker::Copy for
    OperandRefBuilder<'tcx, V> {
}Copy, #[automatically_derived]
impl<'tcx, V: ::core::clone::Clone> ::core::clone::Clone for
    OperandRefBuilder<'tcx, V> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            val: ::core::clone::Clone::clone(&self.val),
            layout: ::core::clone::Clone::clone(&self.layout),
        }
    }
}Clone)]
719pub(super) struct OperandRefBuilder<'tcx, V> {
720    val: OperandValueBuilder<V>,
721    layout: TyAndLayout<'tcx>,
722}
723
724impl<'a, 'tcx, V: CodegenObject> OperandRefBuilder<'tcx, V> {
725    /// Creates an uninitialized builder for an instance of the `layout`.
726    ///
727    /// ICEs for [`BackendRepr::Memory`] types (other than ZSTs), which should
728    /// be built up inside a [`PlaceRef`] instead as they need an allocated place
729    /// into which to write the values of the fields.
730    pub(super) fn new(layout: TyAndLayout<'tcx>) -> Self {
731        let val = match layout.backend_repr {
732            BackendRepr::Memory { .. } if layout.is_zst() => OperandValueBuilder::ZeroSized,
733            BackendRepr::Scalar(s) => OperandValueBuilder::Immediate(Either::Right(s)),
734            BackendRepr::ScalarPair { a, b, b_offset: _ } => {
735                OperandValueBuilder::Pair(Either::Right(a), Either::Right(b))
736            }
737            BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => {
738                OperandValueBuilder::Vector(Either::Right(()))
739            }
740            BackendRepr::Memory { .. } => {
741                ::rustc_span::macros::bug_impl(None,
    format_args!("Cannot use non-ZST Memory-ABI type in operand builder: {0:?}",
        layout), Location::caller());bug!("Cannot use non-ZST Memory-ABI type in operand builder: {layout:?}");
742            }
743        };
744        OperandRefBuilder { val, layout }
745    }
746
747    /// Creates an initialized builder for updating an existing `operand`.
748    ///
749    /// ICEs for [`BackendRepr::Memory`] types (other than ZSTs), which use
750    /// which use [`OperandValue::Ref`]. In this case, updates should be
751    /// performed by writing into the place
752    pub(super) fn from_existing(operand: OperandRef<'tcx, V>) -> Self {
753        let layout = operand.layout;
754        let val = match (operand.val, layout.backend_repr) {
755            (OperandValue::ZeroSized, _) => OperandValueBuilder::ZeroSized,
756            (OperandValue::Immediate(v), BackendRepr::Scalar(_)) => {
757                OperandValueBuilder::Immediate(Either::Left(v))
758            }
759            (OperandValue::Immediate(v), BackendRepr::SimdVector { .. }) => {
760                OperandValueBuilder::Vector(Either::Left(v))
761            }
762            (OperandValue::Pair(a, b), BackendRepr::ScalarPair { a: _, b: _, b_offset: _ }) => {
763                OperandValueBuilder::Pair(Either::Left(a), Either::Left(b))
764            }
765            (_, BackendRepr::Memory { .. }) => {
766                ::rustc_span::macros::bug_impl(None,
    format_args!("Cannot use non-ZST Memory-ABI type in operand builder: {0:?}",
        layout), Location::caller());bug!("Cannot use non-ZST Memory-ABI type in operand builder: {layout:?}");
767            }
768            _ => {
769                ::rustc_span::macros::bug_impl(None,
    format_args!("Operand cannot be used with `from_existing`: {0:?}",
        operand), Location::caller())bug!("Operand cannot be used with `from_existing`: {operand:?}")
770            }
771        };
772        OperandRefBuilder { val, layout }
773    }
774
775    pub(super) fn insert_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
776        &mut self,
777        bx: &mut Bx,
778        variant: VariantIdx,
779        field: FieldIdx,
780        field_operand: OperandRef<'tcx, V>,
781    ) {
782        if let OperandValue::ZeroSized = field_operand.val {
783            // A ZST never adds any state, so just ignore it.
784            // This special-casing is worth it because of things like
785            // `Result<!, !>` where `Ok(never)` is legal to write,
786            // but the type shows as FieldShape::Primitive so we can't
787            // actually look at the layout for the field being set.
788            return;
789        }
790
791        let is_zero_offset = if let abi::FieldsShape::Primitive = self.layout.fields {
792            // The other branch looking at field layouts ICEs for primitives,
793            // so we need to handle them separately.
794            // Because we handled ZSTs above (like the metadata in a thin pointer),
795            // the only possibility is that we're setting the one-and-only field.
796            if !!self.layout.is_zst() {
    ::core::panicking::panic("assertion failed: !self.layout.is_zst()")
};assert!(!self.layout.is_zst());
797            {
    match (&variant, &FIRST_VARIANT) {
        (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!(variant, FIRST_VARIANT);
798            {
    match (&field, &FieldIdx::ZERO) {
        (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!(field, FieldIdx::ZERO);
799            true
800        } else {
801            let variant_layout = self.layout.for_variant(bx.cx(), variant);
802            let field_offset = variant_layout.fields.offset(field.as_usize());
803            field_offset == Size::ZERO
804        };
805
806        let mut update = |tgt: &mut Either<V, abi::Scalar>, src, from_scalar| {
807            let to_scalar = tgt.unwrap_right();
808            // We transmute here (rather than just `from_immediate`) because in
809            // `Result<usize, *const ()>` the field of the `Ok` is an integer,
810            // but the corresponding scalar in the enum is a pointer.
811            let imm = transmute_scalar(bx, src, from_scalar, to_scalar);
812            *tgt = Either::Left(imm);
813        };
814
815        match (field_operand.val, field_operand.layout.backend_repr) {
816            (OperandValue::ZeroSized, _) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Handled above")));
}unreachable!("Handled above"),
817            (OperandValue::Immediate(v), BackendRepr::Scalar(from_scalar)) => match &mut self.val {
818                OperandValueBuilder::Immediate(val @ Either::Right(_)) if is_zero_offset => {
819                    update(val, v, from_scalar);
820                }
821                OperandValueBuilder::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
822                    update(fst, v, from_scalar);
823                }
824                OperandValueBuilder::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
825                    update(snd, v, from_scalar);
826                }
827                _ => {
828                    ::rustc_span::macros::bug_impl(None,
    format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
        field_operand, variant, field, self), Location::caller())bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")
829                }
830            },
831            (OperandValue::Immediate(v), BackendRepr::SimdVector { .. }) => match &mut self.val {
832                OperandValueBuilder::Vector(val @ Either::Right(())) if is_zero_offset => {
833                    *val = Either::Left(v);
834                }
835                _ => {
836                    ::rustc_span::macros::bug_impl(None,
    format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
        field_operand, variant, field, self), Location::caller())bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")
837                }
838            },
839            (
840                OperandValue::Pair(a, b),
841                BackendRepr::ScalarPair { a: from_sa, b: from_sb, b_offset: _ },
842            ) => match &mut self.val {
843                OperandValueBuilder::Pair(fst @ Either::Right(_), snd @ Either::Right(_)) => {
844                    update(fst, a, from_sa);
845                    update(snd, b, from_sb);
846                }
847                _ => {
848                    ::rustc_span::macros::bug_impl(None,
    format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
        field_operand, variant, field, self), Location::caller())bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")
849                }
850            },
851            (OperandValue::Ref(place), BackendRepr::Memory { .. }) => match &mut self.val {
852                OperandValueBuilder::Vector(val @ Either::Right(())) => {
853                    let ibty = bx.cx().immediate_backend_type(self.layout);
854                    let simd = bx.load_from_place(ibty, place);
855                    *val = Either::Left(simd);
856                }
857                _ => {
858                    ::rustc_span::macros::bug_impl(None,
    format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
        field_operand, variant, field, self), Location::caller())bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")
859                }
860            },
861            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("Operand cannot be used with `insert_field`: {0:?}",
        field_operand), Location::caller())bug!("Operand cannot be used with `insert_field`: {field_operand:?}"),
862        }
863    }
864
865    /// Insert the immediate value `imm` for field `f` in the *type itself*,
866    /// rather than into one of the variants.
867    ///
868    /// Most things want [`Self::insert_field`] instead, but this one is
869    /// necessary for writing things like enum tags that aren't in any variant.
870    pub(super) fn insert_imm(&mut self, f: FieldIdx, imm: V) {
871        let field_offset = self.layout.fields.offset(f.as_usize());
872        let is_zero_offset = field_offset == Size::ZERO;
873        match &mut self.val {
874            OperandValueBuilder::Immediate(val @ Either::Right(_)) if is_zero_offset => {
875                *val = Either::Left(imm);
876            }
877            OperandValueBuilder::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
878                *fst = Either::Left(imm);
879            }
880            OperandValueBuilder::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
881                *snd = Either::Left(imm);
882            }
883            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("Tried to insert {0:?} into field {1:?} of {2:?}", imm, f,
        self), Location::caller())bug!("Tried to insert {imm:?} into field {f:?} of {self:?}"),
884        }
885    }
886
887    /// Replaces the current immediate value at the offset `offset`
888    /// with the value `imm`. A value must already be present.
889    ///
890    /// This is used along with [`Self::from_existing`] to perform in-place updates
891    /// of any operand.
892    pub(super) fn update_imm(&mut self, offset: Size, imm: V) {
893        let is_zero_offset = offset == Size::ZERO;
894        match &mut self.val {
895            OperandValueBuilder::Immediate(val @ Either::Left(_)) if is_zero_offset => {
896                *val = Either::Left(imm);
897            }
898            OperandValueBuilder::Pair(fst @ Either::Left(_), _) if is_zero_offset => {
899                *fst = Either::Left(imm);
900            }
901            OperandValueBuilder::Pair(_, snd @ Either::Left(_)) if !is_zero_offset => {
902                *snd = Either::Left(imm);
903            }
904            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("Tried to update {0:?} at offset {1:?} of {2:?}", imm,
        offset, self), Location::caller())bug!("Tried to update {imm:?} at offset {offset:?} of {self:?}"),
905        }
906    }
907
908    /// After having set all necessary fields, this converts the builder back
909    /// to the normal `OperandRef`.
910    ///
911    /// ICEs if any required fields were not set.
912    pub(super) fn build(&self, cx: &impl CodegenMethods<'tcx, Value = V>) -> OperandRef<'tcx, V> {
913        let OperandRefBuilder { val, layout } = *self;
914
915        // For something like `Option::<u32>::None`, it's expected that the
916        // payload scalar will not actually have been set, so this converts
917        // unset scalars to corresponding `undef` values so long as the scalar
918        // from the layout allows uninit.
919        let unwrap = |r: Either<V, abi::Scalar>| match r {
920            Either::Left(v) => v,
921            Either::Right(s) if s.is_uninit_valid() => {
922                let bty = cx.type_from_scalar(s);
923                cx.const_undef(bty)
924            }
925            Either::Right(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("OperandRef::build called while fields are missing {0:?}",
        self), Location::caller())bug!("OperandRef::build called while fields are missing {self:?}"),
926        };
927
928        let val = match val {
929            OperandValueBuilder::ZeroSized => OperandValue::ZeroSized,
930            OperandValueBuilder::Immediate(v) => OperandValue::Immediate(unwrap(v)),
931            OperandValueBuilder::Pair(a, b) => OperandValue::Pair(unwrap(a), unwrap(b)),
932            OperandValueBuilder::Vector(v) => match v {
933                Either::Left(v) => OperandValue::Immediate(v),
934                Either::Right(())
935                    if let BackendRepr::SimdVector { element, .. } = layout.backend_repr
936                        && element.is_uninit_valid() =>
937                {
938                    let bty = cx.immediate_backend_type(layout);
939                    OperandValue::Immediate(cx.const_undef(bty))
940                }
941                Either::Right(()) => {
942                    ::rustc_span::macros::bug_impl(None,
    format_args!("OperandRef::build called while fields are missing {0:?}",
        self), Location::caller())bug!("OperandRef::build called while fields are missing {self:?}")
943                }
944            },
945        };
946        OperandRef { val, layout, move_annotation: None }
947    }
948}
949
950/// Default size limit for move/copy annotations (in bytes). 64 bytes is a common size of a cache
951/// line, and the assumption is that anything this size or below is very cheap to move/copy, so only
952/// annotate copies larger than this.
953const MOVE_ANNOTATION_DEFAULT_LIMIT: u64 = 65;
954
955impl<'a, 'tcx, V: CodegenObject> OperandValue<V> {
956    /// Returns an `OperandValue` that's generally UB to use in any way.
957    ///
958    /// Depending on the `layout`, returns `ZeroSized` for ZSTs, an `Immediate` or
959    /// `Pair` containing poison value(s), or a `Ref` containing a poison pointer.
960    ///
961    /// Supports sized types only.
962    pub fn poison<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
963        bx: &mut Bx,
964        layout: TyAndLayout<'tcx>,
965    ) -> OperandValue<V> {
966        if !layout.is_sized() {
    ::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
967        match layout.backend_repr {
968            _ if layout.is_zst() => OperandValue::ZeroSized,
969            BackendRepr::Scalar(_)
970            | BackendRepr::SimdVector { .. }
971            | BackendRepr::SimdScalableVector { .. } => {
972                let ibty = bx.cx().immediate_backend_type(layout);
973                OperandValue::Immediate(bx.const_poison(ibty))
974            }
975            BackendRepr::ScalarPair { .. } => {
976                let ibty0 = bx.cx().scalar_pair_element_backend_type(layout, 0, true);
977                let ibty1 = bx.cx().scalar_pair_element_backend_type(layout, 1, true);
978                OperandValue::Pair(bx.const_poison(ibty0), bx.const_poison(ibty1))
979            }
980            BackendRepr::Memory { .. } => {
981                let ptr = bx.cx().type_ptr();
982                OperandValue::Ref(PlaceValue::new_sized(bx.const_poison(ptr), layout.align.abi))
983            }
984        }
985    }
986
987    pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
988        self,
989        bx: &mut Bx,
990        dest: PlaceRef<'tcx, V>,
991    ) {
992        self.store_with_flags(bx, dest, MemFlags::empty());
993    }
994
995    pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
996        self,
997        bx: &mut Bx,
998        dest: PlaceRef<'tcx, V>,
999    ) {
1000        self.store_with_flags(bx, dest, MemFlags::VOLATILE);
1001    }
1002
1003    pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
1004        self,
1005        bx: &mut Bx,
1006        dest: PlaceRef<'tcx, V>,
1007    ) {
1008        self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
1009    }
1010
1011    pub(crate) fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
1012        self,
1013        bx: &mut Bx,
1014        dest: PlaceRef<'tcx, V>,
1015        flags: MemFlags,
1016    ) {
1017        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs:1017",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(1017u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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!("OperandRef::store: operand={0:?}, dest={1:?}",
                                                    self, dest) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
1018        match self {
1019            OperandValue::ZeroSized => {
1020                // Avoid generating stores of zero-sized values, because the only way to have a
1021                // zero-sized value is through `undef`/`poison`, and the store itself is useless.
1022            }
1023            OperandValue::Ref(val) => {
1024                if !dest.layout.is_sized() {
    {
        ::core::panicking::panic_fmt(format_args!("cannot directly store unsized values"));
    }
};assert!(dest.layout.is_sized(), "cannot directly store unsized values");
1025                if val.llextra.is_some() {
1026                    ::rustc_span::macros::bug_impl(None,
    format_args!("cannot directly store unsized values"), Location::caller());bug!("cannot directly store unsized values");
1027                }
1028                bx.typed_place_copy_with_flags(dest.val, val, dest.layout, flags);
1029            }
1030            OperandValue::Immediate(s) => {
1031                let val = bx.from_immediate(s);
1032                bx.store_with_flags(val, dest.val.llval, dest.val.align, flags);
1033            }
1034            OperandValue::Pair(a, b) => {
1035                let BackendRepr::ScalarPair { a: _, b: _, b_offset } = dest.layout.backend_repr
1036                else {
1037                    ::rustc_span::macros::bug_impl(None,
    format_args!("store_with_flags: invalid ScalarPair layout: {0:#?}",
        dest.layout), Location::caller());bug!("store_with_flags: invalid ScalarPair layout: {:#?}", dest.layout);
1038                };
1039
1040                let val = bx.from_immediate(a);
1041                let align = dest.val.align;
1042                bx.store_with_flags(val, dest.val.llval, align, flags);
1043
1044                let llptr = bx.inbounds_ptradd(dest.val.llval, bx.const_usize(b_offset.bytes()));
1045                let val = bx.from_immediate(b);
1046                let align = dest.val.align.restrict_for_offset(b_offset);
1047                // The CAPTURES_READ_ONLY flag only applies to the first element.
1048                bx.store_with_flags(val, llptr, align, flags & !MemFlags::CAPTURES_READ_ONLY);
1049            }
1050        }
1051    }
1052}
1053
1054impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
1055    fn maybe_codegen_consume_direct(
1056        &mut self,
1057        bx: &mut Bx,
1058        place_ref: mir::PlaceRef<'tcx>,
1059    ) -> Option<OperandRef<'tcx, Bx::Value>> {
1060        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs:1060",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(1060u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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!("maybe_codegen_consume_direct(place_ref={0:?})",
                                                    place_ref) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("maybe_codegen_consume_direct(place_ref={:?})", place_ref);
1061
1062        match self.locals[place_ref.local] {
1063            LocalRef::Operand(mut o) => {
1064                // We only need to handle the projections that
1065                // `LocalAnalyzer::process_place` let make it here.
1066                for elem in place_ref.projection {
1067                    match *elem {
1068                        mir::ProjectionElem::Field(f, _) => {
1069                            if !!o.layout.ty.is_any_ptr() {
    {
        ::core::panicking::panic_fmt(format_args!("Bad PlaceRef: destructing pointers should use cast/PtrMetadata, but tried to access field {0:?} of pointer {1:?}",
                f, o));
    }
};assert!(
1070                                !o.layout.ty.is_any_ptr(),
1071                                "Bad PlaceRef: destructing pointers should use cast/PtrMetadata, \
1072                                 but tried to access field {f:?} of pointer {o:?}",
1073                            );
1074                            o = o.extract_field(self, bx, f.index());
1075                        }
1076                        mir::PlaceElem::Downcast(_, vidx) => {
1077                            if true {
    {
        match (&o.layout.variants, &abi::Variants::Single { index: vidx }) {
            (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!(
1078                                o.layout.variants,
1079                                abi::Variants::Single { index: vidx },
1080                            );
1081                            let layout = o.layout.for_variant(bx.cx(), vidx);
1082                            o = OperandRef { layout, ..o }
1083                        }
1084                        _ => return None,
1085                    }
1086                }
1087
1088                Some(o)
1089            }
1090            LocalRef::PendingOperand => {
1091                ::rustc_span::macros::bug_impl(None,
    format_args!("use of {0:?} before def", place_ref), Location::caller());bug!("use of {:?} before def", place_ref);
1092            }
1093            LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
1094                // watch out for locals that do not have an
1095                // alloca; they are handled somewhat differently
1096                None
1097            }
1098        }
1099    }
1100
1101    pub fn codegen_consume(
1102        &mut self,
1103        bx: &mut Bx,
1104        place_ref: mir::PlaceRef<'tcx>,
1105    ) -> OperandRef<'tcx, Bx::Value> {
1106        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs:1106",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(1106u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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_consume(place_ref={0:?})",
                                                    place_ref) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("codegen_consume(place_ref={:?})", place_ref);
1107
1108        let ty = self.monomorphized_place_ty(place_ref);
1109        let layout = bx.cx().layout_of(ty);
1110
1111        // ZSTs don't require any actual memory access.
1112        if layout.is_zst() {
1113            return OperandRef::zero_sized(layout);
1114        }
1115
1116        if let Some(o) = self.maybe_codegen_consume_direct(bx, place_ref) {
1117            return o;
1118        }
1119
1120        // for most places, to consume them we just load them
1121        // out from their home
1122        let place = self.codegen_place(bx, place_ref);
1123        bx.load_operand(place)
1124    }
1125
1126    pub fn codegen_operand(
1127        &mut self,
1128        bx: &mut Bx,
1129        operand: &mir::Operand<'tcx>,
1130    ) -> OperandRef<'tcx, Bx::Value> {
1131        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs:1131",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(1131u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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_operand(operand={0:?})",
                                                    operand) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("codegen_operand(operand={:?})", operand);
1132
1133        match *operand {
1134            mir::Operand::Copy(ref place) | mir::Operand::Move(ref place) => {
1135                let kind = match operand {
1136                    mir::Operand::Move(_) => LangItem::CompilerMove,
1137                    mir::Operand::Copy(_) => LangItem::CompilerCopy,
1138                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1139                };
1140
1141                // Check if we should annotate this move/copy for profiling
1142                let move_annotation = self.move_copy_annotation_instance(bx, place.as_ref(), kind);
1143
1144                OperandRef { move_annotation, ..self.codegen_consume(bx, place.as_ref()) }
1145            }
1146
1147            mir::Operand::RuntimeChecks(checks) => {
1148                let layout = bx.layout_of(bx.tcx().types.bool);
1149                let BackendRepr::Scalar(scalar) = layout.backend_repr else {
1150                    ::rustc_span::macros::bug_impl(None,
    format_args!("from_const: invalid ByVal layout: {0:#?}", layout),
    Location::caller());bug!("from_const: invalid ByVal layout: {:#?}", layout);
1151                };
1152                let x = Scalar::from_bool(checks.value(bx.tcx().sess));
1153                let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
1154                let val = OperandValue::Immediate(llval);
1155                OperandRef { val, layout, move_annotation: None }
1156            }
1157
1158            mir::Operand::Constant(ref constant) => {
1159                let constant_ty = self.monomorphize(constant.ty());
1160                // Most SIMD vector constants should be passed as immediates.
1161                // (In particular, some intrinsics really rely on this.)
1162                if constant_ty.is_simd() {
1163                    // However, some SIMD types do not actually use the vector ABI
1164                    // (in particular, packed SIMD types do not). Ensure we exclude those.
1165                    //
1166                    // We also have to exclude vectors of pointers because `immediate_const_vector`
1167                    // does not work for those.
1168                    let layout = bx.layout_of(constant_ty);
1169                    let (_, element_ty) = constant_ty.simd_size_and_type(bx.tcx());
1170                    if let BackendRepr::SimdVector { .. } = layout.backend_repr
1171                        && element_ty.is_numeric()
1172                    {
1173                        let (llval, ty) = self.immediate_const_vector(bx, constant);
1174                        return OperandRef {
1175                            val: OperandValue::Immediate(llval),
1176                            layout: bx.layout_of(ty),
1177                            move_annotation: None,
1178                        };
1179                    }
1180                }
1181                self.eval_mir_constant_to_operand(bx, constant)
1182            }
1183        }
1184    }
1185
1186    /// Creates an `Instance` for annotating a move/copy operation at codegen time.
1187    ///
1188    /// Returns `Some(instance)` if the operation should be annotated with debug info, `None`
1189    /// otherwise. The instance represents a monomorphized `compiler_move<T, SIZE>` or
1190    /// `compiler_copy<T, SIZE>` function that can be used to create debug scopes.
1191    ///
1192    /// There are a number of conditions that must be met for an annotation to be created, but aside
1193    /// from the basics (annotation is enabled, we're generating debuginfo), the primary concern is
1194    /// moves/copies which could result in a real `memcpy`. So we check for the size limit, but also
1195    /// that the underlying representation of the type is in memory.
1196    fn move_copy_annotation_instance(
1197        &self,
1198        bx: &Bx,
1199        place: mir::PlaceRef<'tcx>,
1200        kind: LangItem,
1201    ) -> Option<ty::Instance<'tcx>> {
1202        let tcx = bx.tcx();
1203        let sess = tcx.sess;
1204
1205        // Skip if we're not generating debuginfo
1206        if sess.opts.debuginfo == DebugInfo::None {
1207            return None;
1208        }
1209
1210        // Check if annotation is enabled and get size limit (otherwise skip)
1211        let size_limit = match sess.opts.unstable_opts.annotate_moves {
1212            AnnotateMoves::Disabled => return None,
1213            AnnotateMoves::Enabled(None) => MOVE_ANNOTATION_DEFAULT_LIMIT,
1214            AnnotateMoves::Enabled(Some(limit)) => limit,
1215        };
1216
1217        let ty = self.monomorphized_place_ty(place);
1218        let layout = bx.cx().layout_of(ty);
1219        let ty_size = layout.size.bytes();
1220
1221        // Only annotate if type has a memory representation and exceeds size limit (and has a
1222        // non-zero size)
1223        if layout.is_zst()
1224            || ty_size < size_limit
1225            || !#[allow(non_exhaustive_omitted_patterns)] match layout.backend_repr {
    BackendRepr::Memory { .. } => true,
    _ => false,
}matches!(layout.backend_repr, BackendRepr::Memory { .. })
1226        {
1227            return None;
1228        }
1229
1230        // Look up the DefId for compiler_move or compiler_copy lang item
1231        let def_id = tcx.lang_items().get(kind)?;
1232
1233        // Create generic args: compiler_move<T, SIZE> or compiler_copy<T, SIZE>
1234        let size_const = ty::Const::from_target_usize(tcx, ty_size);
1235        let generic_args = tcx.mk_args(&[ty.into(), size_const.into()]);
1236
1237        // Create the Instance
1238        let typing_env = self.mir.typing_env(tcx);
1239        let instance = ty::Instance::expect_resolve(
1240            tcx,
1241            typing_env,
1242            def_id,
1243            generic_args,
1244            rustc_span::DUMMY_SP, // span only used for error messages
1245        );
1246
1247        Some(instance)
1248    }
1249}