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
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_data_structures::indexed_vec::Idx;
16 use build::{BlockAnd, BlockAndExtension, Builder};
17 use build::expr::category::{Category, RvalueFunc};
19 use rustc::middle::region;
20 use rustc::ty::{self, Ty, UpvarSubsts};
22 use rustc::mir::interpret::EvalErrorKind;
25 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
26 /// See comment on `as_local_operand`
27 pub fn as_local_rvalue<M>(&mut self, block: BasicBlock, expr: M)
28 -> BlockAnd<Rvalue<'tcx>>
29 where M: Mirror<'tcx, Output = Expr<'tcx>>
31 let local_scope = self.local_scope();
32 self.as_rvalue(block, local_scope, expr)
35 /// Compile `expr`, yielding an rvalue.
36 pub fn as_rvalue<M>(&mut self, block: BasicBlock, scope: Option<region::Scope>, expr: M)
37 -> BlockAnd<Rvalue<'tcx>>
38 where M: Mirror<'tcx, Output = Expr<'tcx>>
40 let expr = self.hir.mirror(expr);
41 self.expr_as_rvalue(block, scope, expr)
44 fn expr_as_rvalue(&mut self,
45 mut block: BasicBlock,
46 scope: Option<region::Scope>,
48 -> BlockAnd<Rvalue<'tcx>> {
49 debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
52 let expr_span = expr.span;
53 let source_info = this.source_info(expr_span);
56 ExprKind::Scope { region_scope, lint_level, value } => {
57 let region_scope = (region_scope, source_info);
58 this.in_scope(region_scope, lint_level, block,
59 |this| this.as_rvalue(block, scope, value))
61 ExprKind::Repeat { value, count } => {
62 let value_operand = unpack!(block = this.as_operand(block, scope, value));
63 block.and(Rvalue::Repeat(value_operand, count))
65 ExprKind::Borrow { region, borrow_kind, arg } => {
66 let arg_place = unpack!(block = this.as_place(block, arg));
67 block.and(Rvalue::Ref(region, borrow_kind, arg_place))
69 ExprKind::Binary { op, lhs, rhs } => {
70 let lhs = unpack!(block = this.as_operand(block, scope, lhs));
71 let rhs = unpack!(block = this.as_operand(block, scope, rhs));
72 this.build_binary_op(block, op, expr_span, expr.ty,
75 ExprKind::Unary { op, arg } => {
76 let arg = unpack!(block = this.as_operand(block, scope, arg));
77 // Check for -MIN on signed integers
78 if this.hir.check_overflow() && op == UnOp::Neg && expr.ty.is_signed() {
79 let bool_ty = this.hir.bool_ty();
81 let minval = this.minval_literal(expr_span, expr.ty);
82 let is_min = this.temp(bool_ty, expr_span);
84 this.cfg.push_assign(block, source_info, &is_min,
85 Rvalue::BinaryOp(BinOp::Eq, arg.to_copy(), minval));
87 block = this.assert(block, Operand::Move(is_min), false,
88 EvalErrorKind::OverflowNeg, expr_span);
90 block.and(Rvalue::UnaryOp(op, arg))
92 ExprKind::Box { value } => {
93 let value = this.hir.mirror(value);
94 // The `Box<T>` temporary created here is not a part of the HIR,
95 // and therefore is not considered during generator OIBIT
96 // determination. See the comment about `box` at `yield_in_scope`.
97 let result = this.local_decls.push(
98 LocalDecl::new_internal(expr.ty, expr_span));
99 this.cfg.push(block, Statement {
101 kind: StatementKind::StorageLive(result)
103 if let Some(scope) = scope {
104 // schedule a shallow free of that memory, lest we unwind:
105 this.schedule_drop_storage_and_value(
106 expr_span, scope, &Place::Local(result), value.ty,
110 // malloc some memory of suitable type (thus far, uninitialized):
111 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
112 this.cfg.push_assign(block, source_info, &Place::Local(result), box_);
114 // initialize the box contents:
115 unpack!(block = this.into(&Place::Local(result).deref(), block, value));
116 block.and(Rvalue::Use(Operand::Move(Place::Local(result))))
118 ExprKind::Cast { source } => {
119 let source = this.hir.mirror(source);
121 let source = unpack!(block = this.as_operand(block, scope, source));
122 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
124 ExprKind::Use { source } => {
125 let source = unpack!(block = this.as_operand(block, scope, source));
126 block.and(Rvalue::Use(source))
128 ExprKind::ReifyFnPointer { source } => {
129 let source = unpack!(block = this.as_operand(block, scope, source));
130 block.and(Rvalue::Cast(CastKind::ReifyFnPointer, source, expr.ty))
132 ExprKind::UnsafeFnPointer { source } => {
133 let source = unpack!(block = this.as_operand(block, scope, source));
134 block.and(Rvalue::Cast(CastKind::UnsafeFnPointer, source, expr.ty))
136 ExprKind::ClosureFnPointer { source } => {
137 let source = unpack!(block = this.as_operand(block, scope, source));
138 block.and(Rvalue::Cast(CastKind::ClosureFnPointer, source, expr.ty))
140 ExprKind::Unsize { source } => {
141 let source = unpack!(block = this.as_operand(block, scope, source));
142 block.and(Rvalue::Cast(CastKind::Unsize, source, expr.ty))
144 ExprKind::Array { fields } => {
145 // (*) We would (maybe) be closer to codegen if we
146 // handled this and other aggregate cases via
147 // `into()`, not `as_rvalue` -- in that case, instead
152 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
154 // we could just generate
159 // The problem is that then we would need to:
161 // (a) have a more complex mechanism for handling
163 // (b) distinguish the case where the type `Foo` has a
164 // destructor, in which case creating an instance
165 // as a whole "arms" the destructor, and you can't
166 // write individual fields; and,
167 // (c) handle the case where the type Foo has no
168 // fields. We don't want `let x: ();` to compile
169 // to the same MIR as `let x = ();`.
171 // first process the set of fields
172 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
175 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
178 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
180 ExprKind::Tuple { fields } => { // see (*) above
181 // first process the set of fields
184 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
187 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
189 ExprKind::Closure { closure_id, substs, upvars, movability } => {
191 let mut operands: Vec<_> = upvars
194 let upvar = this.hir.mirror(upvar);
195 match Category::of(&upvar.kind) {
196 // Use as_place to avoid creating a temporary when
197 // moving a variable into a closure, so that
198 // borrowck knows which variables to mark as being
199 // used as mut. This is OK here because the upvar
200 // expressions have no side effects and act on
202 // This occurs when capturing by copy/move, while
203 // by reference captures use as_operand
204 Some(Category::Place) => {
205 let place = unpack!(block = this.as_place(block, upvar));
206 this.consume_by_copy_or_move(place)
209 unpack!(block = this.as_operand(block, scope, upvar))
214 let result = match substs {
215 UpvarSubsts::Generator(substs) => {
216 let movability = movability.unwrap();
217 // Add the state operand since it follows the upvars in the generator
218 // struct. See librustc_mir/transform/generator.rs for more details.
219 operands.push(Operand::Constant(box Constant {
221 ty: this.hir.tcx().types.u32,
222 literal: Literal::Value {
223 value: ty::Const::from_bits(
226 ty::ParamEnv::empty().and(this.hir.tcx().types.u32)),
229 box AggregateKind::Generator(closure_id, substs, movability)
231 UpvarSubsts::Closure(substs) => {
232 box AggregateKind::Closure(closure_id, substs)
235 block.and(Rvalue::Aggregate(result, operands))
238 adt_def, variant_index, substs, fields, base
239 } => { // see (*) above
240 let is_union = adt_def.is_union();
241 let active_field_index = if is_union { Some(fields[0].name.index()) } else { None };
243 // first process the set of fields that were provided
244 // (evaluating them in order given by user)
245 let fields_map: FxHashMap<_, _> = fields.into_iter()
246 .map(|f| (f.name, unpack!(block = this.as_operand(block, scope, f.expr))))
249 let field_names = this.hir.all_fields(adt_def, variant_index);
251 let fields = if let Some(FruInfo { base, field_types }) = base {
252 let base = unpack!(block = this.as_place(block, base));
254 // MIR does not natively support FRU, so for each
255 // base-supplied field, generate an operand that
256 // reads it from the base.
257 field_names.into_iter()
258 .zip(field_types.into_iter())
259 .map(|(n, ty)| match fields_map.get(&n) {
260 Some(v) => v.clone(),
261 None => this.consume_by_copy_or_move(base.clone().field(n, ty))
265 field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
269 box AggregateKind::Adt(adt_def, variant_index, substs, active_field_index);
270 block.and(Rvalue::Aggregate(adt, fields))
272 ExprKind::Assign { .. } |
273 ExprKind::AssignOp { .. } => {
274 block = unpack!(this.stmt_expr(block, expr));
275 block.and(this.unit_rvalue())
277 ExprKind::Yield { value } => {
278 let value = unpack!(block = this.as_operand(block, scope, value));
279 let resume = this.cfg.start_new_block();
280 let cleanup = this.generator_drop_cleanup();
281 this.cfg.terminate(block, source_info, TerminatorKind::Yield {
286 resume.and(this.unit_rvalue())
288 ExprKind::Literal { .. } |
289 ExprKind::Block { .. } |
290 ExprKind::Match { .. } |
291 ExprKind::If { .. } |
292 ExprKind::NeverToAny { .. } |
293 ExprKind::Loop { .. } |
294 ExprKind::LogicalOp { .. } |
295 ExprKind::Call { .. } |
296 ExprKind::Field { .. } |
297 ExprKind::Deref { .. } |
298 ExprKind::Index { .. } |
299 ExprKind::VarRef { .. } |
301 ExprKind::Break { .. } |
302 ExprKind::Continue { .. } |
303 ExprKind::Return { .. } |
304 ExprKind::InlineAsm { .. } |
305 ExprKind::StaticRef { .. } => {
306 // these do not have corresponding `Rvalue` variants,
307 // so make an operand and then return that
308 debug_assert!(match Category::of(&expr.kind) {
309 Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
312 let operand = unpack!(block = this.as_operand(block, scope, expr));
313 block.and(Rvalue::Use(operand))
318 pub fn build_binary_op(&mut self, mut block: BasicBlock,
319 op: BinOp, span: Span, ty: Ty<'tcx>,
320 lhs: Operand<'tcx>, rhs: Operand<'tcx>) -> BlockAnd<Rvalue<'tcx>> {
321 let source_info = self.source_info(span);
322 let bool_ty = self.hir.bool_ty();
323 if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
324 let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
325 let result_value = self.temp(result_tup, span);
327 self.cfg.push_assign(block, source_info,
328 &result_value, Rvalue::CheckedBinaryOp(op,
331 let val_fld = Field::new(0);
332 let of_fld = Field::new(1);
334 let val = result_value.clone().field(val_fld, ty);
335 let of = result_value.field(of_fld, bool_ty);
337 let err = EvalErrorKind::Overflow(op);
339 block = self.assert(block, Operand::Move(of), false,
342 block.and(Rvalue::Use(Operand::Move(val)))
344 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
345 // Checking division and remainder is more complex, since we 1. always check
346 // and 2. there are two possible failure cases, divide-by-zero and overflow.
348 let (zero_err, overflow_err) = if op == BinOp::Div {
349 (EvalErrorKind::DivisionByZero,
350 EvalErrorKind::Overflow(op))
352 (EvalErrorKind::RemainderByZero,
353 EvalErrorKind::Overflow(op))
357 let is_zero = self.temp(bool_ty, span);
358 let zero = self.zero_literal(span, ty);
359 self.cfg.push_assign(block, source_info, &is_zero,
360 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero));
362 block = self.assert(block, Operand::Move(is_zero), false,
365 // We only need to check for the overflow in one case:
366 // MIN / -1, and only for signed values.
368 let neg_1 = self.neg_1_literal(span, ty);
369 let min = self.minval_literal(span, ty);
371 let is_neg_1 = self.temp(bool_ty, span);
372 let is_min = self.temp(bool_ty, span);
373 let of = self.temp(bool_ty, span);
375 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
377 self.cfg.push_assign(block, source_info, &is_neg_1,
378 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1));
379 self.cfg.push_assign(block, source_info, &is_min,
380 Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min));
382 let is_neg_1 = Operand::Move(is_neg_1);
383 let is_min = Operand::Move(is_min);
384 self.cfg.push_assign(block, source_info, &of,
385 Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min));
387 block = self.assert(block, Operand::Move(of), false,
392 block.and(Rvalue::BinaryOp(op, lhs, rhs))
396 // Helper to get a `-1` value of the appropriate type
397 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
398 let param_ty = ty::ParamEnv::empty().and(self.hir.tcx().lift_to_global(&ty).unwrap());
399 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
400 let n = (!0u128) >> (128 - bits);
401 let literal = Literal::Value {
402 value: ty::Const::from_bits(self.hir.tcx(), n, param_ty)
405 self.literal_operand(span, ty, literal)
408 // Helper to get the minimum value of the appropriate type
409 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
410 assert!(ty.is_signed());
411 let param_ty = ty::ParamEnv::empty().and(self.hir.tcx().lift_to_global(&ty).unwrap());
412 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
413 let n = 1 << (bits - 1);
414 let literal = Literal::Value {
415 value: ty::Const::from_bits(self.hir.tcx(), n, param_ty)
418 self.literal_operand(span, ty, literal)