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};
27 use rustc::mir::interpret::{Value, PrimVal};
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>>
37 let local_scope = self.local_scope();
38 self.as_rvalue(block, local_scope, expr)
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>>
46 let expr = self.hir.mirror(expr);
47 self.expr_as_rvalue(block, scope, expr)
50 fn expr_as_rvalue(&mut self,
51 mut block: BasicBlock,
52 scope: Option<region::Scope>,
54 -> BlockAnd<Rvalue<'tcx>> {
55 debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
58 let expr_span = expr.span;
59 let source_info = this.source_info(expr_span);
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))
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))
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))
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,
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();
87 let minval = this.minval_literal(expr_span, expr.ty);
88 let is_min = this.temp(bool_ty, expr_span);
90 this.cfg.push_assign(block, source_info, &is_min,
91 Rvalue::BinaryOp(BinOp::Eq, arg.to_copy(), minval));
93 let err = ConstMathErr::Overflow(Op::Neg);
94 block = this.assert(block, Operand::Move(is_min), false,
95 AssertMessage::Math(err), expr_span);
97 block.and(Rvalue::UnaryOp(op, arg))
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 {
108 kind: StatementKind::StorageLive(result)
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);
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_);
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))))
123 ExprKind::Cast { source } => {
124 let source = this.hir.mirror(source);
126 let source = unpack!(block = this.as_operand(block, scope, source));
127 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
129 ExprKind::Use { source } => {
130 let source = unpack!(block = this.as_operand(block, scope, source));
131 block.and(Rvalue::Use(source))
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))
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))
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))
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))
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
157 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
159 // we could just generate
164 // The problem is that then we would need to:
166 // (a) have a more complex mechanism for handling
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 = ();`.
176 // first process the set of fields
177 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
180 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
183 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
185 ExprKind::Tuple { fields } => { // see (*) above
186 // first process the set of fields
189 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
192 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
194 ExprKind::Closure { closure_id, substs, upvars, interior } => { // see (*) above
195 let mut operands: Vec<_> =
197 .map(|upvar| unpack!(block = this.as_operand(block, scope, upvar)))
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 {
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
212 box AggregateKind::Generator(closure_id, substs, interior)
214 box AggregateKind::Closure(closure_id, substs)
216 block.and(Rvalue::Aggregate(result, operands))
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 };
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))))
230 let field_names = this.hir.all_fields(adt_def, variant_index);
232 let fields = if let Some(FruInfo { base, field_types }) = base {
233 let base = unpack!(block = this.as_place(block, base));
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))
246 field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
250 box AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
251 block.and(Rvalue::Aggregate(adt, fields))
253 ExprKind::Assign { .. } |
254 ExprKind::AssignOp { .. } => {
255 block = unpack!(this.stmt_expr(block, expr));
256 block.and(this.unit_rvalue())
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 {
267 resume.and(this.unit_rvalue())
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 { .. } |
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,
293 let operand = unpack!(block = this.as_operand(block, scope, expr));
294 block.and(Rvalue::Use(operand))
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);
308 self.cfg.push_assign(block, source_info,
309 &result_value, Rvalue::CheckedBinaryOp(op,
312 let val_fld = Field::new(0);
313 let of_fld = Field::new(1);
315 let val = result_value.clone().field(val_fld, ty);
316 let of = result_value.field(of_fld, bool_ty);
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,
325 bug!("MIR build_binary_op: {:?} is not checkable", op)
329 block = self.assert(block, Operand::Move(of), false,
330 AssertMessage::Math(err), span);
332 block.and(Rvalue::Use(Operand::Move(val)))
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.
338 let (zero_err, overflow_err) = if op == BinOp::Div {
339 (ConstMathErr::DivisionByZero,
340 ConstMathErr::Overflow(Op::Div))
342 (ConstMathErr::RemainderByZero,
343 ConstMathErr::Overflow(Op::Rem))
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));
352 block = self.assert(block, Operand::Move(is_zero), false,
353 AssertMessage::Math(zero_err), span);
355 // We only need to check for the overflow in one case:
356 // MIN / -1, and only for signed values.
358 let neg_1 = self.neg_1_literal(span, ty);
359 let min = self.minval_literal(span, ty);
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);
365 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
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));
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));
377 block = self.assert(block, Operand::Move(of), false,
378 AssertMessage::Math(overflow_err), span);
382 block.and(Rvalue::BinaryOp(op, lhs, rhs))
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 {
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();
404 value: self.hir.tcx().mk_const(ty::Const {
405 val: ConstVal::Value(Value::ByVal(PrimVal::Bytes(val.to_u128_unchecked()))),
411 span_bug!(span, "Invalid type for neg_1_literal: `{:?}`", ty)
415 self.literal_operand(span, ty, literal)
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 {
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,
436 let val = ConstIsize::new(min, int_ty).unwrap();
442 value: self.hir.tcx().mk_const(ty::Const {
443 val: ConstVal::Value(Value::ByVal(PrimVal::Bytes(
444 val.to_u128_unchecked()
451 span_bug!(span, "Invalid type for minval_literal: `{:?}`", ty)
455 self.literal_operand(span, ty, literal)