1 //! See docs in `build/expr/mod.rs`.
3 use rustc_index::vec::Idx;
5 use crate::build::expr::category::{Category, RvalueFunc};
6 use crate::build::{BlockAnd, BlockAndExtension, Builder};
8 use rustc::middle::region;
9 use rustc::mir::interpret::PanicInfo;
11 use rustc::ty::{self, Ty, UpvarSubsts};
14 impl<'a, 'tcx> Builder<'a, 'tcx> {
15 /// Returns an rvalue suitable for use until the end of the current
18 /// The operand returned from this function will *not be valid* after
19 /// an ExprKind::Scope is passed, so please do *not* return it from
20 /// functions to avoid bad miscompiles.
21 pub fn as_local_rvalue<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<Rvalue<'tcx>>
23 M: Mirror<'tcx, Output = Expr<'tcx>>,
25 let local_scope = self.local_scope();
26 self.as_rvalue(block, local_scope, expr)
29 /// Compile `expr`, yielding an rvalue.
33 scope: Option<region::Scope>,
35 ) -> BlockAnd<Rvalue<'tcx>>
37 M: Mirror<'tcx, Output = Expr<'tcx>>,
39 let expr = self.hir.mirror(expr);
40 self.expr_as_rvalue(block, scope, expr)
45 mut block: BasicBlock,
46 scope: Option<region::Scope>,
48 ) -> BlockAnd<Rvalue<'tcx>> {
50 "expr_as_rvalue(block={:?}, scope={:?}, expr={:?})",
55 let expr_span = expr.span;
56 let source_info = this.source_info(expr_span);
64 let region_scope = (region_scope, source_info);
65 this.in_scope(region_scope, lint_level, |this| {
66 this.as_rvalue(block, scope, value)
69 ExprKind::Repeat { value, count } => {
70 let value_operand = unpack!(block = this.as_operand(block, scope, value));
71 block.and(Rvalue::Repeat(value_operand, count))
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, lhs, rhs)
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, expr_span);
91 Rvalue::BinaryOp(BinOp::Eq, arg.to_copy(), minval),
96 Operand::Move(is_min),
98 PanicInfo::OverflowNeg,
102 block.and(Rvalue::UnaryOp(op, arg))
104 ExprKind::Box { value } => {
105 let value = this.hir.mirror(value);
106 // The `Box<T>` temporary created here is not a part of the HIR,
107 // and therefore is not considered during generator OIBIT
108 // determination. See the comment about `box` at `yield_in_scope`.
111 .push(LocalDecl::new_internal(expr.ty, expr_span));
116 kind: StatementKind::StorageLive(result),
119 if let Some(scope) = scope {
120 // schedule a shallow free of that memory, lest we unwind:
121 this.schedule_drop_storage_and_value(
128 // malloc some memory of suitable type (thus far, uninitialized):
129 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
131 .push_assign(block, source_info, &Place::from(result), box_);
133 // initialize the box contents:
136 &this.hir.tcx().mk_place_deref(Place::from(result)),
140 block.and(Rvalue::Use(Operand::Move(Place::from(result))))
142 ExprKind::Cast { source } => {
143 let source = unpack!(block = this.as_operand(block, scope, source));
144 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
146 ExprKind::Pointer { cast, source } => {
147 let source = unpack!(block = this.as_operand(block, scope, source));
148 block.and(Rvalue::Cast(CastKind::Pointer(cast), source, expr.ty))
150 ExprKind::Array { fields } => {
151 // (*) We would (maybe) be closer to codegen if we
152 // handled this and other aggregate cases via
153 // `into()`, not `as_rvalue` -- in that case, instead
158 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
160 // we could just generate
165 // The problem is that then we would need to:
167 // (a) have a more complex mechanism for handling
169 // (b) distinguish the case where the type `Foo` has a
170 // destructor, in which case creating an instance
171 // as a whole "arms" the destructor, and you can't
172 // write individual fields; and,
173 // (c) handle the case where the type Foo has no
174 // fields. We don't want `let x: ();` to compile
175 // to the same MIR as `let x = ();`.
177 // first process the set of fields
178 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
179 let fields: Vec<_> = fields
181 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
184 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
186 ExprKind::Tuple { fields } => {
188 // first process the set of fields
189 let fields: Vec<_> = fields
191 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
194 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
203 let operands: Vec<_> = upvars
206 let upvar = this.hir.mirror(upvar);
207 match Category::of(&upvar.kind) {
208 // Use as_place to avoid creating a temporary when
209 // moving a variable into a closure, so that
210 // borrowck knows which variables to mark as being
211 // used as mut. This is OK here because the upvar
212 // expressions have no side effects and act on
214 // This occurs when capturing by copy/move, while
215 // by reference captures use as_operand
216 Some(Category::Place) => {
217 let place = unpack!(block = this.as_place(block, upvar));
218 this.consume_by_copy_or_move(place)
221 // Turn mutable borrow captures into unique
222 // borrow captures when capturing an immutable
223 // variable. This is sound because the mutation
224 // that caused the capture will cause an error.
229 allow_two_phase_borrow: false,
233 block = this.limit_capture_mutability(
234 upvar.span, upvar.ty, scope, block, arg,
237 _ => unpack!(block = this.as_operand(block, scope, upvar)),
242 let result = match substs {
243 UpvarSubsts::Generator(substs) => {
244 // We implicitly set the discriminant to 0. See
245 // librustc_mir/transform/deaggregator.rs for details.
246 let movability = movability.unwrap();
247 box AggregateKind::Generator(closure_id, substs, movability)
249 UpvarSubsts::Closure(substs) => box AggregateKind::Closure(closure_id, substs),
251 block.and(Rvalue::Aggregate(result, operands))
253 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
254 block = unpack!(this.stmt_expr(block, expr, None));
255 block.and(this.unit_rvalue())
257 ExprKind::Yield { value } => {
258 let value = unpack!(block = this.as_operand(block, scope, value));
259 let resume = this.cfg.start_new_block();
260 let cleanup = this.generator_drop_cleanup();
264 TerminatorKind::Yield {
270 resume.and(this.unit_rvalue())
272 ExprKind::Literal { .. }
273 | ExprKind::StaticRef { .. }
274 | ExprKind::Block { .. }
275 | ExprKind::Match { .. }
276 | ExprKind::NeverToAny { .. }
277 | ExprKind::Use { .. }
278 | ExprKind::Borrow { .. }
279 | ExprKind::Adt { .. }
280 | ExprKind::Loop { .. }
281 | ExprKind::LogicalOp { .. }
282 | ExprKind::Call { .. }
283 | ExprKind::Field { .. }
284 | ExprKind::Deref { .. }
285 | ExprKind::Index { .. }
286 | ExprKind::VarRef { .. }
288 | ExprKind::Break { .. }
289 | ExprKind::Continue { .. }
290 | ExprKind::Return { .. }
291 | ExprKind::InlineAsm { .. }
292 | ExprKind::PlaceTypeAscription { .. }
293 | ExprKind::ValueTypeAscription { .. } => {
294 // these do not have corresponding `Rvalue` variants,
295 // so make an operand and then return that
296 debug_assert!(match Category::of(&expr.kind) {
297 Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
300 let operand = unpack!(block = this.as_operand(block, scope, expr));
301 block.and(Rvalue::Use(operand))
306 pub fn build_binary_op(
308 mut block: BasicBlock,
314 ) -> BlockAnd<Rvalue<'tcx>> {
315 let source_info = self.source_info(span);
316 let bool_ty = self.hir.bool_ty();
317 if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
318 let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
319 let result_value = self.temp(result_tup, span);
321 self.cfg.push_assign(
325 Rvalue::CheckedBinaryOp(op, lhs, rhs),
327 let val_fld = Field::new(0);
328 let of_fld = Field::new(1);
330 let tcx = self.hir.tcx();
331 let val = tcx.mk_place_field(result_value.clone(), val_fld, ty);
332 let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
334 let err = PanicInfo::Overflow(op);
336 block = self.assert(block, Operand::Move(of), false, err, span);
338 block.and(Rvalue::Use(Operand::Move(val)))
340 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
341 // Checking division and remainder is more complex, since we 1. always check
342 // and 2. there are two possible failure cases, divide-by-zero and overflow.
344 let zero_err = if op == BinOp::Div {
345 PanicInfo::DivisionByZero
347 PanicInfo::RemainderByZero
349 let overflow_err = PanicInfo::Overflow(op);
352 let is_zero = self.temp(bool_ty, span);
353 let zero = self.zero_literal(span, ty);
354 self.cfg.push_assign(
358 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero),
361 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
363 // We only need to check for the overflow in one case:
364 // MIN / -1, and only for signed values.
366 let neg_1 = self.neg_1_literal(span, ty);
367 let min = self.minval_literal(span, ty);
369 let is_neg_1 = self.temp(bool_ty, span);
370 let is_min = self.temp(bool_ty, span);
371 let of = self.temp(bool_ty, span);
373 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
375 self.cfg.push_assign(
379 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1),
381 self.cfg.push_assign(
385 Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min),
388 let is_neg_1 = Operand::Move(is_neg_1);
389 let is_min = Operand::Move(is_min);
390 self.cfg.push_assign(
394 Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min),
397 block = self.assert(block, Operand::Move(of), false, overflow_err, span);
401 block.and(Rvalue::BinaryOp(op, lhs, rhs))
405 fn limit_capture_mutability(
409 temp_lifetime: Option<region::Scope>,
410 mut block: BasicBlock,
412 ) -> BlockAnd<Operand<'tcx>> {
415 let source_info = this.source_info(upvar_span);
418 .push(LocalDecl::new_temp(upvar_ty, upvar_span));
424 kind: StatementKind::StorageLive(temp),
428 let arg_place = unpack!(block = this.as_place(block, arg));
430 let mutability = match arg_place.as_ref() {
432 base: &PlaceBase::Local(local),
434 } => this.local_decls[local].mutability,
436 base: &PlaceBase::Local(local),
437 projection: &[ProjectionElem::Deref],
440 this.local_decls[local].is_ref_for_guard(),
441 "Unexpected capture place",
443 this.local_decls[local].mutability
447 projection: &[ref proj_base @ .., ProjectionElem::Field(upvar_index, _)],
453 ProjectionElem::Field(upvar_index, _),
454 ProjectionElem::Deref
457 let place = PlaceRef {
459 projection: proj_base,
462 // Not projected from the implicit `self` in a closure.
464 match place.local_or_deref_local() {
465 Some(local) => local == Local::new(1),
468 "Unexpected capture place"
472 this.upvar_mutbls.len() > upvar_index.index(),
473 "Unexpected capture place"
475 this.upvar_mutbls[upvar_index.index()]
477 _ => bug!("Unexpected capture place"),
480 let borrow_kind = match mutability {
481 Mutability::Not => BorrowKind::Unique,
482 Mutability::Mut => BorrowKind::Mut {
483 allow_two_phase_borrow: false,
487 this.cfg.push_assign(
491 Rvalue::Ref(this.hir.tcx().lifetimes.re_erased, borrow_kind, arg_place),
494 // In constants, temp_lifetime is None. We should not need to drop
495 // anything because no values with a destructor can be created in
496 // a constant at this time, even if the type may need dropping.
497 if let Some(temp_lifetime) = temp_lifetime {
498 this.schedule_drop_storage_and_value(
505 block.and(Operand::Move(Place::from(temp)))
508 // Helper to get a `-1` value of the appropriate type
509 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
510 let param_ty = ty::ParamEnv::empty().and(ty);
511 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
512 let n = (!0u128) >> (128 - bits);
513 let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
515 self.literal_operand(span, literal)
518 // Helper to get the minimum value of the appropriate type
519 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
520 assert!(ty.is_signed());
521 let param_ty = ty::ParamEnv::empty().and(ty);
522 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
523 let n = 1 << (bits - 1);
524 let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
526 self.literal_operand(span, literal)