]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/expr/as_rvalue.rs
Rollup merge of #67363 - alexcrichton:wasm-import-modules, r=eddyb
[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::AddressOf { .. }
280             | ExprKind::Adt { .. }
281             | ExprKind::Loop { .. }
282             | ExprKind::LogicalOp { .. }
283             | ExprKind::Call { .. }
284             | ExprKind::Field { .. }
285             | ExprKind::Deref { .. }
286             | ExprKind::Index { .. }
287             | ExprKind::VarRef { .. }
288             | ExprKind::SelfRef
289             | ExprKind::Break { .. }
290             | ExprKind::Continue { .. }
291             | ExprKind::Return { .. }
292             | ExprKind::InlineAsm { .. }
293             | ExprKind::PlaceTypeAscription { .. }
294             | ExprKind::ValueTypeAscription { .. } => {
295                 // these do not have corresponding `Rvalue` variants,
296                 // so make an operand and then return that
297                 debug_assert!(match Category::of(&expr.kind) {
298                     Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
299                     _ => true,
300                 });
301                 let operand = unpack!(block = this.as_operand(block, scope, expr));
302                 block.and(Rvalue::Use(operand))
303             }
304         }
305     }
306
307     pub fn build_binary_op(
308         &mut self,
309         mut block: BasicBlock,
310         op: BinOp,
311         span: Span,
312         ty: Ty<'tcx>,
313         lhs: Operand<'tcx>,
314         rhs: Operand<'tcx>,
315     ) -> BlockAnd<Rvalue<'tcx>> {
316         let source_info = self.source_info(span);
317         let bool_ty = self.hir.bool_ty();
318         if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
319             let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
320             let result_value = self.temp(result_tup, span);
321
322             self.cfg.push_assign(
323                 block,
324                 source_info,
325                 &result_value,
326                 Rvalue::CheckedBinaryOp(op, lhs, rhs),
327             );
328             let val_fld = Field::new(0);
329             let of_fld = Field::new(1);
330
331             let tcx = self.hir.tcx();
332             let val = tcx.mk_place_field(result_value.clone(), val_fld, ty);
333             let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
334
335             let err = PanicInfo::Overflow(op);
336
337             block = self.assert(block, Operand::Move(of), false, err, span);
338
339             block.and(Rvalue::Use(Operand::Move(val)))
340         } else {
341             if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
342                 // Checking division and remainder is more complex, since we 1. always check
343                 // and 2. there are two possible failure cases, divide-by-zero and overflow.
344
345                 let zero_err = if op == BinOp::Div {
346                     PanicInfo::DivisionByZero
347                 } else {
348                     PanicInfo::RemainderByZero
349                 };
350                 let overflow_err = PanicInfo::Overflow(op);
351
352                 // Check for / 0
353                 let is_zero = self.temp(bool_ty, span);
354                 let zero = self.zero_literal(span, ty);
355                 self.cfg.push_assign(
356                     block,
357                     source_info,
358                     &is_zero,
359                     Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero),
360                 );
361
362                 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
363
364                 // We only need to check for the overflow in one case:
365                 // MIN / -1, and only for signed values.
366                 if ty.is_signed() {
367                     let neg_1 = self.neg_1_literal(span, ty);
368                     let min = self.minval_literal(span, ty);
369
370                     let is_neg_1 = self.temp(bool_ty, span);
371                     let is_min = self.temp(bool_ty, span);
372                     let of = self.temp(bool_ty, span);
373
374                     // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
375
376                     self.cfg.push_assign(
377                         block,
378                         source_info,
379                         &is_neg_1,
380                         Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1),
381                     );
382                     self.cfg.push_assign(
383                         block,
384                         source_info,
385                         &is_min,
386                         Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min),
387                     );
388
389                     let is_neg_1 = Operand::Move(is_neg_1);
390                     let is_min = Operand::Move(is_min);
391                     self.cfg.push_assign(
392                         block,
393                         source_info,
394                         &of,
395                         Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min),
396                     );
397
398                     block = self.assert(block, Operand::Move(of), false, overflow_err, span);
399                 }
400             }
401
402             block.and(Rvalue::BinaryOp(op, lhs, rhs))
403         }
404     }
405
406     fn limit_capture_mutability(
407         &mut self,
408         upvar_span: Span,
409         upvar_ty: Ty<'tcx>,
410         temp_lifetime: Option<region::Scope>,
411         mut block: BasicBlock,
412         arg: ExprRef<'tcx>,
413     ) -> BlockAnd<Operand<'tcx>> {
414         let this = self;
415
416         let source_info = this.source_info(upvar_span);
417         let temp = this
418             .local_decls
419             .push(LocalDecl::new_temp(upvar_ty, upvar_span));
420
421         this.cfg.push(
422             block,
423             Statement {
424                 source_info,
425                 kind: StatementKind::StorageLive(temp),
426             },
427         );
428
429         let arg_place = unpack!(block = this.as_place(block, arg));
430
431         let mutability = match arg_place.as_ref() {
432             PlaceRef {
433                 base: &PlaceBase::Local(local),
434                 projection: &[],
435             } => this.local_decls[local].mutability,
436             PlaceRef {
437                 base: &PlaceBase::Local(local),
438                 projection: &[ProjectionElem::Deref],
439             } => {
440                 debug_assert!(
441                     this.local_decls[local].is_ref_for_guard(),
442                     "Unexpected capture place",
443                 );
444                 this.local_decls[local].mutability
445             }
446             PlaceRef {
447                 ref base,
448                 projection: &[ref proj_base @ .., ProjectionElem::Field(upvar_index, _)],
449             }
450             | PlaceRef {
451                 ref base,
452                 projection: &[
453                     ref proj_base @ ..,
454                     ProjectionElem::Field(upvar_index, _),
455                     ProjectionElem::Deref
456                 ],
457             } => {
458                 let place = PlaceRef {
459                     base,
460                     projection: proj_base,
461                 };
462
463                 // Not projected from the implicit `self` in a closure.
464                 debug_assert!(
465                     match place.local_or_deref_local() {
466                         Some(local) => local == Local::new(1),
467                         None => false,
468                     },
469                     "Unexpected capture place"
470                 );
471                 // Not in a closure
472                 debug_assert!(
473                     this.upvar_mutbls.len() > upvar_index.index(),
474                     "Unexpected capture place"
475                 );
476                 this.upvar_mutbls[upvar_index.index()]
477             }
478             _ => bug!("Unexpected capture place"),
479         };
480
481         let borrow_kind = match mutability {
482             Mutability::Not => BorrowKind::Unique,
483             Mutability::Mut => BorrowKind::Mut {
484                 allow_two_phase_borrow: false,
485             },
486         };
487
488         this.cfg.push_assign(
489             block,
490             source_info,
491             &Place::from(temp),
492             Rvalue::Ref(this.hir.tcx().lifetimes.re_erased, borrow_kind, arg_place),
493         );
494
495         // In constants, temp_lifetime is None. We should not need to drop
496         // anything because no values with a destructor can be created in
497         // a constant at this time, even if the type may need dropping.
498         if let Some(temp_lifetime) = temp_lifetime {
499             this.schedule_drop_storage_and_value(
500                 upvar_span,
501                 temp_lifetime,
502                 temp,
503             );
504         }
505
506         block.and(Operand::Move(Place::from(temp)))
507     }
508
509     // Helper to get a `-1` value of the appropriate type
510     fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
511         let param_ty = ty::ParamEnv::empty().and(ty);
512         let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
513         let n = (!0u128) >> (128 - bits);
514         let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
515
516         self.literal_operand(span, literal)
517     }
518
519     // Helper to get the minimum value of the appropriate type
520     fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
521         assert!(ty.is_signed());
522         let param_ty = ty::ParamEnv::empty().and(ty);
523         let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
524         let n = 1 << (bits - 1);
525         let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
526
527         self.literal_operand(span, literal)
528     }
529 }