]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/expr/as_rvalue.rs
Auto merge of #52018 - flip1995:rfc2103, r=oli-obk
[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(expr_span, scope, &Place::Local(result), value.ty);
106                 }
107
108                 // malloc some memory of suitable type (thus far, uninitialized):
109                 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
110                 this.cfg.push_assign(block, source_info, &Place::Local(result), box_);
111
112                 // initialize the box contents:
113                 unpack!(block = this.into(&Place::Local(result).deref(), block, value));
114                 block.and(Rvalue::Use(Operand::Move(Place::Local(result))))
115             }
116             ExprKind::Cast { source } => {
117                 let source = this.hir.mirror(source);
118
119                 let source = unpack!(block = this.as_operand(block, scope, source));
120                 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
121             }
122             ExprKind::Use { source } => {
123                 let source = unpack!(block = this.as_operand(block, scope, source));
124                 block.and(Rvalue::Use(source))
125             }
126             ExprKind::ReifyFnPointer { source } => {
127                 let source = unpack!(block = this.as_operand(block, scope, source));
128                 block.and(Rvalue::Cast(CastKind::ReifyFnPointer, source, expr.ty))
129             }
130             ExprKind::UnsafeFnPointer { source } => {
131                 let source = unpack!(block = this.as_operand(block, scope, source));
132                 block.and(Rvalue::Cast(CastKind::UnsafeFnPointer, source, expr.ty))
133             }
134             ExprKind::ClosureFnPointer { source } => {
135                 let source = unpack!(block = this.as_operand(block, scope, source));
136                 block.and(Rvalue::Cast(CastKind::ClosureFnPointer, source, expr.ty))
137             }
138             ExprKind::Unsize { source } => {
139                 let source = unpack!(block = this.as_operand(block, scope, source));
140                 block.and(Rvalue::Cast(CastKind::Unsize, source, expr.ty))
141             }
142             ExprKind::Array { fields } => {
143                 // (*) We would (maybe) be closer to codegen if we
144                 // handled this and other aggregate cases via
145                 // `into()`, not `as_rvalue` -- in that case, instead
146                 // of generating
147                 //
148                 //     let tmp1 = ...1;
149                 //     let tmp2 = ...2;
150                 //     dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
151                 //
152                 // we could just generate
153                 //
154                 //     dest.f = ...1;
155                 //     dest.g = ...2;
156                 //
157                 // The problem is that then we would need to:
158                 //
159                 // (a) have a more complex mechanism for handling
160                 //     partial cleanup;
161                 // (b) distinguish the case where the type `Foo` has a
162                 //     destructor, in which case creating an instance
163                 //     as a whole "arms" the destructor, and you can't
164                 //     write individual fields; and,
165                 // (c) handle the case where the type Foo has no
166                 //     fields. We don't want `let x: ();` to compile
167                 //     to the same MIR as `let x = ();`.
168
169                 // first process the set of fields
170                 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
171                 let fields: Vec<_> =
172                     fields.into_iter()
173                           .map(|f| unpack!(block = this.as_operand(block, scope, f)))
174                           .collect();
175
176                 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
177             }
178             ExprKind::Tuple { fields } => { // see (*) above
179                 // first process the set of fields
180                 let fields: Vec<_> =
181                     fields.into_iter()
182                           .map(|f| unpack!(block = this.as_operand(block, scope, f)))
183                           .collect();
184
185                 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
186             }
187             ExprKind::Closure { closure_id, substs, upvars, movability } => {
188                 // see (*) above
189                 let mut operands: Vec<_> = upvars
190                     .into_iter()
191                     .map(|upvar| {
192                         let upvar = this.hir.mirror(upvar);
193                         match Category::of(&upvar.kind) {
194                             // Use as_place to avoid creating a temporary when
195                             // moving a variable into a closure, so that
196                             // borrowck knows which variables to mark as being
197                             // used as mut. This is OK here because the upvar
198                             // expressions have no side effects and act on
199                             // disjoint places.
200                             // This occurs when capturing by copy/move, while
201                             // by reference captures use as_operand
202                             Some(Category::Place) => {
203                                 let place = unpack!(block = this.as_place(block, upvar));
204                                 this.consume_by_copy_or_move(place)
205                             }
206                             _ => {
207                                 unpack!(block = this.as_operand(block, scope, upvar))
208                             }
209                         }
210                     })
211                     .collect();
212                 let result = match substs {
213                     UpvarSubsts::Generator(substs) => {
214                         let movability = movability.unwrap();
215                         // Add the state operand since it follows the upvars in the generator
216                         // struct. See librustc_mir/transform/generator.rs for more details.
217                         operands.push(Operand::Constant(box Constant {
218                             span: expr_span,
219                             ty: this.hir.tcx().types.u32,
220                             literal: Literal::Value {
221                                 value: ty::Const::from_bits(
222                                     this.hir.tcx(),
223                                     0,
224                                     ty::ParamEnv::empty().and(this.hir.tcx().types.u32)),
225                             },
226                         }));
227                         box AggregateKind::Generator(closure_id, substs, movability)
228                     }
229                     UpvarSubsts::Closure(substs) => {
230                         box AggregateKind::Closure(closure_id, substs)
231                     }
232                 };
233                 block.and(Rvalue::Aggregate(result, operands))
234             }
235             ExprKind::Adt {
236                 adt_def, variant_index, substs, fields, base
237             } => { // see (*) above
238                 let is_union = adt_def.is_union();
239                 let active_field_index = if is_union { Some(fields[0].name.index()) } else { None };
240
241                 // first process the set of fields that were provided
242                 // (evaluating them in order given by user)
243                 let fields_map: FxHashMap<_, _> = fields.into_iter()
244                     .map(|f| (f.name, unpack!(block = this.as_operand(block, scope, f.expr))))
245                     .collect();
246
247                 let field_names = this.hir.all_fields(adt_def, variant_index);
248
249                 let fields = if let Some(FruInfo { base, field_types }) = base {
250                     let base = unpack!(block = this.as_place(block, base));
251
252                     // MIR does not natively support FRU, so for each
253                     // base-supplied field, generate an operand that
254                     // reads it from the base.
255                     field_names.into_iter()
256                         .zip(field_types.into_iter())
257                         .map(|(n, ty)| match fields_map.get(&n) {
258                             Some(v) => v.clone(),
259                             None => this.consume_by_copy_or_move(base.clone().field(n, ty))
260                         })
261                         .collect()
262                 } else {
263                     field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
264                 };
265
266                 let adt =
267                     box AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
268                 block.and(Rvalue::Aggregate(adt, fields))
269             }
270             ExprKind::Assign { .. } |
271             ExprKind::AssignOp { .. } => {
272                 block = unpack!(this.stmt_expr(block, expr));
273                 block.and(this.unit_rvalue())
274             }
275             ExprKind::Yield { value } => {
276                 let value = unpack!(block = this.as_operand(block, scope, value));
277                 let resume = this.cfg.start_new_block();
278                 let cleanup = this.generator_drop_cleanup();
279                 this.cfg.terminate(block, source_info, TerminatorKind::Yield {
280                     value: value,
281                     resume: resume,
282                     drop: cleanup,
283                 });
284                 resume.and(this.unit_rvalue())
285             }
286             ExprKind::Literal { .. } |
287             ExprKind::Block { .. } |
288             ExprKind::Match { .. } |
289             ExprKind::If { .. } |
290             ExprKind::NeverToAny { .. } |
291             ExprKind::Loop { .. } |
292             ExprKind::LogicalOp { .. } |
293             ExprKind::Call { .. } |
294             ExprKind::Field { .. } |
295             ExprKind::Deref { .. } |
296             ExprKind::Index { .. } |
297             ExprKind::VarRef { .. } |
298             ExprKind::SelfRef |
299             ExprKind::Break { .. } |
300             ExprKind::Continue { .. } |
301             ExprKind::Return { .. } |
302             ExprKind::InlineAsm { .. } |
303             ExprKind::StaticRef { .. } => {
304                 // these do not have corresponding `Rvalue` variants,
305                 // so make an operand and then return that
306                 debug_assert!(match Category::of(&expr.kind) {
307                     Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
308                     _ => true,
309                 });
310                 let operand = unpack!(block = this.as_operand(block, scope, expr));
311                 block.and(Rvalue::Use(operand))
312             }
313         }
314     }
315
316     pub fn build_binary_op(&mut self, mut block: BasicBlock,
317                            op: BinOp, span: Span, ty: Ty<'tcx>,
318                            lhs: Operand<'tcx>, rhs: Operand<'tcx>) -> BlockAnd<Rvalue<'tcx>> {
319         let source_info = self.source_info(span);
320         let bool_ty = self.hir.bool_ty();
321         if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
322             let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
323             let result_value = self.temp(result_tup, span);
324
325             self.cfg.push_assign(block, source_info,
326                                  &result_value, Rvalue::CheckedBinaryOp(op,
327                                                                         lhs,
328                                                                         rhs));
329             let val_fld = Field::new(0);
330             let of_fld = Field::new(1);
331
332             let val = result_value.clone().field(val_fld, ty);
333             let of = result_value.field(of_fld, bool_ty);
334
335             let err = EvalErrorKind::Overflow(op);
336
337             block = self.assert(block, Operand::Move(of), false,
338                                 err, span);
339
340             block.and(Rvalue::Use(Operand::Move(val)))
341         } else {
342             if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
343                 // Checking division and remainder is more complex, since we 1. always check
344                 // and 2. there are two possible failure cases, divide-by-zero and overflow.
345
346                 let (zero_err, overflow_err) = if op == BinOp::Div {
347                     (EvalErrorKind::DivisionByZero,
348                      EvalErrorKind::Overflow(op))
349                 } else {
350                     (EvalErrorKind::RemainderByZero,
351                      EvalErrorKind::Overflow(op))
352                 };
353
354                 // Check for / 0
355                 let is_zero = self.temp(bool_ty, span);
356                 let zero = self.zero_literal(span, ty);
357                 self.cfg.push_assign(block, source_info, &is_zero,
358                                      Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero));
359
360                 block = self.assert(block, Operand::Move(is_zero), false,
361                                     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(block, source_info, &is_neg_1,
376                                          Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1));
377                     self.cfg.push_assign(block, source_info, &is_min,
378                                          Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min));
379
380                     let is_neg_1 = Operand::Move(is_neg_1);
381                     let is_min = Operand::Move(is_min);
382                     self.cfg.push_assign(block, source_info, &of,
383                                          Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min));
384
385                     block = self.assert(block, Operand::Move(of), false,
386                                         overflow_err, span);
387                 }
388             }
389
390             block.and(Rvalue::BinaryOp(op, lhs, rhs))
391         }
392     }
393
394     // Helper to get a `-1` value of the appropriate type
395     fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
396         let param_ty = ty::ParamEnv::empty().and(self.hir.tcx().lift_to_global(&ty).unwrap());
397         let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
398         let n = (!0u128) >> (128 - bits);
399         let literal = Literal::Value {
400             value: ty::Const::from_bits(self.hir.tcx(), n, param_ty)
401         };
402
403         self.literal_operand(span, ty, literal)
404     }
405
406     // Helper to get the minimum value of the appropriate type
407     fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
408         assert!(ty.is_signed());
409         let param_ty = ty::ParamEnv::empty().and(self.hir.tcx().lift_to_global(&ty).unwrap());
410         let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
411         let n = 1 << (bits - 1);
412         let literal = Literal::Value {
413             value: ty::Const::from_bits(self.hir.tcx(), n, param_ty)
414         };
415
416         self.literal_operand(span, ty, literal)
417     }
418 }