]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/expr/as_rvalue.rs
Auto merge of #52046 - cramertj:fix-generator-mir, r=eddyb
[rust.git] / src / librustc_mir / build / expr / as_rvalue.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! See docs in build/expr/mod.rs
12
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_data_structures::indexed_vec::Idx;
15
16 use build::{BlockAnd, BlockAndExtension, Builder};
17 use build::expr::category::{Category, RvalueFunc};
18 use hair::*;
19 use rustc::middle::region;
20 use rustc::ty::{self, Ty, UpvarSubsts};
21 use rustc::mir::*;
22 use rustc::mir::interpret::EvalErrorKind;
23 use syntax_pos::Span;
24
25 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
26     /// See comment on `as_local_operand`
27     pub fn as_local_rvalue<M>(&mut self, block: BasicBlock, expr: M)
28                              -> BlockAnd<Rvalue<'tcx>>
29         where M: Mirror<'tcx, Output = Expr<'tcx>>
30     {
31         let local_scope = self.local_scope();
32         self.as_rvalue(block, local_scope, expr)
33     }
34
35     /// Compile `expr`, yielding an rvalue.
36     pub fn as_rvalue<M>(&mut self, block: BasicBlock, scope: Option<region::Scope>, expr: M)
37                         -> BlockAnd<Rvalue<'tcx>>
38         where 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(&mut self,
45                       mut block: BasicBlock,
46                       scope: Option<region::Scope>,
47                       expr: Expr<'tcx>)
48                       -> BlockAnd<Rvalue<'tcx>> {
49         debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
50
51         let this = self;
52         let expr_span = expr.span;
53         let source_info = this.source_info(expr_span);
54
55         match expr.kind {
56             ExprKind::Scope { region_scope, lint_level, value } => {
57                 let region_scope = (region_scope, source_info);
58                 this.in_scope(region_scope, lint_level, block,
59                               |this| this.as_rvalue(block, scope, value))
60             }
61             ExprKind::Repeat { value, count } => {
62                 let value_operand = unpack!(block = this.as_operand(block, scope, value));
63                 block.and(Rvalue::Repeat(value_operand, count))
64             }
65             ExprKind::Borrow { region, borrow_kind, arg } => {
66                 let arg_place = unpack!(block = this.as_place(block, arg));
67                 block.and(Rvalue::Ref(region, borrow_kind, arg_place))
68             }
69             ExprKind::Binary { op, lhs, rhs } => {
70                 let lhs = unpack!(block = this.as_operand(block, scope, lhs));
71                 let rhs = unpack!(block = this.as_operand(block, scope, rhs));
72                 this.build_binary_op(block, op, expr_span, expr.ty,
73                                      lhs, rhs)
74             }
75             ExprKind::Unary { op, arg } => {
76                 let arg = unpack!(block = this.as_operand(block, scope, arg));
77                 // Check for -MIN on signed integers
78                 if this.hir.check_overflow() && op == UnOp::Neg && expr.ty.is_signed() {
79                     let bool_ty = this.hir.bool_ty();
80
81                     let minval = this.minval_literal(expr_span, expr.ty);
82                     let is_min = this.temp(bool_ty, expr_span);
83
84                     this.cfg.push_assign(block, source_info, &is_min,
85                                          Rvalue::BinaryOp(BinOp::Eq, arg.to_copy(), minval));
86
87                     block = this.assert(block, Operand::Move(is_min), false,
88                                         EvalErrorKind::OverflowNeg, expr_span);
89                 }
90                 block.and(Rvalue::UnaryOp(op, arg))
91             }
92             ExprKind::Box { value } => {
93                 let value = this.hir.mirror(value);
94                 // The `Box<T>` temporary created here is not a part of the HIR,
95                 // and therefore is not considered during generator OIBIT
96                 // determination. See the comment about `box` at `yield_in_scope`.
97                 let result = this.local_decls.push(
98                     LocalDecl::new_internal(expr.ty, expr_span));
99                 this.cfg.push(block, Statement {
100                     source_info,
101                     kind: StatementKind::StorageLive(result)
102                 });
103                 if let Some(scope) = scope {
104                     // schedule a shallow free of that memory, lest we unwind:
105                     this.schedule_drop_storage_and_value(
106                         expr_span, scope, &Place::Local(result), value.ty,
107                     );
108                 }
109
110                 // malloc some memory of suitable type (thus far, uninitialized):
111                 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
112                 this.cfg.push_assign(block, source_info, &Place::Local(result), box_);
113
114                 // initialize the box contents:
115                 unpack!(block = this.into(&Place::Local(result).deref(), block, value));
116                 block.and(Rvalue::Use(Operand::Move(Place::Local(result))))
117             }
118             ExprKind::Cast { source } => {
119                 let source = this.hir.mirror(source);
120
121                 let source = unpack!(block = this.as_operand(block, scope, source));
122                 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
123             }
124             ExprKind::Use { source } => {
125                 let source = unpack!(block = this.as_operand(block, scope, source));
126                 block.and(Rvalue::Use(source))
127             }
128             ExprKind::ReifyFnPointer { source } => {
129                 let source = unpack!(block = this.as_operand(block, scope, source));
130                 block.and(Rvalue::Cast(CastKind::ReifyFnPointer, source, expr.ty))
131             }
132             ExprKind::UnsafeFnPointer { source } => {
133                 let source = unpack!(block = this.as_operand(block, scope, source));
134                 block.and(Rvalue::Cast(CastKind::UnsafeFnPointer, source, expr.ty))
135             }
136             ExprKind::ClosureFnPointer { source } => {
137                 let source = unpack!(block = this.as_operand(block, scope, source));
138                 block.and(Rvalue::Cast(CastKind::ClosureFnPointer, source, expr.ty))
139             }
140             ExprKind::Unsize { source } => {
141                 let source = unpack!(block = this.as_operand(block, scope, source));
142                 block.and(Rvalue::Cast(CastKind::Unsize, source, expr.ty))
143             }
144             ExprKind::Array { fields } => {
145                 // (*) We would (maybe) be closer to codegen if we
146                 // handled this and other aggregate cases via
147                 // `into()`, not `as_rvalue` -- in that case, instead
148                 // of generating
149                 //
150                 //     let tmp1 = ...1;
151                 //     let tmp2 = ...2;
152                 //     dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
153                 //
154                 // we could just generate
155                 //
156                 //     dest.f = ...1;
157                 //     dest.g = ...2;
158                 //
159                 // The problem is that then we would need to:
160                 //
161                 // (a) have a more complex mechanism for handling
162                 //     partial cleanup;
163                 // (b) distinguish the case where the type `Foo` has a
164                 //     destructor, in which case creating an instance
165                 //     as a whole "arms" the destructor, and you can't
166                 //     write individual fields; and,
167                 // (c) handle the case where the type Foo has no
168                 //     fields. We don't want `let x: ();` to compile
169                 //     to the same MIR as `let x = ();`.
170
171                 // first process the set of fields
172                 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
173                 let fields: Vec<_> =
174                     fields.into_iter()
175                           .map(|f| unpack!(block = this.as_operand(block, scope, f)))
176                           .collect();
177
178                 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
179             }
180             ExprKind::Tuple { fields } => { // see (*) above
181                 // first process the set of fields
182                 let fields: Vec<_> =
183                     fields.into_iter()
184                           .map(|f| unpack!(block = this.as_operand(block, scope, f)))
185                           .collect();
186
187                 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
188             }
189             ExprKind::Closure { closure_id, substs, upvars, movability } => {
190                 // see (*) above
191                 let mut operands: Vec<_> = upvars
192                     .into_iter()
193                     .map(|upvar| {
194                         let upvar = this.hir.mirror(upvar);
195                         match Category::of(&upvar.kind) {
196                             // Use as_place to avoid creating a temporary when
197                             // moving a variable into a closure, so that
198                             // borrowck knows which variables to mark as being
199                             // used as mut. This is OK here because the upvar
200                             // expressions have no side effects and act on
201                             // disjoint places.
202                             // This occurs when capturing by copy/move, while
203                             // by reference captures use as_operand
204                             Some(Category::Place) => {
205                                 let place = unpack!(block = this.as_place(block, upvar));
206                                 this.consume_by_copy_or_move(place)
207                             }
208                             _ => {
209                                 unpack!(block = this.as_operand(block, scope, upvar))
210                             }
211                         }
212                     })
213                     .collect();
214                 let result = match substs {
215                     UpvarSubsts::Generator(substs) => {
216                         let movability = movability.unwrap();
217                         // Add the state operand since it follows the upvars in the generator
218                         // struct. See librustc_mir/transform/generator.rs for more details.
219                         operands.push(Operand::Constant(box Constant {
220                             span: expr_span,
221                             ty: this.hir.tcx().types.u32,
222                             literal: Literal::Value {
223                                 value: ty::Const::from_bits(
224                                     this.hir.tcx(),
225                                     0,
226                                     ty::ParamEnv::empty().and(this.hir.tcx().types.u32)),
227                             },
228                         }));
229                         box AggregateKind::Generator(closure_id, substs, movability)
230                     }
231                     UpvarSubsts::Closure(substs) => {
232                         box AggregateKind::Closure(closure_id, substs)
233                     }
234                 };
235                 block.and(Rvalue::Aggregate(result, operands))
236             }
237             ExprKind::Adt {
238                 adt_def, variant_index, substs, fields, base
239             } => { // see (*) above
240                 let is_union = adt_def.is_union();
241                 let active_field_index = if is_union { Some(fields[0].name.index()) } else { None };
242
243                 // first process the set of fields that were provided
244                 // (evaluating them in order given by user)
245                 let fields_map: FxHashMap<_, _> = fields.into_iter()
246                     .map(|f| (f.name, unpack!(block = this.as_operand(block, scope, f.expr))))
247                     .collect();
248
249                 let field_names = this.hir.all_fields(adt_def, variant_index);
250
251                 let fields = if let Some(FruInfo { base, field_types }) = base {
252                     let base = unpack!(block = this.as_place(block, base));
253
254                     // MIR does not natively support FRU, so for each
255                     // base-supplied field, generate an operand that
256                     // reads it from the base.
257                     field_names.into_iter()
258                         .zip(field_types.into_iter())
259                         .map(|(n, ty)| match fields_map.get(&n) {
260                             Some(v) => v.clone(),
261                             None => this.consume_by_copy_or_move(base.clone().field(n, ty))
262                         })
263                         .collect()
264                 } else {
265                     field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
266                 };
267
268                 let adt =
269                     box AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
270                 block.and(Rvalue::Aggregate(adt, fields))
271             }
272             ExprKind::Assign { .. } |
273             ExprKind::AssignOp { .. } => {
274                 block = unpack!(this.stmt_expr(block, expr));
275                 block.and(this.unit_rvalue())
276             }
277             ExprKind::Yield { value } => {
278                 let value = unpack!(block = this.as_operand(block, scope, value));
279                 let resume = this.cfg.start_new_block();
280                 let cleanup = this.generator_drop_cleanup();
281                 this.cfg.terminate(block, source_info, TerminatorKind::Yield {
282                     value: value,
283                     resume: resume,
284                     drop: cleanup,
285                 });
286                 resume.and(this.unit_rvalue())
287             }
288             ExprKind::Literal { .. } |
289             ExprKind::Block { .. } |
290             ExprKind::Match { .. } |
291             ExprKind::If { .. } |
292             ExprKind::NeverToAny { .. } |
293             ExprKind::Loop { .. } |
294             ExprKind::LogicalOp { .. } |
295             ExprKind::Call { .. } |
296             ExprKind::Field { .. } |
297             ExprKind::Deref { .. } |
298             ExprKind::Index { .. } |
299             ExprKind::VarRef { .. } |
300             ExprKind::SelfRef |
301             ExprKind::Break { .. } |
302             ExprKind::Continue { .. } |
303             ExprKind::Return { .. } |
304             ExprKind::InlineAsm { .. } |
305             ExprKind::StaticRef { .. } => {
306                 // these do not have corresponding `Rvalue` variants,
307                 // so make an operand and then return that
308                 debug_assert!(match Category::of(&expr.kind) {
309                     Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
310                     _ => true,
311                 });
312                 let operand = unpack!(block = this.as_operand(block, scope, expr));
313                 block.and(Rvalue::Use(operand))
314             }
315         }
316     }
317
318     pub fn build_binary_op(&mut self, mut block: BasicBlock,
319                            op: BinOp, span: Span, ty: Ty<'tcx>,
320                            lhs: Operand<'tcx>, rhs: Operand<'tcx>) -> BlockAnd<Rvalue<'tcx>> {
321         let source_info = self.source_info(span);
322         let bool_ty = self.hir.bool_ty();
323         if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
324             let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
325             let result_value = self.temp(result_tup, span);
326
327             self.cfg.push_assign(block, source_info,
328                                  &result_value, Rvalue::CheckedBinaryOp(op,
329                                                                         lhs,
330                                                                         rhs));
331             let val_fld = Field::new(0);
332             let of_fld = Field::new(1);
333
334             let val = result_value.clone().field(val_fld, ty);
335             let of = result_value.field(of_fld, bool_ty);
336
337             let err = EvalErrorKind::Overflow(op);
338
339             block = self.assert(block, Operand::Move(of), false,
340                                 err, span);
341
342             block.and(Rvalue::Use(Operand::Move(val)))
343         } else {
344             if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
345                 // Checking division and remainder is more complex, since we 1. always check
346                 // and 2. there are two possible failure cases, divide-by-zero and overflow.
347
348                 let (zero_err, overflow_err) = if op == BinOp::Div {
349                     (EvalErrorKind::DivisionByZero,
350                      EvalErrorKind::Overflow(op))
351                 } else {
352                     (EvalErrorKind::RemainderByZero,
353                      EvalErrorKind::Overflow(op))
354                 };
355
356                 // Check for / 0
357                 let is_zero = self.temp(bool_ty, span);
358                 let zero = self.zero_literal(span, ty);
359                 self.cfg.push_assign(block, source_info, &is_zero,
360                                      Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero));
361
362                 block = self.assert(block, Operand::Move(is_zero), false,
363                                     zero_err, span);
364
365                 // We only need to check for the overflow in one case:
366                 // MIN / -1, and only for signed values.
367                 if ty.is_signed() {
368                     let neg_1 = self.neg_1_literal(span, ty);
369                     let min = self.minval_literal(span, ty);
370
371                     let is_neg_1 = self.temp(bool_ty, span);
372                     let is_min   = self.temp(bool_ty, span);
373                     let of       = self.temp(bool_ty, span);
374
375                     // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
376
377                     self.cfg.push_assign(block, source_info, &is_neg_1,
378                                          Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1));
379                     self.cfg.push_assign(block, source_info, &is_min,
380                                          Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min));
381
382                     let is_neg_1 = Operand::Move(is_neg_1);
383                     let is_min = Operand::Move(is_min);
384                     self.cfg.push_assign(block, source_info, &of,
385                                          Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min));
386
387                     block = self.assert(block, Operand::Move(of), false,
388                                         overflow_err, span);
389                 }
390             }
391
392             block.and(Rvalue::BinaryOp(op, lhs, rhs))
393         }
394     }
395
396     // Helper to get a `-1` value of the appropriate type
397     fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
398         let param_ty = ty::ParamEnv::empty().and(self.hir.tcx().lift_to_global(&ty).unwrap());
399         let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
400         let n = (!0u128) >> (128 - bits);
401         let literal = Literal::Value {
402             value: ty::Const::from_bits(self.hir.tcx(), n, param_ty)
403         };
404
405         self.literal_operand(span, ty, literal)
406     }
407
408     // Helper to get the minimum value of the appropriate type
409     fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
410         assert!(ty.is_signed());
411         let param_ty = ty::ParamEnv::empty().and(self.hir.tcx().lift_to_global(&ty).unwrap());
412         let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
413         let n = 1 << (bits - 1);
414         let literal = Literal::Value {
415             value: ty::Const::from_bits(self.hir.tcx(), n, param_ty)
416         };
417
418         self.literal_operand(span, ty, literal)
419     }
420 }