1use std::assert_matches;
2
3use itertools::Itertools as _;
4use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT};
5use rustc_index::IndexVec;
6use rustc_middle::ty::adjustment::PointerCoercion;
7use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
8use rustc_middle::ty::{self, Instance, Mutability, Ty, TyCtxt};
9use rustc_middle::{bug, mir, span_bug};
10use rustc_session::config::OptLevel;
11use tracing::{debug, instrument};
12
13use super::FunctionCx;
14use super::operand::{OperandRef, OperandRefBuilder, OperandValue};
15use super::place::{PlaceRef, PlaceValue, codegen_tag_value};
16use crate::common::{IntPredicate, TypeKind};
17use crate::traits::*;
18use crate::{MemFlags, base};
19
20impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
21 fn try_codegen_const_aggregate_as_immediate(
22 &mut self,
23 bx: &mut Bx,
24 dest: PlaceRef<'tcx, Bx::Value>,
25 kind: &mir::AggregateKind<'tcx>,
26 operands: &IndexVec<abi::FieldIdx, mir::Operand<'tcx>>,
27 ) -> bool {
28 let variant_index = match kind {
33 mir::AggregateKind::Tuple => FIRST_VARIANT,
34 mir::AggregateKind::Adt(_, variant_index, _, _, None) => *variant_index,
35 _ => return false,
36 };
37 if !#[allow(non_exhaustive_omitted_patterns)] match dest.layout.fields {
abi::FieldsShape::Arbitrary { .. } => true,
_ => false,
}matches!(dest.layout.fields, abi::FieldsShape::Arbitrary { .. }) {
38 return false;
39 }
40 if !#[allow(non_exhaustive_omitted_patterns)] match dest.layout.variants {
abi::Variants::Single { index } if index == variant_index => true,
_ => false,
}matches!(dest.layout.variants, abi::Variants::Single { index } if index == variant_index)
48 {
49 return false;
50 }
51 if true {
{
match (&operands.len(), &dest.layout.fields.count()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(operands.len(), dest.layout.fields.count());
54
55 let size = dest.layout.size.bytes();
56 let llty = match size {
57 1 => bx.cx().type_i8(),
58 2 => bx.cx().type_i16(),
59 4 => bx.cx().type_i32(),
60 8 => bx.cx().type_i64(),
61 16 => bx.cx().type_i128(),
62 _ => return false,
63 };
64
65 let mut value = 0u128;
66 for (field_idx, operand) in operands.iter_enumerated() {
67 let field_layout = dest.layout.field(bx.cx(), field_idx.as_usize());
68 if field_layout.is_zst() {
69 continue;
70 }
71 let mir::Operand::Constant(constant) = operand else {
72 return false;
73 };
74 let Some(field_value) = self.eval_mir_constant(constant).try_to_bits(field_layout.size)
75 else {
76 return false;
77 };
78
79 let field_size = field_layout.size.bytes();
80 let field_offset = dest.layout.fields.offset(field_idx.as_usize()).bytes();
81 if true {
if !(field_offset + field_size <= size) {
::core::panicking::panic("assertion failed: field_offset + field_size <= size")
};
};debug_assert!(field_offset + field_size <= size);
82 let shift = match bx.tcx().data_layout.endian {
83 abi::Endian::Little => field_offset * 8,
84 abi::Endian::Big => (size - field_offset - field_size) * 8,
85 };
86 value |= field_value << shift;
87 }
88
89 let value = bx.cx().const_uint_big(llty, value);
90 bx.store_to_place(value, dest.val);
91 true
92 }
93
94 fn is_entirely_uninit_const(&self, operand: &mir::Operand<'tcx>) -> bool {
95 let mir::Operand::Constant(const_op) = operand else { return false };
96 self.eval_mir_constant(const_op).all_bytes_uninit(self.cx.tcx())
97 }
98
99 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("codegen_rvalue",
"rustc_codegen_ssa::mir::rvalue", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
::tracing_core::__macro_support::Option::Some(99u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("dest")
}> =
::tracing::__macro_support::FieldName::new("dest");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("rvalue")
}> =
::tracing::__macro_support::FieldName::new("rvalue");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dest)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rvalue)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
match *rvalue {
mir::Rvalue::Use(ref operand, with_retag) => {
if self.is_entirely_uninit_const(operand) { return; }
let cg_operand = self.codegen_operand(bx, operand);
if #[allow(non_exhaustive_omitted_patterns)] match cg_operand.layout.backend_repr
{
BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. } =>
true,
_ => false,
} {
if true {
if !!#[allow(non_exhaustive_omitted_patterns)] match cg_operand.val
{
OperandValue::Ref(..) => true,
_ => false,
} {
::core::panicking::panic("assertion failed: !matches!(cg_operand.val, OperandValue::Ref(..))")
};
};
}
let flags =
if let ty::Ref(_, pointee_ty, Mutability::Not) =
cg_operand.layout.ty.kind() && with_retag.yes() &&
pointee_ty.is_freeze(self.cx.tcx(), self.cx.typing_env()) {
MemFlags::CAPTURES_READ_ONLY
} else { MemFlags::empty() };
cg_operand.store_with_annotation_and_flags(bx, dest, flags);
}
mir::Rvalue::Cast(mir::CastKind::PointerCoercion(PointerCoercion::Unsize,
_), ref source, _) => {
if let BackendRepr::ScalarPair { .. } =
dest.layout.backend_repr {
let temp = self.codegen_rvalue_operand(bx, rvalue);
temp.store_with_annotation(bx, dest);
return;
}
let operand = self.codegen_operand(bx, source);
match operand.val {
OperandValue::Pair(..) | OperandValue::Immediate(_) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/rvalue.rs:165",
"rustc_codegen_ssa::mir::rvalue", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
::tracing_core::__macro_support::Option::Some(165u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_rvalue: creating ugly alloca")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let scratch = PlaceRef::alloca(bx, operand.layout);
scratch.storage_live(bx);
operand.store_with_annotation(bx, scratch);
base::coerce_unsized_into(bx, scratch, dest);
scratch.storage_dead(bx);
}
OperandValue::Ref(val) => {
if val.llextra.is_some() {
::rustc_middle::util::bug::bug_fmt(format_args!("unsized coercion on an unsized rvalue"));
}
base::coerce_unsized_into(bx, val.with_type(operand.layout),
dest);
}
OperandValue::ZeroSized => {
::rustc_middle::util::bug::bug_fmt(format_args!("unsized coercion on a ZST rvalue"));
}
}
}
mir::Rvalue::Cast(mir::CastKind::Transmute |
mir::CastKind::Subtype, ref operand, _ty) => {
let src = self.codegen_operand(bx, operand);
self.codegen_transmute(bx, src, dest);
}
mir::Rvalue::Repeat(ref elem, count) => {
if dest.layout.is_zst() { return; }
if self.is_entirely_uninit_const(elem) {
let size = bx.const_usize(dest.layout.size.bytes());
bx.memset(dest.val.llval, bx.const_undef(bx.type_i8()),
size, dest.val.align, MemFlags::empty());
return;
}
let cg_elem = self.codegen_operand(bx, elem);
let try_init_all_same =
|bx: &mut Bx, v|
{
let start = dest.val.llval;
let size = bx.const_usize(dest.layout.size.bytes());
if let Some(int) = bx.cx().const_to_opt_u128(v, false) &&
let bytes =
&int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()] &&
let Ok(&byte) = bytes.iter().all_equal_value() {
let fill = bx.cx().const_u8(byte);
bx.memset(start, fill, size, dest.val.align,
MemFlags::empty());
return true;
}
let v = bx.from_immediate(v);
if bx.cx().val_ty(v) == bx.cx().type_i8() {
bx.memset(start, v, size, dest.val.align,
MemFlags::empty());
return true;
}
false
};
if let OperandValue::Immediate(v) = cg_elem.val &&
try_init_all_same(bx, v) {
return;
}
let count =
self.monomorphize(count).try_to_target_usize(bx.tcx()).expect("expected monomorphic const in codegen");
bx.write_operand_repeatedly(cg_elem, count, dest);
}
mir::Rvalue::Aggregate(ref kind, ref operands) if
!#[allow(non_exhaustive_omitted_patterns)] match **kind {
mir::AggregateKind::RawPtr(..) => true,
_ => false,
} => {
if self.try_codegen_const_aggregate_as_immediate(bx, dest,
kind, operands) {
return;
}
let (variant_index, variant_dest, active_field_index) =
match **kind {
mir::AggregateKind::Adt(_, variant_index, _, _,
active_field_index) => {
let variant_dest = dest.project_downcast(bx, variant_index);
(variant_index, variant_dest, active_field_index)
}
_ => (FIRST_VARIANT, dest, None),
};
if active_field_index.is_some() {
{
match (&operands.len(), &1) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
}
for (i, operand) in operands.iter_enumerated() {
if self.is_entirely_uninit_const(operand) { continue; }
let op = self.codegen_operand(bx, operand);
if !op.layout.is_zst() {
let field_index = active_field_index.unwrap_or(i);
let field =
if let mir::AggregateKind::Array(_) = **kind {
let llindex =
bx.cx().const_usize(field_index.as_u32().into());
variant_dest.project_index(bx, llindex)
} else {
variant_dest.project_field(bx, field_index.as_usize())
};
op.store_with_annotation(bx, field);
}
}
dest.codegen_set_discr(bx, variant_index);
}
_ => {
let temp = self.codegen_rvalue_operand(bx, rvalue);
temp.store_with_annotation(bx, dest);
}
}
}
}
}#[instrument(level = "trace", skip(self, bx))]
100 pub(crate) fn codegen_rvalue(
101 &mut self,
102 bx: &mut Bx,
103 dest: PlaceRef<'tcx, Bx::Value>,
104 rvalue: &mir::Rvalue<'tcx>,
105 ) {
106 match *rvalue {
107 mir::Rvalue::Use(ref operand, with_retag) => {
108 if self.is_entirely_uninit_const(operand) {
109 return;
110 }
111 let cg_operand = self.codegen_operand(bx, operand);
112 if matches!(
116 cg_operand.layout.backend_repr,
117 BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. },
118 ) {
119 debug_assert!(!matches!(cg_operand.val, OperandValue::Ref(..)));
120 }
121 let flags = if let ty::Ref(_, pointee_ty, Mutability::Not) =
124 cg_operand.layout.ty.kind()
125 && with_retag.yes()
126 && pointee_ty.is_freeze(self.cx.tcx(), self.cx.typing_env())
127 {
128 MemFlags::CAPTURES_READ_ONLY
129 } else {
130 MemFlags::empty()
131 };
132 cg_operand.store_with_annotation_and_flags(bx, dest, flags);
135 }
136
137 mir::Rvalue::Cast(
138 mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
139 ref source,
140 _,
141 ) => {
142 if let BackendRepr::ScalarPair { .. } = dest.layout.backend_repr {
145 let temp = self.codegen_rvalue_operand(bx, rvalue);
148 temp.store_with_annotation(bx, dest);
149 return;
150 }
151
152 let operand = self.codegen_operand(bx, source);
157 match operand.val {
158 OperandValue::Pair(..) | OperandValue::Immediate(_) => {
159 debug!("codegen_rvalue: creating ugly alloca");
166 let scratch = PlaceRef::alloca(bx, operand.layout);
167 scratch.storage_live(bx);
168 operand.store_with_annotation(bx, scratch);
169 base::coerce_unsized_into(bx, scratch, dest);
170 scratch.storage_dead(bx);
171 }
172 OperandValue::Ref(val) => {
173 if val.llextra.is_some() {
174 bug!("unsized coercion on an unsized rvalue");
175 }
176 base::coerce_unsized_into(bx, val.with_type(operand.layout), dest);
177 }
178 OperandValue::ZeroSized => {
179 bug!("unsized coercion on a ZST rvalue");
180 }
181 }
182 }
183
184 mir::Rvalue::Cast(
185 mir::CastKind::Transmute | mir::CastKind::Subtype,
186 ref operand,
187 _ty,
188 ) => {
189 let src = self.codegen_operand(bx, operand);
190 self.codegen_transmute(bx, src, dest);
191 }
192
193 mir::Rvalue::Repeat(ref elem, count) => {
194 if dest.layout.is_zst() {
196 return;
197 }
198
199 if self.is_entirely_uninit_const(elem) {
202 let size = bx.const_usize(dest.layout.size.bytes());
203 bx.memset(
204 dest.val.llval,
205 bx.const_undef(bx.type_i8()),
206 size,
207 dest.val.align,
208 MemFlags::empty(),
209 );
210 return;
211 }
212
213 let cg_elem = self.codegen_operand(bx, elem);
214
215 let try_init_all_same = |bx: &mut Bx, v| {
216 let start = dest.val.llval;
217 let size = bx.const_usize(dest.layout.size.bytes());
218
219 if let Some(int) = bx.cx().const_to_opt_u128(v, false)
221 && let bytes = &int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()]
222 && let Ok(&byte) = bytes.iter().all_equal_value()
223 {
224 let fill = bx.cx().const_u8(byte);
225 bx.memset(start, fill, size, dest.val.align, MemFlags::empty());
226 return true;
227 }
228
229 let v = bx.from_immediate(v);
231 if bx.cx().val_ty(v) == bx.cx().type_i8() {
232 bx.memset(start, v, size, dest.val.align, MemFlags::empty());
233 return true;
234 }
235 false
236 };
237
238 if let OperandValue::Immediate(v) = cg_elem.val
239 && try_init_all_same(bx, v)
240 {
241 return;
242 }
243
244 let count = self
245 .monomorphize(count)
246 .try_to_target_usize(bx.tcx())
247 .expect("expected monomorphic const in codegen");
248
249 bx.write_operand_repeatedly(cg_elem, count, dest);
250 }
251
252 mir::Rvalue::Aggregate(ref kind, ref operands)
255 if !matches!(**kind, mir::AggregateKind::RawPtr(..)) =>
256 {
257 if self.try_codegen_const_aggregate_as_immediate(bx, dest, kind, operands) {
258 return;
259 }
260
261 let (variant_index, variant_dest, active_field_index) = match **kind {
262 mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
263 let variant_dest = dest.project_downcast(bx, variant_index);
264 (variant_index, variant_dest, active_field_index)
265 }
266 _ => (FIRST_VARIANT, dest, None),
267 };
268 if active_field_index.is_some() {
269 assert_eq!(operands.len(), 1);
270 }
271 for (i, operand) in operands.iter_enumerated() {
272 if self.is_entirely_uninit_const(operand) {
275 continue;
276 }
277 let op = self.codegen_operand(bx, operand);
278 if !op.layout.is_zst() {
280 let field_index = active_field_index.unwrap_or(i);
281 let field = if let mir::AggregateKind::Array(_) = **kind {
282 let llindex = bx.cx().const_usize(field_index.as_u32().into());
283 variant_dest.project_index(bx, llindex)
284 } else {
285 variant_dest.project_field(bx, field_index.as_usize())
286 };
287 op.store_with_annotation(bx, field);
288 }
289 }
290 dest.codegen_set_discr(bx, variant_index);
291 }
292
293 _ => {
294 let temp = self.codegen_rvalue_operand(bx, rvalue);
295 temp.store_with_annotation(bx, dest);
296 }
297 }
298 }
299
300 fn codegen_transmute(
305 &mut self,
306 bx: &mut Bx,
307 src: OperandRef<'tcx, Bx::Value>,
308 dst: PlaceRef<'tcx, Bx::Value>,
309 ) {
310 if !src.layout.is_sized() {
::core::panicking::panic("assertion failed: src.layout.is_sized()")
};assert!(src.layout.is_sized());
312 if !dst.layout.is_sized() {
::core::panicking::panic("assertion failed: dst.layout.is_sized()")
};assert!(dst.layout.is_sized());
313
314 if src.layout.size != dst.layout.size
315 || src.layout.is_uninhabited()
316 || dst.layout.is_uninhabited()
317 {
318 bx.unreachable_nonterminator();
321 } else {
322 src.store_with_annotation(bx, dst.val.with_type(src.layout));
326 }
327 }
328
329 pub(crate) fn codegen_transmute_operand(
334 &mut self,
335 bx: &mut Bx,
336 operand: OperandRef<'tcx, Bx::Value>,
337 cast: TyAndLayout<'tcx>,
338 ) -> OperandValue<Bx::Value> {
339 if let abi::BackendRepr::Memory { .. } = cast.backend_repr
340 && !cast.is_zst()
341 {
342 ::rustc_middle::util::bug::span_bug_fmt(self.mir.span,
format_args!("Use `codegen_transmute` to transmute to {0:?}", cast));span_bug!(self.mir.span, "Use `codegen_transmute` to transmute to {cast:?}");
343 }
344
345 if abi::Layout::eq(&operand.layout.layout, &cast.layout) {
348 return operand.val;
349 }
350
351 if operand.layout.size != cast.size
353 || operand.layout.is_uninhabited()
354 || cast.is_uninhabited()
355 {
356 bx.unreachable_nonterminator();
357
358 return OperandValue::poison(bx, cast);
361 }
362
363 #[inline]
366 fn vector_can_bitcast(x: abi::Scalar) -> bool {
367 #[allow(non_exhaustive_omitted_patterns)] match x {
abi::Scalar::Initialized {
value: abi::Primitive::Int(..) | abi::Primitive::Float(..), .. } =>
true,
_ => false,
}matches!(
368 x,
369 abi::Scalar::Initialized {
370 value: abi::Primitive::Int(..) | abi::Primitive::Float(..),
371 ..
372 }
373 )
374 }
375
376 let cx = bx.cx();
377 match (operand.val, operand.layout.backend_repr, cast.backend_repr) {
378 _ if cast.is_zst() => OperandValue::ZeroSized,
379 (OperandValue::Ref(source_place_val), abi::BackendRepr::Memory { .. }, _) => {
380 {
match (&source_place_val.llextra, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(source_place_val.llextra, None);
381 bx.load_operand(source_place_val.with_type(cast)).val
384 }
385 (
386 OperandValue::Immediate(imm),
387 abi::BackendRepr::Scalar(from_scalar),
388 abi::BackendRepr::Scalar(to_scalar),
389 ) if from_scalar.size(cx) == to_scalar.size(cx) => {
390 OperandValue::Immediate(transmute_scalar(bx, imm, from_scalar, to_scalar))
391 }
392 (
393 OperandValue::Immediate(imm),
394 abi::BackendRepr::SimdVector { element: from_scalar, .. },
395 abi::BackendRepr::SimdVector { element: to_scalar, .. },
396 ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
397 let to_backend_ty = bx.cx().immediate_backend_type(cast);
398 OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
399 }
400 (
401 OperandValue::Immediate(imm),
402 abi::BackendRepr::SimdScalableVector { element: from_scalar, .. },
403 abi::BackendRepr::SimdScalableVector { element: to_scalar, .. },
404 ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
405 let to_backend_ty = bx.cx().immediate_backend_type(cast);
406 OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
407 }
408 (
409 OperandValue::Pair(imm_a, imm_b),
410 abi::BackendRepr::ScalarPair { a: in_a, b: in_b, b_offset: in_offset },
411 abi::BackendRepr::ScalarPair { a: out_a, b: out_b, b_offset: out_offset },
412 ) if in_a.size(cx) == out_a.size(cx)
413 && in_b.size(cx) == out_b.size(cx)
414 && in_offset == out_offset =>
415 {
416 OperandValue::Pair(
417 transmute_scalar(bx, imm_a, in_a, out_a),
418 transmute_scalar(bx, imm_b, in_b, out_b),
419 )
420 }
421 _ => {
422 let align = Ord::max(operand.layout.align.abi, cast.align.abi);
432 let size = Ord::max(operand.layout.size, cast.size);
433 let temp = PlaceValue::alloca(bx, size, align);
434 bx.lifetime_start(temp.llval, size);
435 operand.store_with_annotation(bx, temp.with_type(operand.layout));
436 let val = bx.load_operand(temp.with_type(cast)).val;
437 bx.lifetime_end(temp.llval, size);
438 val
439 }
440 }
441 }
442
443 fn cast_immediate(
448 &self,
449 bx: &mut Bx,
450 mut imm: Bx::Value,
451 from_scalar: abi::Scalar,
452 from_backend_ty: Bx::Type,
453 to_scalar: abi::Scalar,
454 to_backend_ty: Bx::Type,
455 ) -> Option<Bx::Value> {
456 use abi::Primitive::*;
457
458 assume_scalar_range(bx, imm, from_scalar, from_backend_ty, None);
463
464 imm = match (from_scalar.primitive(), to_scalar.primitive()) {
465 (Int(_, is_signed), Int(..)) => bx.intcast(imm, to_backend_ty, is_signed),
466 (Float(_), Float(_)) => {
467 let srcsz = bx.cx().float_width(from_backend_ty);
468 let dstsz = bx.cx().float_width(to_backend_ty);
469 if dstsz > srcsz {
470 bx.fpext(imm, to_backend_ty)
471 } else if srcsz > dstsz {
472 bx.fptrunc(imm, to_backend_ty)
473 } else {
474 imm
475 }
476 }
477 (Int(_, is_signed), Float(_)) => {
478 if is_signed {
479 bx.sitofp(imm, to_backend_ty)
480 } else {
481 bx.uitofp(imm, to_backend_ty)
482 }
483 }
484 (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
485 (Int(_, is_signed), Pointer(..)) => {
486 let usize_imm = bx.intcast(imm, bx.cx().type_isize(), is_signed);
487 bx.inttoptr(usize_imm, to_backend_ty)
488 }
489 (Float(_), Int(_, is_signed)) => bx.cast_float_to_int(is_signed, imm, to_backend_ty),
490 _ => return None,
491 };
492 Some(imm)
493 }
494
495 pub(crate) fn codegen_rvalue_operand(
496 &mut self,
497 bx: &mut Bx,
498 rvalue: &mir::Rvalue<'tcx>,
499 ) -> OperandRef<'tcx, Bx::Value> {
500 match *rvalue {
501 mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
502 let operand = self.codegen_operand(bx, source);
503 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/rvalue.rs:503",
"rustc_codegen_ssa::mir::rvalue", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
::tracing_core::__macro_support::Option::Some(503u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("cast operand is {0:?}",
operand) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("cast operand is {:?}", operand);
504 let cast = bx.cx().layout_of(self.monomorphize(mir_cast_ty));
505
506 let val = match *kind {
507 mir::CastKind::PointerExposeProvenance => {
508 if !cast.backend_repr.is_scalar_or_simd() {
::core::panicking::panic("assertion failed: cast.backend_repr.is_scalar_or_simd()")
};assert!(cast.backend_repr.is_scalar_or_simd());
509 let llptr = operand.immediate();
510 let llcast_ty = bx.cx().immediate_backend_type(cast);
511 let lladdr = bx.ptrtoint(llptr, llcast_ty);
512 OperandValue::Immediate(lladdr)
513 }
514 mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _) => {
515 match *operand.layout.ty.kind() {
516 ty::FnDef(def_id, args) => {
517 let instance = ty::Instance::resolve_for_fn_ptr(
518 bx.tcx(),
519 bx.typing_env(),
520 def_id,
521 args.no_bound_vars().unwrap(),
522 )
523 .unwrap();
524 OperandValue::Immediate(
525 bx.get_fn_addr(
526 instance,
527 bx.sess().pointer_authentication_functions(),
528 ),
529 )
530 }
531 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} cannot be reified to a fn ptr",
operand.layout.ty))bug!("{} cannot be reified to a fn ptr", operand.layout.ty),
532 }
533 }
534 mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => {
535 match *operand.layout.ty.kind() {
536 ty::Closure(def_id, args) => {
537 let instance = Instance::resolve_closure(
538 bx.cx().tcx(),
539 def_id,
540 args,
541 ty::ClosureKind::FnOnce,
542 );
543 OperandValue::Immediate(
544 bx.cx().get_fn_addr(
545 instance,
546 bx.sess().pointer_authentication_functions(),
547 ),
548 )
549 }
550 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} cannot be cast to a fn ptr",
operand.layout.ty))bug!("{} cannot be cast to a fn ptr", operand.layout.ty),
551 }
552 }
553 mir::CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
554 operand.val
556 }
557 mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
558 {
match cast.backend_repr {
BackendRepr::ScalarPair { .. } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"BackendRepr::ScalarPair { .. }",
::core::option::Option::None);
}
}
};assert_matches!(cast.backend_repr, BackendRepr::ScalarPair { .. });
559 let (lldata, llextra) = operand.val.pointer_parts();
560 let (lldata, llextra) =
561 base::unsize_ptr(bx, lldata, operand.layout.ty, cast.ty, llextra);
562 OperandValue::Pair(lldata, llextra)
563 }
564 mir::CastKind::PointerCoercion(
565 PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer,
566 _,
567 ) => {
568 ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} is for borrowck, and should never appear in codegen",
kind));bug!("{kind:?} is for borrowck, and should never appear in codegen");
569 }
570 mir::CastKind::PtrToPtr if let BackendRepr::ScalarPair { .. } = operand.layout.backend_repr => {
571 if let OperandValue::Pair(data_ptr, meta) = operand.val {
572 if let BackendRepr::ScalarPair { .. } = cast.layout.backend_repr {
573 OperandValue::Pair(data_ptr, meta)
574 } else {
575 OperandValue::Immediate(data_ptr)
577 }
578 } else {
579 ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected non-pair operand"));bug!("unexpected non-pair operand");
580 }
581 }
582 | mir::CastKind::IntToInt
583 | mir::CastKind::FloatToInt
584 | mir::CastKind::FloatToFloat
585 | mir::CastKind::IntToFloat
586 | mir::CastKind::PtrToPtr
587 | mir::CastKind::FnPtrToPtr
588 | mir::CastKind::PointerWithExposedProvenance => {
592 let imm = operand.immediate();
593 let abi::BackendRepr::Scalar(from_scalar) = operand.layout.backend_repr
594 else {
595 ::rustc_middle::util::bug::bug_fmt(format_args!("Found non-scalar for operand {0:?}",
operand));bug!("Found non-scalar for operand {operand:?}");
596 };
597 let from_backend_ty = bx.cx().immediate_backend_type(operand.layout);
598
599 if !cast.backend_repr.is_scalar_or_simd() {
::core::panicking::panic("assertion failed: cast.backend_repr.is_scalar_or_simd()")
};assert!(cast.backend_repr.is_scalar_or_simd());
600 let to_backend_ty = bx.cx().immediate_backend_type(cast);
601 if operand.layout.is_uninhabited() {
602 let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty));
603 return OperandRef { val, layout: cast, move_annotation: None };
604 }
605 let abi::BackendRepr::Scalar(to_scalar) = cast.layout.backend_repr else {
606 ::rustc_middle::util::bug::bug_fmt(format_args!("Found non-scalar for cast {0:?}",
cast));bug!("Found non-scalar for cast {cast:?}");
607 };
608
609 self.cast_immediate(
610 bx,
611 imm,
612 from_scalar,
613 from_backend_ty,
614 to_scalar,
615 to_backend_ty,
616 )
617 .map(OperandValue::Immediate)
618 .unwrap_or_else(|| {
619 ::rustc_middle::util::bug::bug_fmt(format_args!("Unsupported cast of {0:?} to {1:?}",
operand, cast));bug!("Unsupported cast of {operand:?} to {cast:?}");
620 })
621 }
622 mir::CastKind::Transmute | mir::CastKind::BoxDerefTransmute | mir::CastKind::Subtype => {
623 self.codegen_transmute_operand(bx, operand, cast)
624 }
625 };
626 OperandRef { val, layout: cast, move_annotation: None }
627 }
628
629 mir::Rvalue::Ref(_, bk, place) => {
630 let mk_ref = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
631 Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, bk.to_mutbl_lossy())
632 };
633 let op = self.codegen_place_to_pointer(bx, place, mk_ref);
634 if self.cx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some() {
635 self.codegen_retag_operand(bx, op, false)
636 } else {
637 op
638 }
639 }
640
641 mir::Rvalue::Reborrow(_, _, place) => {
646 self.codegen_operand(bx, &mir::Operand::Copy(place))
647 }
648
649 mir::Rvalue::RawPtr(kind, place) => {
650 let mk_ptr = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
651 Ty::new_ptr(tcx, ty, kind.to_mutbl_lossy())
652 };
653 self.codegen_place_to_pointer(bx, place, mk_ptr)
654 }
655
656 mir::Rvalue::BinaryOp(op_with_overflow, (ref lhs, ref rhs))
657 if let Some(op) = op_with_overflow.overflowing_to_wrapping() =>
658 {
659 let lhs = self.codegen_operand(bx, lhs);
660 let rhs = self.codegen_operand(bx, rhs);
661 let result = self.codegen_scalar_checked_binop(
662 bx,
663 op,
664 lhs.immediate(),
665 rhs.immediate(),
666 lhs.layout.ty,
667 );
668 let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
669 let operand_ty = Ty::new_tup(bx.tcx(), &[val_ty, bx.tcx().types.bool]);
670 OperandRef {
671 val: result,
672 layout: bx.cx().layout_of(operand_ty),
673 move_annotation: None,
674 }
675 }
676
677 mir::Rvalue::BinaryOp(op, (ref lhs, ref rhs)) => {
678 let lhs = self.codegen_operand(bx, lhs);
679 let rhs = self.codegen_operand(bx, rhs);
680 let llresult = match (lhs.val, rhs.val) {
681 (
682 OperandValue::Pair(lhs_addr, lhs_extra),
683 OperandValue::Pair(rhs_addr, rhs_extra),
684 ) => self.codegen_wide_ptr_binop(
685 bx,
686 op,
687 lhs_addr,
688 lhs_extra,
689 rhs_addr,
690 rhs_extra,
691 lhs.layout.ty,
692 ),
693
694 (OperandValue::Immediate(lhs_val), OperandValue::Immediate(rhs_val)) => self
695 .codegen_scalar_binop(
696 bx,
697 op,
698 lhs_val,
699 rhs_val,
700 lhs.layout.ty,
701 rhs.layout.ty,
702 ),
703
704 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
705 };
706 OperandRef {
707 val: OperandValue::Immediate(llresult),
708 layout: bx.cx().layout_of(op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
709 move_annotation: None,
710 }
711 }
712
713 mir::Rvalue::UnaryOp(op, ref operand) => {
714 let operand = self.codegen_operand(bx, operand);
715 let is_float = operand.layout.ty.is_floating_point();
716 let (val, layout) = match op {
717 mir::UnOp::Not => {
718 let llval = bx.not(operand.immediate());
719 (OperandValue::Immediate(llval), operand.layout)
720 }
721 mir::UnOp::Neg => {
722 let llval = if is_float {
723 bx.fneg(operand.immediate())
724 } else {
725 bx.neg(operand.immediate())
726 };
727 (OperandValue::Immediate(llval), operand.layout)
728 }
729 mir::UnOp::PtrMetadata => {
730 if !(operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref()) {
::core::panicking::panic("assertion failed: operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref()")
};assert!(operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref(),);
731 let (_, meta) = operand.val.pointer_parts();
732 {
match (&(operand.layout.fields.count() > 1), &meta.is_some()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(operand.layout.fields.count() > 1, meta.is_some());
733 if let Some(meta) = meta {
734 (OperandValue::Immediate(meta), operand.layout.field(self.cx, 1))
735 } else {
736 (OperandValue::ZeroSized, bx.cx().layout_of(bx.tcx().types.unit))
737 }
738 }
739 };
740 if !val.is_expected_variant_for_type(layout) {
{
::core::panicking::panic_fmt(format_args!("Made wrong variant {0:?} for type {1:?}",
val, layout));
}
};assert!(
741 val.is_expected_variant_for_type(layout),
742 "Made wrong variant {val:?} for type {layout:?}",
743 );
744 OperandRef { val, layout, move_annotation: None }
745 }
746
747 mir::Rvalue::Discriminant(ref place) => {
748 let discr_ty = rvalue.ty(self.mir, bx.tcx());
749 let discr_ty = self.monomorphize(discr_ty);
750 let operand = self.codegen_consume(bx, place.as_ref());
751 let discr = operand.codegen_get_discr(self, bx, discr_ty);
752 OperandRef {
753 val: OperandValue::Immediate(discr),
754 layout: self.cx.layout_of(discr_ty),
755 move_annotation: None,
756 }
757 }
758
759 mir::Rvalue::ThreadLocalRef(def_id) => {
760 if !bx.cx().tcx().is_static(def_id) {
::core::panicking::panic("assertion failed: bx.cx().tcx().is_static(def_id)")
};assert!(bx.cx().tcx().is_static(def_id));
761 let layout = bx.layout_of(bx.cx().tcx().static_ptr_ty(def_id, bx.typing_env()));
762 let static_ = if !def_id.is_local() && bx.cx().tcx().needs_thread_local_shim(def_id)
763 {
764 let instance = ty::Instance {
765 def: ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(def_id)),
766 args: ty::GenericArgs::empty(),
767 };
768 let fn_ptr =
769 bx.get_fn_addr(instance, bx.sess().pointer_authentication_functions());
770 let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty());
771 let fn_ty = bx.fn_decl_backend_type(fn_abi);
772 let fn_attrs = if bx.tcx().def_kind(instance.def_id()).has_codegen_attrs() {
773 Some(bx.tcx().codegen_instance_attrs(instance.def))
774 } else {
775 None
776 };
777 bx.call(
778 fn_ty,
779 fn_attrs.as_deref(),
780 Some(fn_abi),
781 fn_ptr,
782 &[],
783 None,
784 Some(instance),
785 )
786 } else {
787 bx.get_static(def_id)
788 };
789 OperandRef { val: OperandValue::Immediate(static_), layout, move_annotation: None }
790 }
791
792 mir::Rvalue::Use(ref operand, _) => self.codegen_operand(bx, operand),
793
794 mir::Rvalue::Repeat(ref elem, len_const) => {
795 let operand = self.codegen_operand(bx, elem);
799 let array_ty = Ty::new_array_with_const_len(bx.tcx(), operand.layout.ty, len_const);
800 let array_ty = self.monomorphize(array_ty);
801 let array_layout = bx.layout_of(array_ty);
802 if !array_layout.is_zst() {
::core::panicking::panic("assertion failed: array_layout.is_zst()")
};assert!(array_layout.is_zst());
803 OperandRef {
804 val: OperandValue::ZeroSized,
805 layout: array_layout,
806 move_annotation: None,
807 }
808 }
809
810 mir::Rvalue::Aggregate(ref kind, ref fields) => {
811 let (variant_index, active_field_index) = match **kind {
812 mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
813 (variant_index, active_field_index)
814 }
815 _ => (FIRST_VARIANT, None),
816 };
817
818 let ty = rvalue.ty(self.mir, self.cx.tcx());
819 let ty = self.monomorphize(ty);
820 let layout = self.cx.layout_of(ty);
821
822 let mut builder = OperandRefBuilder::new(layout);
823 for (field_idx, field) in fields.iter_enumerated() {
824 let op = self.codegen_operand(bx, field);
825 let fi = active_field_index.unwrap_or(field_idx);
826 builder.insert_field(bx, variant_index, fi, op);
827 }
828
829 let tag_result = codegen_tag_value(self.cx, variant_index, layout);
830 match tag_result {
831 Err(super::place::UninhabitedVariantError) => {
832 bx.abort();
836 let val = OperandValue::poison(bx, layout);
837 OperandRef { val, layout, move_annotation: None }
838 }
839 Ok(maybe_tag_value) => {
840 if let Some((tag_field, tag_imm)) = maybe_tag_value {
841 builder.insert_imm(tag_field, tag_imm);
842 }
843 builder.build(bx.cx())
844 }
845 }
846 }
847
848 mir::Rvalue::WrapUnsafeBinder(ref operand, binder_ty) => {
849 let operand = self.codegen_operand(bx, operand);
850 let binder_ty = self.monomorphize(binder_ty);
851 let layout = bx.cx().layout_of(binder_ty);
852 OperandRef { val: operand.val, layout, move_annotation: None }
853 }
854
855 mir::Rvalue::CopyForDeref(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("`CopyForDeref` in codegen"))bug!("`CopyForDeref` in codegen"),
856 }
857 }
858
859 fn codegen_place_to_pointer(
861 &mut self,
862 bx: &mut Bx,
863 place: mir::Place<'tcx>,
864 mk_ptr_ty: impl FnOnce(TyCtxt<'tcx>, Ty<'tcx>) -> Ty<'tcx>,
865 ) -> OperandRef<'tcx, Bx::Value> {
866 let cg_place = self.codegen_place(bx, place.as_ref());
867 let val = cg_place.val.address();
868
869 let ty = cg_place.layout.ty;
870 if !if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {
#[allow(non_exhaustive_omitted_patterns)]
match val { OperandValue::Pair(..) => true, _ => false, }
} else {
#[allow(non_exhaustive_omitted_patterns)]
match val { OperandValue::Immediate(..) => true, _ => false, }
} {
{
::core::panicking::panic_fmt(format_args!("Address of place was unexpectedly {0:?} for pointee type {1:?}",
val, ty));
}
};assert!(
871 if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {
872 matches!(val, OperandValue::Pair(..))
873 } else {
874 matches!(val, OperandValue::Immediate(..))
875 },
876 "Address of place was unexpectedly {val:?} for pointee type {ty:?}",
877 );
878
879 OperandRef {
880 val,
881 layout: self.cx.layout_of(mk_ptr_ty(self.cx.tcx(), ty)),
882 move_annotation: None,
883 }
884 }
885
886 fn codegen_scalar_binop(
887 &mut self,
888 bx: &mut Bx,
889 op: mir::BinOp,
890 lhs: Bx::Value,
891 rhs: Bx::Value,
892 lhs_ty: Ty<'tcx>,
893 rhs_ty: Ty<'tcx>,
894 ) -> Bx::Value {
895 let is_float = lhs_ty.is_floating_point();
896 let is_signed = lhs_ty.is_signed();
897 match op {
898 mir::BinOp::Add => {
899 if is_float {
900 bx.fadd(lhs, rhs)
901 } else {
902 bx.add(lhs, rhs)
903 }
904 }
905 mir::BinOp::AddUnchecked => {
906 if is_signed {
907 bx.unchecked_sadd(lhs, rhs)
908 } else {
909 bx.unchecked_uadd(lhs, rhs)
910 }
911 }
912 mir::BinOp::Sub => {
913 if is_float {
914 bx.fsub(lhs, rhs)
915 } else {
916 bx.sub(lhs, rhs)
917 }
918 }
919 mir::BinOp::SubUnchecked => {
920 if is_signed {
921 bx.unchecked_ssub(lhs, rhs)
922 } else {
923 bx.unchecked_usub(lhs, rhs)
924 }
925 }
926 mir::BinOp::Mul => {
927 if is_float {
928 bx.fmul(lhs, rhs)
929 } else {
930 bx.mul(lhs, rhs)
931 }
932 }
933 mir::BinOp::MulUnchecked => {
934 if is_signed {
935 bx.unchecked_smul(lhs, rhs)
936 } else {
937 bx.unchecked_umul(lhs, rhs)
938 }
939 }
940 mir::BinOp::Div => {
941 if is_float {
942 bx.fdiv(lhs, rhs)
943 } else if is_signed {
944 bx.sdiv(lhs, rhs)
945 } else {
946 bx.udiv(lhs, rhs)
947 }
948 }
949 mir::BinOp::Rem => {
950 if is_float {
951 bx.frem(lhs, rhs)
952 } else if is_signed {
953 bx.srem(lhs, rhs)
954 } else {
955 bx.urem(lhs, rhs)
956 }
957 }
958 mir::BinOp::BitOr => bx.or(lhs, rhs),
959 mir::BinOp::BitAnd => bx.and(lhs, rhs),
960 mir::BinOp::BitXor => bx.xor(lhs, rhs),
961 mir::BinOp::Offset => {
962 let pointee_type = lhs_ty
963 .builtin_deref(true)
964 .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("deref of non-pointer {0:?}",
lhs_ty))bug!("deref of non-pointer {:?}", lhs_ty));
965 let pointee_layout = bx.cx().layout_of(pointee_type);
966 if pointee_layout.is_zst() {
967 lhs
970 } else {
971 let llty = bx.cx().backend_type(pointee_layout);
972 if !rhs_ty.is_signed() {
973 bx.inbounds_nuw_gep(llty, lhs, &[rhs])
974 } else {
975 bx.inbounds_gep(llty, lhs, &[rhs])
976 }
977 }
978 }
979 mir::BinOp::Shl | mir::BinOp::ShlUnchecked => {
980 let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShlUnchecked);
981 bx.shl(lhs, rhs)
982 }
983 mir::BinOp::Shr | mir::BinOp::ShrUnchecked => {
984 let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShrUnchecked);
985 if is_signed { bx.ashr(lhs, rhs) } else { bx.lshr(lhs, rhs) }
986 }
987 mir::BinOp::Ne
988 | mir::BinOp::Lt
989 | mir::BinOp::Gt
990 | mir::BinOp::Eq
991 | mir::BinOp::Le
992 | mir::BinOp::Ge => {
993 if is_float {
994 bx.fcmp(base::bin_op_to_fcmp_predicate(op), lhs, rhs)
995 } else {
996 bx.icmp(base::bin_op_to_icmp_predicate(op, is_signed), lhs, rhs)
997 }
998 }
999 mir::BinOp::Cmp => {
1000 if !!is_float { ::core::panicking::panic("assertion failed: !is_float") };assert!(!is_float);
1001 bx.three_way_compare(lhs_ty, lhs, rhs)
1002 }
1003 mir::BinOp::AddWithOverflow
1004 | mir::BinOp::SubWithOverflow
1005 | mir::BinOp::MulWithOverflow => {
1006 ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} needs to return a pair, so call codegen_scalar_checked_binop instead",
op))bug!("{op:?} needs to return a pair, so call codegen_scalar_checked_binop instead")
1007 }
1008 }
1009 }
1010
1011 fn codegen_wide_ptr_binop(
1012 &mut self,
1013 bx: &mut Bx,
1014 op: mir::BinOp,
1015 lhs_addr: Bx::Value,
1016 lhs_extra: Bx::Value,
1017 rhs_addr: Bx::Value,
1018 rhs_extra: Bx::Value,
1019 _input_ty: Ty<'tcx>,
1020 ) -> Bx::Value {
1021 match op {
1022 mir::BinOp::Eq => {
1023 let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1024 let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
1025 bx.and(lhs, rhs)
1026 }
1027 mir::BinOp::Ne => {
1028 let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
1029 let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
1030 bx.or(lhs, rhs)
1031 }
1032 mir::BinOp::Le | mir::BinOp::Lt | mir::BinOp::Ge | mir::BinOp::Gt => {
1033 let (op, strict_op) = match op {
1035 mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
1036 mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
1037 mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
1038 mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
1039 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1040 };
1041 let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
1042 let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1043 let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
1044 let rhs = bx.and(and_lhs, and_rhs);
1045 bx.or(lhs, rhs)
1046 }
1047 _ => {
1048 ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected wide ptr binop"));bug!("unexpected wide ptr binop");
1049 }
1050 }
1051 }
1052
1053 fn codegen_scalar_checked_binop(
1054 &mut self,
1055 bx: &mut Bx,
1056 op: mir::BinOp,
1057 lhs: Bx::Value,
1058 rhs: Bx::Value,
1059 input_ty: Ty<'tcx>,
1060 ) -> OperandValue<Bx::Value> {
1061 let (val, of) = match op {
1062 mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
1064 let oop = match op {
1065 mir::BinOp::Add => OverflowOp::Add,
1066 mir::BinOp::Sub => OverflowOp::Sub,
1067 mir::BinOp::Mul => OverflowOp::Mul,
1068 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1069 };
1070 bx.checked_binop(oop, input_ty, lhs, rhs)
1071 }
1072 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Operator `{0:?}` is not a checkable operator",
op))bug!("Operator `{:?}` is not a checkable operator", op),
1073 };
1074
1075 OperandValue::Pair(val, of)
1076 }
1077}
1078
1079pub(super) fn transmute_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1087 bx: &mut Bx,
1088 mut imm: Bx::Value,
1089 from_scalar: abi::Scalar,
1090 to_scalar: abi::Scalar,
1091) -> Bx::Value {
1092 {
match (&from_scalar.size(bx.cx()), &to_scalar.size(bx.cx())) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(from_scalar.size(bx.cx()), to_scalar.size(bx.cx()));
1093 let imm_ty = bx.cx().val_ty(imm);
1094 {
match (&(bx.cx().type_kind(imm_ty)), &(TypeKind::Vector)) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("Vector type {0:?} not allowed in transmute_scalar {1:?} -> {2:?}",
imm_ty, from_scalar, to_scalar)));
}
}
}
};assert_ne!(
1095 bx.cx().type_kind(imm_ty),
1096 TypeKind::Vector,
1097 "Vector type {imm_ty:?} not allowed in transmute_scalar {from_scalar:?} -> {to_scalar:?}"
1098 );
1099
1100 if from_scalar == to_scalar {
1104 return imm;
1105 }
1106
1107 use abi::Primitive::*;
1108 imm = bx.from_immediate(imm);
1109
1110 let from_backend_ty = bx.cx().type_from_scalar(from_scalar);
1111 if true {
{
match (&bx.cx().val_ty(imm), &from_backend_ty) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(bx.cx().val_ty(imm), from_backend_ty);
1112 let to_backend_ty = bx.cx().type_from_scalar(to_scalar);
1113
1114 assume_scalar_range(bx, imm, from_scalar, from_backend_ty, Some(&to_scalar));
1124
1125 imm = match (from_scalar.primitive(), to_scalar.primitive()) {
1126 (Int(..) | Float(_), Int(..) | Float(_)) => bx.bitcast(imm, to_backend_ty),
1127 (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
1128 (Int(..), Pointer(..)) => bx.inttoptr(imm, to_backend_ty),
1129 (Pointer(..), Int(..)) => {
1130 bx.ptrtoint(imm, to_backend_ty)
1132 }
1133 (Float(_), Pointer(..)) => {
1134 let int_imm = bx.bitcast(imm, bx.cx().type_isize());
1135 bx.inttoptr(int_imm, to_backend_ty)
1136 }
1137 (Pointer(..), Float(_)) => {
1138 let int_imm = bx.ptrtoint(imm, bx.cx().type_isize());
1140 bx.bitcast(int_imm, to_backend_ty)
1141 }
1142 };
1143
1144 if true {
{
match (&bx.cx().val_ty(imm), &to_backend_ty) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(bx.cx().val_ty(imm), to_backend_ty);
1145
1146 assume_scalar_range(bx, imm, to_scalar, to_backend_ty, Some(&from_scalar));
1152
1153 imm = bx.to_immediate_scalar(imm, to_scalar);
1154 imm
1155}
1156
1157fn assume_scalar_range<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1162 bx: &mut Bx,
1163 imm: Bx::Value,
1164 scalar: abi::Scalar,
1165 backend_ty: Bx::Type,
1166 known: Option<&abi::Scalar>,
1167) {
1168 if #[allow(non_exhaustive_omitted_patterns)] match bx.cx().sess().opts.optimize {
OptLevel::No => true,
_ => false,
}matches!(bx.cx().sess().opts.optimize, OptLevel::No) {
1169 return;
1170 }
1171
1172 match (scalar, known) {
1173 (abi::Scalar::Union { .. }, _) => return,
1174 (_, None) => {
1175 if scalar.is_always_valid(bx.cx()) {
1176 return;
1177 }
1178 }
1179 (abi::Scalar::Initialized { valid_range, .. }, Some(known)) => {
1180 let known_range = known.valid_range(bx.cx());
1181 if valid_range.contains_range(known_range, scalar.size(bx.cx())) {
1182 return;
1183 }
1184 }
1185 }
1186
1187 match scalar.primitive() {
1188 abi::Primitive::Int(..) => {
1189 let range = scalar.valid_range(bx.cx());
1190 bx.assume_integer_range(imm, backend_ty, range);
1191 }
1192 abi::Primitive::Pointer(abi::AddressSpace::ZERO)
1193 if !scalar.valid_range(bx.cx()).contains(0) =>
1194 {
1195 bx.assume_nonnull(imm);
1196 }
1197 abi::Primitive::Pointer(..) | abi::Primitive::Float(..) => {}
1198 }
1199}