]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_rvalue.rs
15f2d17c4e08b2ddc45d181ea9f89d0a2c408cfa
[rust.git] / compiler / rustc_mir_build / src / build / expr / as_rvalue.rs
1 //! See docs in `build/expr/mod.rs`.
2
3 use rustc_index::vec::Idx;
4 use rustc_middle::ty::util::IntTypeExt;
5
6 use crate::build::expr::as_place::PlaceBase;
7 use crate::build::expr::category::{Category, RvalueFunc};
8 use crate::build::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary};
9 use rustc_hir::lang_items::LangItem;
10 use rustc_middle::middle::region;
11 use rustc_middle::mir::AssertKind;
12 use rustc_middle::mir::Place;
13 use rustc_middle::mir::*;
14 use rustc_middle::thir::*;
15 use rustc_middle::ty::cast::CastTy;
16 use rustc_middle::ty::{self, Ty, UpvarSubsts};
17 use rustc_span::Span;
18
19 impl<'a, 'tcx> Builder<'a, 'tcx> {
20     /// Returns an rvalue suitable for use until the end of the current
21     /// scope expression.
22     ///
23     /// The operand returned from this function will *not be valid* after
24     /// an ExprKind::Scope is passed, so please do *not* return it from
25     /// functions to avoid bad miscompiles.
26     pub(crate) fn as_local_rvalue(
27         &mut self,
28         block: BasicBlock,
29         expr: &Expr<'tcx>,
30     ) -> BlockAnd<Rvalue<'tcx>> {
31         let local_scope = self.local_scope();
32         self.as_rvalue(block, Some(local_scope), expr)
33     }
34
35     /// Compile `expr`, yielding an rvalue.
36     pub(crate) fn as_rvalue(
37         &mut self,
38         mut block: BasicBlock,
39         scope: Option<region::Scope>,
40         expr: &Expr<'tcx>,
41     ) -> BlockAnd<Rvalue<'tcx>> {
42         debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
43
44         let this = self;
45         let expr_span = expr.span;
46         let source_info = this.source_info(expr_span);
47
48         match expr.kind {
49             ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(did)),
50             ExprKind::Scope { region_scope, lint_level, value } => {
51                 let region_scope = (region_scope, source_info);
52                 this.in_scope(region_scope, lint_level, |this| {
53                     this.as_rvalue(block, scope, &this.thir[value])
54                 })
55             }
56             ExprKind::Repeat { value, count } => {
57                 if Some(0) == count.try_eval_usize(this.tcx, this.param_env) {
58                     this.build_zero_repeat(block, value, scope, source_info)
59                 } else {
60                     let value_operand = unpack!(
61                         block = this.as_operand(
62                             block,
63                             scope,
64                             &this.thir[value],
65                             None,
66                             NeedsTemporary::No
67                         )
68                     );
69                     block.and(Rvalue::Repeat(value_operand, count))
70                 }
71             }
72             ExprKind::Binary { op, lhs, rhs } => {
73                 let lhs = unpack!(
74                     block =
75                         this.as_operand(block, scope, &this.thir[lhs], None, NeedsTemporary::Maybe)
76                 );
77                 let rhs = unpack!(
78                     block =
79                         this.as_operand(block, scope, &this.thir[rhs], None, NeedsTemporary::No)
80                 );
81                 this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
82             }
83             ExprKind::Unary { op, arg } => {
84                 let arg = unpack!(
85                     block =
86                         this.as_operand(block, scope, &this.thir[arg], None, NeedsTemporary::No)
87                 );
88                 // Check for -MIN on signed integers
89                 if this.check_overflow && op == UnOp::Neg && expr.ty.is_signed() {
90                     let bool_ty = this.tcx.types.bool;
91
92                     let minval = this.minval_literal(expr_span, expr.ty);
93                     let is_min = this.temp(bool_ty, expr_span);
94
95                     this.cfg.push_assign(
96                         block,
97                         source_info,
98                         is_min,
99                         Rvalue::BinaryOp(BinOp::Eq, Box::new((arg.to_copy(), minval))),
100                     );
101
102                     block = this.assert(
103                         block,
104                         Operand::Move(is_min),
105                         false,
106                         AssertKind::OverflowNeg(arg.to_copy()),
107                         expr_span,
108                     );
109                 }
110                 block.and(Rvalue::UnaryOp(op, arg))
111             }
112             ExprKind::Box { value } => {
113                 let value = &this.thir[value];
114                 let tcx = this.tcx;
115
116                 // `exchange_malloc` is unsafe but box is safe, so need a new scope.
117                 let synth_scope = this.new_source_scope(
118                     expr_span,
119                     LintLevel::Inherited,
120                     Some(Safety::BuiltinUnsafe),
121                 );
122                 let synth_info = SourceInfo { span: expr_span, scope: synth_scope };
123
124                 let size = this.temp(tcx.types.usize, expr_span);
125                 this.cfg.push_assign(
126                     block,
127                     synth_info,
128                     size,
129                     Rvalue::NullaryOp(NullOp::SizeOf, value.ty),
130                 );
131
132                 let align = this.temp(tcx.types.usize, expr_span);
133                 this.cfg.push_assign(
134                     block,
135                     synth_info,
136                     align,
137                     Rvalue::NullaryOp(NullOp::AlignOf, value.ty),
138                 );
139
140                 // malloc some memory of suitable size and align:
141                 let exchange_malloc = Operand::function_handle(
142                     tcx,
143                     tcx.require_lang_item(LangItem::ExchangeMalloc, Some(expr_span)),
144                     ty::List::empty(),
145                     expr_span,
146                 );
147                 let storage = this.temp(tcx.mk_mut_ptr(tcx.types.u8), expr_span);
148                 let success = this.cfg.start_new_block();
149                 this.cfg.terminate(
150                     block,
151                     synth_info,
152                     TerminatorKind::Call {
153                         func: exchange_malloc,
154                         args: vec![Operand::Move(size), Operand::Move(align)],
155                         destination: storage,
156                         target: Some(success),
157                         cleanup: None,
158                         from_hir_call: false,
159                         fn_span: expr_span,
160                     },
161                 );
162                 this.diverge_from(block);
163                 block = success;
164
165                 // The `Box<T>` temporary created here is not a part of the HIR,
166                 // and therefore is not considered during generator auto-trait
167                 // determination. See the comment about `box` at `yield_in_scope`.
168                 let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span).internal());
169                 this.cfg.push(
170                     block,
171                     Statement { source_info, kind: StatementKind::StorageLive(result) },
172                 );
173                 if let Some(scope) = scope {
174                     // schedule a shallow free of that memory, lest we unwind:
175                     this.schedule_drop_storage_and_value(expr_span, scope, result);
176                 }
177
178                 // Transmute `*mut u8` to the box (thus far, uninitialized):
179                 let box_ = Rvalue::ShallowInitBox(Operand::Move(storage), value.ty);
180                 this.cfg.push_assign(block, source_info, Place::from(result), box_);
181
182                 // initialize the box contents:
183                 unpack!(
184                     block = this.expr_into_dest(
185                         this.tcx.mk_place_deref(Place::from(result)),
186                         block,
187                         value
188                     )
189                 );
190                 block.and(Rvalue::Use(Operand::Move(Place::from(result))))
191             }
192             ExprKind::Cast { source } => {
193                 let source = &this.thir[source];
194
195                 // Casting an enum to an integer is equivalent to computing the discriminant and casting the
196                 // discriminant. Previously every backend had to repeat the logic for this operation. Now we
197                 // create all the steps directly in MIR with operations all backends need to support anyway.
198                 let (source, ty) = if let ty::Adt(adt_def, ..) = source.ty.kind() && adt_def.is_enum() {
199                     let discr_ty = adt_def.repr().discr_type().to_ty(this.tcx);
200                     let place = unpack!(block = this.as_place(block, source));
201                     let discr = this.temp(discr_ty, source.span);
202                     this.cfg.push_assign(
203                         block,
204                         source_info,
205                         discr,
206                         Rvalue::Discriminant(place),
207                     );
208
209                     (Operand::Move(discr), discr_ty)
210                 } else {
211                     let ty = source.ty;
212                     let source = unpack!(
213                         block = this.as_operand(block, scope, source, None, NeedsTemporary::No)
214                     );
215                     (source, ty)
216                 };
217                 let from_ty = CastTy::from_ty(ty);
218                 let cast_ty = CastTy::from_ty(expr.ty);
219                 let cast_kind = match (from_ty, cast_ty) {
220                     (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => {
221                         CastKind::PointerExposeAddress
222                     }
223                     (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => {
224                         CastKind::PointerFromExposedAddress
225                     }
226                     (_, _) => CastKind::Misc,
227                 };
228                 block.and(Rvalue::Cast(cast_kind, source, expr.ty))
229             }
230             ExprKind::Pointer { cast, source } => {
231                 let source = unpack!(
232                     block =
233                         this.as_operand(block, scope, &this.thir[source], None, NeedsTemporary::No)
234                 );
235                 block.and(Rvalue::Cast(CastKind::Pointer(cast), source, expr.ty))
236             }
237             ExprKind::Array { ref fields } => {
238                 // (*) We would (maybe) be closer to codegen if we
239                 // handled this and other aggregate cases via
240                 // `into()`, not `as_rvalue` -- in that case, instead
241                 // of generating
242                 //
243                 //     let tmp1 = ...1;
244                 //     let tmp2 = ...2;
245                 //     dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
246                 //
247                 // we could just generate
248                 //
249                 //     dest.f = ...1;
250                 //     dest.g = ...2;
251                 //
252                 // The problem is that then we would need to:
253                 //
254                 // (a) have a more complex mechanism for handling
255                 //     partial cleanup;
256                 // (b) distinguish the case where the type `Foo` has a
257                 //     destructor, in which case creating an instance
258                 //     as a whole "arms" the destructor, and you can't
259                 //     write individual fields; and,
260                 // (c) handle the case where the type Foo has no
261                 //     fields. We don't want `let x: ();` to compile
262                 //     to the same MIR as `let x = ();`.
263
264                 // first process the set of fields
265                 let el_ty = expr.ty.sequence_element_type(this.tcx);
266                 let fields: Vec<_> = fields
267                     .into_iter()
268                     .copied()
269                     .map(|f| {
270                         unpack!(
271                             block = this.as_operand(
272                                 block,
273                                 scope,
274                                 &this.thir[f],
275                                 None,
276                                 NeedsTemporary::Maybe
277                             )
278                         )
279                     })
280                     .collect();
281
282                 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(el_ty)), fields))
283             }
284             ExprKind::Tuple { ref fields } => {
285                 // see (*) above
286                 // first process the set of fields
287                 let fields: Vec<_> = fields
288                     .into_iter()
289                     .copied()
290                     .map(|f| {
291                         unpack!(
292                             block = this.as_operand(
293                                 block,
294                                 scope,
295                                 &this.thir[f],
296                                 None,
297                                 NeedsTemporary::Maybe
298                             )
299                         )
300                     })
301                     .collect();
302
303                 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Tuple), fields))
304             }
305             ExprKind::Closure { closure_id, substs, ref upvars, movability, ref fake_reads } => {
306                 // Convert the closure fake reads, if any, from `ExprRef` to mir `Place`
307                 // and push the fake reads.
308                 // This must come before creating the operands. This is required in case
309                 // there is a fake read and a borrow of the same path, since otherwise the
310                 // fake read might interfere with the borrow. Consider an example like this
311                 // one:
312                 // ```
313                 // let mut x = 0;
314                 // let c = || {
315                 //     &mut x; // mutable borrow of `x`
316                 //     match x { _ => () } // fake read of `x`
317                 // };
318                 // ```
319                 //
320                 for (thir_place, cause, hir_id) in fake_reads.into_iter() {
321                     let place_builder =
322                         unpack!(block = this.as_place_builder(block, &this.thir[*thir_place]));
323
324                     if let Ok(place_builder_resolved) =
325                         place_builder.try_upvars_resolved(this.tcx, this.typeck_results)
326                     {
327                         let mir_place =
328                             place_builder_resolved.into_place(this.tcx, this.typeck_results);
329                         this.cfg.push_fake_read(
330                             block,
331                             this.source_info(this.tcx.hir().span(*hir_id)),
332                             *cause,
333                             mir_place,
334                         );
335                     }
336                 }
337
338                 // see (*) above
339                 let operands: Vec<_> = upvars
340                     .into_iter()
341                     .copied()
342                     .map(|upvar| {
343                         let upvar = &this.thir[upvar];
344                         match Category::of(&upvar.kind) {
345                             // Use as_place to avoid creating a temporary when
346                             // moving a variable into a closure, so that
347                             // borrowck knows which variables to mark as being
348                             // used as mut. This is OK here because the upvar
349                             // expressions have no side effects and act on
350                             // disjoint places.
351                             // This occurs when capturing by copy/move, while
352                             // by reference captures use as_operand
353                             Some(Category::Place) => {
354                                 let place = unpack!(block = this.as_place(block, upvar));
355                                 this.consume_by_copy_or_move(place)
356                             }
357                             _ => {
358                                 // Turn mutable borrow captures into unique
359                                 // borrow captures when capturing an immutable
360                                 // variable. This is sound because the mutation
361                                 // that caused the capture will cause an error.
362                                 match upvar.kind {
363                                     ExprKind::Borrow {
364                                         borrow_kind:
365                                             BorrowKind::Mut { allow_two_phase_borrow: false },
366                                         arg,
367                                     } => unpack!(
368                                         block = this.limit_capture_mutability(
369                                             upvar.span,
370                                             upvar.ty,
371                                             scope,
372                                             block,
373                                             &this.thir[arg],
374                                         )
375                                     ),
376                                     _ => {
377                                         unpack!(
378                                             block = this.as_operand(
379                                                 block,
380                                                 scope,
381                                                 upvar,
382                                                 None,
383                                                 NeedsTemporary::Maybe
384                                             )
385                                         )
386                                     }
387                                 }
388                             }
389                         }
390                     })
391                     .collect();
392
393                 let result = match substs {
394                     UpvarSubsts::Generator(substs) => {
395                         // We implicitly set the discriminant to 0. See
396                         // librustc_mir/transform/deaggregator.rs for details.
397                         let movability = movability.unwrap();
398                         Box::new(AggregateKind::Generator(closure_id, substs, movability))
399                     }
400                     UpvarSubsts::Closure(substs) => {
401                         Box::new(AggregateKind::Closure(closure_id, substs))
402                     }
403                 };
404                 block.and(Rvalue::Aggregate(result, operands))
405             }
406             ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
407                 block = unpack!(this.stmt_expr(block, expr, None));
408                 block.and(Rvalue::Use(Operand::Constant(Box::new(Constant {
409                     span: expr_span,
410                     user_ty: None,
411                     literal: ConstantKind::zero_sized(this.tcx.types.unit),
412                 }))))
413             }
414
415             ExprKind::Literal { .. }
416             | ExprKind::NamedConst { .. }
417             | ExprKind::NonHirLiteral { .. }
418             | ExprKind::ZstLiteral { .. }
419             | ExprKind::ConstParam { .. }
420             | ExprKind::ConstBlock { .. }
421             | ExprKind::StaticRef { .. } => {
422                 let constant = this.as_constant(expr);
423                 block.and(Rvalue::Use(Operand::Constant(Box::new(constant))))
424             }
425
426             ExprKind::Yield { .. }
427             | ExprKind::Block { .. }
428             | ExprKind::Match { .. }
429             | ExprKind::If { .. }
430             | ExprKind::NeverToAny { .. }
431             | ExprKind::Use { .. }
432             | ExprKind::Borrow { .. }
433             | ExprKind::AddressOf { .. }
434             | ExprKind::Adt { .. }
435             | ExprKind::Loop { .. }
436             | ExprKind::LogicalOp { .. }
437             | ExprKind::Call { .. }
438             | ExprKind::Field { .. }
439             | ExprKind::Let { .. }
440             | ExprKind::Deref { .. }
441             | ExprKind::Index { .. }
442             | ExprKind::VarRef { .. }
443             | ExprKind::UpvarRef { .. }
444             | ExprKind::Break { .. }
445             | ExprKind::Continue { .. }
446             | ExprKind::Return { .. }
447             | ExprKind::InlineAsm { .. }
448             | ExprKind::PlaceTypeAscription { .. }
449             | ExprKind::ValueTypeAscription { .. } => {
450                 // these do not have corresponding `Rvalue` variants,
451                 // so make an operand and then return that
452                 debug_assert!(!matches!(
453                     Category::of(&expr.kind),
454                     Some(Category::Rvalue(RvalueFunc::AsRvalue) | Category::Constant)
455                 ));
456                 let operand =
457                     unpack!(block = this.as_operand(block, scope, expr, None, NeedsTemporary::No));
458                 block.and(Rvalue::Use(operand))
459             }
460         }
461     }
462
463     pub(crate) fn build_binary_op(
464         &mut self,
465         mut block: BasicBlock,
466         op: BinOp,
467         span: Span,
468         ty: Ty<'tcx>,
469         lhs: Operand<'tcx>,
470         rhs: Operand<'tcx>,
471     ) -> BlockAnd<Rvalue<'tcx>> {
472         let source_info = self.source_info(span);
473         let bool_ty = self.tcx.types.bool;
474         if self.check_overflow && op.is_checkable() && ty.is_integral() {
475             let result_tup = self.tcx.intern_tup(&[ty, bool_ty]);
476             let result_value = self.temp(result_tup, span);
477
478             self.cfg.push_assign(
479                 block,
480                 source_info,
481                 result_value,
482                 Rvalue::CheckedBinaryOp(op, Box::new((lhs.to_copy(), rhs.to_copy()))),
483             );
484             let val_fld = Field::new(0);
485             let of_fld = Field::new(1);
486
487             let tcx = self.tcx;
488             let val = tcx.mk_place_field(result_value, val_fld, ty);
489             let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
490
491             let err = AssertKind::Overflow(op, lhs, rhs);
492
493             block = self.assert(block, Operand::Move(of), false, err, span);
494
495             block.and(Rvalue::Use(Operand::Move(val)))
496         } else {
497             if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
498                 // Checking division and remainder is more complex, since we 1. always check
499                 // and 2. there are two possible failure cases, divide-by-zero and overflow.
500
501                 let zero_err = if op == BinOp::Div {
502                     AssertKind::DivisionByZero(lhs.to_copy())
503                 } else {
504                     AssertKind::RemainderByZero(lhs.to_copy())
505                 };
506                 let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
507
508                 // Check for / 0
509                 let is_zero = self.temp(bool_ty, span);
510                 let zero = self.zero_literal(span, ty);
511                 self.cfg.push_assign(
512                     block,
513                     source_info,
514                     is_zero,
515                     Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), zero))),
516                 );
517
518                 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
519
520                 // We only need to check for the overflow in one case:
521                 // MIN / -1, and only for signed values.
522                 if ty.is_signed() {
523                     let neg_1 = self.neg_1_literal(span, ty);
524                     let min = self.minval_literal(span, ty);
525
526                     let is_neg_1 = self.temp(bool_ty, span);
527                     let is_min = self.temp(bool_ty, span);
528                     let of = self.temp(bool_ty, span);
529
530                     // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
531
532                     self.cfg.push_assign(
533                         block,
534                         source_info,
535                         is_neg_1,
536                         Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), neg_1))),
537                     );
538                     self.cfg.push_assign(
539                         block,
540                         source_info,
541                         is_min,
542                         Rvalue::BinaryOp(BinOp::Eq, Box::new((lhs.to_copy(), min))),
543                     );
544
545                     let is_neg_1 = Operand::Move(is_neg_1);
546                     let is_min = Operand::Move(is_min);
547                     self.cfg.push_assign(
548                         block,
549                         source_info,
550                         of,
551                         Rvalue::BinaryOp(BinOp::BitAnd, Box::new((is_neg_1, is_min))),
552                     );
553
554                     block = self.assert(block, Operand::Move(of), false, overflow_err, span);
555                 }
556             }
557
558             block.and(Rvalue::BinaryOp(op, Box::new((lhs, rhs))))
559         }
560     }
561
562     fn build_zero_repeat(
563         &mut self,
564         mut block: BasicBlock,
565         value: ExprId,
566         scope: Option<region::Scope>,
567         outer_source_info: SourceInfo,
568     ) -> BlockAnd<Rvalue<'tcx>> {
569         let this = self;
570         let value = &this.thir[value];
571         let elem_ty = value.ty;
572         if let Some(Category::Constant) = Category::of(&value.kind) {
573             // Repeating a const does nothing
574         } else {
575             // For a non-const, we may need to generate an appropriate `Drop`
576             let value_operand =
577                 unpack!(block = this.as_operand(block, scope, value, None, NeedsTemporary::No));
578             if let Operand::Move(to_drop) = value_operand {
579                 let success = this.cfg.start_new_block();
580                 this.cfg.terminate(
581                     block,
582                     outer_source_info,
583                     TerminatorKind::Drop { place: to_drop, target: success, unwind: None },
584                 );
585                 this.diverge_from(block);
586                 block = success;
587             }
588             this.record_operands_moved(&[value_operand]);
589         }
590         block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), Vec::new()))
591     }
592
593     fn limit_capture_mutability(
594         &mut self,
595         upvar_span: Span,
596         upvar_ty: Ty<'tcx>,
597         temp_lifetime: Option<region::Scope>,
598         mut block: BasicBlock,
599         arg: &Expr<'tcx>,
600     ) -> BlockAnd<Operand<'tcx>> {
601         let this = self;
602
603         let source_info = this.source_info(upvar_span);
604         let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
605
606         this.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(temp) });
607
608         let arg_place_builder = unpack!(block = this.as_place_builder(block, arg));
609
610         let mutability = match arg_place_builder.base() {
611             // We are capturing a path that starts off a local variable in the parent.
612             // The mutability of the current capture is same as the mutability
613             // of the local declaration in the parent.
614             PlaceBase::Local(local) => this.local_decls[local].mutability,
615             // Parent is a closure and we are capturing a path that is captured
616             // by the parent itself. The mutability of the current capture
617             // is same as that of the capture in the parent closure.
618             PlaceBase::Upvar { .. } => {
619                 let enclosing_upvars_resolved =
620                     arg_place_builder.clone().into_place(this.tcx, this.typeck_results);
621
622                 match enclosing_upvars_resolved.as_ref() {
623                     PlaceRef {
624                         local,
625                         projection: &[ProjectionElem::Field(upvar_index, _), ..],
626                     }
627                     | PlaceRef {
628                         local,
629                         projection:
630                             &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
631                     } => {
632                         // Not in a closure
633                         debug_assert!(
634                             local == ty::CAPTURE_STRUCT_LOCAL,
635                             "Expected local to be Local(1), found {:?}",
636                             local
637                         );
638                         // Not in a closure
639                         debug_assert!(
640                             this.upvar_mutbls.len() > upvar_index.index(),
641                             "Unexpected capture place, upvar_mutbls={:#?}, upvar_index={:?}",
642                             this.upvar_mutbls,
643                             upvar_index
644                         );
645                         this.upvar_mutbls[upvar_index.index()]
646                     }
647                     _ => bug!("Unexpected capture place"),
648                 }
649             }
650         };
651
652         let borrow_kind = match mutability {
653             Mutability::Not => BorrowKind::Unique,
654             Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
655         };
656
657         let arg_place = arg_place_builder.into_place(this.tcx, this.typeck_results);
658
659         this.cfg.push_assign(
660             block,
661             source_info,
662             Place::from(temp),
663             Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place),
664         );
665
666         // See the comment in `expr_as_temp` and on the `rvalue_scopes` field for why
667         // this can be `None`.
668         if let Some(temp_lifetime) = temp_lifetime {
669             this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
670         }
671
672         block.and(Operand::Move(Place::from(temp)))
673     }
674
675     // Helper to get a `-1` value of the appropriate type
676     fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
677         let param_ty = ty::ParamEnv::empty().and(ty);
678         let size = self.tcx.layout_of(param_ty).unwrap().size;
679         let literal = ConstantKind::from_bits(self.tcx, size.unsigned_int_max(), param_ty);
680
681         self.literal_operand(span, literal)
682     }
683
684     // Helper to get the minimum value of the appropriate type
685     fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
686         assert!(ty.is_signed());
687         let param_ty = ty::ParamEnv::empty().and(ty);
688         let bits = self.tcx.layout_of(param_ty).unwrap().size.bits();
689         let n = 1 << (bits - 1);
690         let literal = ConstantKind::from_bits(self.tcx, n, param_ty);
691
692         self.literal_operand(span, literal)
693     }
694 }