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(
26 ) -> BlockAnd<Rvalue<'tcx>> {
27 let local_scope = self.local_scope();
28 self.as_rvalue(block, Some(local_scope), expr)
31 /// Compile `expr`, yielding an rvalue.
34 mut block: BasicBlock,
35 scope: Option<region::Scope>,
37 ) -> BlockAnd<Rvalue<'tcx>> {
38 debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
41 let expr_span = expr.span;
42 let source_info = this.source_info(expr_span);
45 ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(*did)),
46 ExprKind::Scope { region_scope, lint_level, value } => {
47 let region_scope = (*region_scope, source_info);
48 this.in_scope(region_scope, *lint_level, |this| {
49 this.as_rvalue(block, scope, &value)
52 ExprKind::Repeat { value, count } => {
53 let value_operand = unpack!(block = this.as_operand(block, scope, &value));
54 block.and(Rvalue::Repeat(value_operand, count))
56 ExprKind::Binary { op, lhs, rhs } => {
57 let lhs = unpack!(block = this.as_operand(block, scope, &lhs));
58 let rhs = unpack!(block = this.as_operand(block, scope, &rhs));
59 this.build_binary_op(block, *op, expr_span, expr.ty, lhs, rhs)
61 ExprKind::Unary { op, arg } => {
62 let arg = unpack!(block = this.as_operand(block, scope, &arg));
63 // Check for -MIN on signed integers
64 if this.check_overflow && *op == UnOp::Neg && expr.ty.is_signed() {
65 let bool_ty = this.tcx.types.bool;
67 let minval = this.minval_literal(expr_span, expr.ty);
68 let is_min = this.temp(bool_ty, expr_span);
74 Rvalue::BinaryOp(BinOp::Eq, box (arg.to_copy(), minval)),
79 Operand::Move(is_min),
81 AssertKind::OverflowNeg(arg.to_copy()),
85 block.and(Rvalue::UnaryOp(*op, arg))
87 ExprKind::Box { value } => {
88 // The `Box<T>` temporary created here is not a part of the HIR,
89 // and therefore is not considered during generator auto-trait
90 // determination. See the comment about `box` at `yield_in_scope`.
91 let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span).internal());
94 Statement { source_info, kind: StatementKind::StorageLive(result) },
96 if let Some(scope) = scope {
97 // schedule a shallow free of that memory, lest we unwind:
98 this.schedule_drop_storage_and_value(expr_span, scope, result);
101 // malloc some memory of suitable type (thus far, uninitialized):
102 let box_ = Rvalue::NullaryOp(NullOp::Box, value.ty);
103 this.cfg.push_assign(block, source_info, Place::from(result), box_);
105 // initialize the box contents:
107 block = this.expr_into_dest(
108 this.tcx.mk_place_deref(Place::from(result)),
113 block.and(Rvalue::Use(Operand::Move(Place::from(result))))
115 ExprKind::Cast { source } => {
116 let source = unpack!(block = this.as_operand(block, scope, &source));
117 block.and(Rvalue::Cast(CastKind::Misc, source, expr.ty))
119 ExprKind::Pointer { cast, source } => {
120 let source = unpack!(block = this.as_operand(block, scope, &source));
121 block.and(Rvalue::Cast(CastKind::Pointer(*cast), source, expr.ty))
123 ExprKind::Array { fields } => {
124 // (*) We would (maybe) be closer to codegen if we
125 // handled this and other aggregate cases via
126 // `into()`, not `as_rvalue` -- in that case, instead
131 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
133 // we could just generate
138 // The problem is that then we would need to:
140 // (a) have a more complex mechanism for handling
142 // (b) distinguish the case where the type `Foo` has a
143 // destructor, in which case creating an instance
144 // as a whole "arms" the destructor, and you can't
145 // write individual fields; and,
146 // (c) handle the case where the type Foo has no
147 // fields. We don't want `let x: ();` to compile
148 // to the same MIR as `let x = ();`.
150 // first process the set of fields
151 let el_ty = expr.ty.sequence_element_type(this.tcx);
152 let fields: Vec<_> = fields
154 .map(|f| unpack!(block = this.as_operand(block, scope, &f)))
157 block.and(Rvalue::Aggregate(box AggregateKind::Array(el_ty), fields))
159 ExprKind::Tuple { fields } => {
161 // first process the set of fields
162 let fields: Vec<_> = fields
164 .map(|f| unpack!(block = this.as_operand(block, scope, &f)))
167 block.and(Rvalue::Aggregate(box AggregateKind::Tuple, fields))
169 ExprKind::Closure { closure_id, substs, upvars, movability } => {
171 let operands: Vec<_> = upvars
174 match Category::of(&upvar.kind) {
175 // Use as_place to avoid creating a temporary when
176 // moving a variable into a closure, so that
177 // borrowck knows which variables to mark as being
178 // used as mut. This is OK here because the upvar
179 // expressions have no side effects and act on
181 // This occurs when capturing by copy/move, while
182 // by reference captures use as_operand
183 Some(Category::Place) => {
184 let place = unpack!(block = this.as_place(block, &upvar));
185 this.consume_by_copy_or_move(place)
188 // Turn mutable borrow captures into unique
189 // borrow captures when capturing an immutable
190 // variable. This is sound because the mutation
191 // that caused the capture will cause an error.
195 BorrowKind::Mut { allow_two_phase_borrow: false },
198 block = this.limit_capture_mutability(
199 upvar.span, upvar.ty, scope, block, &arg,
202 _ => unpack!(block = this.as_operand(block, scope, &upvar)),
208 let result = match substs {
209 UpvarSubsts::Generator(substs) => {
210 // We implicitly set the discriminant to 0. See
211 // librustc_mir/transform/deaggregator.rs for details.
212 let movability = movability.unwrap();
213 box AggregateKind::Generator(*closure_id, substs, movability)
215 UpvarSubsts::Closure(substs) => box AggregateKind::Closure(*closure_id, substs),
217 block.and(Rvalue::Aggregate(result, operands))
219 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
220 block = unpack!(this.stmt_expr(block, expr, None));
221 block.and(Rvalue::Use(Operand::Constant(box Constant {
224 literal: ty::Const::zero_sized(this.tcx, this.tcx.types.unit),
227 ExprKind::Yield { .. }
228 | ExprKind::Literal { .. }
229 | ExprKind::ConstBlock { .. }
230 | ExprKind::StaticRef { .. }
231 | ExprKind::Block { .. }
232 | ExprKind::Match { .. }
233 | ExprKind::If { .. }
234 | ExprKind::NeverToAny { .. }
235 | ExprKind::Use { .. }
236 | ExprKind::Borrow { .. }
237 | ExprKind::AddressOf { .. }
238 | ExprKind::Adt { .. }
239 | ExprKind::Loop { .. }
240 | ExprKind::LogicalOp { .. }
241 | ExprKind::Call { .. }
242 | ExprKind::Field { .. }
243 | ExprKind::Deref { .. }
244 | ExprKind::Index { .. }
245 | ExprKind::VarRef { .. }
246 | ExprKind::UpvarRef { .. }
247 | ExprKind::Break { .. }
248 | ExprKind::Continue { .. }
249 | ExprKind::Return { .. }
250 | ExprKind::InlineAsm { .. }
251 | ExprKind::LlvmInlineAsm { .. }
252 | ExprKind::PlaceTypeAscription { .. }
253 | ExprKind::ValueTypeAscription { .. } => {
254 // these do not have corresponding `Rvalue` variants,
255 // so make an operand and then return that
256 debug_assert!(!matches!(
257 Category::of(&expr.kind),
258 Some(Category::Rvalue(RvalueFunc::AsRvalue))
260 let operand = unpack!(block = this.as_operand(block, scope, expr));
261 block.and(Rvalue::Use(operand))
266 crate fn build_binary_op(
268 mut block: BasicBlock,
274 ) -> BlockAnd<Rvalue<'tcx>> {
275 let source_info = self.source_info(span);
276 let bool_ty = self.tcx.types.bool;
277 if self.check_overflow && op.is_checkable() && ty.is_integral() {
278 let result_tup = self.tcx.intern_tup(&[ty, bool_ty]);
279 let result_value = self.temp(result_tup, span);
281 self.cfg.push_assign(
285 Rvalue::CheckedBinaryOp(op, box (lhs.to_copy(), rhs.to_copy())),
287 let val_fld = Field::new(0);
288 let of_fld = Field::new(1);
291 let val = tcx.mk_place_field(result_value, val_fld, ty);
292 let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
294 let err = AssertKind::Overflow(op, lhs, rhs);
296 block = self.assert(block, Operand::Move(of), false, err, span);
298 block.and(Rvalue::Use(Operand::Move(val)))
300 if ty.is_integral() && (op == BinOp::Div || op == BinOp::Rem) {
301 // Checking division and remainder is more complex, since we 1. always check
302 // and 2. there are two possible failure cases, divide-by-zero and overflow.
304 let zero_err = if op == BinOp::Div {
305 AssertKind::DivisionByZero(lhs.to_copy())
307 AssertKind::RemainderByZero(lhs.to_copy())
309 let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
312 let is_zero = self.temp(bool_ty, span);
313 let zero = self.zero_literal(span, ty);
314 self.cfg.push_assign(
318 Rvalue::BinaryOp(BinOp::Eq, box (rhs.to_copy(), zero)),
321 block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
323 // We only need to check for the overflow in one case:
324 // MIN / -1, and only for signed values.
326 let neg_1 = self.neg_1_literal(span, ty);
327 let min = self.minval_literal(span, ty);
329 let is_neg_1 = self.temp(bool_ty, span);
330 let is_min = self.temp(bool_ty, span);
331 let of = self.temp(bool_ty, span);
333 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
335 self.cfg.push_assign(
339 Rvalue::BinaryOp(BinOp::Eq, box (rhs.to_copy(), neg_1)),
341 self.cfg.push_assign(
345 Rvalue::BinaryOp(BinOp::Eq, box (lhs.to_copy(), min)),
348 let is_neg_1 = Operand::Move(is_neg_1);
349 let is_min = Operand::Move(is_min);
350 self.cfg.push_assign(
354 Rvalue::BinaryOp(BinOp::BitAnd, box (is_neg_1, is_min)),
357 block = self.assert(block, Operand::Move(of), false, overflow_err, span);
361 block.and(Rvalue::BinaryOp(op, box (lhs, rhs)))
365 fn limit_capture_mutability(
369 temp_lifetime: Option<region::Scope>,
370 mut block: BasicBlock,
372 ) -> BlockAnd<Operand<'tcx>> {
375 let source_info = this.source_info(upvar_span);
376 let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
378 this.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(temp) });
380 let arg_place_builder = unpack!(block = this.as_place_builder(block, arg));
382 let mutability = match arg_place_builder.base() {
383 // We are capturing a path that starts off a local variable in the parent.
384 // The mutability of the current capture is same as the mutability
385 // of the local declaration in the parent.
386 PlaceBase::Local(local) => this.local_decls[local].mutability,
387 // Parent is a closure and we are capturing a path that is captured
388 // by the parent itself. The mutability of the current capture
389 // is same as that of the capture in the parent closure.
390 PlaceBase::Upvar { .. } => {
391 let enclosing_upvars_resolved =
392 arg_place_builder.clone().into_place(this.tcx, this.typeck_results);
394 match enclosing_upvars_resolved.as_ref() {
397 projection: &[ProjectionElem::Field(upvar_index, _), ..],
402 &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
406 local == Local::new(1),
407 "Expected local to be Local(1), found {:?}",
412 this.upvar_mutbls.len() > upvar_index.index(),
413 "Unexpected capture place, upvar_mutbls={:#?}, upvar_index={:?}",
417 this.upvar_mutbls[upvar_index.index()]
419 _ => bug!("Unexpected capture place"),
424 let borrow_kind = match mutability {
425 Mutability::Not => BorrowKind::Unique,
426 Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
429 let arg_place = arg_place_builder.into_place(this.tcx, this.typeck_results);
431 this.cfg.push_assign(
435 Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place),
438 // See the comment in `expr_as_temp` and on the `rvalue_scopes` field for why
439 // this can be `None`.
440 if let Some(temp_lifetime) = temp_lifetime {
441 this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
444 block.and(Operand::Move(Place::from(temp)))
447 // Helper to get a `-1` value of the appropriate type
448 fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
449 let param_ty = ty::ParamEnv::empty().and(ty);
450 let bits = self.tcx.layout_of(param_ty).unwrap().size.bits();
451 let n = (!0u128) >> (128 - bits);
452 let literal = ty::Const::from_bits(self.tcx, n, param_ty);
454 self.literal_operand(span, literal)
457 // Helper to get the minimum value of the appropriate type
458 fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
459 assert!(ty.is_signed());
460 let param_ty = ty::ParamEnv::empty().and(ty);
461 let bits = self.tcx.layout_of(param_ty).unwrap().size.bits();
462 let n = 1 << (bits - 1);
463 let literal = ty::Const::from_bits(self.tcx, n, param_ty);
465 self.literal_operand(span, literal)