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::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};
1718use super::place::{PlaceRef, PlaceValue};
19use super::rvalue::transmute_scalar;
20use super::{FunctionCx, LocalRef};
21use crate::MemFlags;
22use crate::common::IntPredicate;
23use crate::traits::*;
2425/// 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
47Ref(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.
64Immediate(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`].
80Pair(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.
89ZeroSized,
90}
9192impl<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.
95pub(crate) fn try_pointer_parts(self) -> Option<(V, Option<V>)> {
96match 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 }
102103/// 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.
107pub(crate) fn pointer_parts(self) -> (V, Option<V>) {
108self.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 }
111112/// 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`].
119pub(crate) fn deref(self, align: Align) -> PlaceValue<V> {
120let (llval, llextra) = self.pointer_parts();
121PlaceValue { llval, llextra, align }
122 }
123124#[must_use]
125pub(crate) fn is_expected_variant_for_type<'tcx>(&self, ty: TyAndLayout<'tcx>) -> bool {
126match (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}
140141/// 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.
152pub val: OperandValue<V>,
153154/// The layout of value, based on its Rust type.
155pub layout: TyAndLayout<'tcx>,
156157/// Annotation for profiler visibility of move/copy operations.
158 /// When set, the store operation should appear as an inlined call to this function.
159pub move_annotation: Option<ty::Instance<'tcx>>,
160}
161162impl<V: CodegenObject> fmt::Debugfor OperandRef<'_, V> {
163fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164f.write_fmt(format_args!("OperandRef({0:?} @ {1:?})", self.val, self.layout))write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)165 }
166}
167168impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
169pub fn zero_sized(layout: TyAndLayout<'tcx>) -> OperandRef<'tcx, V> {
170if !layout.is_zst() {
::core::panicking::panic("assertion failed: layout.is_zst()")
};assert!(layout.is_zst());
171OperandRef { val: OperandValue::ZeroSized, layout, move_annotation: None }
172 }
173174pub(crate) fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
175 bx: &mut Bx,
176 val: mir::ConstValue,
177 ty: Ty<'tcx>,
178 ) -> Self {
179let layout = bx.layout_of(ty);
180181let val = match val {
182 ConstValue::Scalar(x) => {
183let 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 };
186let 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 } => {
191let BackendRepr::ScalarPair { a: a_scalar, b: _, b_offset: _ } =
192layout.backend_repr
193else {
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 };
196let a = Scalar::from_pointer(Pointer::new(alloc_id.into(), Size::ZERO), &bx.tcx());
197let a_llval = bx.scalar_to_backend(
198a,
199a_scalar,
200bx.scalar_pair_element_backend_type(layout, 0, true),
201 );
202let b_llval = bx.const_usize(meta);
203 OperandValue::Pair(a_llval, b_llval)
204 }
205 ConstValue::Indirect { alloc_id, offset } => {
206let alloc = bx.tcx().global_alloc(alloc_id).unwrap_memory();
207return Self::from_const_alloc(bx, layout, alloc, offset);
208 }
209 };
210211OperandRef { val, layout, move_annotation: None }
212 }
213214fn 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 {
220let alloc_align = alloc.inner().align;
221if !(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);
222223let read_scalar = |start, size, s: abi::Scalar, ty| {
224match alloc.0.read_scalar(
225bx,
226alloc_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 ) {
229Ok(val) => bx.scalar_to_backend(val, s, ty),
230Err(_) => bx.const_poison(ty),
231 }
232 };
233234// 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`).
240match layout.backend_repr {
241 BackendRepr::Scalar(s @ abi::Scalar::Initialized { .. }) => {
242let 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");
244let val = read_scalar(offset, size, s, bx.immediate_backend_type(layout));
245OperandRef { 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 } => {
252let (a_size, b_size) = (a.size(bx), b.size(bx));
253let alloc_b_offset = offset + local_b_offset;
254if !(alloc_b_offset.bytes() > 0) {
::core::panicking::panic("assertion failed: alloc_b_offset.bytes() > 0")
};assert!(alloc_b_offset.bytes() > 0);
255let a_val = read_scalar(
256offset,
257a_size,
258a,
259bx.scalar_pair_element_backend_type(layout, 0, true),
260 );
261let b_val = read_scalar(
262alloc_b_offset,
263b_size,
264b,
265bx.scalar_pair_element_backend_type(layout, 1, true),
266 );
267OperandRef { 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
272let base_addr = bx.static_addr_of(alloc, None);
273274let llval = bx.const_ptr_byte_offset(base_addr, offset);
275bx.load_operand(PlaceRef::new_sized(llval, layout))
276 }
277 }
278 }
279280/// Asserts that this operand refers to a scalar and returns
281 /// a reference to its value.
282pub fn immediate(self) -> V {
283match 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 }
288289/// 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`].
298pub fn deref<Cx: CodegenMethods<'tcx>>(self, cx: &Cx) -> PlaceRef<'tcx, V> {
299if 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 }
303304let projected_ty = self305 .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));
309310let layout = cx.layout_of(projected_ty);
311self.val.deref(layout.align.abi).with_type(layout)
312 }
313314/// 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.
318pub fn store_with_annotation<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
319self,
320 bx: &mut Bx,
321 dest: PlaceRef<'tcx, V>,
322 ) {
323self.store_with_annotation_and_flags(bx, dest, MemFlags::empty())
324 }
325326/// Same as store_with_annotation(), but also specify flags for the store.
327pub fn store_with_annotation_and_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
328self,
329 bx: &mut Bx,
330 dest: PlaceRef<'tcx, V>,
331 flags: MemFlags,
332 ) {
333if let Some(instance) = self.move_annotation {
334bx.with_move_annotation(instance, |bx| self.val.store_with_flags(bx, dest, flags))
335 } else {
336self.val.store_with_flags(bx, dest, flags)
337 }
338 }
339340/// 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.
345pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
346self,
347 bx: &mut Bx,
348 ) -> V {
349if let OperandValue::Pair(a, b) = self.val {
350let 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.
353let mut llpair = bx.cx().const_poison(llty);
354llpair = bx.insert_value(llpair, a, 0);
355llpair = bx.insert_value(llpair, b, 1);
356llpair357 } else {
358self.immediate()
359 }
360 }
361362/// 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.
366pub 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 {
371let 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);
373374// Deconstruct the immediate aggregate.
375let a_llval = bx.extract_value(llval, 0);
376let b_llval = bx.extract_value(llval, 1);
377 OperandValue::Pair(a_llval, b_llval)
378 } else {
379 OperandValue::Immediate(llval)
380 };
381OperandRef { val, layout, move_annotation: None }
382 }
383384pub(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 {
390let field = self.layout.field(bx.cx(), i);
391let offset = self.layout.fields.offset(i);
392393if 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 }
400401let val = if field.is_zst() {
402 OperandValue::ZeroSized403 } 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);
405fx.codegen_transmute_operand(bx, *self, field)
406 } else {
407let (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 ) => {
413if 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 }
422423_ => {
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) => {
430let Some(in_scalar) = in_scalarelse {
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",
434self
435)436 };
437if 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.
442let backend = bx.from_immediate(imm);
443bx.to_immediate_scalar(backend, out_scalar)
444 } else {
445imm446 }
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 };
453454OperandRef { val, layout: field, move_annotation: None }
455 }
456457/// 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))]459pub fn codegen_get_discr<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
460self,
461 fx: &mut FunctionCx<'a, 'tcx, Bx>,
462 bx: &mut Bx,
463 cast_to: Ty<'tcx>,
464 ) -> V {
465let dl = &bx.tcx().data_layout;
466let cast_to_layout = bx.cx().layout_of(cast_to);
467let cast_to = bx.cx().immediate_backend_type(cast_to_layout);
468469// We check uninhabitedness separately because a type like
470 // `enum Foo { Bar(i32, !) }` is still reported as `Variants::Single`,
471 // *not* as `Variants::Empty`.
472if self.layout.is_uninhabited() {
473return bx.cx().const_poison(cast_to);
474 }
475476let (tag_scalar, tag_encoding, tag_field) = match self.layout.variants {
477 Variants::Empty => unreachable!("we already handled uninhabited types"),
478 Variants::Single { index } => {
479let discr_val =
480if 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.
485assert_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.
4880
489};
490return 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 };
496497// Read the tag/niche-encoded discriminant from memory.
498let tag_op = match self.val {
499 OperandValue::ZeroSized => bug!(),
500 OperandValue::Immediate(_) | OperandValue::Pair(_, _) => {
501self.extract_field(fx, bx, tag_field.as_usize())
502 }
503 OperandValue::Ref(place) => {
504let tag = place.with_type(self.layout).project_field(bx, tag_field.as_usize());
505 bx.load_operand(tag)
506 }
507 };
508let tag_imm = tag_op.immediate();
509510// Decode the discriminant (specifically if it's niche-encoded).
511match *tag_encoding {
512 TagEncoding::Direct => {
513let 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`.
518Primitive::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.
526let (tag, tag_llty) = match tag_scalar.primitive() {
527// FIXME(erikdesjardins): handle non-default addrspace ptr sizes
528Primitive::Pointer(_) => {
529let t = bx.type_from_integer(dl.ptr_sized_integer());
530let tag = bx.ptrtoint(tag_imm, t);
531 (tag, t)
532 }
533_ => (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)),
534 };
535536// `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.
538539let relative_max = niche_variants.last.as_u32() - niche_variants.start.as_u32();
540let niche_start_const = bx.cx().const_uint_big(tag_llty, niche_start);
541542// 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.
556let (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 // }
566let is_niche = bx.icmp(IntPredicate::IntEQ, tag, niche_start_const);
567let 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.
589if niche_variants.contains(&untagged_variant)
590 && bx.cx().sess().opts.optimize != OptLevel::No
591 {
592let impossible = niche_start
593 .wrapping_add(u128::from(untagged_variant.as_u32()))
594 .wrapping_sub(u128::from(niche_variants.start.as_u32()));
595let impossible = bx.cx().const_uint_big(tag_llty, impossible);
596let ne = bx.icmp(IntPredicate::IntNE, tag, impossible);
597 bx.assume(ne);
598 }
599600// 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.
646647let tag_range = tag_scalar.valid_range(&dl);
648let tag_size = tag_scalar.size(&dl);
649let niche_end = u128::from(relative_max).wrapping_add(niche_start);
650let niche_end = tag_size.truncate(niche_end);
651652let relative_discr = bx.sub(tag, niche_start_const);
653let cast_tag = bx.intcast(relative_discr, cast_to, false);
654let is_niche = if tag_range.no_unsigned_wraparound(tag_size) == Ok(true) {
655if niche_start == tag_range.start {
656let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end);
657 bx.icmp(IntPredicate::IntULE, tag, niche_end_const)
658 } else {
659assert_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) {
663if niche_start == tag_range.start {
664let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end);
665 bx.icmp(IntPredicate::IntSLE, tag, niche_end_const)
666 } else {
667assert_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 };
677678 (is_niche, cast_tag, niche_variants.start.as_u32() as u128)
679 };
680681let tagged_discr = if delta == 0 {
682 tagged_discr
683 } else {
684 bx.add(tagged_discr, bx.cx().const_uint_big(cast_to, delta))
685 };
686687let untagged_variant_const =
688 bx.cx().const_uint(cast_to, u64::from(untagged_variant.as_u32()));
689690let discr = bx.select(is_niche, tagged_discr, untagged_variant_const);
691692// 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.
696697discr
698 }
699 }
700 }
701}
702703/// 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`].
714Vector(Either<V, ()>),
715}
716717/// 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}
723724impl<'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.
730pub(super) fn new(layout: TyAndLayout<'tcx>) -> Self {
731let 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 };
744OperandRefBuilder { val, layout }
745 }
746747/// 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
752pub(super) fn from_existing(operand: OperandRef<'tcx, V>) -> Self {
753let layout = operand.layout;
754let 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 };
772OperandRefBuilder { val, layout }
773 }
774775pub(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 ) {
782if 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.
788return;
789 }
790791let 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.
796if !!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);
799true
800} else {
801let variant_layout = self.layout.for_variant(bx.cx(), variant);
802let field_offset = variant_layout.fields.offset(field.as_usize());
803field_offset == Size::ZERO804 };
805806let mut update = |tgt: &mut Either<V, abi::Scalar>, src, from_scalar| {
807let 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.
811let imm = transmute_scalar(bx, src, from_scalar, to_scalar);
812*tgt = Either::Left(imm);
813 };
814815match (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 => {
819update(val, v, from_scalar);
820 }
821 OperandValueBuilder::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
822update(fst, v, from_scalar);
823 }
824 OperandValueBuilder::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
825update(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(_)) => {
844update(fst, a, from_sa);
845update(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(())) => {
853let ibty = bx.cx().immediate_backend_type(self.layout);
854let 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 }
864865/// 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.
870pub(super) fn insert_imm(&mut self, f: FieldIdx, imm: V) {
871let field_offset = self.layout.fields.offset(f.as_usize());
872let is_zero_offset = field_offset == Size::ZERO;
873match &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 }
886887/// 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.
892pub(super) fn update_imm(&mut self, offset: Size, imm: V) {
893let is_zero_offset = offset == Size::ZERO;
894match &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 }
907908/// 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.
912pub(super) fn build(&self, cx: &impl CodegenMethods<'tcx, Value = V>) -> OperandRef<'tcx, V> {
913let OperandRefBuilder { val, layout } = *self;
914915// 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.
919let unwrap = |r: Either<V, abi::Scalar>| match r {
920 Either::Left(v) => v,
921 Either::Right(s) if s.is_uninit_valid() => {
922let bty = cx.type_from_scalar(s);
923cx.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 };
927928let 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(())
935if let BackendRepr::SimdVector { element, .. } = layout.backend_repr
936 && element.is_uninit_valid() =>
937 {
938let 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 };
946OperandRef { val, layout, move_annotation: None }
947 }
948}
949950/// 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;
954955impl<'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.
962pub fn poison<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
963 bx: &mut Bx,
964 layout: TyAndLayout<'tcx>,
965 ) -> OperandValue<V> {
966if !layout.is_sized() {
::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
967match layout.backend_repr {
968_ if layout.is_zst() => OperandValue::ZeroSized,
969 BackendRepr::Scalar(_)
970 | BackendRepr::SimdVector { .. }
971 | BackendRepr::SimdScalableVector { .. } => {
972let ibty = bx.cx().immediate_backend_type(layout);
973 OperandValue::Immediate(bx.const_poison(ibty))
974 }
975 BackendRepr::ScalarPair { .. } => {
976let ibty0 = bx.cx().scalar_pair_element_backend_type(layout, 0, true);
977let 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 { .. } => {
981let ptr = bx.cx().type_ptr();
982 OperandValue::Ref(PlaceValue::new_sized(bx.const_poison(ptr), layout.align.abi))
983 }
984 }
985 }
986987pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
988self,
989 bx: &mut Bx,
990 dest: PlaceRef<'tcx, V>,
991 ) {
992self.store_with_flags(bx, dest, MemFlags::empty());
993 }
994995pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
996self,
997 bx: &mut Bx,
998 dest: PlaceRef<'tcx, V>,
999 ) {
1000self.store_with_flags(bx, dest, MemFlags::VOLATILE);
1001 }
10021003pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
1004self,
1005 bx: &mut Bx,
1006 dest: PlaceRef<'tcx, V>,
1007 ) {
1008self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
1009 }
10101011pub(crate) fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
1012self,
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);
1018match 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) => {
1024if !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");
1025if 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 }
1028bx.typed_place_copy_with_flags(dest.val, val, dest.layout, flags);
1029 }
1030 OperandValue::Immediate(s) => {
1031let val = bx.from_immediate(s);
1032bx.store_with_flags(val, dest.val.llval, dest.val.align, flags);
1033 }
1034 OperandValue::Pair(a, b) => {
1035let BackendRepr::ScalarPair { a: _, b: _, b_offset } = dest.layout.backend_repr
1036else {
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 };
10391040let val = bx.from_immediate(a);
1041let align = dest.val.align;
1042bx.store_with_flags(val, dest.val.llval, align, flags);
10431044let llptr = bx.inbounds_ptradd(dest.val.llval, bx.const_usize(b_offset.bytes()));
1045let val = bx.from_immediate(b);
1046let align = dest.val.align.restrict_for_offset(b_offset);
1047// The CAPTURES_READ_ONLY flag only applies to the first element.
1048bx.store_with_flags(val, llptr, align, flags & !MemFlags::CAPTURES_READ_ONLY);
1049 }
1050 }
1051 }
1052}
10531054impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
1055fn 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);
10611062match 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.
1066for elem in place_ref.projection {
1067match *elem {
1068 mir::ProjectionElem::Field(f, _) => {
1069if !!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) => {
1077if 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 );
1081let layout = o.layout.for_variant(bx.cx(), vidx);
1082 o = OperandRef { layout, ..o }
1083 }
1084_ => return None,
1085 }
1086 }
10871088Some(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
1096None1097 }
1098 }
1099 }
11001101pub 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);
11071108let ty = self.monomorphized_place_ty(place_ref);
1109let layout = bx.cx().layout_of(ty);
11101111// ZSTs don't require any actual memory access.
1112if layout.is_zst() {
1113return OperandRef::zero_sized(layout);
1114 }
11151116if let Some(o) = self.maybe_codegen_consume_direct(bx, place_ref) {
1117return o;
1118 }
11191120// for most places, to consume them we just load them
1121 // out from their home
1122let place = self.codegen_place(bx, place_ref);
1123bx.load_operand(place)
1124 }
11251126pub 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);
11321133match *operand {
1134 mir::Operand::Copy(ref place) | mir::Operand::Move(ref place) => {
1135let 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 };
11401141// Check if we should annotate this move/copy for profiling
1142let move_annotation = self.move_copy_annotation_instance(bx, place.as_ref(), kind);
11431144OperandRef { move_annotation, ..self.codegen_consume(bx, place.as_ref()) }
1145 }
11461147 mir::Operand::RuntimeChecks(checks) => {
1148let layout = bx.layout_of(bx.tcx().types.bool);
1149let 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 };
1152let x = Scalar::from_bool(checks.value(bx.tcx().sess));
1153let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
1154let val = OperandValue::Immediate(llval);
1155OperandRef { val, layout, move_annotation: None }
1156 }
11571158 mir::Operand::Constant(ref constant) => {
1159let 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.)
1162if 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.
1168let layout = bx.layout_of(constant_ty);
1169let (_, element_ty) = constant_ty.simd_size_and_type(bx.tcx());
1170if let BackendRepr::SimdVector { .. } = layout.backend_repr
1171 && element_ty.is_numeric()
1172 {
1173let (llval, ty) = self.immediate_const_vector(bx, constant);
1174return OperandRef {
1175 val: OperandValue::Immediate(llval),
1176 layout: bx.layout_of(ty),
1177 move_annotation: None,
1178 };
1179 }
1180 }
1181self.eval_mir_constant_to_operand(bx, constant)
1182 }
1183 }
1184 }
11851186/// 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.
1196fn move_copy_annotation_instance(
1197&self,
1198 bx: &Bx,
1199 place: mir::PlaceRef<'tcx>,
1200 kind: LangItem,
1201 ) -> Option<ty::Instance<'tcx>> {
1202let tcx = bx.tcx();
1203let sess = tcx.sess;
12041205// Skip if we're not generating debuginfo
1206if sess.opts.debuginfo == DebugInfo::None {
1207return None;
1208 }
12091210// Check if annotation is enabled and get size limit (otherwise skip)
1211let 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 };
12161217let ty = self.monomorphized_place_ty(place);
1218let layout = bx.cx().layout_of(ty);
1219let ty_size = layout.size.bytes();
12201221// Only annotate if type has a memory representation and exceeds size limit (and has a
1222 // non-zero size)
1223if layout.is_zst()
1224 || ty_size < size_limit1225 || !#[allow(non_exhaustive_omitted_patterns)] match layout.backend_repr {
BackendRepr::Memory { .. } => true,
_ => false,
}matches!(layout.backend_repr, BackendRepr::Memory { .. })1226 {
1227return None;
1228 }
12291230// Look up the DefId for compiler_move or compiler_copy lang item
1231let def_id = tcx.lang_items().get(kind)?;
12321233// Create generic args: compiler_move<T, SIZE> or compiler_copy<T, SIZE>
1234let size_const = ty::Const::from_target_usize(tcx, ty_size);
1235let generic_args = tcx.mk_args(&[ty.into(), size_const.into()]);
12361237// Create the Instance
1238let typing_env = self.mir.typing_env(tcx);
1239let instance = ty::Instance::expect_resolve(
1240tcx,
1241typing_env,
1242def_id,
1243generic_args,
1244 rustc_span::DUMMY_SP, // span only used for error messages
1245);
12461247Some(instance)
1248 }
1249}