]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/expr/as_rvalue.rs
Rollup merge of #50846 - GuillaumeGomez:add-e0665, r=frewsxcv
[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<_> =
190                     upvars.into_iter()
191                           .map(|upvar| unpack!(block = this.as_operand(block, scope, upvar)))
192                           .collect();
193                 let result = match substs {
194                     UpvarSubsts::Generator(substs) => {
195                         let movability = movability.unwrap();
196                         // Add the state operand since it follows the upvars in the generator
197                         // struct. See librustc_mir/transform/generator.rs for more details.
198                         operands.push(Operand::Constant(box Constant {
199                             span: expr_span,
200                             ty: this.hir.tcx().types.u32,
201                             literal: Literal::Value {
202                                 value: ty::Const::from_bits(
203                                     this.hir.tcx(),
204                                     0,
205                                     this.hir.tcx().types.u32),
206                             },
207                         }));
208                         box AggregateKind::Generator(closure_id, substs, movability)
209                     }
210                     UpvarSubsts::Closure(substs) => {
211                         box AggregateKind::Closure(closure_id, substs)
212                     }
213                 };
214                 block.and(Rvalue::Aggregate(result, operands))
215             }
216             ExprKind::Adt {
217                 adt_def, variant_index, substs, fields, base
218             } => { // see (*) above
219                 let is_union = adt_def.is_union();
220                 let active_field_index = if is_union { Some(fields[0].name.index()) } else { None };
221
222                 // first process the set of fields that were provided
223                 // (evaluating them in order given by user)
224                 let fields_map: FxHashMap<_, _> = fields.into_iter()
225                     .map(|f| (f.name, unpack!(block = this.as_operand(block, scope, f.expr))))
226                     .collect();
227
228                 let field_names = this.hir.all_fields(adt_def, variant_index);
229
230                 let fields = if let Some(FruInfo { base, field_types }) = base {
231                     let base = unpack!(block = this.as_place(block, base));
232
233                     // MIR does not natively support FRU, so for each
234                     // base-supplied field, generate an operand that
235                     // reads it from the base.
236                     field_names.into_iter()
237                         .zip(field_types.into_iter())
238                         .map(|(n, ty)| match fields_map.get(&n) {
239                             Some(v) => v.clone(),
240                             None => this.consume_by_copy_or_move(base.clone().field(n, ty))
241                         })
242                         .collect()
243                 } else {
244                     field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
245                 };
246
247                 let adt =
248                     box AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
249                 block.and(Rvalue::Aggregate(adt, fields))
250             }
251             ExprKind::Assign { .. } |
252             ExprKind::AssignOp { .. } => {
253                 block = unpack!(this.stmt_expr(block, expr));
254                 block.and(this.unit_rvalue())
255             }
256             ExprKind::Yield { value } => {
257                 let value = unpack!(block = this.as_operand(block, scope, value));
258                 let resume = this.cfg.start_new_block();
259                 let cleanup = this.generator_drop_cleanup();
260                 this.cfg.terminate(block, source_info, TerminatorKind::Yield {
261                     value: value,
262                     resume: resume,
263                     drop: cleanup,
264                 });
265                 resume.and(this.unit_rvalue())
266             }
267             ExprKind::Literal { .. } |
268             ExprKind::Block { .. } |
269             ExprKind::Match { .. } |
270             ExprKind::If { .. } |
271             ExprKind::NeverToAny { .. } |
272             ExprKind::Loop { .. } |
273             ExprKind::LogicalOp { .. } |
274             ExprKind::Call { .. } |
275             ExprKind::Field { .. } |
276             ExprKind::Deref { .. } |
277             ExprKind::Index { .. } |
278             ExprKind::VarRef { .. } |
279             ExprKind::SelfRef |
280             ExprKind::Break { .. } |
281             ExprKind::Continue { .. } |
282             ExprKind::Return { .. } |
283             ExprKind::InlineAsm { .. } |
284             ExprKind::StaticRef { .. } => {
285                 // these do not have corresponding `Rvalue` variants,
286                 // so make an operand and then return that
287                 debug_assert!(match Category::of(&expr.kind) {
288                     Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
289                     _ => true,
290                 });
291                 let operand = unpack!(block = this.as_operand(block, scope, expr));
292                 block.and(Rvalue::Use(operand))
293             }
294         }
295     }
296
297     pub fn build_binary_op(&mut self, mut block: BasicBlock,
298                            op: BinOp, span: Span, ty: Ty<'tcx>,
299                            lhs: Operand<'tcx>, rhs: Operand<'tcx>) -> BlockAnd<Rvalue<'tcx>> {
300         let source_info = self.source_info(span);
301         let bool_ty = self.hir.bool_ty();
302         if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
303             let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
304             let result_value = self.temp(result_tup, span);
305
306             self.cfg.push_assign(block, source_info,
307                                  &result_value, Rvalue::CheckedBinaryOp(op,
308                                                                         lhs,
309                                                                         rhs));
310             let val_fld = Field::new(0);
311             let of_fld = Field::new(1);
312
313             let val = result_value.clone().field(val_fld, ty);
314             let of = result_value.field(of_fld, bool_ty);
315
316             let err = EvalErrorKind::Overflow(op);
317
318             block = self.assert(block, Operand::Move(of), false,
319                                 err, span);
320
321             block.and(Rvalue::Use(Operand::Move(val)))
322         } else {
323             if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
324                 // Checking division and remainder is more complex, since we 1. always check
325                 // and 2. there are two possible failure cases, divide-by-zero and overflow.
326
327                 let (zero_err, overflow_err) = if op == BinOp::Div {
328                     (EvalErrorKind::DivisionByZero,
329                      EvalErrorKind::Overflow(op))
330                 } else {
331                     (EvalErrorKind::RemainderByZero,
332                      EvalErrorKind::Overflow(op))
333                 };
334
335                 // Check for / 0
336                 let is_zero = self.temp(bool_ty, span);
337                 let zero = self.zero_literal(span, ty);
338                 self.cfg.push_assign(block, source_info, &is_zero,
339                                      Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero));
340
341                 block = self.assert(block, Operand::Move(is_zero), false,
342                                     zero_err, span);
343
344                 // We only need to check for the overflow in one case:
345                 // MIN / -1, and only for signed values.
346                 if ty.is_signed() {
347                     let neg_1 = self.neg_1_literal(span, ty);
348                     let min = self.minval_literal(span, ty);
349
350                     let is_neg_1 = self.temp(bool_ty, span);
351                     let is_min   = self.temp(bool_ty, span);
352                     let of       = self.temp(bool_ty, span);
353
354                     // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
355
356                     self.cfg.push_assign(block, source_info, &is_neg_1,
357                                          Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1));
358                     self.cfg.push_assign(block, source_info, &is_min,
359                                          Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min));
360
361                     let is_neg_1 = Operand::Move(is_neg_1);
362                     let is_min = Operand::Move(is_min);
363                     self.cfg.push_assign(block, source_info, &of,
364                                          Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min));
365
366                     block = self.assert(block, Operand::Move(of), false,
367                                         overflow_err, span);
368                 }
369             }
370
371             block.and(Rvalue::BinaryOp(op, lhs, rhs))
372         }
373     }
374
375     // Helper to get a `-1` value of the appropriate type
376     fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
377         let bits = self.hir.integer_bit_width(ty);
378         let n = (!0u128) >> (128 - bits);
379         let literal = Literal::Value {
380             value: ty::Const::from_bits(self.hir.tcx(), n, ty)
381         };
382
383         self.literal_operand(span, ty, literal)
384     }
385
386     // Helper to get the minimum value of the appropriate type
387     fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
388         assert!(ty.is_signed());
389         let bits = self.hir.integer_bit_width(ty);
390         let n = 1 << (bits - 1);
391         let literal = Literal::Value {
392             value: ty::Const::from_bits(self.hir.tcx(), n, ty)
393         };
394
395         self.literal_operand(span, ty, literal)
396     }
397 }