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