1use rustc_abi::FieldIdx;
4use rustc_hir::lang_items::LangItem;
5use rustc_index::{Idx, IndexVec};
6use rustc_middle::bug;
7use rustc_middle::middle::region;
8use rustc_middle::mir::interpret::Scalar;
9use rustc_middle::mir::*;
10use rustc_middle::thir::*;
11use rustc_middle::ty::cast::{CastTy, mir_cast_kind};
12use rustc_middle::ty::util::IntTypeExt;
13use rustc_middle::ty::{self, Ty, UpvarArgs};
14use rustc_span::source_map::Spanned;
15use rustc_span::{DUMMY_SP, Span};
16use tracing::debug;
17
18use crate::builder::expr::as_place::PlaceBase;
19use crate::builder::expr::category::{Category, RvalueFunc};
20use crate::builder::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary};
21
22impl<'a, 'tcx> Builder<'a, 'tcx> {
23 pub(crate) fn as_local_rvalue(
30 &mut self,
31 block: BasicBlock,
32 expr_id: ExprId,
33 ) -> BlockAnd<Rvalue<'tcx>> {
34 let local_scope = self.local_scope();
35 self.as_rvalue(
36 block,
37 TempLifetime { temp_lifetime: Some(local_scope), backwards_incompatible: None },
38 expr_id,
39 )
40 }
41
42 pub(crate) fn as_rvalue(
44 &mut self,
45 mut block: BasicBlock,
46 scope: TempLifetime,
47 expr_id: ExprId,
48 ) -> BlockAnd<Rvalue<'tcx>> {
49 let this = self;
50 let expr = &this.thir[expr_id];
51 debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
52
53 let expr_span = expr.span;
54 let source_info = this.source_info(expr_span);
55
56 match expr.kind {
57 ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(did)),
58 ExprKind::Scope { region_scope, lint_level, value } => {
59 let region_scope = (region_scope, source_info);
60 this.in_scope(region_scope, lint_level, |this| this.as_rvalue(block, scope, value))
61 }
62 ExprKind::Repeat { value, count } => {
63 if Some(0) == count.try_to_target_usize(this.tcx) {
64 this.build_zero_repeat(block, value, scope, source_info)
65 } else {
66 let value_operand = unpack!(
67 block = this.as_operand(
68 block,
69 scope,
70 value,
71 LocalInfo::Boring,
72 NeedsTemporary::No
73 )
74 );
75 block.and(Rvalue::Repeat(value_operand, count))
76 }
77 }
78 ExprKind::Binary { op, lhs, rhs } => {
79 let lhs = unpack!(
80 block = this.as_operand(
81 block,
82 scope,
83 lhs,
84 LocalInfo::Boring,
85 NeedsTemporary::Maybe
86 )
87 );
88 let rhs = unpack!(
89 block =
90 this.as_operand(block, scope, rhs, LocalInfo::Boring, NeedsTemporary::No)
91 );
92 this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
93 }
94 ExprKind::Unary { op, arg } => {
95 let arg = unpack!(
96 block =
97 this.as_operand(block, scope, arg, LocalInfo::Boring, NeedsTemporary::No)
98 );
99 if this.check_overflow && op == UnOp::Neg && expr.ty.is_signed() {
101 let bool_ty = this.tcx.types.bool;
102
103 let minval = this.minval_literal(expr_span, expr.ty);
104 let is_min = this.temp(bool_ty, expr_span);
105
106 this.cfg.push_assign(
107 block,
108 source_info,
109 is_min,
110 Rvalue::BinaryOp(BinOp::Eq, Box::new((arg.to_copy(), minval))),
111 );
112
113 block = this.assert(
114 block,
115 Operand::Move(is_min),
116 false,
117 AssertKind::OverflowNeg(arg.to_copy()),
118 expr_span,
119 );
120 }
121 block.and(Rvalue::UnaryOp(op, arg))
122 }
123 ExprKind::Box { value } => {
124 let value_ty = this.thir[value].ty;
125 let tcx = this.tcx;
126 let source_info = this.source_info(expr_span);
127
128 let size = this.temp(tcx.types.usize, expr_span);
129 this.cfg.push_assign(
130 block,
131 source_info,
132 size,
133 Rvalue::NullaryOp(NullOp::SizeOf, value_ty),
134 );
135
136 let align = this.temp(tcx.types.usize, expr_span);
137 this.cfg.push_assign(
138 block,
139 source_info,
140 align,
141 Rvalue::NullaryOp(NullOp::AlignOf, value_ty),
142 );
143
144 let exchange_malloc = Operand::function_handle(
146 tcx,
147 tcx.require_lang_item(LangItem::ExchangeMalloc, expr_span),
148 [],
149 expr_span,
150 );
151 let storage = this.temp(Ty::new_mut_ptr(tcx, tcx.types.u8), expr_span);
152 let success = this.cfg.start_new_block();
153 this.cfg.terminate(
154 block,
155 source_info,
156 TerminatorKind::Call {
157 func: exchange_malloc,
158 args: [
159 Spanned { node: Operand::Move(size), span: DUMMY_SP },
160 Spanned { node: Operand::Move(align), span: DUMMY_SP },
161 ]
162 .into(),
163 destination: storage,
164 target: Some(success),
165 unwind: UnwindAction::Continue,
166 call_source: CallSource::Misc,
167 fn_span: expr_span,
168 },
169 );
170 this.diverge_from(block);
171 block = success;
172
173 let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span));
174 this.cfg
175 .push(block, Statement::new(source_info, StatementKind::StorageLive(result)));
176 if let Some(scope) = scope.temp_lifetime {
177 this.schedule_drop_storage_and_value(expr_span, scope, result);
179 }
180
181 let box_ = Rvalue::ShallowInitBox(Operand::Move(storage), value_ty);
183 this.cfg.push_assign(block, source_info, Place::from(result), box_);
184
185 block = this
187 .expr_into_dest(this.tcx.mk_place_deref(Place::from(result)), block, value)
188 .into_block();
189 block.and(Rvalue::Use(Operand::Move(Place::from(result))))
190 }
191 ExprKind::Cast { source } => {
192 let source_expr = &this.thir[source];
193
194 let (source, ty) = if let ty::Adt(adt_def, ..) = source_expr.ty.kind()
198 && adt_def.is_enum()
199 {
200 let discr_ty = adt_def.repr().discr_type().to_ty(this.tcx);
201 let temp = unpack!(block = this.as_temp(block, scope, source, Mutability::Not));
202 let discr = this.temp(discr_ty, source_expr.span);
203 this.cfg.push_assign(
204 block,
205 source_info,
206 discr,
207 Rvalue::Discriminant(temp.into()),
208 );
209 (Operand::Move(discr), discr_ty)
210 } else {
211 let ty = source_expr.ty;
212 let source = unpack!(
213 block = this.as_operand(
214 block,
215 scope,
216 source,
217 LocalInfo::Boring,
218 NeedsTemporary::No
219 )
220 );
221 (source, ty)
222 };
223 let from_ty = CastTy::from_ty(ty);
224 let cast_ty = CastTy::from_ty(expr.ty);
225 debug!("ExprKind::Cast from_ty={from_ty:?}, cast_ty={:?}/{cast_ty:?}", expr.ty);
226 let cast_kind = mir_cast_kind(ty, expr.ty);
227 block.and(Rvalue::Cast(cast_kind, source, expr.ty))
228 }
229 ExprKind::PointerCoercion { cast, source, is_from_as_cast } => {
230 let source = unpack!(
231 block = this.as_operand(
232 block,
233 scope,
234 source,
235 LocalInfo::Boring,
236 NeedsTemporary::No
237 )
238 );
239 let origin =
240 if is_from_as_cast { CoercionSource::AsCast } else { CoercionSource::Implicit };
241 block.and(Rvalue::Cast(CastKind::PointerCoercion(cast, origin), source, expr.ty))
242 }
243 ExprKind::Array { ref fields } => {
244 let el_ty = expr.ty.sequence_element_type(this.tcx);
272 let fields: IndexVec<FieldIdx, _> = fields
273 .into_iter()
274 .copied()
275 .map(|f| {
276 unpack!(
277 block = this.as_operand(
278 block,
279 scope,
280 f,
281 LocalInfo::Boring,
282 NeedsTemporary::Maybe
283 )
284 )
285 })
286 .collect();
287
288 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(el_ty)), fields))
289 }
290 ExprKind::Tuple { ref fields } => {
291 let fields: IndexVec<FieldIdx, _> = fields
294 .into_iter()
295 .copied()
296 .map(|f| {
297 unpack!(
298 block = this.as_operand(
299 block,
300 scope,
301 f,
302 LocalInfo::Boring,
303 NeedsTemporary::Maybe
304 )
305 )
306 })
307 .collect();
308
309 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Tuple), fields))
310 }
311 ExprKind::Closure(box ClosureExpr {
312 closure_id,
313 args,
314 ref upvars,
315 ref fake_reads,
316 movability: _,
317 }) => {
318 for (thir_place, cause, hir_id) in fake_reads.into_iter() {
333 let place_builder = unpack!(block = this.as_place_builder(block, *thir_place));
334
335 if let Some(mir_place) = place_builder.try_to_place(this) {
336 this.cfg.push_fake_read(
337 block,
338 this.source_info(this.tcx.hir_span(*hir_id)),
339 *cause,
340 mir_place,
341 );
342 }
343 }
344
345 let operands: IndexVec<FieldIdx, _> = upvars
347 .into_iter()
348 .copied()
349 .map(|upvar| {
350 let upvar_expr = &this.thir[upvar];
351 match Category::of(&upvar_expr.kind) {
352 Some(Category::Place) => {
361 let place = unpack!(block = this.as_place(block, upvar));
362 this.consume_by_copy_or_move(place)
363 }
364 _ => {
365 match upvar_expr.kind {
370 ExprKind::Borrow {
371 borrow_kind:
372 BorrowKind::Mut { kind: MutBorrowKind::Default },
373 arg,
374 } => unpack!(
375 block = this.limit_capture_mutability(
376 upvar_expr.span,
377 upvar_expr.ty,
378 scope.temp_lifetime,
379 block,
380 arg,
381 )
382 ),
383 _ => {
384 unpack!(
385 block = this.as_operand(
386 block,
387 scope,
388 upvar,
389 LocalInfo::Boring,
390 NeedsTemporary::Maybe
391 )
392 )
393 }
394 }
395 }
396 }
397 })
398 .collect();
399
400 let result = match args {
401 UpvarArgs::Coroutine(args) => {
402 Box::new(AggregateKind::Coroutine(closure_id.to_def_id(), args))
403 }
404 UpvarArgs::Closure(args) => {
405 Box::new(AggregateKind::Closure(closure_id.to_def_id(), args))
406 }
407 UpvarArgs::CoroutineClosure(args) => {
408 Box::new(AggregateKind::CoroutineClosure(closure_id.to_def_id(), args))
409 }
410 };
411 block.and(Rvalue::Aggregate(result, operands))
412 }
413 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
414 block = this.stmt_expr(block, expr_id, None).into_block();
415 block.and(Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
416 span: expr_span,
417 user_ty: None,
418 const_: Const::zero_sized(this.tcx.types.unit),
419 }))))
420 }
421
422 ExprKind::OffsetOf { container, fields } => {
423 block.and(Rvalue::NullaryOp(NullOp::OffsetOf(fields), container))
424 }
425
426 ExprKind::Literal { .. }
427 | ExprKind::NamedConst { .. }
428 | ExprKind::NonHirLiteral { .. }
429 | ExprKind::ZstLiteral { .. }
430 | ExprKind::ConstParam { .. }
431 | ExprKind::ConstBlock { .. }
432 | ExprKind::StaticRef { .. } => {
433 let constant = this.as_constant(expr);
434 block.and(Rvalue::Use(Operand::Constant(Box::new(constant))))
435 }
436
437 ExprKind::WrapUnsafeBinder { source } => {
438 let source = unpack!(
439 block = this.as_operand(
440 block,
441 scope,
442 source,
443 LocalInfo::Boring,
444 NeedsTemporary::Maybe
445 )
446 );
447 block.and(Rvalue::WrapUnsafeBinder(source, expr.ty))
448 }
449
450 ExprKind::Yield { .. }
451 | ExprKind::Block { .. }
452 | ExprKind::Match { .. }
453 | ExprKind::If { .. }
454 | ExprKind::NeverToAny { .. }
455 | ExprKind::Use { .. }
456 | ExprKind::Borrow { .. }
457 | ExprKind::RawBorrow { .. }
458 | ExprKind::Adt { .. }
459 | ExprKind::Loop { .. }
460 | ExprKind::LoopMatch { .. }
461 | ExprKind::LogicalOp { .. }
462 | ExprKind::Call { .. }
463 | ExprKind::Field { .. }
464 | ExprKind::Let { .. }
465 | ExprKind::Deref { .. }
466 | ExprKind::Index { .. }
467 | ExprKind::VarRef { .. }
468 | ExprKind::UpvarRef { .. }
469 | ExprKind::Break { .. }
470 | ExprKind::Continue { .. }
471 | ExprKind::ConstContinue { .. }
472 | ExprKind::Return { .. }
473 | ExprKind::Become { .. }
474 | ExprKind::InlineAsm { .. }
475 | ExprKind::PlaceTypeAscription { .. }
476 | ExprKind::ValueTypeAscription { .. }
477 | ExprKind::PlaceUnwrapUnsafeBinder { .. }
478 | ExprKind::ValueUnwrapUnsafeBinder { .. } => {
479 debug_assert!(!matches!(
482 Category::of(&expr.kind),
483 Some(Category::Rvalue(RvalueFunc::AsRvalue) | Category::Constant)
484 ));
485 let operand = unpack!(
486 block = this.as_operand(
487 block,
488 scope,
489 expr_id,
490 LocalInfo::Boring,
491 NeedsTemporary::No,
492 )
493 );
494 block.and(Rvalue::Use(operand))
495 }
496
497 ExprKind::ByUse { expr, span: _ } => {
498 let operand = unpack!(
499 block =
500 this.as_operand(block, scope, expr, LocalInfo::Boring, NeedsTemporary::No)
501 );
502 block.and(Rvalue::Use(operand))
503 }
504 }
505 }
506
507 pub(crate) fn build_binary_op(
508 &mut self,
509 mut block: BasicBlock,
510 op: BinOp,
511 span: Span,
512 ty: Ty<'tcx>,
513 lhs: Operand<'tcx>,
514 rhs: Operand<'tcx>,
515 ) -> BlockAnd<Rvalue<'tcx>> {
516 let source_info = self.source_info(span);
517 let bool_ty = self.tcx.types.bool;
518 let rvalue = match op {
519 BinOp::Add | BinOp::Sub | BinOp::Mul if self.check_overflow && ty.is_integral() => {
520 let result_tup = Ty::new_tup(self.tcx, &[ty, bool_ty]);
521 let result_value = self.temp(result_tup, span);
522
523 let op_with_overflow = op.wrapping_to_overflowing().unwrap();
524
525 self.cfg.push_assign(
526 block,
527 source_info,
528 result_value,
529 Rvalue::BinaryOp(op_with_overflow, Box::new((lhs.to_copy(), rhs.to_copy()))),
530 );
531 let val_fld = FieldIdx::ZERO;
532 let of_fld = FieldIdx::new(1);
533
534 let tcx = self.tcx;
535 let val = tcx.mk_place_field(result_value, val_fld, ty);
536 let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
537
538 let err = AssertKind::Overflow(op, lhs, rhs);
539 block = self.assert(block, Operand::Move(of), false, err, span);
540
541 Rvalue::Use(Operand::Move(val))
542 }
543 BinOp::Shl | BinOp::Shr if self.check_overflow && ty.is_integral() => {
544 let (lhs_size, _) = ty.int_size_and_signed(self.tcx);
551 assert!(lhs_size.bits() <= 128);
552 let rhs_ty = rhs.ty(&self.local_decls, self.tcx);
553 let (rhs_size, _) = rhs_ty.int_size_and_signed(self.tcx);
554
555 let (unsigned_rhs, unsigned_ty) = match rhs_ty.kind() {
556 ty::Uint(_) => (rhs.to_copy(), rhs_ty),
557 ty::Int(int_width) => {
558 let uint_ty = Ty::new_uint(self.tcx, int_width.to_unsigned());
559 let rhs_temp = self.temp(uint_ty, span);
560 self.cfg.push_assign(
561 block,
562 source_info,
563 rhs_temp,
564 Rvalue::Cast(CastKind::IntToInt, rhs.to_copy(), uint_ty),
565 );
566 (Operand::Move(rhs_temp), uint_ty)
567 }
568 _ => unreachable!("only integers are shiftable"),
569 };
570
571 let lhs_bits = Operand::const_from_scalar(
574 self.tcx,
575 unsigned_ty,
576 Scalar::from_uint(lhs_size.bits(), rhs_size),
577 span,
578 );
579
580 let inbounds = self.temp(bool_ty, span);
581 self.cfg.push_assign(
582 block,
583 source_info,
584 inbounds,
585 Rvalue::BinaryOp(BinOp::Lt, Box::new((unsigned_rhs, lhs_bits))),
586 );
587
588 let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
589 block = self.assert(block, Operand::Move(inbounds), true, overflow_err, span);
590 Rvalue::BinaryOp(op, Box::new((lhs, rhs)))
591 }
592 BinOp::Div | BinOp::Rem if ty.is_integral() => {
593 let zero_err = if op == BinOp::Div {
597 AssertKind::DivisionByZero(lhs.to_copy())
598 } else {
599 AssertKind::RemainderByZero(lhs.to_copy())
600 };
601 let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
602
603 let is_zero = self.temp(bool_ty, span);
605 let zero = self.zero_literal(span, ty);
606 self.cfg.push_assign(
607 block,
608 source_info,
609 is_zero,
610 Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), zero))),
611 );
612
613 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
614
615 if ty.is_signed() {
618 let neg_1 = self.neg_1_literal(span, ty);
619 let min = self.minval_literal(span, ty);
620
621 let is_neg_1 = self.temp(bool_ty, span);
622 let is_min = self.temp(bool_ty, span);
623 let of = self.temp(bool_ty, span);
624
625 self.cfg.push_assign(
628 block,
629 source_info,
630 is_neg_1,
631 Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), neg_1))),
632 );
633 self.cfg.push_assign(
634 block,
635 source_info,
636 is_min,
637 Rvalue::BinaryOp(BinOp::Eq, Box::new((lhs.to_copy(), min))),
638 );
639
640 let is_neg_1 = Operand::Move(is_neg_1);
641 let is_min = Operand::Move(is_min);
642 self.cfg.push_assign(
643 block,
644 source_info,
645 of,
646 Rvalue::BinaryOp(BinOp::BitAnd, Box::new((is_neg_1, is_min))),
647 );
648
649 block = self.assert(block, Operand::Move(of), false, overflow_err, span);
650 }
651
652 Rvalue::BinaryOp(op, Box::new((lhs, rhs)))
653 }
654 _ => Rvalue::BinaryOp(op, Box::new((lhs, rhs))),
655 };
656 block.and(rvalue)
657 }
658
659 fn build_zero_repeat(
660 &mut self,
661 mut block: BasicBlock,
662 value: ExprId,
663 scope: TempLifetime,
664 outer_source_info: SourceInfo,
665 ) -> BlockAnd<Rvalue<'tcx>> {
666 let this = self;
667 let value_expr = &this.thir[value];
668 let elem_ty = value_expr.ty;
669 if let Some(Category::Constant) = Category::of(&value_expr.kind) {
670 } else {
672 let value_operand = unpack!(
674 block = this.as_operand(block, scope, value, LocalInfo::Boring, NeedsTemporary::No)
675 );
676 if let Operand::Move(to_drop) = value_operand {
677 let success = this.cfg.start_new_block();
678 this.cfg.terminate(
679 block,
680 outer_source_info,
681 TerminatorKind::Drop {
682 place: to_drop,
683 target: success,
684 unwind: UnwindAction::Continue,
685 replace: false,
686 drop: None,
687 async_fut: None,
688 },
689 );
690 this.diverge_from(block);
691 block = success;
692 }
693 this.record_operands_moved(&[Spanned { node: value_operand, span: DUMMY_SP }]);
694 }
695 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), IndexVec::new()))
696 }
697
698 fn limit_capture_mutability(
699 &mut self,
700 upvar_span: Span,
701 upvar_ty: Ty<'tcx>,
702 temp_lifetime: Option<region::Scope>,
703 mut block: BasicBlock,
704 arg: ExprId,
705 ) -> BlockAnd<Operand<'tcx>> {
706 let this = self;
707
708 let source_info = this.source_info(upvar_span);
709 let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
710
711 this.cfg.push(block, Statement::new(source_info, StatementKind::StorageLive(temp)));
712
713 let arg_place_builder = unpack!(block = this.as_place_builder(block, arg));
714
715 let mutability = match arg_place_builder.base() {
716 PlaceBase::Local(local) => this.local_decls[local].mutability,
720 PlaceBase::Upvar { .. } => {
724 let enclosing_upvars_resolved = arg_place_builder.to_place(this);
725
726 match enclosing_upvars_resolved.as_ref() {
727 PlaceRef {
728 local,
729 projection: &[ProjectionElem::Field(upvar_index, _), ..],
730 }
731 | PlaceRef {
732 local,
733 projection:
734 &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
735 } => {
736 debug_assert!(
738 local == ty::CAPTURE_STRUCT_LOCAL,
739 "Expected local to be Local(1), found {local:?}"
740 );
741 debug_assert!(
743 this.upvars.len() > upvar_index.index(),
744 "Unexpected capture place, upvars={:#?}, upvar_index={:?}",
745 this.upvars,
746 upvar_index
747 );
748 this.upvars[upvar_index.index()].mutability
749 }
750 _ => bug!("Unexpected capture place"),
751 }
752 }
753 };
754
755 let borrow_kind = match mutability {
756 Mutability::Not => BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
757 Mutability::Mut => BorrowKind::Mut { kind: MutBorrowKind::Default },
758 };
759
760 let arg_place = arg_place_builder.to_place(this);
761
762 this.cfg.push_assign(
763 block,
764 source_info,
765 Place::from(temp),
766 Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place),
767 );
768
769 if let Some(temp_lifetime) = temp_lifetime {
772 this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
773 }
774
775 block.and(Operand::Move(Place::from(temp)))
776 }
777
778 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
780 let typing_env = ty::TypingEnv::fully_monomorphized();
781 let size = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size;
782 let literal = Const::from_bits(self.tcx, size.unsigned_int_max(), typing_env, ty);
783
784 self.literal_operand(span, literal)
785 }
786
787 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
789 assert!(ty.is_signed());
790 let typing_env = ty::TypingEnv::fully_monomorphized();
791 let bits = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size.bits();
792 let n = 1 << (bits - 1);
793 let literal = Const::from_bits(self.tcx, n, typing_env, ty);
794
795 self.literal_operand(span, literal)
796 }
797}