]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_rvalue.rs
Rollup merge of #82091 - henryboisdequin:use-place-ref-more, r=RalfJung
[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
5 use crate::build::expr::as_place::PlaceBase;
6 use crate::build::expr::category::{Category, RvalueFunc};
7 use crate::build::{BlockAnd, BlockAndExtension, Builder};
8 use crate::thir::*;
9 use rustc_middle::middle::region;
10 use rustc_middle::mir::AssertKind;
11 use rustc_middle::mir::*;
12 use rustc_middle::ty::{self, Ty, UpvarSubsts};
13 use rustc_span::Span;
14
15 impl<'a, 'tcx> Builder<'a, 'tcx> {
16     /// Returns an rvalue suitable for use until the end of the current
17     /// scope expression.
18     ///
19     /// The operand returned from this function will *not be valid* after
20     /// an ExprKind::Scope is passed, so please do *not* return it from
21     /// functions to avoid bad miscompiles.
22     crate fn as_local_rvalue<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<Rvalue<'tcx>>
23     where
24         M: Mirror<'tcx, Output = Expr<'tcx>>,
25     {
26         let local_scope = self.local_scope();
27         self.as_rvalue(block, Some(local_scope), expr)
28     }
29
30     /// Compile `expr`, yielding an rvalue.
31     fn as_rvalue<M>(
32         &mut self,
33         block: BasicBlock,
34         scope: Option<region::Scope>,
35         expr: M,
36     ) -> BlockAnd<Rvalue<'tcx>>
37     where
38         M: Mirror<'tcx, Output = Expr<'tcx>>,
39     {
40         let expr = self.hir.mirror(expr);
41         self.expr_as_rvalue(block, scope, expr)
42     }
43
44     fn expr_as_rvalue(
45         &mut self,
46         mut block: BasicBlock,
47         scope: Option<region::Scope>,
48         expr: Expr<'tcx>,
49     ) -> BlockAnd<Rvalue<'tcx>> {
50         debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
51
52         let this = self;
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                 let value_operand = unpack!(block = this.as_operand(block, scope, value));
64                 block.and(Rvalue::Repeat(value_operand, count))
65             }
66             ExprKind::Binary { op, lhs, rhs } => {
67                 let lhs = unpack!(block = this.as_operand(block, scope, lhs));
68                 let rhs = unpack!(block = this.as_operand(block, scope, rhs));
69                 this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
70             }
71             ExprKind::Unary { op, arg } => {
72                 let arg = unpack!(block = this.as_operand(block, scope, arg));
73                 // Check for -MIN on signed integers
74                 if this.hir.check_overflow() && op == UnOp::Neg && expr.ty.is_signed() {
75                     let bool_ty = this.hir.bool_ty();
76
77                     let minval = this.minval_literal(expr_span, expr.ty);
78                     let is_min = this.temp(bool_ty, expr_span);
79
80                     this.cfg.push_assign(
81                         block,
82                         source_info,
83                         is_min,
84                         Rvalue::BinaryOp(BinOp::Eq, arg.to_copy(), minval),
85                     );
86
87                     block = this.assert(
88                         block,
89                         Operand::Move(is_min),
90                         false,
91                         AssertKind::OverflowNeg(arg.to_copy()),
92                         expr_span,
93                     );
94                 }
95                 block.and(Rvalue::UnaryOp(op, arg))
96             }
97             ExprKind::Box { value } => {
98                 let value = this.hir.mirror(value);
99                 // The `Box<T>` temporary created here is not a part of the HIR,
100                 // and therefore is not considered during generator auto-trait
101                 // determination. See the comment about `box` at `yield_in_scope`.
102                 let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span).internal());
103                 this.cfg.push(
104                     block,
105                     Statement { source_info, kind: StatementKind::StorageLive(result) },
106                 );
107                 if let Some(scope) = scope {
108                     // schedule a shallow free of that memory, lest we unwind:
109                     this.schedule_drop_storage_and_value(expr_span, scope, result);
110                 }
111
112                 // malloc some memory of suitable type (thus far, uninitialized):
113                 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
114                 this.cfg.push_assign(block, source_info, Place::from(result), box_);
115
116                 // initialize the box contents:
117                 unpack!(
118                     block =
119                         this.into(this.hir.tcx().mk_place_deref(Place::from(result)), block, value)
120                 );
121                 block.and(Rvalue::Use(Operand::Move(Place::from(result))))
122             }
123             ExprKind::Cast { source } => {
124                 let source = unpack!(block = this.as_operand(block, scope, source));
125                 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
126             }
127             ExprKind::Pointer { cast, source } => {
128                 let source = unpack!(block = this.as_operand(block, scope, source));
129                 block.and(Rvalue::Cast(CastKind::Pointer(cast), source, expr.ty))
130             }
131             ExprKind::Array { fields } => {
132                 // (*) We would (maybe) be closer to codegen if we
133                 // handled this and other aggregate cases via
134                 // `into()`, not `as_rvalue` -- in that case, instead
135                 // of generating
136                 //
137                 //     let tmp1 = ...1;
138                 //     let tmp2 = ...2;
139                 //     dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
140                 //
141                 // we could just generate
142                 //
143                 //     dest.f = ...1;
144                 //     dest.g = ...2;
145                 //
146                 // The problem is that then we would need to:
147                 //
148                 // (a) have a more complex mechanism for handling
149                 //     partial cleanup;
150                 // (b) distinguish the case where the type `Foo` has a
151                 //     destructor, in which case creating an instance
152                 //     as a whole "arms" the destructor, and you can't
153                 //     write individual fields; and,
154                 // (c) handle the case where the type Foo has no
155                 //     fields. We don't want `let x: ();` to compile
156                 //     to the same MIR as `let x = ();`.
157
158                 // first process the set of fields
159                 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
160                 let fields: Vec<_> = fields
161                     .into_iter()
162                     .map(|f| unpack!(block = this.as_operand(block, scope, f)))
163                     .collect();
164
165                 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
166             }
167             ExprKind::Tuple { fields } => {
168                 // see (*) above
169                 // first process the set of fields
170                 let fields: Vec<_> = fields
171                     .into_iter()
172                     .map(|f| unpack!(block = this.as_operand(block, scope, f)))
173                     .collect();
174
175                 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
176             }
177             ExprKind::Closure { closure_id, substs, upvars, movability } => {
178                 // see (*) above
179                 let operands: Vec<_> = upvars
180                     .into_iter()
181                     .map(|upvar| {
182                         let upvar = this.hir.mirror(upvar);
183                         match Category::of(&upvar.kind) {
184                             // Use as_place to avoid creating a temporary when
185                             // moving a variable into a closure, so that
186                             // borrowck knows which variables to mark as being
187                             // used as mut. This is OK here because the upvar
188                             // expressions have no side effects and act on
189                             // disjoint places.
190                             // This occurs when capturing by copy/move, while
191                             // by reference captures use as_operand
192                             Some(Category::Place) => {
193                                 let place = unpack!(block = this.as_place(block, upvar));
194                                 this.consume_by_copy_or_move(place)
195                             }
196                             _ => {
197                                 // Turn mutable borrow captures into unique
198                                 // borrow captures when capturing an immutable
199                                 // variable. This is sound because the mutation
200                                 // that caused the capture will cause an error.
201                                 match upvar.kind {
202                                     ExprKind::Borrow {
203                                         borrow_kind:
204                                             BorrowKind::Mut { allow_two_phase_borrow: false },
205                                         arg,
206                                     } => unpack!(
207                                         block = this.limit_capture_mutability(
208                                             upvar.span, upvar.ty, scope, block, arg,
209                                         )
210                                     ),
211                                     _ => unpack!(block = this.as_operand(block, scope, upvar)),
212                                 }
213                             }
214                         }
215                     })
216                     .collect();
217                 let result = match substs {
218                     UpvarSubsts::Generator(substs) => {
219                         // We implicitly set the discriminant to 0. See
220                         // librustc_mir/transform/deaggregator.rs for details.
221                         let movability = movability.unwrap();
222                         box AggregateKind::Generator(closure_id, substs, movability)
223                     }
224                     UpvarSubsts::Closure(substs) => box AggregateKind::Closure(closure_id, substs),
225                 };
226                 block.and(Rvalue::Aggregate(result, operands))
227             }
228             ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
229                 block = unpack!(this.stmt_expr(block, expr, None));
230                 block.and(Rvalue::Use(Operand::Constant(box Constant {
231                     span: expr_span,
232                     user_ty: None,
233                     literal: ty::Const::zero_sized(this.hir.tcx(), this.hir.tcx().types.unit),
234                 })))
235             }
236             ExprKind::Yield { .. }
237             | ExprKind::Literal { .. }
238             | ExprKind::ConstBlock { .. }
239             | ExprKind::StaticRef { .. }
240             | ExprKind::Block { .. }
241             | ExprKind::Match { .. }
242             | ExprKind::If { .. }
243             | ExprKind::NeverToAny { .. }
244             | ExprKind::Use { .. }
245             | ExprKind::Borrow { .. }
246             | ExprKind::AddressOf { .. }
247             | ExprKind::Adt { .. }
248             | ExprKind::Loop { .. }
249             | ExprKind::LogicalOp { .. }
250             | ExprKind::Call { .. }
251             | ExprKind::Field { .. }
252             | ExprKind::Deref { .. }
253             | ExprKind::Index { .. }
254             | ExprKind::VarRef { .. }
255             | ExprKind::UpvarRef { .. }
256             | ExprKind::Break { .. }
257             | ExprKind::Continue { .. }
258             | ExprKind::Return { .. }
259             | ExprKind::InlineAsm { .. }
260             | ExprKind::LlvmInlineAsm { .. }
261             | ExprKind::PlaceTypeAscription { .. }
262             | ExprKind::ValueTypeAscription { .. } => {
263                 // these do not have corresponding `Rvalue` variants,
264                 // so make an operand and then return that
265                 debug_assert!(!matches!(
266                     Category::of(&expr.kind),
267                     Some(Category::Rvalue(RvalueFunc::AsRvalue))
268                 ));
269                 let operand = unpack!(block = this.as_operand(block, scope, expr));
270                 block.and(Rvalue::Use(operand))
271             }
272         }
273     }
274
275     crate fn build_binary_op(
276         &mut self,
277         mut block: BasicBlock,
278         op: BinOp,
279         span: Span,
280         ty: Ty<'tcx>,
281         lhs: Operand<'tcx>,
282         rhs: Operand<'tcx>,
283     ) -> BlockAnd<Rvalue<'tcx>> {
284         let source_info = self.source_info(span);
285         let bool_ty = self.hir.bool_ty();
286         if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
287             let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
288             let result_value = self.temp(result_tup, span);
289
290             self.cfg.push_assign(
291                 block,
292                 source_info,
293                 result_value,
294                 Rvalue::CheckedBinaryOp(op, lhs.to_copy(), rhs.to_copy()),
295             );
296             let val_fld = Field::new(0);
297             let of_fld = Field::new(1);
298
299             let tcx = self.hir.tcx();
300             let val = tcx.mk_place_field(result_value, val_fld, ty);
301             let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
302
303             let err = AssertKind::Overflow(op, lhs, rhs);
304
305             block = self.assert(block, Operand::Move(of), false, err, span);
306
307             block.and(Rvalue::Use(Operand::Move(val)))
308         } else {
309             if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
310                 // Checking division and remainder is more complex, since we 1. always check
311                 // and 2. there are two possible failure cases, divide-by-zero and overflow.
312
313                 let zero_err = if op == BinOp::Div {
314                     AssertKind::DivisionByZero(lhs.to_copy())
315                 } else {
316                     AssertKind::RemainderByZero(lhs.to_copy())
317                 };
318                 let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
319
320                 // Check for / 0
321                 let is_zero = self.temp(bool_ty, span);
322                 let zero = self.zero_literal(span, ty);
323                 self.cfg.push_assign(
324                     block,
325                     source_info,
326                     is_zero,
327                     Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero),
328                 );
329
330                 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
331
332                 // We only need to check for the overflow in one case:
333                 // MIN / -1, and only for signed values.
334                 if ty.is_signed() {
335                     let neg_1 = self.neg_1_literal(span, ty);
336                     let min = self.minval_literal(span, ty);
337
338                     let is_neg_1 = self.temp(bool_ty, span);
339                     let is_min = self.temp(bool_ty, span);
340                     let of = self.temp(bool_ty, span);
341
342                     // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
343
344                     self.cfg.push_assign(
345                         block,
346                         source_info,
347                         is_neg_1,
348                         Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1),
349                     );
350                     self.cfg.push_assign(
351                         block,
352                         source_info,
353                         is_min,
354                         Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min),
355                     );
356
357                     let is_neg_1 = Operand::Move(is_neg_1);
358                     let is_min = Operand::Move(is_min);
359                     self.cfg.push_assign(
360                         block,
361                         source_info,
362                         of,
363                         Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min),
364                     );
365
366                     block = self.assert(block, Operand::Move(of), false, overflow_err, span);
367                 }
368             }
369
370             block.and(Rvalue::BinaryOp(op, lhs, rhs))
371         }
372     }
373
374     fn limit_capture_mutability(
375         &mut self,
376         upvar_span: Span,
377         upvar_ty: Ty<'tcx>,
378         temp_lifetime: Option<region::Scope>,
379         mut block: BasicBlock,
380         arg: ExprRef<'tcx>,
381     ) -> BlockAnd<Operand<'tcx>> {
382         let this = self;
383
384         let source_info = this.source_info(upvar_span);
385         let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
386
387         this.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(temp) });
388
389         let arg_place_builder = unpack!(block = this.as_place_builder(block, arg));
390
391         let mutability = match arg_place_builder.base() {
392             // We are capturing a path that starts off a local variable in the parent.
393             // The mutability of the current capture is same as the mutability
394             // of the local declaration in the parent.
395             PlaceBase::Local(local) => this.local_decls[local].mutability,
396             // Parent is a closure and we are capturing a path that is captured
397             // by the parent itself. The mutability of the current capture
398             // is same as that of the capture in the parent closure.
399             PlaceBase::Upvar { .. } => {
400                 let enclosing_upvars_resolved =
401                     arg_place_builder.clone().into_place(this.hir.tcx(), this.hir.typeck_results());
402
403                 match enclosing_upvars_resolved.as_ref() {
404                     PlaceRef {
405                         local,
406                         projection: &[ProjectionElem::Field(upvar_index, _), ..],
407                     }
408                     | PlaceRef {
409                         local,
410                         projection:
411                             &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
412                     } => {
413                         // Not in a closure
414                         debug_assert!(
415                             local == Local::new(1),
416                             "Expected local to be Local(1), found {:?}",
417                             local
418                         );
419                         // Not in a closure
420                         debug_assert!(
421                             this.upvar_mutbls.len() > upvar_index.index(),
422                             "Unexpected capture place, upvar_mutbls={:#?}, upvar_index={:?}",
423                             this.upvar_mutbls,
424                             upvar_index
425                         );
426                         this.upvar_mutbls[upvar_index.index()]
427                     }
428                     _ => bug!("Unexpected capture place"),
429                 }
430             }
431         };
432
433         let borrow_kind = match mutability {
434             Mutability::Not => BorrowKind::Unique,
435             Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
436         };
437
438         let arg_place = arg_place_builder.into_place(this.hir.tcx(), this.hir.typeck_results());
439
440         this.cfg.push_assign(
441             block,
442             source_info,
443             Place::from(temp),
444             Rvalue::Ref(this.hir.tcx().lifetimes.re_erased, borrow_kind, arg_place),
445         );
446
447         // See the comment in `expr_as_temp` and on the `rvalue_scopes` field for why
448         // this can be `None`.
449         if let Some(temp_lifetime) = temp_lifetime {
450             this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
451         }
452
453         block.and(Operand::Move(Place::from(temp)))
454     }
455
456     // Helper to get a `-1` value of the appropriate type
457     fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
458         let param_ty = ty::ParamEnv::empty().and(ty);
459         let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
460         let n = (!0u128) >> (128 - bits);
461         let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
462
463         self.literal_operand(span, literal)
464     }
465
466     // Helper to get the minimum value of the appropriate type
467     fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
468         assert!(ty.is_signed());
469         let param_ty = ty::ParamEnv::empty().and(ty);
470         let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
471         let n = 1 << (bits - 1);
472         let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
473
474         self.literal_operand(span, literal)
475     }
476 }