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.
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.
11 //! See docs in build/expr/mod.rs
15 use rustc_const_math::{ConstMathErr, Op};
16 use rustc_data_structures::fx::FxHashMap;
17 use rustc_data_structures::indexed_vec::Idx;
19 use build::{BlockAnd, BlockAndExtension, Builder};
20 use build::expr::category::{Category, RvalueFunc};
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};
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>>
36 let local_scope = self.local_scope();
37 self.as_rvalue(block, local_scope, expr)
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>>
45 let expr = self.hir.mirror(expr);
46 self.expr_as_rvalue(block, scope, expr)
49 fn expr_as_rvalue(&mut self,
50 mut block: BasicBlock,
51 scope: Option<region::Scope>,
53 -> BlockAnd<Rvalue<'tcx>> {
54 debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
57 let expr_span = expr.span;
58 let source_info = this.source_info(expr_span);
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))
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))
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))
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,
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();
85 let minval = this.minval_literal(expr_span, expr.ty);
86 let is_min = this.temp(bool_ty, expr_span);
88 this.cfg.push_assign(block, source_info, &is_min,
89 Rvalue::BinaryOp(BinOp::Eq, arg.clone(), minval));
91 let err = ConstMathErr::Overflow(Op::Neg);
92 block = this.assert(block, Operand::Consume(is_min), false,
93 AssertMessage::Math(err), expr_span);
95 block.and(Rvalue::UnaryOp(op, arg))
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 {
102 kind: StatementKind::StorageLive(result)
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);
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_);
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))))
117 ExprKind::Cast { source } => {
118 let source = this.hir.mirror(source);
120 let source = unpack!(block = this.as_operand(block, scope, source));
121 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
123 ExprKind::Use { source } => {
124 let source = unpack!(block = this.as_operand(block, scope, source));
125 block.and(Rvalue::Use(source))
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))
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))
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))
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))
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
151 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
153 // we could just generate
158 // The problem is that then we would need to:
160 // (a) have a more complex mechanism for handling
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 = ();`.
170 // first process the set of fields
171 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
174 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
177 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
179 ExprKind::Tuple { fields } => { // see (*) above
180 // first process the set of fields
183 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
186 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
188 ExprKind::Closure { closure_id, substs, upvars, interior } => { // see (*) above
189 let mut operands: Vec<_> =
191 .map(|upvar| unpack!(block = this.as_operand(block, scope, upvar)))
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 {
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
206 box AggregateKind::Generator(closure_id, substs, interior)
208 box AggregateKind::Closure(closure_id, substs)
210 block.and(Rvalue::Aggregate(result, operands))
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 };
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))))
224 let field_names = this.hir.all_fields(adt_def, variant_index);
226 let fields = if let Some(FruInfo { base, field_types }) = base {
227 let base = unpack!(block = this.as_lvalue(block, base));
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))
240 field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
244 box AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
245 block.and(Rvalue::Aggregate(adt, fields))
247 ExprKind::Assign { .. } |
248 ExprKind::AssignOp { .. } => {
249 block = unpack!(this.stmt_expr(block, expr));
250 block.and(this.unit_rvalue())
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 {
261 resume.and(this.unit_rvalue())
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 { .. } |
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,
287 let operand = unpack!(block = this.as_operand(block, scope, expr));
288 block.and(Rvalue::Use(operand))
293 pub fn build_binary_op(&mut self, mut block: BasicBlock,
294 op: BinOp, span: Span, 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);
302 self.cfg.push_assign(block, source_info,
303 &result_value, Rvalue::CheckedBinaryOp(op,
306 let val_fld = Field::new(0);
307 let of_fld = Field::new(1);
309 let val = result_value.clone().field(val_fld, ty);
310 let of = result_value.field(of_fld, bool_ty);
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,
319 bug!("MIR build_binary_op: {:?} is not checkable", op)
323 block = self.assert(block, Operand::Consume(of), false,
324 AssertMessage::Math(err), span);
326 block.and(Rvalue::Use(Operand::Consume(val)))
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.
332 let (zero_err, overflow_err) = if op == BinOp::Div {
333 (ConstMathErr::DivisionByZero,
334 ConstMathErr::Overflow(Op::Div))
336 (ConstMathErr::RemainderByZero,
337 ConstMathErr::Overflow(Op::Rem))
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));
346 block = self.assert(block, Operand::Consume(is_zero), false,
347 AssertMessage::Math(zero_err), span);
349 // We only need to check for the overflow in one case:
350 // MIN / -1, and only for signed values.
352 let neg_1 = self.neg_1_literal(span, ty);
353 let min = self.minval_literal(span, ty);
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);
359 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
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));
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));
371 block = self.assert(block, Operand::Consume(of), false,
372 AssertMessage::Math(overflow_err), span);
376 block.and(Rvalue::BinaryOp(op, lhs, rhs))
380 // Helper to get a `-1` value of the appropriate type
381 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
382 let literal = match ty.sty {
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),
391 let int_ty = self.hir.tcx().sess.target.isize_ty;
392 let val = ConstIsize::new(-1, int_ty).unwrap();
398 value: self.hir.tcx().mk_const(ty::Const {
399 val: ConstVal::Integral(val),
405 span_bug!(span, "Invalid type for neg_1_literal: `{:?}`", ty)
409 self.literal_operand(span, ty, literal)
412 // Helper to get the minimum value of the appropriate type
413 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
414 let literal = match ty.sty {
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()),
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,
430 let val = ConstIsize::new(min, int_ty).unwrap();
436 value: self.hir.tcx().mk_const(ty::Const {
437 val: ConstVal::Integral(val),
443 span_bug!(span, "Invalid type for minval_literal: `{:?}`", ty)
447 self.literal_operand(span, ty, literal)