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::CodeExtent;
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 topmost_scope = self.topmost_scope(); // FIXME(#6393)
37 self.as_rvalue(block, Some(topmost_scope), expr)
40 /// Compile `expr`, yielding an rvalue.
41 pub fn as_rvalue<M>(&mut self, block: BasicBlock, scope: Option<CodeExtent>, 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<CodeExtent>,
53 -> BlockAnd<Rvalue<'tcx>> {
54 debug!("expr_as_rvalue(block={:?}, expr={:?})", block, expr);
57 let expr_span = expr.span;
58 let source_info = this.source_info(expr_span);
61 ExprKind::Scope { extent, value } => {
62 this.in_scope(extent, block, |this| this.as_rvalue(block, scope, value))
64 ExprKind::Repeat { value, count } => {
65 let value_operand = unpack!(block = this.as_operand(block, scope, value));
66 block.and(Rvalue::Repeat(value_operand, count))
68 ExprKind::Borrow { region, borrow_kind, arg } => {
69 let arg_lvalue = unpack!(block = this.as_lvalue(block, arg));
70 block.and(Rvalue::Ref(region, borrow_kind, arg_lvalue))
72 ExprKind::Binary { op, lhs, rhs } => {
73 let lhs = unpack!(block = this.as_operand(block, scope, lhs));
74 let rhs = unpack!(block = this.as_operand(block, scope, rhs));
75 this.build_binary_op(block, op, expr_span, expr.ty,
78 ExprKind::Unary { op, arg } => {
79 let arg = unpack!(block = this.as_operand(block, scope, arg));
80 // Check for -MIN on signed integers
81 if this.hir.check_overflow() && op == UnOp::Neg && expr.ty.is_signed() {
82 let bool_ty = this.hir.bool_ty();
84 let minval = this.minval_literal(expr_span, expr.ty);
85 let is_min = this.temp(bool_ty);
87 this.cfg.push_assign(block, source_info, &is_min,
88 Rvalue::BinaryOp(BinOp::Eq, arg.clone(), minval));
90 let err = ConstMathErr::Overflow(Op::Neg);
91 block = this.assert(block, Operand::Consume(is_min), false,
92 AssertMessage::Math(err), expr_span);
94 block.and(Rvalue::UnaryOp(op, arg))
96 ExprKind::Box { value, value_extents } => {
97 let value = this.hir.mirror(value);
98 let result = this.temp(expr.ty);
99 // to start, malloc some memory of suitable type (thus far, uninitialized):
100 this.cfg.push_assign(block, source_info, &result, Rvalue::Box(value.ty));
101 this.in_scope(value_extents, block, |this| {
102 // schedule a shallow free of that memory, lest we unwind:
103 this.schedule_box_free(expr_span, value_extents, &result, value.ty);
104 // initialize the box contents:
105 unpack!(block = this.into(&result.clone().deref(), block, value));
106 block.and(Rvalue::Use(Operand::Consume(result)))
109 ExprKind::Cast { source } => {
110 let source = this.hir.mirror(source);
112 let source = unpack!(block = this.as_operand(block, scope, source));
113 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
115 ExprKind::Use { source } => {
116 let source = unpack!(block = this.as_operand(block, scope, source));
117 block.and(Rvalue::Use(source))
119 ExprKind::ReifyFnPointer { source } => {
120 let source = unpack!(block = this.as_operand(block, scope, source));
121 block.and(Rvalue::Cast(CastKind::ReifyFnPointer, source, expr.ty))
123 ExprKind::UnsafeFnPointer { source } => {
124 let source = unpack!(block = this.as_operand(block, scope, source));
125 block.and(Rvalue::Cast(CastKind::UnsafeFnPointer, source, expr.ty))
127 ExprKind::ClosureFnPointer { source } => {
128 let source = unpack!(block = this.as_operand(block, scope, source));
129 block.and(Rvalue::Cast(CastKind::ClosureFnPointer, source, expr.ty))
131 ExprKind::Unsize { source } => {
132 let source = unpack!(block = this.as_operand(block, scope, source));
133 block.and(Rvalue::Cast(CastKind::Unsize, source, expr.ty))
135 ExprKind::Array { fields } => {
136 // (*) We would (maybe) be closer to trans if we
137 // handled this and other aggregate cases via
138 // `into()`, not `as_rvalue` -- in that case, instead
143 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
145 // we could just generate
150 // The problem is that then we would need to:
152 // (a) have a more complex mechanism for handling
154 // (b) distinguish the case where the type `Foo` has a
155 // destructor, in which case creating an instance
156 // as a whole "arms" the destructor, and you can't
157 // write individual fields; and,
158 // (c) handle the case where the type Foo has no
159 // fields. We don't want `let x: ();` to compile
160 // to the same MIR as `let x = ();`.
162 // first process the set of fields
163 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
166 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
169 block.and(Rvalue::Aggregate(AggregateKind::Array(el_ty), fields))
171 ExprKind::Tuple { fields } => { // see (*) above
172 // first process the set of fields
175 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
178 block.and(Rvalue::Aggregate(AggregateKind::Tuple, fields))
180 ExprKind::Closure { closure_id, substs, upvars } => { // see (*) above
183 .map(|upvar| unpack!(block = this.as_operand(block, scope, upvar)))
185 block.and(Rvalue::Aggregate(AggregateKind::Closure(closure_id, substs), upvars))
188 adt_def, variant_index, substs, fields, base
189 } => { // see (*) above
190 let is_union = adt_def.is_union();
191 let active_field_index = if is_union { Some(fields[0].name.index()) } else { None };
193 // first process the set of fields that were provided
194 // (evaluating them in order given by user)
195 let fields_map: FxHashMap<_, _> = fields.into_iter()
196 .map(|f| (f.name, unpack!(block = this.as_operand(block, scope, f.expr))))
199 let field_names = this.hir.all_fields(adt_def, variant_index);
201 let fields = if let Some(FruInfo { base, field_types }) = base {
202 let base = unpack!(block = this.as_lvalue(block, base));
204 // MIR does not natively support FRU, so for each
205 // base-supplied field, generate an operand that
206 // reads it from the base.
207 field_names.into_iter()
208 .zip(field_types.into_iter())
209 .map(|(n, ty)| match fields_map.get(&n) {
210 Some(v) => v.clone(),
211 None => Operand::Consume(base.clone().field(n, ty))
215 field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
218 let adt = AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
219 block.and(Rvalue::Aggregate(adt, fields))
221 ExprKind::Assign { .. } |
222 ExprKind::AssignOp { .. } => {
223 block = unpack!(this.stmt_expr(block, expr));
224 block.and(this.unit_rvalue())
226 ExprKind::Literal { .. } |
227 ExprKind::Block { .. } |
228 ExprKind::Match { .. } |
229 ExprKind::If { .. } |
230 ExprKind::NeverToAny { .. } |
231 ExprKind::Loop { .. } |
232 ExprKind::LogicalOp { .. } |
233 ExprKind::Call { .. } |
234 ExprKind::Field { .. } |
235 ExprKind::Deref { .. } |
236 ExprKind::Index { .. } |
237 ExprKind::VarRef { .. } |
239 ExprKind::Break { .. } |
240 ExprKind::Continue { .. } |
241 ExprKind::Return { .. } |
242 ExprKind::InlineAsm { .. } |
243 ExprKind::StaticRef { .. } => {
244 // these do not have corresponding `Rvalue` variants,
245 // so make an operand and then return that
246 debug_assert!(match Category::of(&expr.kind) {
247 Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
250 let operand = unpack!(block = this.as_operand(block, scope, expr));
251 block.and(Rvalue::Use(operand))
256 pub fn build_binary_op(&mut self, mut block: BasicBlock,
257 op: BinOp, span: Span, ty: ty::Ty<'tcx>,
258 lhs: Operand<'tcx>, rhs: Operand<'tcx>) -> BlockAnd<Rvalue<'tcx>> {
259 let source_info = self.source_info(span);
260 let bool_ty = self.hir.bool_ty();
261 if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
262 let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty], false);
263 let result_value = self.temp(result_tup);
265 self.cfg.push_assign(block, source_info,
266 &result_value, Rvalue::CheckedBinaryOp(op,
269 let val_fld = Field::new(0);
270 let of_fld = Field::new(1);
272 let val = result_value.clone().field(val_fld, ty);
273 let of = result_value.field(of_fld, bool_ty);
275 let err = ConstMathErr::Overflow(match op {
276 BinOp::Add => Op::Add,
277 BinOp::Sub => Op::Sub,
278 BinOp::Mul => Op::Mul,
279 BinOp::Shl => Op::Shl,
280 BinOp::Shr => Op::Shr,
282 bug!("MIR build_binary_op: {:?} is not checkable", op)
286 block = self.assert(block, Operand::Consume(of), false,
287 AssertMessage::Math(err), span);
289 block.and(Rvalue::Use(Operand::Consume(val)))
291 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
292 // Checking division and remainder is more complex, since we 1. always check
293 // and 2. there are two possible failure cases, divide-by-zero and overflow.
295 let (zero_err, overflow_err) = if op == BinOp::Div {
296 (ConstMathErr::DivisionByZero,
297 ConstMathErr::Overflow(Op::Div))
299 (ConstMathErr::RemainderByZero,
300 ConstMathErr::Overflow(Op::Rem))
304 let is_zero = self.temp(bool_ty);
305 let zero = self.zero_literal(span, ty);
306 self.cfg.push_assign(block, source_info, &is_zero,
307 Rvalue::BinaryOp(BinOp::Eq, rhs.clone(), zero));
309 block = self.assert(block, Operand::Consume(is_zero), false,
310 AssertMessage::Math(zero_err), span);
312 // We only need to check for the overflow in one case:
313 // MIN / -1, and only for signed values.
315 let neg_1 = self.neg_1_literal(span, ty);
316 let min = self.minval_literal(span, ty);
318 let is_neg_1 = self.temp(bool_ty);
319 let is_min = self.temp(bool_ty);
320 let of = self.temp(bool_ty);
322 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
324 self.cfg.push_assign(block, source_info, &is_neg_1,
325 Rvalue::BinaryOp(BinOp::Eq, rhs.clone(), neg_1));
326 self.cfg.push_assign(block, source_info, &is_min,
327 Rvalue::BinaryOp(BinOp::Eq, lhs.clone(), min));
329 let is_neg_1 = Operand::Consume(is_neg_1);
330 let is_min = Operand::Consume(is_min);
331 self.cfg.push_assign(block, source_info, &of,
332 Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min));
334 block = self.assert(block, Operand::Consume(of), false,
335 AssertMessage::Math(overflow_err), span);
339 block.and(Rvalue::BinaryOp(op, lhs, rhs))
343 // Helper to get a `-1` value of the appropriate type
344 fn neg_1_literal(&mut self, span: Span, ty: ty::Ty<'tcx>) -> Operand<'tcx> {
345 let literal = match ty.sty {
347 let val = match ity {
348 ast::IntTy::I8 => ConstInt::I8(-1),
349 ast::IntTy::I16 => ConstInt::I16(-1),
350 ast::IntTy::I32 => ConstInt::I32(-1),
351 ast::IntTy::I64 => ConstInt::I64(-1),
352 ast::IntTy::I128 => ConstInt::I128(-1),
354 let int_ty = self.hir.tcx().sess.target.int_type;
355 let val = ConstIsize::new(-1, int_ty).unwrap();
360 Literal::Value { value: ConstVal::Integral(val) }
363 span_bug!(span, "Invalid type for neg_1_literal: `{:?}`", ty)
367 self.literal_operand(span, ty, literal)
370 // Helper to get the minimum value of the appropriate type
371 fn minval_literal(&mut self, span: Span, ty: ty::Ty<'tcx>) -> Operand<'tcx> {
372 let literal = match ty.sty {
374 let val = match ity {
375 ast::IntTy::I8 => ConstInt::I8(i8::min_value()),
376 ast::IntTy::I16 => ConstInt::I16(i16::min_value()),
377 ast::IntTy::I32 => ConstInt::I32(i32::min_value()),
378 ast::IntTy::I64 => ConstInt::I64(i64::min_value()),
379 ast::IntTy::I128 => ConstInt::I128(i128::min_value()),
381 let int_ty = self.hir.tcx().sess.target.int_type;
382 let min = match int_ty {
383 ast::IntTy::I16 => std::i16::MIN as i64,
384 ast::IntTy::I32 => std::i32::MIN as i64,
385 ast::IntTy::I64 => std::i64::MIN,
388 let val = ConstIsize::new(min, int_ty).unwrap();
393 Literal::Value { value: ConstVal::Integral(val) }
396 span_bug!(span, "Invalid type for minval_literal: `{:?}`", ty)
400 self.literal_operand(span, ty, literal)