rustc_mir_build/builder/expr/
as_rvalue.rs

1//! See docs in `build/expr/mod.rs`.
2
3use rustc_abi::{BackendRepr, FieldIdx, Primitive};
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::layout::IntegerExt;
13use rustc_middle::ty::util::IntTypeExt;
14use rustc_middle::ty::{self, Ty, UpvarArgs};
15use rustc_span::source_map::Spanned;
16use rustc_span::{DUMMY_SP, Span};
17use tracing::debug;
18
19use crate::builder::expr::as_place::PlaceBase;
20use crate::builder::expr::category::{Category, RvalueFunc};
21use crate::builder::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary};
22
23impl<'a, 'tcx> Builder<'a, 'tcx> {
24    /// Returns an rvalue suitable for use until the end of the current
25    /// scope expression.
26    ///
27    /// The operand returned from this function will *not be valid* after
28    /// an ExprKind::Scope is passed, so please do *not* return it from
29    /// functions to avoid bad miscompiles.
30    pub(crate) fn as_local_rvalue(
31        &mut self,
32        block: BasicBlock,
33        expr_id: ExprId,
34    ) -> BlockAnd<Rvalue<'tcx>> {
35        let local_scope = self.local_scope();
36        self.as_rvalue(
37            block,
38            TempLifetime { temp_lifetime: Some(local_scope), backwards_incompatible: None },
39            expr_id,
40        )
41    }
42
43    /// Compile `expr`, yielding an rvalue.
44    pub(crate) fn as_rvalue(
45        &mut self,
46        mut block: BasicBlock,
47        scope: TempLifetime,
48        expr_id: ExprId,
49    ) -> BlockAnd<Rvalue<'tcx>> {
50        let this = self;
51        let expr = &this.thir[expr_id];
52        debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
53
54        let expr_span = expr.span;
55        let source_info = this.source_info(expr_span);
56
57        match expr.kind {
58            ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(did)),
59            ExprKind::Scope { region_scope, lint_level, value } => {
60                let region_scope = (region_scope, source_info);
61                this.in_scope(region_scope, lint_level, |this| this.as_rvalue(block, scope, value))
62            }
63            ExprKind::Repeat { value, count } => {
64                if Some(0) == count.try_to_target_usize(this.tcx) {
65                    this.build_zero_repeat(block, value, scope, source_info)
66                } else {
67                    let value_operand = unpack!(
68                        block = this.as_operand(
69                            block,
70                            scope,
71                            value,
72                            LocalInfo::Boring,
73                            NeedsTemporary::No
74                        )
75                    );
76                    block.and(Rvalue::Repeat(value_operand, count))
77                }
78            }
79            ExprKind::Binary { op, lhs, rhs } => {
80                let lhs = unpack!(
81                    block = this.as_operand(
82                        block,
83                        scope,
84                        lhs,
85                        LocalInfo::Boring,
86                        NeedsTemporary::Maybe
87                    )
88                );
89                let rhs = unpack!(
90                    block =
91                        this.as_operand(block, scope, rhs, LocalInfo::Boring, NeedsTemporary::No)
92                );
93                this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
94            }
95            ExprKind::Unary { op, arg } => {
96                let arg = unpack!(
97                    block =
98                        this.as_operand(block, scope, arg, LocalInfo::Boring, NeedsTemporary::No)
99                );
100                // Check for -MIN on signed integers
101                if this.check_overflow && op == UnOp::Neg && expr.ty.is_signed() {
102                    let bool_ty = this.tcx.types.bool;
103
104                    let minval = this.minval_literal(expr_span, expr.ty);
105                    let is_min = this.temp(bool_ty, expr_span);
106
107                    this.cfg.push_assign(
108                        block,
109                        source_info,
110                        is_min,
111                        Rvalue::BinaryOp(BinOp::Eq, Box::new((arg.to_copy(), minval))),
112                    );
113
114                    block = this.assert(
115                        block,
116                        Operand::Move(is_min),
117                        false,
118                        AssertKind::OverflowNeg(arg.to_copy()),
119                        expr_span,
120                    );
121                }
122                block.and(Rvalue::UnaryOp(op, arg))
123            }
124            ExprKind::Box { value } => {
125                let value_ty = this.thir[value].ty;
126                let tcx = this.tcx;
127                let source_info = this.source_info(expr_span);
128
129                let size = this.temp(tcx.types.usize, expr_span);
130                this.cfg.push_assign(
131                    block,
132                    source_info,
133                    size,
134                    Rvalue::NullaryOp(NullOp::SizeOf, value_ty),
135                );
136
137                let align = this.temp(tcx.types.usize, expr_span);
138                this.cfg.push_assign(
139                    block,
140                    source_info,
141                    align,
142                    Rvalue::NullaryOp(NullOp::AlignOf, value_ty),
143                );
144
145                // malloc some memory of suitable size and align:
146                let exchange_malloc = Operand::function_handle(
147                    tcx,
148                    tcx.require_lang_item(LangItem::ExchangeMalloc, Some(expr_span)),
149                    [],
150                    expr_span,
151                );
152                let storage = this.temp(Ty::new_mut_ptr(tcx, tcx.types.u8), expr_span);
153                let success = this.cfg.start_new_block();
154                this.cfg.terminate(
155                    block,
156                    source_info,
157                    TerminatorKind::Call {
158                        func: exchange_malloc,
159                        args: [
160                            Spanned { node: Operand::Move(size), span: DUMMY_SP },
161                            Spanned { node: Operand::Move(align), span: DUMMY_SP },
162                        ]
163                        .into(),
164                        destination: storage,
165                        target: Some(success),
166                        unwind: UnwindAction::Continue,
167                        call_source: CallSource::Misc,
168                        fn_span: expr_span,
169                    },
170                );
171                this.diverge_from(block);
172                block = success;
173
174                // The `Box<T>` temporary created here is not a part of the HIR,
175                // and therefore is not considered during coroutine auto-trait
176                // determination. See the comment about `box` at `yield_in_scope`.
177                let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span));
178                this.cfg.push(
179                    block,
180                    Statement { source_info, kind: StatementKind::StorageLive(result) },
181                );
182                if let Some(scope) = scope.temp_lifetime {
183                    // schedule a shallow free of that memory, lest we unwind:
184                    this.schedule_drop_storage_and_value(expr_span, scope, result);
185                }
186
187                // Transmute `*mut u8` to the box (thus far, uninitialized):
188                let box_ = Rvalue::ShallowInitBox(Operand::Move(storage), value_ty);
189                this.cfg.push_assign(block, source_info, Place::from(result), box_);
190
191                // initialize the box contents:
192                block = this
193                    .expr_into_dest(this.tcx.mk_place_deref(Place::from(result)), block, value)
194                    .into_block();
195                block.and(Rvalue::Use(Operand::Move(Place::from(result))))
196            }
197            ExprKind::Cast { source } => {
198                let source_expr = &this.thir[source];
199
200                // Casting an enum to an integer is equivalent to computing the discriminant and casting the
201                // discriminant. Previously every backend had to repeat the logic for this operation. Now we
202                // create all the steps directly in MIR with operations all backends need to support anyway.
203                let (source, ty) = if let ty::Adt(adt_def, ..) = source_expr.ty.kind()
204                    && adt_def.is_enum()
205                {
206                    let discr_ty = adt_def.repr().discr_type().to_ty(this.tcx);
207                    let temp = unpack!(block = this.as_temp(block, scope, source, Mutability::Not));
208                    let layout =
209                        this.tcx.layout_of(this.typing_env().as_query_input(source_expr.ty));
210                    let discr = this.temp(discr_ty, source_expr.span);
211                    this.cfg.push_assign(
212                        block,
213                        source_info,
214                        discr,
215                        Rvalue::Discriminant(temp.into()),
216                    );
217                    let (op, ty) = (Operand::Move(discr), discr_ty);
218
219                    if let BackendRepr::Scalar(scalar) = layout.unwrap().backend_repr
220                        && !scalar.is_always_valid(&this.tcx)
221                        && let Primitive::Int(int_width, _signed) = scalar.primitive()
222                    {
223                        let unsigned_ty = int_width.to_ty(this.tcx, false);
224                        let unsigned_place = this.temp(unsigned_ty, expr_span);
225                        this.cfg.push_assign(
226                            block,
227                            source_info,
228                            unsigned_place,
229                            Rvalue::Cast(CastKind::IntToInt, Operand::Copy(discr), unsigned_ty),
230                        );
231
232                        let bool_ty = this.tcx.types.bool;
233                        let range = scalar.valid_range(&this.tcx);
234                        let merge_op =
235                            if range.start <= range.end { BinOp::BitAnd } else { BinOp::BitOr };
236
237                        let mut comparer = |range: u128, bin_op: BinOp| -> Place<'tcx> {
238                            // We can use `ty::TypingEnv::fully_monomorphized()` here
239                            // as we only need it to compute the layout of a primitive.
240                            let range_val = Const::from_bits(
241                                this.tcx,
242                                range,
243                                ty::TypingEnv::fully_monomorphized(),
244                                unsigned_ty,
245                            );
246                            let lit_op = this.literal_operand(expr.span, range_val);
247                            let is_bin_op = this.temp(bool_ty, expr_span);
248                            this.cfg.push_assign(
249                                block,
250                                source_info,
251                                is_bin_op,
252                                Rvalue::BinaryOp(
253                                    bin_op,
254                                    Box::new((Operand::Copy(unsigned_place), lit_op)),
255                                ),
256                            );
257                            is_bin_op
258                        };
259                        let assert_place = if range.start == 0 {
260                            comparer(range.end, BinOp::Le)
261                        } else {
262                            let start_place = comparer(range.start, BinOp::Ge);
263                            let end_place = comparer(range.end, BinOp::Le);
264                            let merge_place = this.temp(bool_ty, expr_span);
265                            this.cfg.push_assign(
266                                block,
267                                source_info,
268                                merge_place,
269                                Rvalue::BinaryOp(
270                                    merge_op,
271                                    Box::new((
272                                        Operand::Move(start_place),
273                                        Operand::Move(end_place),
274                                    )),
275                                ),
276                            );
277                            merge_place
278                        };
279                        this.cfg.push(
280                            block,
281                            Statement {
282                                source_info,
283                                kind: StatementKind::Intrinsic(Box::new(
284                                    NonDivergingIntrinsic::Assume(Operand::Move(assert_place)),
285                                )),
286                            },
287                        );
288                    }
289
290                    (op, ty)
291                } else {
292                    let ty = source_expr.ty;
293                    let source = unpack!(
294                        block = this.as_operand(
295                            block,
296                            scope,
297                            source,
298                            LocalInfo::Boring,
299                            NeedsTemporary::No
300                        )
301                    );
302                    (source, ty)
303                };
304                let from_ty = CastTy::from_ty(ty);
305                let cast_ty = CastTy::from_ty(expr.ty);
306                debug!("ExprKind::Cast from_ty={from_ty:?}, cast_ty={:?}/{cast_ty:?}", expr.ty);
307                let cast_kind = mir_cast_kind(ty, expr.ty);
308                block.and(Rvalue::Cast(cast_kind, source, expr.ty))
309            }
310            ExprKind::PointerCoercion { cast, source, is_from_as_cast } => {
311                let source = unpack!(
312                    block = this.as_operand(
313                        block,
314                        scope,
315                        source,
316                        LocalInfo::Boring,
317                        NeedsTemporary::No
318                    )
319                );
320                let origin =
321                    if is_from_as_cast { CoercionSource::AsCast } else { CoercionSource::Implicit };
322                block.and(Rvalue::Cast(CastKind::PointerCoercion(cast, origin), source, expr.ty))
323            }
324            ExprKind::Array { ref fields } => {
325                // (*) We would (maybe) be closer to codegen if we
326                // handled this and other aggregate cases via
327                // `into()`, not `as_rvalue` -- in that case, instead
328                // of generating
329                //
330                //     let tmp1 = ...1;
331                //     let tmp2 = ...2;
332                //     dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
333                //
334                // we could just generate
335                //
336                //     dest.f = ...1;
337                //     dest.g = ...2;
338                //
339                // The problem is that then we would need to:
340                //
341                // (a) have a more complex mechanism for handling
342                //     partial cleanup;
343                // (b) distinguish the case where the type `Foo` has a
344                //     destructor, in which case creating an instance
345                //     as a whole "arms" the destructor, and you can't
346                //     write individual fields; and,
347                // (c) handle the case where the type Foo has no
348                //     fields. We don't want `let x: ();` to compile
349                //     to the same MIR as `let x = ();`.
350
351                // first process the set of fields
352                let el_ty = expr.ty.sequence_element_type(this.tcx);
353                let fields: IndexVec<FieldIdx, _> = fields
354                    .into_iter()
355                    .copied()
356                    .map(|f| {
357                        unpack!(
358                            block = this.as_operand(
359                                block,
360                                scope,
361                                f,
362                                LocalInfo::Boring,
363                                NeedsTemporary::Maybe
364                            )
365                        )
366                    })
367                    .collect();
368
369                block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(el_ty)), fields))
370            }
371            ExprKind::Tuple { ref fields } => {
372                // see (*) above
373                // first process the set of fields
374                let fields: IndexVec<FieldIdx, _> = fields
375                    .into_iter()
376                    .copied()
377                    .map(|f| {
378                        unpack!(
379                            block = this.as_operand(
380                                block,
381                                scope,
382                                f,
383                                LocalInfo::Boring,
384                                NeedsTemporary::Maybe
385                            )
386                        )
387                    })
388                    .collect();
389
390                block.and(Rvalue::Aggregate(Box::new(AggregateKind::Tuple), fields))
391            }
392            ExprKind::Closure(box ClosureExpr {
393                closure_id,
394                args,
395                ref upvars,
396                ref fake_reads,
397                movability: _,
398            }) => {
399                // Convert the closure fake reads, if any, from `ExprRef` to mir `Place`
400                // and push the fake reads.
401                // This must come before creating the operands. This is required in case
402                // there is a fake read and a borrow of the same path, since otherwise the
403                // fake read might interfere with the borrow. Consider an example like this
404                // one:
405                // ```
406                // let mut x = 0;
407                // let c = || {
408                //     &mut x; // mutable borrow of `x`
409                //     match x { _ => () } // fake read of `x`
410                // };
411                // ```
412                //
413                for (thir_place, cause, hir_id) in fake_reads.into_iter() {
414                    let place_builder = unpack!(block = this.as_place_builder(block, *thir_place));
415
416                    if let Some(mir_place) = place_builder.try_to_place(this) {
417                        this.cfg.push_fake_read(
418                            block,
419                            this.source_info(this.tcx.hir().span(*hir_id)),
420                            *cause,
421                            mir_place,
422                        );
423                    }
424                }
425
426                // see (*) above
427                let operands: IndexVec<FieldIdx, _> = upvars
428                    .into_iter()
429                    .copied()
430                    .map(|upvar| {
431                        let upvar_expr = &this.thir[upvar];
432                        match Category::of(&upvar_expr.kind) {
433                            // Use as_place to avoid creating a temporary when
434                            // moving a variable into a closure, so that
435                            // borrowck knows which variables to mark as being
436                            // used as mut. This is OK here because the upvar
437                            // expressions have no side effects and act on
438                            // disjoint places.
439                            // This occurs when capturing by copy/move, while
440                            // by reference captures use as_operand
441                            Some(Category::Place) => {
442                                let place = unpack!(block = this.as_place(block, upvar));
443                                this.consume_by_copy_or_move(place)
444                            }
445                            _ => {
446                                // Turn mutable borrow captures into unique
447                                // borrow captures when capturing an immutable
448                                // variable. This is sound because the mutation
449                                // that caused the capture will cause an error.
450                                match upvar_expr.kind {
451                                    ExprKind::Borrow {
452                                        borrow_kind:
453                                            BorrowKind::Mut { kind: MutBorrowKind::Default },
454                                        arg,
455                                    } => unpack!(
456                                        block = this.limit_capture_mutability(
457                                            upvar_expr.span,
458                                            upvar_expr.ty,
459                                            scope.temp_lifetime,
460                                            block,
461                                            arg,
462                                        )
463                                    ),
464                                    _ => {
465                                        unpack!(
466                                            block = this.as_operand(
467                                                block,
468                                                scope,
469                                                upvar,
470                                                LocalInfo::Boring,
471                                                NeedsTemporary::Maybe
472                                            )
473                                        )
474                                    }
475                                }
476                            }
477                        }
478                    })
479                    .collect();
480
481                let result = match args {
482                    UpvarArgs::Coroutine(args) => {
483                        Box::new(AggregateKind::Coroutine(closure_id.to_def_id(), args))
484                    }
485                    UpvarArgs::Closure(args) => {
486                        Box::new(AggregateKind::Closure(closure_id.to_def_id(), args))
487                    }
488                    UpvarArgs::CoroutineClosure(args) => {
489                        Box::new(AggregateKind::CoroutineClosure(closure_id.to_def_id(), args))
490                    }
491                };
492                block.and(Rvalue::Aggregate(result, operands))
493            }
494            ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
495                block = this.stmt_expr(block, expr_id, None).into_block();
496                block.and(Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
497                    span: expr_span,
498                    user_ty: None,
499                    const_: Const::zero_sized(this.tcx.types.unit),
500                }))))
501            }
502
503            ExprKind::OffsetOf { container, fields } => {
504                block.and(Rvalue::NullaryOp(NullOp::OffsetOf(fields), container))
505            }
506
507            ExprKind::Literal { .. }
508            | ExprKind::NamedConst { .. }
509            | ExprKind::NonHirLiteral { .. }
510            | ExprKind::ZstLiteral { .. }
511            | ExprKind::ConstParam { .. }
512            | ExprKind::ConstBlock { .. }
513            | ExprKind::StaticRef { .. } => {
514                let constant = this.as_constant(expr);
515                block.and(Rvalue::Use(Operand::Constant(Box::new(constant))))
516            }
517
518            ExprKind::WrapUnsafeBinder { source } => {
519                let source = unpack!(
520                    block = this.as_operand(
521                        block,
522                        scope,
523                        source,
524                        LocalInfo::Boring,
525                        NeedsTemporary::Maybe
526                    )
527                );
528                block.and(Rvalue::WrapUnsafeBinder(source, expr.ty))
529            }
530
531            ExprKind::Yield { .. }
532            | ExprKind::Block { .. }
533            | ExprKind::Match { .. }
534            | ExprKind::If { .. }
535            | ExprKind::NeverToAny { .. }
536            | ExprKind::Use { .. }
537            | ExprKind::Borrow { .. }
538            | ExprKind::RawBorrow { .. }
539            | ExprKind::Adt { .. }
540            | ExprKind::Loop { .. }
541            | ExprKind::LogicalOp { .. }
542            | ExprKind::Call { .. }
543            | ExprKind::Field { .. }
544            | ExprKind::Let { .. }
545            | ExprKind::Deref { .. }
546            | ExprKind::Index { .. }
547            | ExprKind::VarRef { .. }
548            | ExprKind::UpvarRef { .. }
549            | ExprKind::Break { .. }
550            | ExprKind::Continue { .. }
551            | ExprKind::Return { .. }
552            | ExprKind::Become { .. }
553            | ExprKind::InlineAsm { .. }
554            | ExprKind::PlaceTypeAscription { .. }
555            | ExprKind::ValueTypeAscription { .. }
556            | ExprKind::PlaceUnwrapUnsafeBinder { .. }
557            | ExprKind::ValueUnwrapUnsafeBinder { .. } => {
558                // these do not have corresponding `Rvalue` variants,
559                // so make an operand and then return that
560                debug_assert!(!matches!(
561                    Category::of(&expr.kind),
562                    Some(Category::Rvalue(RvalueFunc::AsRvalue) | Category::Constant)
563                ));
564                let operand = unpack!(
565                    block = this.as_operand(
566                        block,
567                        scope,
568                        expr_id,
569                        LocalInfo::Boring,
570                        NeedsTemporary::No,
571                    )
572                );
573                block.and(Rvalue::Use(operand))
574            }
575        }
576    }
577
578    pub(crate) fn build_binary_op(
579        &mut self,
580        mut block: BasicBlock,
581        op: BinOp,
582        span: Span,
583        ty: Ty<'tcx>,
584        lhs: Operand<'tcx>,
585        rhs: Operand<'tcx>,
586    ) -> BlockAnd<Rvalue<'tcx>> {
587        let source_info = self.source_info(span);
588        let bool_ty = self.tcx.types.bool;
589        let rvalue = match op {
590            BinOp::Add | BinOp::Sub | BinOp::Mul if self.check_overflow && ty.is_integral() => {
591                let result_tup = Ty::new_tup(self.tcx, &[ty, bool_ty]);
592                let result_value = self.temp(result_tup, span);
593
594                let op_with_overflow = op.wrapping_to_overflowing().unwrap();
595
596                self.cfg.push_assign(
597                    block,
598                    source_info,
599                    result_value,
600                    Rvalue::BinaryOp(op_with_overflow, Box::new((lhs.to_copy(), rhs.to_copy()))),
601                );
602                let val_fld = FieldIdx::ZERO;
603                let of_fld = FieldIdx::new(1);
604
605                let tcx = self.tcx;
606                let val = tcx.mk_place_field(result_value, val_fld, ty);
607                let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
608
609                let err = AssertKind::Overflow(op, lhs, rhs);
610                block = self.assert(block, Operand::Move(of), false, err, span);
611
612                Rvalue::Use(Operand::Move(val))
613            }
614            BinOp::Shl | BinOp::Shr if self.check_overflow && ty.is_integral() => {
615                // For an unsigned RHS, the shift is in-range for `rhs < bits`.
616                // For a signed RHS, `IntToInt` cast to the equivalent unsigned
617                // type and do that same comparison.
618                // A negative value will be *at least* 128 after the cast (that's i8::MIN),
619                // and 128 is an overflowing shift amount for all our currently existing types,
620                // so this cast can never make us miss an overflow.
621                let (lhs_size, _) = ty.int_size_and_signed(self.tcx);
622                assert!(lhs_size.bits() <= 128);
623                let rhs_ty = rhs.ty(&self.local_decls, self.tcx);
624                let (rhs_size, _) = rhs_ty.int_size_and_signed(self.tcx);
625
626                let (unsigned_rhs, unsigned_ty) = match rhs_ty.kind() {
627                    ty::Uint(_) => (rhs.to_copy(), rhs_ty),
628                    ty::Int(int_width) => {
629                        let uint_ty = Ty::new_uint(self.tcx, int_width.to_unsigned());
630                        let rhs_temp = self.temp(uint_ty, span);
631                        self.cfg.push_assign(
632                            block,
633                            source_info,
634                            rhs_temp,
635                            Rvalue::Cast(CastKind::IntToInt, rhs.to_copy(), uint_ty),
636                        );
637                        (Operand::Move(rhs_temp), uint_ty)
638                    }
639                    _ => unreachable!("only integers are shiftable"),
640                };
641
642                // This can't overflow because the largest shiftable types are 128-bit,
643                // which fits in `u8`, the smallest possible `unsigned_ty`.
644                let lhs_bits = Operand::const_from_scalar(
645                    self.tcx,
646                    unsigned_ty,
647                    Scalar::from_uint(lhs_size.bits(), rhs_size),
648                    span,
649                );
650
651                let inbounds = self.temp(bool_ty, span);
652                self.cfg.push_assign(
653                    block,
654                    source_info,
655                    inbounds,
656                    Rvalue::BinaryOp(BinOp::Lt, Box::new((unsigned_rhs, lhs_bits))),
657                );
658
659                let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
660                block = self.assert(block, Operand::Move(inbounds), true, overflow_err, span);
661                Rvalue::BinaryOp(op, Box::new((lhs, rhs)))
662            }
663            BinOp::Div | BinOp::Rem if ty.is_integral() => {
664                // Checking division and remainder is more complex, since we 1. always check
665                // and 2. there are two possible failure cases, divide-by-zero and overflow.
666
667                let zero_err = if op == BinOp::Div {
668                    AssertKind::DivisionByZero(lhs.to_copy())
669                } else {
670                    AssertKind::RemainderByZero(lhs.to_copy())
671                };
672                let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
673
674                // Check for / 0
675                let is_zero = self.temp(bool_ty, span);
676                let zero = self.zero_literal(span, ty);
677                self.cfg.push_assign(
678                    block,
679                    source_info,
680                    is_zero,
681                    Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), zero))),
682                );
683
684                block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
685
686                // We only need to check for the overflow in one case:
687                // MIN / -1, and only for signed values.
688                if ty.is_signed() {
689                    let neg_1 = self.neg_1_literal(span, ty);
690                    let min = self.minval_literal(span, ty);
691
692                    let is_neg_1 = self.temp(bool_ty, span);
693                    let is_min = self.temp(bool_ty, span);
694                    let of = self.temp(bool_ty, span);
695
696                    // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
697
698                    self.cfg.push_assign(
699                        block,
700                        source_info,
701                        is_neg_1,
702                        Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), neg_1))),
703                    );
704                    self.cfg.push_assign(
705                        block,
706                        source_info,
707                        is_min,
708                        Rvalue::BinaryOp(BinOp::Eq, Box::new((lhs.to_copy(), min))),
709                    );
710
711                    let is_neg_1 = Operand::Move(is_neg_1);
712                    let is_min = Operand::Move(is_min);
713                    self.cfg.push_assign(
714                        block,
715                        source_info,
716                        of,
717                        Rvalue::BinaryOp(BinOp::BitAnd, Box::new((is_neg_1, is_min))),
718                    );
719
720                    block = self.assert(block, Operand::Move(of), false, overflow_err, span);
721                }
722
723                Rvalue::BinaryOp(op, Box::new((lhs, rhs)))
724            }
725            _ => Rvalue::BinaryOp(op, Box::new((lhs, rhs))),
726        };
727        block.and(rvalue)
728    }
729
730    fn build_zero_repeat(
731        &mut self,
732        mut block: BasicBlock,
733        value: ExprId,
734        scope: TempLifetime,
735        outer_source_info: SourceInfo,
736    ) -> BlockAnd<Rvalue<'tcx>> {
737        let this = self;
738        let value_expr = &this.thir[value];
739        let elem_ty = value_expr.ty;
740        if let Some(Category::Constant) = Category::of(&value_expr.kind) {
741            // Repeating a const does nothing
742        } else {
743            // For a non-const, we may need to generate an appropriate `Drop`
744            let value_operand = unpack!(
745                block = this.as_operand(block, scope, value, LocalInfo::Boring, NeedsTemporary::No)
746            );
747            if let Operand::Move(to_drop) = value_operand {
748                let success = this.cfg.start_new_block();
749                this.cfg.terminate(
750                    block,
751                    outer_source_info,
752                    TerminatorKind::Drop {
753                        place: to_drop,
754                        target: success,
755                        unwind: UnwindAction::Continue,
756                        replace: false,
757                    },
758                );
759                this.diverge_from(block);
760                block = success;
761            }
762            this.record_operands_moved(&[Spanned { node: value_operand, span: DUMMY_SP }]);
763        }
764        block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), IndexVec::new()))
765    }
766
767    fn limit_capture_mutability(
768        &mut self,
769        upvar_span: Span,
770        upvar_ty: Ty<'tcx>,
771        temp_lifetime: Option<region::Scope>,
772        mut block: BasicBlock,
773        arg: ExprId,
774    ) -> BlockAnd<Operand<'tcx>> {
775        let this = self;
776
777        let source_info = this.source_info(upvar_span);
778        let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
779
780        this.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(temp) });
781
782        let arg_place_builder = unpack!(block = this.as_place_builder(block, arg));
783
784        let mutability = match arg_place_builder.base() {
785            // We are capturing a path that starts off a local variable in the parent.
786            // The mutability of the current capture is same as the mutability
787            // of the local declaration in the parent.
788            PlaceBase::Local(local) => this.local_decls[local].mutability,
789            // Parent is a closure and we are capturing a path that is captured
790            // by the parent itself. The mutability of the current capture
791            // is same as that of the capture in the parent closure.
792            PlaceBase::Upvar { .. } => {
793                let enclosing_upvars_resolved = arg_place_builder.to_place(this);
794
795                match enclosing_upvars_resolved.as_ref() {
796                    PlaceRef {
797                        local,
798                        projection: &[ProjectionElem::Field(upvar_index, _), ..],
799                    }
800                    | PlaceRef {
801                        local,
802                        projection:
803                            &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
804                    } => {
805                        // Not in a closure
806                        debug_assert!(
807                            local == ty::CAPTURE_STRUCT_LOCAL,
808                            "Expected local to be Local(1), found {local:?}"
809                        );
810                        // Not in a closure
811                        debug_assert!(
812                            this.upvars.len() > upvar_index.index(),
813                            "Unexpected capture place, upvars={:#?}, upvar_index={:?}",
814                            this.upvars,
815                            upvar_index
816                        );
817                        this.upvars[upvar_index.index()].mutability
818                    }
819                    _ => bug!("Unexpected capture place"),
820                }
821            }
822        };
823
824        let borrow_kind = match mutability {
825            Mutability::Not => BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
826            Mutability::Mut => BorrowKind::Mut { kind: MutBorrowKind::Default },
827        };
828
829        let arg_place = arg_place_builder.to_place(this);
830
831        this.cfg.push_assign(
832            block,
833            source_info,
834            Place::from(temp),
835            Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place),
836        );
837
838        // See the comment in `expr_as_temp` and on the `rvalue_scopes` field for why
839        // this can be `None`.
840        if let Some(temp_lifetime) = temp_lifetime {
841            this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
842        }
843
844        block.and(Operand::Move(Place::from(temp)))
845    }
846
847    // Helper to get a `-1` value of the appropriate type
848    fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
849        let typing_env = ty::TypingEnv::fully_monomorphized();
850        let size = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size;
851        let literal = Const::from_bits(self.tcx, size.unsigned_int_max(), typing_env, ty);
852
853        self.literal_operand(span, literal)
854    }
855
856    // Helper to get the minimum value of the appropriate type
857    fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
858        assert!(ty.is_signed());
859        let typing_env = ty::TypingEnv::fully_monomorphized();
860        let bits = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size.bits();
861        let n = 1 << (bits - 1);
862        let literal = Const::from_bits(self.tcx, n, typing_env, ty);
863
864        self.literal_operand(span, literal)
865    }
866}