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