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