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_attr_ir::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) =>
OperandValue::Ref(::core::clone::Clone::clone(__self_0)),
Self::Immediate(__self_0) =>
OperandValue::Immediate(::core::clone::Clone::clone(__self_0)),
Self::Pair(__self_0, __self_1) =>
OperandValue::Pair(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
Self::ZeroSized => OperandValue::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 {
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)]
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/32dba69d69c5b10ea89a4042de8d0619f7756203/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/32dba69d69c5b10ea89a4042de8d0619f7756203/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/32dba69d69c5b10ea89a4042de8d0619f7756203/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/32dba69d69c5b10ea89a4042de8d0619f7756203/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/32dba69d69c5b10ea89a4042de8d0619f7756203/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, variants) =
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, ref variants } => {
(tag, tag_encoding, tag_field, variants)
}
};
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,
};
if bx.cx().sess().opts.optimize != OptLevel::No {
let vals: Vec<u128> =
variants.iter_enumerated().filter_map(|(idx, layout)|
{
(!layout.is_uninhabited()).then(||
{
self.layout.ty.discriminant_for_variant(bx.tcx(),
idx).unwrap().val
})
}).collect();
if vals.iter().all(|val| val.is_power_of_two()) {
let one = bx.cx().const_i32(1);
let ctpop = bx.ctpop(tag_imm);
let is_one = bx.icmp(IntPredicate::IntEQ, ctpop, one);
bx.assume(is_one);
}
}
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, variants) = 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, ref variants } => {
493 (tag, tag_encoding, tag_field, variants)
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 };
521if bx.cx().sess().opts.optimize != OptLevel::No {
522let vals: Vec<u128> = variants
523 .iter_enumerated()
524 .filter_map(|(idx, layout)| {
525 (!layout.is_uninhabited()).then(|| {
526self.layout.ty.discriminant_for_variant(bx.tcx(), idx).unwrap().val
527 })
528 })
529 .collect();
530// Recording all possible discriminant values using `assume(v == c1 || v == c2 || v == c3)` may introduce
531 // additional compile-time overhead, but we can use `assume(ctpop(v) == 1)` when all possible values are known to be powers of two.
532if vals.iter().all(|val| val.is_power_of_two()) {
533let one = bx.cx().const_i32(1);
534let ctpop = bx.ctpop(tag_imm);
535let is_one = bx.icmp(IntPredicate::IntEQ, ctpop, one);
536 bx.assume(is_one);
537 }
538 }
539 bx.intcast(tag_imm, cast_to, signed)
540 }
541 TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => {
542// Cast to an integer so we don't have to treat a pointer as a
543 // special case.
544let (tag, tag_llty) = match tag_scalar.primitive() {
545// FIXME(erikdesjardins): handle non-default addrspace ptr sizes
546Primitive::Pointer(_) => {
547let t = bx.type_from_integer(dl.ptr_sized_integer());
548let tag = bx.ptrtoint(tag_imm, t);
549 (tag, t)
550 }
551_ => (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)),
552 };
553554// `layout_sanity_check` ensures that we only get here for cases where the discriminant
555 // value and the variant index match, since that's all `Niche` can encode.
556557let relative_max = niche_variants.last.as_u32() - niche_variants.start.as_u32();
558let niche_start_const = bx.cx().const_uint_big(tag_llty, niche_start);
559560// We have a subrange `niche_start..=niche_end` inside `range`.
561 // If the value of the tag is inside this subrange, it's a
562 // "niche value", an increment of the discriminant. Otherwise it
563 // indicates the untagged variant.
564 // A general algorithm to extract the discriminant from the tag
565 // is:
566 // relative_tag = tag - niche_start
567 // is_niche = relative_tag <= (ule) relative_max
568 // discr = if is_niche {
569 // cast(relative_tag) + niche_variants.start()
570 // } else {
571 // untagged_variant
572 // }
573 // However, we will likely be able to emit simpler code.
574let (is_niche, tagged_discr, delta) = if relative_max == 0 {
575// Best case scenario: only one tagged variant. This will
576 // likely become just a comparison and a jump.
577 // The algorithm is:
578 // is_niche = tag == niche_start
579 // discr = if is_niche {
580 // niche_start
581 // } else {
582 // untagged_variant
583 // }
584let is_niche = bx.icmp(IntPredicate::IntEQ, tag, niche_start_const);
585let tagged_discr =
586 bx.cx().const_uint(cast_to, niche_variants.start.as_u32() as u64);
587 (is_niche, tagged_discr, 0)
588 } else {
589// Thanks to parameter attributes and load metadata, LLVM already knows
590 // the general valid range of the tag. It's possible, though, for there
591 // to be an impossible value *in the middle*, which those ranges don't
592 // communicate, so it's worth an `assume` to let the optimizer know.
593 // Most importantly, this means when optimizing a variant test like
594 // `SELECT(is_niche, complex, CONST) == CONST` it's ok to simplify that
595 // to `!is_niche` because the `complex` part can't possibly match.
596 //
597 // This was previously asserted on `tagged_discr` below, where the
598 // impossible value is more obvious, but that caused an intermediate
599 // value to become multi-use and thus not optimize, so instead this
600 // assumes on the original input which is always multi-use. See
601 // <https://github.com/llvm/llvm-project/issues/134024#issuecomment-3131782555>
602 //
603 // FIXME: If we ever get range assume operand bundles in LLVM (so we
604 // don't need the `icmp`s in the instruction stream any more), it
605 // might be worth moving this back to being on the switch argument
606 // where it's more obviously applicable.
607if niche_variants.contains(&untagged_variant)
608 && bx.cx().sess().opts.optimize != OptLevel::No
609 {
610let impossible = niche_start
611 .wrapping_add(u128::from(untagged_variant.as_u32()))
612 .wrapping_sub(u128::from(niche_variants.start.as_u32()));
613let impossible = bx.cx().const_uint_big(tag_llty, impossible);
614let ne = bx.icmp(IntPredicate::IntNE, tag, impossible);
615 bx.assume(ne);
616 }
617618// With multiple niched variants we'll have to actually compute
619 // the variant index from the stored tag.
620 //
621 // However, there's still one small optimization we can often do for
622 // determining *whether* a tag value is a natural value or a niched
623 // variant. The general algorithm involves a subtraction that often
624 // wraps in practice, making it tricky to analyse. However, in cases
625 // where there are few enough possible values of the tag that it doesn't
626 // need to wrap around, we can instead just look for the contiguous
627 // tag values on the end of the range with a single comparison.
628 //
629 // For example, take the type `enum Demo { A, B, Untagged(bool) }`.
630 // The `bool` is {0, 1}, and the two other variants are given the
631 // tags {2, 3} respectively. That means the `tag_range` is
632 // `[0, 3]`, which doesn't wrap as unsigned (nor as signed), so
633 // we can test for the niched variants with just `>= 2`.
634 //
635 // That means we're looking either for the niche values *above*
636 // the natural values of the untagged variant:
637 //
638 // niche_start niche_end
639 // | |
640 // v v
641 // MIN -------------+---------------------------+---------- MAX
642 // ^ | is niche |
643 // | +---------------------------+
644 // | |
645 // tag_range.start tag_range.end
646 //
647 // Or *below* the natural values:
648 //
649 // niche_start niche_end
650 // | |
651 // v v
652 // MIN ----+-----------------------+---------------------- MAX
653 // | is niche | ^
654 // +-----------------------+ |
655 // | |
656 // tag_range.start tag_range.end
657 //
658 // With those two options and having the flexibility to choose
659 // between a signed or unsigned comparison on the tag, that
660 // covers most realistic scenarios. The tests have a (contrived)
661 // example of a 1-byte enum with over 128 niched variants which
662 // wraps both as signed as unsigned, though, and for something
663 // like that we're stuck with the general algorithm.
664665let tag_range = tag_scalar.valid_range(&dl);
666let tag_size = tag_scalar.size(&dl);
667let niche_end = u128::from(relative_max).wrapping_add(niche_start);
668let niche_end = tag_size.truncate(niche_end);
669670let relative_discr = bx.sub(tag, niche_start_const);
671let cast_tag = bx.intcast(relative_discr, cast_to, false);
672let is_niche = if tag_range.no_unsigned_wraparound(tag_size) == Ok(true) {
673if niche_start == tag_range.start {
674let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end);
675 bx.icmp(IntPredicate::IntULE, tag, niche_end_const)
676 } else {
677assert_eq!(niche_end, tag_range.end);
678 bx.icmp(IntPredicate::IntUGE, tag, niche_start_const)
679 }
680 } else if tag_range.no_signed_wraparound(tag_size) == Ok(true) {
681if niche_start == tag_range.start {
682let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end);
683 bx.icmp(IntPredicate::IntSLE, tag, niche_end_const)
684 } else {
685assert_eq!(niche_end, tag_range.end);
686 bx.icmp(IntPredicate::IntSGE, tag, niche_start_const)
687 }
688 } else {
689 bx.icmp(
690 IntPredicate::IntULE,
691 relative_discr,
692 bx.cx().const_uint(tag_llty, relative_max as u64),
693 )
694 };
695696 (is_niche, cast_tag, niche_variants.start.as_u32() as u128)
697 };
698699let tagged_discr = if delta == 0 {
700 tagged_discr
701 } else {
702 bx.add(tagged_discr, bx.cx().const_uint_big(cast_to, delta))
703 };
704705let untagged_variant_const =
706 bx.cx().const_uint(cast_to, u64::from(untagged_variant.as_u32()));
707708let discr = bx.select(is_niche, tagged_discr, untagged_variant_const);
709710// In principle we could insert assumes on the possible range of `discr`, but
711 // currently in LLVM this isn't worth it because the original `tag` will
712 // have either a `range` parameter attribute or `!range` metadata,
713 // or come from a `transmute` that already `assume`d it.
714715discr
716 }
717 }
718 }
719}
720721/// Each of these variants starts out as `Either::Right` when it's uninitialized,
722/// then setting the field changes that to `Either::Left` with the backend value.
723#[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 => OperandValueBuilder::ZeroSized,
Self::Immediate(__self_0) =>
OperandValueBuilder::Immediate(::core::clone::Clone::clone(__self_0)),
Self::Pair(__self_0, __self_1) =>
OperandValueBuilder::Pair(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
Self::Vector(__self_0) =>
OperandValueBuilder::Vector(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
724enum OperandValueBuilder<V> {
725 ZeroSized,
726 Immediate(Either<V, abi::Scalar>),
727 Pair(Either<V, abi::Scalar>, Either<V, abi::Scalar>),
728/// `repr(simd)` types need special handling because they each have a non-empty
729 /// array field (which uses [`OperandValue::Ref`]) despite the SIMD type itself
730 /// using [`OperandValue::Immediate`] which for any other kind of type would
731 /// mean that its one non-ZST field would also be [`OperandValue::Immediate`].
732Vector(Either<V, ()>),
733}
734735/// Allows building up an `OperandRef` by setting fields one at a time.
736#[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 {
OperandRefBuilder {
val: ::core::clone::Clone::clone(&self.val),
layout: ::core::clone::Clone::clone(&self.layout),
}
}
}Clone)]
737pub(super) struct OperandRefBuilder<'tcx, V> {
738 val: OperandValueBuilder<V>,
739 layout: TyAndLayout<'tcx>,
740}
741742impl<'a, 'tcx, V: CodegenObject> OperandRefBuilder<'tcx, V> {
743/// Creates an uninitialized builder for an instance of the `layout`.
744 ///
745 /// ICEs for [`BackendRepr::Memory`] types (other than ZSTs), which should
746 /// be built up inside a [`PlaceRef`] instead as they need an allocated place
747 /// into which to write the values of the fields.
748pub(super) fn new(layout: TyAndLayout<'tcx>) -> Self {
749let val = match layout.backend_repr {
750 BackendRepr::Memory { .. } if layout.is_zst() => OperandValueBuilder::ZeroSized,
751 BackendRepr::Scalar(s) => OperandValueBuilder::Immediate(Either::Right(s)),
752 BackendRepr::ScalarPair { a, b, b_offset: _ } => {
753 OperandValueBuilder::Pair(Either::Right(a), Either::Right(b))
754 }
755 BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => {
756 OperandValueBuilder::Vector(Either::Right(()))
757 }
758 BackendRepr::Memory { .. } => {
759::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:?}");
760 }
761 };
762OperandRefBuilder { val, layout }
763 }
764765/// Creates an initialized builder for updating an existing `operand`.
766 ///
767 /// ICEs for [`BackendRepr::Memory`] types (other than ZSTs), which use
768 /// which use [`OperandValue::Ref`]. In this case, updates should be
769 /// performed by writing into the place
770pub(super) fn from_existing(operand: OperandRef<'tcx, V>) -> Self {
771let layout = operand.layout;
772let val = match (operand.val, layout.backend_repr) {
773 (OperandValue::ZeroSized, _) => OperandValueBuilder::ZeroSized,
774 (OperandValue::Immediate(v), BackendRepr::Scalar(_)) => {
775 OperandValueBuilder::Immediate(Either::Left(v))
776 }
777 (OperandValue::Immediate(v), BackendRepr::SimdVector { .. }) => {
778 OperandValueBuilder::Vector(Either::Left(v))
779 }
780 (OperandValue::Pair(a, b), BackendRepr::ScalarPair { a: _, b: _, b_offset: _ }) => {
781 OperandValueBuilder::Pair(Either::Left(a), Either::Left(b))
782 }
783 (_, BackendRepr::Memory { .. }) => {
784::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:?}");
785 }
786_ => {
787::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:?}")788 }
789 };
790OperandRefBuilder { val, layout }
791 }
792793pub(super) fn insert_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
794&mut self,
795 bx: &mut Bx,
796 variant: VariantIdx,
797 field: FieldIdx,
798 field_operand: OperandRef<'tcx, V>,
799 ) {
800if let OperandValue::ZeroSized = field_operand.val {
801// A ZST never adds any state, so just ignore it.
802 // This special-casing is worth it because of things like
803 // `Result<!, !>` where `Ok(never)` is legal to write,
804 // but the type shows as FieldShape::Primitive so we can't
805 // actually look at the layout for the field being set.
806return;
807 }
808809let is_zero_offset = if let abi::FieldsShape::Primitive = self.layout.fields {
810// The other branch looking at field layouts ICEs for primitives,
811 // so we need to handle them separately.
812 // Because we handled ZSTs above (like the metadata in a thin pointer),
813 // the only possibility is that we're setting the one-and-only field.
814if !!self.layout.is_zst() {
::core::panicking::panic("assertion failed: !self.layout.is_zst()")
};assert!(!self.layout.is_zst());
815{
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);
816{
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);
817true
818} else {
819let variant_layout = self.layout.for_variant(bx.cx(), variant);
820let field_offset = variant_layout.fields.offset(field.as_usize());
821field_offset == Size::ZERO822 };
823824let mut update = |tgt: &mut Either<V, abi::Scalar>, src, from_scalar| {
825let to_scalar = tgt.unwrap_right();
826// We transmute here (rather than just `from_immediate`) because in
827 // `Result<usize, *const ()>` the field of the `Ok` is an integer,
828 // but the corresponding scalar in the enum is a pointer.
829let imm = transmute_scalar(bx, src, from_scalar, to_scalar);
830*tgt = Either::Left(imm);
831 };
832833match (field_operand.val, field_operand.layout.backend_repr) {
834 (OperandValue::ZeroSized, _) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("Handled above")));
}unreachable!("Handled above"),
835 (OperandValue::Immediate(v), BackendRepr::Scalar(from_scalar)) => match &mut self.val {
836 OperandValueBuilder::Immediate(val @ Either::Right(_)) if is_zero_offset => {
837update(val, v, from_scalar);
838 }
839 OperandValueBuilder::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
840update(fst, v, from_scalar);
841 }
842 OperandValueBuilder::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
843update(snd, v, from_scalar);
844 }
845_ => {
846::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:?}")847 }
848 },
849 (OperandValue::Immediate(v), BackendRepr::SimdVector { .. }) => match &mut self.val {
850 OperandValueBuilder::Vector(val @ Either::Right(())) if is_zero_offset => {
851*val = Either::Left(v);
852 }
853_ => {
854::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:?}")855 }
856 },
857 (
858 OperandValue::Pair(a, b),
859 BackendRepr::ScalarPair { a: from_sa, b: from_sb, b_offset: _ },
860 ) => match &mut self.val {
861 OperandValueBuilder::Pair(fst @ Either::Right(_), snd @ Either::Right(_)) => {
862update(fst, a, from_sa);
863update(snd, b, from_sb);
864 }
865_ => {
866::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:?}")867 }
868 },
869 (OperandValue::Ref(place), BackendRepr::Memory { .. }) => match &mut self.val {
870 OperandValueBuilder::Vector(val @ Either::Right(())) => {
871let ibty = bx.cx().immediate_backend_type(self.layout);
872let simd = bx.load_from_place(ibty, place);
873*val = Either::Left(simd);
874 }
875_ => {
876::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:?}")877 }
878 },
879_ => ::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:?}"),
880 }
881 }
882883/// Insert the immediate value `imm` for field `f` in the *type itself*,
884 /// rather than into one of the variants.
885 ///
886 /// Most things want [`Self::insert_field`] instead, but this one is
887 /// necessary for writing things like enum tags that aren't in any variant.
888pub(super) fn insert_imm(&mut self, f: FieldIdx, imm: V) {
889let field_offset = self.layout.fields.offset(f.as_usize());
890let is_zero_offset = field_offset == Size::ZERO;
891match &mut self.val {
892 OperandValueBuilder::Immediate(val @ Either::Right(_)) if is_zero_offset => {
893*val = Either::Left(imm);
894 }
895 OperandValueBuilder::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
896*fst = Either::Left(imm);
897 }
898 OperandValueBuilder::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
899*snd = Either::Left(imm);
900 }
901_ => ::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:?}"),
902 }
903 }
904905/// Replaces the current immediate value at the offset `offset`
906 /// with the value `imm`. A value must already be present.
907 ///
908 /// This is used along with [`Self::from_existing`] to perform in-place updates
909 /// of any operand.
910pub(super) fn update_imm(&mut self, offset: Size, imm: V) {
911let is_zero_offset = offset == Size::ZERO;
912match &mut self.val {
913 OperandValueBuilder::Immediate(val @ Either::Left(_)) if is_zero_offset => {
914*val = Either::Left(imm);
915 }
916 OperandValueBuilder::Pair(fst @ Either::Left(_), _) if is_zero_offset => {
917*fst = Either::Left(imm);
918 }
919 OperandValueBuilder::Pair(_, snd @ Either::Left(_)) if !is_zero_offset => {
920*snd = Either::Left(imm);
921 }
922_ => ::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:?}"),
923 }
924 }
925926/// After having set all necessary fields, this converts the builder back
927 /// to the normal `OperandRef`.
928 ///
929 /// ICEs if any required fields were not set.
930pub(super) fn build(&self, cx: &impl CodegenMethods<'tcx, Value = V>) -> OperandRef<'tcx, V> {
931let OperandRefBuilder { val, layout } = *self;
932933// For something like `Option::<u32>::None`, it's expected that the
934 // payload scalar will not actually have been set, so this converts
935 // unset scalars to corresponding `undef` values so long as the scalar
936 // from the layout allows uninit.
937let unwrap = |r: Either<V, abi::Scalar>| match r {
938 Either::Left(v) => v,
939 Either::Right(s) if s.is_uninit_valid() => {
940let bty = cx.type_from_scalar(s);
941cx.const_undef(bty)
942 }
943 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:?}"),
944 };
945946let val = match val {
947 OperandValueBuilder::ZeroSized => OperandValue::ZeroSized,
948 OperandValueBuilder::Immediate(v) => OperandValue::Immediate(unwrap(v)),
949 OperandValueBuilder::Pair(a, b) => OperandValue::Pair(unwrap(a), unwrap(b)),
950 OperandValueBuilder::Vector(v) => match v {
951 Either::Left(v) => OperandValue::Immediate(v),
952 Either::Right(())
953if let BackendRepr::SimdVector { element, .. } = layout.backend_repr
954 && element.is_uninit_valid() =>
955 {
956let bty = cx.immediate_backend_type(layout);
957 OperandValue::Immediate(cx.const_undef(bty))
958 }
959 Either::Right(()) => {
960::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:?}")961 }
962 },
963 };
964OperandRef { val, layout, move_annotation: None }
965 }
966}
967968/// Default size limit for move/copy annotations (in bytes). 64 bytes is a common size of a cache
969/// line, and the assumption is that anything this size or below is very cheap to move/copy, so only
970/// annotate copies larger than this.
971const MOVE_ANNOTATION_DEFAULT_LIMIT: u64 = 65;
972973impl<'a, 'tcx, V: CodegenObject> OperandValue<V> {
974/// Returns an `OperandValue` that's generally UB to use in any way.
975 ///
976 /// Depending on the `layout`, returns `ZeroSized` for ZSTs, an `Immediate` or
977 /// `Pair` containing poison value(s), or a `Ref` containing a poison pointer.
978 ///
979 /// Supports sized types only.
980pub fn poison<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
981 bx: &mut Bx,
982 layout: TyAndLayout<'tcx>,
983 ) -> OperandValue<V> {
984if !layout.is_sized() {
::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
985match layout.backend_repr {
986_ if layout.is_zst() => OperandValue::ZeroSized,
987 BackendRepr::Scalar(_)
988 | BackendRepr::SimdVector { .. }
989 | BackendRepr::SimdScalableVector { .. } => {
990let ibty = bx.cx().immediate_backend_type(layout);
991 OperandValue::Immediate(bx.const_poison(ibty))
992 }
993 BackendRepr::ScalarPair { .. } => {
994let ibty0 = bx.cx().scalar_pair_element_backend_type(layout, 0, true);
995let ibty1 = bx.cx().scalar_pair_element_backend_type(layout, 1, true);
996 OperandValue::Pair(bx.const_poison(ibty0), bx.const_poison(ibty1))
997 }
998 BackendRepr::Memory { .. } => {
999let ptr = bx.cx().type_ptr();
1000 OperandValue::Ref(PlaceValue::new_sized(bx.const_poison(ptr), layout.align.abi))
1001 }
1002 }
1003 }
10041005pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
1006self,
1007 bx: &mut Bx,
1008 dest: PlaceRef<'tcx, V>,
1009 ) {
1010self.store_with_flags(bx, dest, MemFlags::empty());
1011 }
10121013pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
1014self,
1015 bx: &mut Bx,
1016 dest: PlaceRef<'tcx, V>,
1017 ) {
1018self.store_with_flags(bx, dest, MemFlags::VOLATILE);
1019 }
10201021pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
1022self,
1023 bx: &mut Bx,
1024 dest: PlaceRef<'tcx, V>,
1025 ) {
1026self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
1027 }
10281029pub(crate) fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
1030self,
1031 bx: &mut Bx,
1032 dest: PlaceRef<'tcx, V>,
1033 flags: MemFlags,
1034 ) {
1035{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_codegen_ssa/src/mir/operand.rs:1035",
"rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_codegen_ssa/src/mir/operand.rs"),
::tracing_core::__macro_support::Option::Some(1035u32),
::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);
1036match self {
1037 OperandValue::ZeroSized => {
1038// Avoid generating stores of zero-sized values, because the only way to have a
1039 // zero-sized value is through `undef`/`poison`, and the store itself is useless.
1040}
1041 OperandValue::Ref(val) => {
1042if !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");
1043if val.llextra.is_some() {
1044::rustc_span::macros::bug_impl(None,
format_args!("cannot directly store unsized values"), Location::caller());bug!("cannot directly store unsized values");
1045 }
1046bx.typed_place_copy_with_flags(dest.val, val, dest.layout, flags);
1047 }
1048 OperandValue::Immediate(s) => {
1049let val = bx.from_immediate(s);
1050bx.store_with_flags(val, dest.val.llval, dest.val.align, flags);
1051 }
1052 OperandValue::Pair(a, b) => {
1053let BackendRepr::ScalarPair { a: _, b: _, b_offset } = dest.layout.backend_repr
1054else {
1055::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);
1056 };
10571058let val = bx.from_immediate(a);
1059let align = dest.val.align;
1060bx.store_with_flags(val, dest.val.llval, align, flags);
10611062let llptr = bx.inbounds_ptradd(dest.val.llval, bx.const_usize(b_offset.bytes()));
1063let val = bx.from_immediate(b);
1064let align = dest.val.align.restrict_for_offset(b_offset);
1065// The CAPTURES_READ_ONLY flag only applies to the first element.
1066bx.store_with_flags(val, llptr, align, flags & !MemFlags::CAPTURES_READ_ONLY);
1067 }
1068 }
1069 }
1070}
10711072impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
1073fn maybe_codegen_consume_direct(
1074&mut self,
1075 bx: &mut Bx,
1076 place_ref: mir::PlaceRef<'tcx>,
1077 ) -> Option<OperandRef<'tcx, Bx::Value>> {
1078{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_codegen_ssa/src/mir/operand.rs:1078",
"rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_codegen_ssa/src/mir/operand.rs"),
::tracing_core::__macro_support::Option::Some(1078u32),
::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);
10791080match self.locals[place_ref.local] {
1081 LocalRef::Operand(mut o) => {
1082// We only need to handle the projections that
1083 // `LocalAnalyzer::process_place` let make it here.
1084for elem in place_ref.projection {
1085match *elem {
1086 mir::ProjectionElem::Field(f, _) => {
1087if !!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!(
1088 !o.layout.ty.is_any_ptr(),
1089"Bad PlaceRef: destructing pointers should use cast/PtrMetadata, \
1090 but tried to access field {f:?} of pointer {o:?}",
1091 );
1092 o = o.extract_field(self, bx, f.index());
1093 }
1094 mir::PlaceElem::Downcast(_, vidx) => {
1095if 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!(
1096 o.layout.variants,
1097 abi::Variants::Single { index: vidx },
1098 );
1099let layout = o.layout.for_variant(bx.cx(), vidx);
1100 o = OperandRef { layout, ..o }
1101 }
1102_ => return None,
1103 }
1104 }
11051106Some(o)
1107 }
1108 LocalRef::PendingOperand => {
1109::rustc_span::macros::bug_impl(None,
format_args!("use of {0:?} before def", place_ref), Location::caller());bug!("use of {:?} before def", place_ref);
1110 }
1111 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
1112// watch out for locals that do not have an
1113 // alloca; they are handled somewhat differently
1114None1115 }
1116 }
1117 }
11181119pub fn codegen_consume(
1120&mut self,
1121 bx: &mut Bx,
1122 place_ref: mir::PlaceRef<'tcx>,
1123 ) -> OperandRef<'tcx, Bx::Value> {
1124{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_codegen_ssa/src/mir/operand.rs:1124",
"rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_codegen_ssa/src/mir/operand.rs"),
::tracing_core::__macro_support::Option::Some(1124u32),
::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);
11251126let ty = self.monomorphized_place_ty(place_ref);
1127let layout = bx.cx().layout_of(ty);
11281129// ZSTs don't require any actual memory access.
1130if layout.is_zst() {
1131return OperandRef::zero_sized(layout);
1132 }
11331134if let Some(o) = self.maybe_codegen_consume_direct(bx, place_ref) {
1135return o;
1136 }
11371138// for most places, to consume them we just load them
1139 // out from their home
1140let place = self.codegen_place(bx, place_ref);
1141bx.load_operand(place)
1142 }
11431144pub fn codegen_operand(
1145&mut self,
1146 bx: &mut Bx,
1147 operand: &mir::Operand<'tcx>,
1148 ) -> OperandRef<'tcx, Bx::Value> {
1149{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_codegen_ssa/src/mir/operand.rs:1149",
"rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/32dba69d69c5b10ea89a4042de8d0619f7756203/compiler/rustc_codegen_ssa/src/mir/operand.rs"),
::tracing_core::__macro_support::Option::Some(1149u32),
::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);
11501151match *operand {
1152 mir::Operand::Copy(ref place) | mir::Operand::Move(ref place) => {
1153let kind = match operand {
1154 mir::Operand::Move(_) => LangItem::CompilerMove,
1155 mir::Operand::Copy(_) => LangItem::CompilerCopy,
1156_ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1157 };
11581159// Check if we should annotate this move/copy for profiling
1160let move_annotation = self.move_copy_annotation_instance(bx, place.as_ref(), kind);
11611162OperandRef { move_annotation, ..self.codegen_consume(bx, place.as_ref()) }
1163 }
11641165 mir::Operand::RuntimeChecks(checks) => {
1166let layout = bx.layout_of(bx.tcx().types.bool);
1167let BackendRepr::Scalar(scalar) = layout.backend_repr else {
1168::rustc_span::macros::bug_impl(None,
format_args!("from_const: invalid ByVal layout: {0:#?}", layout),
Location::caller());bug!("from_const: invalid ByVal layout: {:#?}", layout);
1169 };
1170let x = Scalar::from_bool(checks.value(bx.tcx().sess));
1171let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
1172let val = OperandValue::Immediate(llval);
1173OperandRef { val, layout, move_annotation: None }
1174 }
11751176 mir::Operand::Constant(ref constant) => {
1177let constant_ty = self.monomorphize(constant.ty());
1178// Most SIMD vector constants should be passed as immediates.
1179 // (In particular, some intrinsics really rely on this.)
1180if constant_ty.is_simd() {
1181// However, some SIMD types do not actually use the vector ABI
1182 // (in particular, packed SIMD types do not). Ensure we exclude those.
1183 //
1184 // We also have to exclude vectors of pointers because `immediate_const_vector`
1185 // does not work for those.
1186let layout = bx.layout_of(constant_ty);
1187let (_, element_ty) = constant_ty.simd_size_and_type(bx.tcx());
1188if let BackendRepr::SimdVector { .. } = layout.backend_repr
1189 && element_ty.is_numeric()
1190 {
1191let (llval, ty) = self.immediate_const_vector(bx, constant);
1192return OperandRef {
1193 val: OperandValue::Immediate(llval),
1194 layout: bx.layout_of(ty),
1195 move_annotation: None,
1196 };
1197 }
1198 }
1199self.eval_mir_constant_to_operand(bx, constant)
1200 }
1201 }
1202 }
12031204/// Creates an `Instance` for annotating a move/copy operation at codegen time.
1205 ///
1206 /// Returns `Some(instance)` if the operation should be annotated with debug info, `None`
1207 /// otherwise. The instance represents a monomorphized `compiler_move<T, SIZE>` or
1208 /// `compiler_copy<T, SIZE>` function that can be used to create debug scopes.
1209 ///
1210 /// There are a number of conditions that must be met for an annotation to be created, but aside
1211 /// from the basics (annotation is enabled, we're generating debuginfo), the primary concern is
1212 /// moves/copies which could result in a real `memcpy`. So we check for the size limit, but also
1213 /// that the underlying representation of the type is in memory.
1214fn move_copy_annotation_instance(
1215&self,
1216 bx: &Bx,
1217 place: mir::PlaceRef<'tcx>,
1218 kind: LangItem,
1219 ) -> Option<ty::Instance<'tcx>> {
1220let tcx = bx.tcx();
1221let sess = tcx.sess;
12221223// Skip if we're not generating debuginfo
1224if sess.opts.debuginfo == DebugInfo::None {
1225return None;
1226 }
12271228// Check if annotation is enabled and get size limit (otherwise skip)
1229let size_limit = match sess.opts.unstable_opts.annotate_moves {
1230 AnnotateMoves::Disabled => return None,
1231 AnnotateMoves::Enabled(None) => MOVE_ANNOTATION_DEFAULT_LIMIT,
1232 AnnotateMoves::Enabled(Some(limit)) => limit,
1233 };
12341235let ty = self.monomorphized_place_ty(place);
1236let layout = bx.cx().layout_of(ty);
1237let ty_size = layout.size.bytes();
12381239// Only annotate if type has a memory representation and exceeds size limit (and has a
1240 // non-zero size)
1241if layout.is_zst()
1242 || ty_size < size_limit1243 || !#[allow(non_exhaustive_omitted_patterns)] match layout.backend_repr {
BackendRepr::Memory { .. } => true,
_ => false,
}matches!(layout.backend_repr, BackendRepr::Memory { .. })1244 {
1245return None;
1246 }
12471248// Look up the DefId for compiler_move or compiler_copy lang item
1249let def_id = tcx.lang_items().get(kind)?;
12501251// Create generic args: compiler_move<T, SIZE> or compiler_copy<T, SIZE>
1252let size_const = ty::Const::from_target_usize(tcx, ty_size);
1253let generic_args = tcx.mk_args(&[ty.into(), size_const.into()]);
12541255// Create the Instance
1256let typing_env = self.mir.typing_env(tcx);
1257let instance = ty::Instance::expect_resolve(
1258tcx,
1259typing_env,
1260def_id,
1261generic_args,
1262 rustc_span::DUMMY_SP, // span only used for error messages
1263);
12641265Some(instance)
1266 }
1267}