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