1use std::assert_matches::assert_matches;
2use std::fmt;
3
4use arrayvec::ArrayVec;
5use either::Either;
6use rustc_abi as abi;
7use rustc_abi::{Align, BackendRepr, Size};
8use rustc_middle::bug;
9use rustc_middle::mir::interpret::{Pointer, Scalar, alloc_range};
10use rustc_middle::mir::{self, ConstValue};
11use rustc_middle::ty::Ty;
12use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
13use tracing::debug;
14
15use super::place::{PlaceRef, PlaceValue};
16use super::{FunctionCx, LocalRef};
17use crate::traits::*;
18use crate::{MemFlags, size_of_val};
19
20#[derive(Copy, Clone, Debug)]
24pub enum OperandValue<V> {
25 Ref(PlaceValue<V>),
38 Immediate(V),
45 Pair(V, V),
53 ZeroSized,
62}
63
64impl<V: CodegenObject> OperandValue<V> {
65 #[inline]
68 pub(crate) fn immediates_or_place(self) -> Either<ArrayVec<V, 2>, PlaceValue<V>> {
69 match self {
70 OperandValue::ZeroSized => Either::Left(ArrayVec::new()),
71 OperandValue::Immediate(a) => Either::Left(ArrayVec::from_iter([a])),
72 OperandValue::Pair(a, b) => Either::Left([a, b].into()),
73 OperandValue::Ref(p) => Either::Right(p),
74 }
75 }
76
77 #[inline]
79 pub(crate) fn from_immediates(immediates: ArrayVec<V, 2>) -> Self {
80 let mut it = immediates.into_iter();
81 let Some(a) = it.next() else {
82 return OperandValue::ZeroSized;
83 };
84 let Some(b) = it.next() else {
85 return OperandValue::Immediate(a);
86 };
87 OperandValue::Pair(a, b)
88 }
89
90 pub(crate) fn pointer_parts(self) -> (V, Option<V>) {
95 match self {
96 OperandValue::Immediate(llptr) => (llptr, None),
97 OperandValue::Pair(llptr, llextra) => (llptr, Some(llextra)),
98 _ => bug!("OperandValue cannot be a pointer: {self:?}"),
99 }
100 }
101
102 pub(crate) fn deref(self, align: Align) -> PlaceValue<V> {
110 let (llval, llextra) = self.pointer_parts();
111 PlaceValue { llval, llextra, align }
112 }
113
114 pub(crate) fn is_expected_variant_for_type<'tcx, Cx: LayoutTypeCodegenMethods<'tcx>>(
115 &self,
116 cx: &Cx,
117 ty: TyAndLayout<'tcx>,
118 ) -> bool {
119 match self {
120 OperandValue::ZeroSized => ty.is_zst(),
121 OperandValue::Immediate(_) => cx.is_backend_immediate(ty),
122 OperandValue::Pair(_, _) => cx.is_backend_scalar_pair(ty),
123 OperandValue::Ref(_) => cx.is_backend_ref(ty),
124 }
125 }
126}
127
128#[derive(Copy, Clone)]
137pub struct OperandRef<'tcx, V> {
138 pub val: OperandValue<V>,
140
141 pub layout: TyAndLayout<'tcx>,
143}
144
145impl<V: CodegenObject> fmt::Debug for OperandRef<'_, V> {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
148 }
149}
150
151impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
152 pub fn zero_sized(layout: TyAndLayout<'tcx>) -> OperandRef<'tcx, V> {
153 assert!(layout.is_zst());
154 OperandRef { val: OperandValue::ZeroSized, layout }
155 }
156
157 pub(crate) fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
158 bx: &mut Bx,
159 val: mir::ConstValue<'tcx>,
160 ty: Ty<'tcx>,
161 ) -> Self {
162 let layout = bx.layout_of(ty);
163
164 let val = match val {
165 ConstValue::Scalar(x) => {
166 let BackendRepr::Scalar(scalar) = layout.backend_repr else {
167 bug!("from_const: invalid ByVal layout: {:#?}", layout);
168 };
169 let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
170 OperandValue::Immediate(llval)
171 }
172 ConstValue::ZeroSized => return OperandRef::zero_sized(layout),
173 ConstValue::Slice { data, meta } => {
174 let BackendRepr::ScalarPair(a_scalar, _) = layout.backend_repr else {
175 bug!("from_const: invalid ScalarPair layout: {:#?}", layout);
176 };
177 let a = Scalar::from_pointer(
178 Pointer::new(bx.tcx().reserve_and_set_memory_alloc(data).into(), Size::ZERO),
179 &bx.tcx(),
180 );
181 let a_llval = bx.scalar_to_backend(
182 a,
183 a_scalar,
184 bx.scalar_pair_element_backend_type(layout, 0, true),
185 );
186 let b_llval = bx.const_usize(meta);
187 OperandValue::Pair(a_llval, b_llval)
188 }
189 ConstValue::Indirect { alloc_id, offset } => {
190 let alloc = bx.tcx().global_alloc(alloc_id).unwrap_memory();
191 return Self::from_const_alloc(bx, layout, alloc, offset);
192 }
193 };
194
195 OperandRef { val, layout }
196 }
197
198 fn from_const_alloc<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
199 bx: &mut Bx,
200 layout: TyAndLayout<'tcx>,
201 alloc: rustc_middle::mir::interpret::ConstAllocation<'tcx>,
202 offset: Size,
203 ) -> Self {
204 let alloc_align = alloc.inner().align;
205 assert!(alloc_align >= layout.align.abi);
206
207 let read_scalar = |start, size, s: abi::Scalar, ty| {
210 let range = alloc_range(start, size);
211 match alloc.0.read_scalar(
212 bx,
213 range,
214 matches!(s.primitive(), abi::Primitive::Pointer(_)),
215 ) {
216 Ok(val) => Some(bx.scalar_to_backend(val, s, ty)),
217 Err(_) => {
218 if alloc.0.provenance().range_empty(range, &bx.tcx())
221 && alloc.0.init_mask().is_range_initialized(range).unwrap_err() == range
225 {
226 Some(bx.const_undef(ty))
227 } else {
228 None
229 }
230 }
231 }
232 };
233
234 match layout.backend_repr {
241 BackendRepr::Scalar(s) => {
242 let size = s.size(bx);
243 assert_eq!(size, layout.size, "abi::Scalar size does not match layout size");
244 if let Some(val) = read_scalar(offset, size, s, bx.immediate_backend_type(layout)) {
245 return OperandRef { val: OperandValue::Immediate(val), layout };
246 }
247 }
248 BackendRepr::ScalarPair(a, b) => {
249 let (a_size, b_size) = (a.size(bx), b.size(bx));
250 let b_offset = (offset + a_size).align_to(b.align(bx).abi);
251 assert!(b_offset.bytes() > 0);
252 let a_val = read_scalar(
253 offset,
254 a_size,
255 a,
256 bx.scalar_pair_element_backend_type(layout, 0, true),
257 );
258 let b_val = read_scalar(
259 b_offset,
260 b_size,
261 b,
262 bx.scalar_pair_element_backend_type(layout, 1, true),
263 );
264 if let (Some(a_val), Some(b_val)) = (a_val, b_val) {
265 return OperandRef { val: OperandValue::Pair(a_val, b_val), layout };
266 }
267 }
268 _ if layout.is_zst() => return OperandRef::zero_sized(layout),
269 _ => {}
270 }
271 let init = bx.const_data_from_alloc(alloc);
275 let base_addr = bx.static_addr_of(init, alloc_align, None);
276
277 let llval = bx.const_ptr_byte_offset(base_addr, offset);
278 bx.load_operand(PlaceRef::new_sized(llval, layout))
279 }
280
281 pub fn immediate(self) -> V {
284 match self.val {
285 OperandValue::Immediate(s) => s,
286 _ => bug!("not immediate: {:?}", self),
287 }
288 }
289
290 pub fn deref<Cx: CodegenMethods<'tcx>>(self, cx: &Cx) -> PlaceRef<'tcx, V> {
300 if self.layout.ty.is_box() {
301 bug!("dereferencing {:?} in codegen", self.layout.ty);
303 }
304
305 let projected_ty = self
306 .layout
307 .ty
308 .builtin_deref(true)
309 .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self));
310
311 let layout = cx.layout_of(projected_ty);
312 self.val.deref(layout.align.abi).with_type(layout)
313 }
314
315 pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
318 self,
319 bx: &mut Bx,
320 ) -> V {
321 if let OperandValue::Pair(a, b) = self.val {
322 let llty = bx.cx().immediate_backend_type(self.layout);
323 debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}", self, llty);
324 let mut llpair = bx.cx().const_poison(llty);
326 llpair = bx.insert_value(llpair, a, 0);
327 llpair = bx.insert_value(llpair, b, 1);
328 llpair
329 } else {
330 self.immediate()
331 }
332 }
333
334 pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
336 bx: &mut Bx,
337 llval: V,
338 layout: TyAndLayout<'tcx>,
339 ) -> Self {
340 let val = if let BackendRepr::ScalarPair(..) = layout.backend_repr {
341 debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}", llval, layout);
342
343 let a_llval = bx.extract_value(llval, 0);
345 let b_llval = bx.extract_value(llval, 1);
346 OperandValue::Pair(a_llval, b_llval)
347 } else {
348 OperandValue::Immediate(llval)
349 };
350 OperandRef { val, layout }
351 }
352
353 pub(crate) fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
354 &self,
355 bx: &mut Bx,
356 i: usize,
357 ) -> Self {
358 let field = self.layout.field(bx.cx(), i);
359 let offset = self.layout.fields.offset(i);
360
361 let mut val = match (self.val, self.layout.backend_repr) {
362 _ if field.is_zst() => OperandValue::ZeroSized,
364
365 (OperandValue::Immediate(_) | OperandValue::Pair(..), _)
367 if field.size == self.layout.size =>
368 {
369 assert_eq!(offset.bytes(), 0);
370 self.val
371 }
372
373 (OperandValue::Pair(a_llval, b_llval), BackendRepr::ScalarPair(a, b)) => {
375 if offset.bytes() == 0 {
376 assert_eq!(field.size, a.size(bx.cx()));
377 OperandValue::Immediate(a_llval)
378 } else {
379 assert_eq!(offset, a.size(bx.cx()).align_to(b.align(bx.cx()).abi));
380 assert_eq!(field.size, b.size(bx.cx()));
381 OperandValue::Immediate(b_llval)
382 }
383 }
384
385 (OperandValue::Immediate(llval), BackendRepr::Vector { .. }) => {
387 OperandValue::Immediate(bx.extract_element(llval, bx.cx().const_usize(i as u64)))
388 }
389
390 _ => bug!("OperandRef::extract_field({:?}): not applicable", self),
391 };
392
393 match (&mut val, field.backend_repr) {
394 (OperandValue::ZeroSized, _) => {}
395 (
396 OperandValue::Immediate(llval),
397 BackendRepr::Scalar(_) | BackendRepr::ScalarPair(..) | BackendRepr::Vector { .. },
398 ) => {
399 *llval = bx.to_immediate(*llval, field);
401 }
402 (OperandValue::Pair(a, b), BackendRepr::ScalarPair(a_abi, b_abi)) => {
403 *a = bx.to_immediate_scalar(*a, a_abi);
405 *b = bx.to_immediate_scalar(*b, b_abi);
406 }
407 (OperandValue::Immediate(llval), BackendRepr::Memory { sized: true }) => {
409 assert_matches!(self.layout.backend_repr, BackendRepr::Vector { .. });
410
411 let llfield_ty = bx.cx().backend_type(field);
412
413 let llptr = bx.alloca(field.size, field.align.abi);
415 bx.store(*llval, llptr, field.align.abi);
416 *llval = bx.load(llfield_ty, llptr, field.align.abi);
417 }
418 (
419 OperandValue::Immediate(_),
420 BackendRepr::Uninhabited | BackendRepr::Memory { sized: false },
421 ) => {
422 bug!()
423 }
424 (OperandValue::Pair(..), _) => bug!(),
425 (OperandValue::Ref(..), _) => bug!(),
426 }
427
428 OperandRef { val, layout: field }
429 }
430}
431
432impl<'a, 'tcx, V: CodegenObject> OperandValue<V> {
433 pub fn poison<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
440 bx: &mut Bx,
441 layout: TyAndLayout<'tcx>,
442 ) -> OperandValue<V> {
443 assert!(layout.is_sized());
444 if layout.is_zst() {
445 OperandValue::ZeroSized
446 } else if bx.cx().is_backend_immediate(layout) {
447 let ibty = bx.cx().immediate_backend_type(layout);
448 OperandValue::Immediate(bx.const_poison(ibty))
449 } else if bx.cx().is_backend_scalar_pair(layout) {
450 let ibty0 = bx.cx().scalar_pair_element_backend_type(layout, 0, true);
451 let ibty1 = bx.cx().scalar_pair_element_backend_type(layout, 1, true);
452 OperandValue::Pair(bx.const_poison(ibty0), bx.const_poison(ibty1))
453 } else {
454 let ptr = bx.cx().type_ptr();
455 OperandValue::Ref(PlaceValue::new_sized(bx.const_poison(ptr), layout.align.abi))
456 }
457 }
458
459 pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
460 self,
461 bx: &mut Bx,
462 dest: PlaceRef<'tcx, V>,
463 ) {
464 self.store_with_flags(bx, dest, MemFlags::empty());
465 }
466
467 pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
468 self,
469 bx: &mut Bx,
470 dest: PlaceRef<'tcx, V>,
471 ) {
472 self.store_with_flags(bx, dest, MemFlags::VOLATILE);
473 }
474
475 pub fn unaligned_volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
476 self,
477 bx: &mut Bx,
478 dest: PlaceRef<'tcx, V>,
479 ) {
480 self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
481 }
482
483 pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
484 self,
485 bx: &mut Bx,
486 dest: PlaceRef<'tcx, V>,
487 ) {
488 self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
489 }
490
491 pub(crate) fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
492 self,
493 bx: &mut Bx,
494 dest: PlaceRef<'tcx, V>,
495 flags: MemFlags,
496 ) {
497 debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
498 match self {
499 OperandValue::ZeroSized => {
500 }
503 OperandValue::Ref(val) => {
504 assert!(dest.layout.is_sized(), "cannot directly store unsized values");
505 if val.llextra.is_some() {
506 bug!("cannot directly store unsized values");
507 }
508 bx.typed_place_copy_with_flags(dest.val, val, dest.layout, flags);
509 }
510 OperandValue::Immediate(s) => {
511 let val = bx.from_immediate(s);
512 bx.store_with_flags(val, dest.val.llval, dest.val.align, flags);
513 }
514 OperandValue::Pair(a, b) => {
515 let BackendRepr::ScalarPair(a_scalar, b_scalar) = dest.layout.backend_repr else {
516 bug!("store_with_flags: invalid ScalarPair layout: {:#?}", dest.layout);
517 };
518 let b_offset = a_scalar.size(bx).align_to(b_scalar.align(bx).abi);
519
520 let val = bx.from_immediate(a);
521 let align = dest.val.align;
522 bx.store_with_flags(val, dest.val.llval, align, flags);
523
524 let llptr = bx.inbounds_ptradd(dest.val.llval, bx.const_usize(b_offset.bytes()));
525 let val = bx.from_immediate(b);
526 let align = dest.val.align.restrict_for_offset(b_offset);
527 bx.store_with_flags(val, llptr, align, flags);
528 }
529 }
530 }
531
532 pub fn store_unsized<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
533 self,
534 bx: &mut Bx,
535 indirect_dest: PlaceRef<'tcx, V>,
536 ) {
537 debug!("OperandRef::store_unsized: operand={:?}, indirect_dest={:?}", self, indirect_dest);
538 let unsized_ty = indirect_dest
540 .layout
541 .ty
542 .builtin_deref(true)
543 .unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest));
544
545 let OperandValue::Ref(PlaceValue { llval: llptr, llextra: Some(llextra), .. }) = self
546 else {
547 bug!("store_unsized called with a sized value (or with an extern type)")
548 };
549
550 let (size, align) = size_of_val::size_and_align_of_dst(bx, unsized_ty, Some(llextra));
554 let one = bx.const_usize(1);
555 let align_minus_1 = bx.sub(align, one);
556 let size_extra = bx.add(size, align_minus_1);
557 let min_align = Align::ONE;
558 let alloca = bx.dynamic_alloca(size_extra, min_align);
559 let address = bx.ptrtoint(alloca, bx.type_isize());
560 let neg_address = bx.neg(address);
561 let offset = bx.and(neg_address, align_minus_1);
562 let dst = bx.inbounds_ptradd(alloca, offset);
563 bx.memcpy(dst, min_align, llptr, min_align, size, MemFlags::empty());
564
565 let indirect_operand = OperandValue::Pair(dst, llextra);
567 indirect_operand.store(bx, indirect_dest);
568 }
569}
570
571impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
572 fn maybe_codegen_consume_direct(
573 &mut self,
574 bx: &mut Bx,
575 place_ref: mir::PlaceRef<'tcx>,
576 ) -> Option<OperandRef<'tcx, Bx::Value>> {
577 debug!("maybe_codegen_consume_direct(place_ref={:?})", place_ref);
578
579 match self.locals[place_ref.local] {
580 LocalRef::Operand(mut o) => {
581 for elem in place_ref.projection.iter() {
583 match elem {
584 mir::ProjectionElem::Field(ref f, _) => {
585 assert!(
586 !o.layout.ty.is_any_ptr(),
587 "Bad PlaceRef: destructing pointers should use cast/PtrMetadata, \
588 but tried to access field {f:?} of pointer {o:?}",
589 );
590 o = o.extract_field(bx, f.index());
591 }
592 mir::ProjectionElem::Index(_)
593 | mir::ProjectionElem::ConstantIndex { .. } => {
594 let elem = o.layout.field(bx.cx(), 0);
598 if elem.is_zst() {
599 o = OperandRef::zero_sized(elem);
600 } else {
601 return None;
602 }
603 }
604 _ => return None,
605 }
606 }
607
608 Some(o)
609 }
610 LocalRef::PendingOperand => {
611 bug!("use of {:?} before def", place_ref);
612 }
613 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
614 None
617 }
618 }
619 }
620
621 pub fn codegen_consume(
622 &mut self,
623 bx: &mut Bx,
624 place_ref: mir::PlaceRef<'tcx>,
625 ) -> OperandRef<'tcx, Bx::Value> {
626 debug!("codegen_consume(place_ref={:?})", place_ref);
627
628 let ty = self.monomorphized_place_ty(place_ref);
629 let layout = bx.cx().layout_of(ty);
630
631 if layout.is_zst() {
633 return OperandRef::zero_sized(layout);
634 }
635
636 if let Some(o) = self.maybe_codegen_consume_direct(bx, place_ref) {
637 return o;
638 }
639
640 let place = self.codegen_place(bx, place_ref);
643 bx.load_operand(place)
644 }
645
646 pub fn codegen_operand(
647 &mut self,
648 bx: &mut Bx,
649 operand: &mir::Operand<'tcx>,
650 ) -> OperandRef<'tcx, Bx::Value> {
651 debug!("codegen_operand(operand={:?})", operand);
652
653 match *operand {
654 mir::Operand::Copy(ref place) | mir::Operand::Move(ref place) => {
655 self.codegen_consume(bx, place.as_ref())
656 }
657
658 mir::Operand::Constant(ref constant) => {
659 let constant_ty = self.monomorphize(constant.ty());
660 if constant_ty.is_simd() {
663 let layout = bx.layout_of(constant_ty);
666 if let BackendRepr::Vector { .. } = layout.backend_repr {
667 let (llval, ty) = self.immediate_const_vector(bx, constant);
668 return OperandRef {
669 val: OperandValue::Immediate(llval),
670 layout: bx.layout_of(ty),
671 };
672 }
673 }
674 self.eval_mir_constant_to_operand(bx, constant)
675 }
676 }
677 }
678}