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