1 //! See docs in `build/expr/mod.rs`.
3 use rustc_index::vec::Idx;
5 use crate::build::expr::as_place::PlaceBase;
6 use crate::build::expr::category::{Category, RvalueFunc};
7 use crate::build::{BlockAnd, BlockAndExtension, Builder};
9 use rustc_middle::middle::region;
10 use rustc_middle::mir::AssertKind;
11 use rustc_middle::mir::*;
12 use rustc_middle::ty::{self, Ty, UpvarSubsts};
15 impl<'a, 'tcx> Builder<'a, 'tcx> {
16 /// Returns an rvalue suitable for use until the end of the current
19 /// The operand returned from this function will *not be valid* after
20 /// an ExprKind::Scope is passed, so please do *not* return it from
21 /// functions to avoid bad miscompiles.
22 crate fn as_local_rvalue<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<Rvalue<'tcx>>
24 M: Mirror<'tcx, Output = Expr<'tcx>>,
26 let local_scope = self.local_scope();
27 self.as_rvalue(block, Some(local_scope), expr)
30 /// Compile `expr`, yielding an rvalue.
34 scope: Option<region::Scope>,
36 ) -> BlockAnd<Rvalue<'tcx>>
38 M: Mirror<'tcx, Output = Expr<'tcx>>,
40 let expr = self.hir.mirror(expr);
41 self.expr_as_rvalue(block, scope, expr)
46 mut block: BasicBlock,
47 scope: Option<region::Scope>,
49 ) -> BlockAnd<Rvalue<'tcx>> {
50 debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
53 let expr_span = expr.span;
54 let source_info = this.source_info(expr_span);
57 ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(did)),
58 ExprKind::Scope { region_scope, lint_level, value } => {
59 let region_scope = (region_scope, source_info);
60 this.in_scope(region_scope, lint_level, |this| this.as_rvalue(block, scope, value))
62 ExprKind::Repeat { value, count } => {
63 let value_operand = unpack!(block = this.as_operand(block, scope, value));
64 block.and(Rvalue::Repeat(value_operand, count))
66 ExprKind::Binary { op, lhs, rhs } => {
67 let lhs = unpack!(block = this.as_operand(block, scope, lhs));
68 let rhs = unpack!(block = this.as_operand(block, scope, rhs));
69 this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
71 ExprKind::Unary { op, arg } => {
72 let arg = unpack!(block = this.as_operand(block, scope, arg));
73 // Check for -MIN on signed integers
74 if this.hir.check_overflow() && op == UnOp::Neg && expr.ty.is_signed() {
75 let bool_ty = this.hir.bool_ty();
77 let minval = this.minval_literal(expr_span, expr.ty);
78 let is_min = this.temp(bool_ty, expr_span);
84 Rvalue::BinaryOp(BinOp::Eq, arg.to_copy(), minval),
89 Operand::Move(is_min),
91 AssertKind::OverflowNeg(arg.to_copy()),
95 block.and(Rvalue::UnaryOp(op, arg))
97 ExprKind::Box { value } => {
98 let value = this.hir.mirror(value);
99 // The `Box<T>` temporary created here is not a part of the HIR,
100 // and therefore is not considered during generator auto-trait
101 // determination. See the comment about `box` at `yield_in_scope`.
102 let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span).internal());
105 Statement { source_info, kind: StatementKind::StorageLive(result) },
107 if let Some(scope) = scope {
108 // schedule a shallow free of that memory, lest we unwind:
109 this.schedule_drop_storage_and_value(expr_span, scope, result);
112 // malloc some memory of suitable type (thus far, uninitialized):
113 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
114 this.cfg.push_assign(block, source_info, Place::from(result), box_);
116 // initialize the box contents:
119 this.into(this.hir.tcx().mk_place_deref(Place::from(result)), block, value)
121 block.and(Rvalue::Use(Operand::Move(Place::from(result))))
123 ExprKind::Cast { source } => {
124 let source = unpack!(block = this.as_operand(block, scope, source));
125 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
127 ExprKind::Pointer { cast, source } => {
128 let source = unpack!(block = this.as_operand(block, scope, source));
129 block.and(Rvalue::Cast(CastKind::Pointer(cast), source, expr.ty))
131 ExprKind::Array { fields } => {
132 // (*) We would (maybe) be closer to codegen if we
133 // handled this and other aggregate cases via
134 // `into()`, not `as_rvalue` -- in that case, instead
139 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
141 // we could just generate
146 // The problem is that then we would need to:
148 // (a) have a more complex mechanism for handling
150 // (b) distinguish the case where the type `Foo` has a
151 // destructor, in which case creating an instance
152 // as a whole "arms" the destructor, and you can't
153 // write individual fields; and,
154 // (c) handle the case where the type Foo has no
155 // fields. We don't want `let x: ();` to compile
156 // to the same MIR as `let x = ();`.
158 // first process the set of fields
159 let el_ty = expr.ty.sequence_element_type(this.hir.tcx());
160 let fields: Vec<_> = fields
162 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
165 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
167 ExprKind::Tuple { fields } => {
169 // first process the set of fields
170 let fields: Vec<_> = fields
172 .map(|f| unpack!(block = this.as_operand(block, scope, f)))
175 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
177 ExprKind::Closure { closure_id, substs, upvars, movability } => {
179 let operands: Vec<_> = upvars
182 let upvar = this.hir.mirror(upvar);
183 match Category::of(&upvar.kind) {
184 // Use as_place to avoid creating a temporary when
185 // moving a variable into a closure, so that
186 // borrowck knows which variables to mark as being
187 // used as mut. This is OK here because the upvar
188 // expressions have no side effects and act on
190 // This occurs when capturing by copy/move, while
191 // by reference captures use as_operand
192 Some(Category::Place) => {
193 let place = unpack!(block = this.as_place(block, upvar));
194 this.consume_by_copy_or_move(place)
197 // Turn mutable borrow captures into unique
198 // borrow captures when capturing an immutable
199 // variable. This is sound because the mutation
200 // that caused the capture will cause an error.
204 BorrowKind::Mut { allow_two_phase_borrow: false },
207 block = this.limit_capture_mutability(
208 upvar.span, upvar.ty, scope, block, arg,
211 _ => unpack!(block = this.as_operand(block, scope, upvar)),
217 let result = match substs {
218 UpvarSubsts::Generator(substs) => {
219 // We implicitly set the discriminant to 0. See
220 // librustc_mir/transform/deaggregator.rs for details.
221 let movability = movability.unwrap();
222 box AggregateKind::Generator(closure_id, substs, movability)
224 UpvarSubsts::Closure(substs) => box AggregateKind::Closure(closure_id, substs),
226 block.and(Rvalue::Aggregate(result, operands))
228 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
229 block = unpack!(this.stmt_expr(block, expr, None));
230 block.and(Rvalue::Use(Operand::Constant(box Constant {
233 literal: ty::Const::zero_sized(this.hir.tcx(), this.hir.tcx().types.unit),
236 ExprKind::Yield { .. }
237 | ExprKind::Literal { .. }
238 | ExprKind::ConstBlock { .. }
239 | ExprKind::StaticRef { .. }
240 | ExprKind::Block { .. }
241 | ExprKind::Match { .. }
242 | ExprKind::If { .. }
243 | ExprKind::NeverToAny { .. }
244 | ExprKind::Use { .. }
245 | ExprKind::Borrow { .. }
246 | ExprKind::AddressOf { .. }
247 | ExprKind::Adt { .. }
248 | ExprKind::Loop { .. }
249 | ExprKind::LogicalOp { .. }
250 | ExprKind::Call { .. }
251 | ExprKind::Field { .. }
252 | ExprKind::Deref { .. }
253 | ExprKind::Index { .. }
254 | ExprKind::VarRef { .. }
255 | ExprKind::UpvarRef { .. }
256 | ExprKind::Break { .. }
257 | ExprKind::Continue { .. }
258 | ExprKind::Return { .. }
259 | ExprKind::InlineAsm { .. }
260 | ExprKind::LlvmInlineAsm { .. }
261 | ExprKind::PlaceTypeAscription { .. }
262 | ExprKind::ValueTypeAscription { .. } => {
263 // these do not have corresponding `Rvalue` variants,
264 // so make an operand and then return that
265 debug_assert!(!matches!(
266 Category::of(&expr.kind),
267 Some(Category::Rvalue(RvalueFunc::AsRvalue))
269 let operand = unpack!(block = this.as_operand(block, scope, expr));
270 block.and(Rvalue::Use(operand))
275 crate fn build_binary_op(
277 mut block: BasicBlock,
283 ) -> BlockAnd<Rvalue<'tcx>> {
284 let source_info = self.source_info(span);
285 let bool_ty = self.hir.bool_ty();
286 if self.hir.check_overflow() && op.is_checkable() && ty.is_integral() {
287 let result_tup = self.hir.tcx().intern_tup(&[ty, bool_ty]);
288 let result_value = self.temp(result_tup, span);
290 self.cfg.push_assign(
294 Rvalue::CheckedBinaryOp(op, lhs.to_copy(), rhs.to_copy()),
296 let val_fld = Field::new(0);
297 let of_fld = Field::new(1);
299 let tcx = self.hir.tcx();
300 let val = tcx.mk_place_field(result_value, val_fld, ty);
301 let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
303 let err = AssertKind::Overflow(op, lhs, rhs);
305 block = self.assert(block, Operand::Move(of), false, err, span);
307 block.and(Rvalue::Use(Operand::Move(val)))
309 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
310 // Checking division and remainder is more complex, since we 1. always check
311 // and 2. there are two possible failure cases, divide-by-zero and overflow.
313 let zero_err = if op == BinOp::Div {
314 AssertKind::DivisionByZero(lhs.to_copy())
316 AssertKind::RemainderByZero(lhs.to_copy())
318 let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
321 let is_zero = self.temp(bool_ty, span);
322 let zero = self.zero_literal(span, ty);
323 self.cfg.push_assign(
327 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), zero),
330 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
332 // We only need to check for the overflow in one case:
333 // MIN / -1, and only for signed values.
335 let neg_1 = self.neg_1_literal(span, ty);
336 let min = self.minval_literal(span, ty);
338 let is_neg_1 = self.temp(bool_ty, span);
339 let is_min = self.temp(bool_ty, span);
340 let of = self.temp(bool_ty, span);
342 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
344 self.cfg.push_assign(
348 Rvalue::BinaryOp(BinOp::Eq, rhs.to_copy(), neg_1),
350 self.cfg.push_assign(
354 Rvalue::BinaryOp(BinOp::Eq, lhs.to_copy(), min),
357 let is_neg_1 = Operand::Move(is_neg_1);
358 let is_min = Operand::Move(is_min);
359 self.cfg.push_assign(
363 Rvalue::BinaryOp(BinOp::BitAnd, is_neg_1, is_min),
366 block = self.assert(block, Operand::Move(of), false, overflow_err, span);
370 block.and(Rvalue::BinaryOp(op, lhs, rhs))
374 fn limit_capture_mutability(
378 temp_lifetime: Option<region::Scope>,
379 mut block: BasicBlock,
381 ) -> BlockAnd<Operand<'tcx>> {
384 let source_info = this.source_info(upvar_span);
385 let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
387 this.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(temp) });
389 let arg_place_builder = unpack!(block = this.as_place_builder(block, arg));
391 let mutability = match arg_place_builder.base() {
392 // We are capturing a path that starts off a local variable in the parent.
393 // The mutability of the current capture is same as the mutability
394 // of the local declaration in the parent.
395 PlaceBase::Local(local) => this.local_decls[local].mutability,
396 // Parent is a closure and we are capturing a path that is captured
397 // by the parent itself. The mutability of the current capture
398 // is same as that of the capture in the parent closure.
399 PlaceBase::Upvar { .. } => {
400 let enclosing_upvars_resolved =
401 arg_place_builder.clone().into_place(this.hir.tcx(), this.hir.typeck_results());
403 match enclosing_upvars_resolved.as_ref() {
406 projection: &[ProjectionElem::Field(upvar_index, _), ..],
411 &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
415 local == Local::new(1),
416 "Expected local to be Local(1), found {:?}",
421 this.upvar_mutbls.len() > upvar_index.index(),
422 "Unexpected capture place, upvar_mutbls={:#?}, upvar_index={:?}",
426 this.upvar_mutbls[upvar_index.index()]
428 _ => bug!("Unexpected capture place"),
433 let borrow_kind = match mutability {
434 Mutability::Not => BorrowKind::Unique,
435 Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
438 let arg_place = arg_place_builder.into_place(this.hir.tcx(), this.hir.typeck_results());
440 this.cfg.push_assign(
444 Rvalue::Ref(this.hir.tcx().lifetimes.re_erased, borrow_kind, arg_place),
447 // See the comment in `expr_as_temp` and on the `rvalue_scopes` field for why
448 // this can be `None`.
449 if let Some(temp_lifetime) = temp_lifetime {
450 this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
453 block.and(Operand::Move(Place::from(temp)))
456 // Helper to get a `-1` value of the appropriate type
457 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
458 let param_ty = ty::ParamEnv::empty().and(ty);
459 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
460 let n = (!0u128) >> (128 - bits);
461 let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
463 self.literal_operand(span, literal)
466 // Helper to get the minimum value of the appropriate type
467 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
468 assert!(ty.is_signed());
469 let param_ty = ty::ParamEnv::empty().and(ty);
470 let bits = self.hir.tcx().layout_of(param_ty).unwrap().size.bits();
471 let n = 1 << (bits - 1);
472 let literal = ty::Const::from_bits(self.hir.tcx(), n, param_ty);
474 self.literal_operand(span, literal)