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
::middle
::region
;
9 use rustc_middle
::mir
::AssertKind
;
10 use rustc_middle
::mir
::*;
11 use rustc_middle
::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 crate 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
>> {
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
::ThreadLocalRef(did
) => block
.and(Rvalue
::ThreadLocalRef(did
)),
57 ExprKind
::Scope { region_scope, lint_level, value }
=> {
58 let region_scope
= (region_scope
, source_info
);
59 this
.in_scope(region_scope
, lint_level
, |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
::Binary { op, lhs, rhs }
=> {
66 let lhs
= unpack
!(block
= this
.as_operand(block
, scope
, lhs
));
67 let rhs
= unpack
!(block
= this
.as_operand(block
, scope
, rhs
));
68 this
.build_binary_op(block
, op
, expr_span
, expr
.ty
, lhs
, rhs
)
70 ExprKind
::Unary { op, arg }
=> {
71 let arg
= unpack
!(block
= this
.as_operand(block
, scope
, arg
));
72 // Check for -MIN on signed integers
73 if this
.hir
.check_overflow() && op
== UnOp
::Neg
&& expr
.ty
.is_signed() {
74 let bool_ty
= this
.hir
.bool_ty();
76 let minval
= this
.minval_literal(expr_span
, expr
.ty
);
77 let is_min
= this
.temp(bool_ty
, expr_span
);
83 Rvalue
::BinaryOp(BinOp
::Eq
, arg
.to_copy(), minval
),
88 Operand
::Move(is_min
),
90 AssertKind
::OverflowNeg(arg
.to_copy()),
94 block
.and(Rvalue
::UnaryOp(op
, arg
))
96 ExprKind
::Box { value }
=> {
97 let value
= this
.hir
.mirror(value
);
98 // The `Box<T>` temporary created here is not a part of the HIR,
99 // and therefore is not considered during generator OIBIT
100 // determination. See the comment about `box` at `yield_in_scope`.
101 let result
= this
.local_decls
.push(LocalDecl
::new(expr
.ty
, expr_span
).internal());
104 Statement { source_info, kind: StatementKind::StorageLive(result) }
,
106 if let Some(scope
) = scope
{
107 // schedule a shallow free of that memory, lest we unwind:
108 this
.schedule_drop_storage_and_value(expr_span
, scope
, result
);
111 // malloc some memory of suitable type (thus far, uninitialized):
112 let box_
= Rvalue
::NullaryOp(NullOp
::Box
, value
.ty
);
113 this
.cfg
.push_assign(block
, source_info
, Place
::from(result
), box_
);
115 // initialize the box contents:
118 this
.into(this
.hir
.tcx().mk_place_deref(Place
::from(result
)), block
, value
)
120 block
.and(Rvalue
::Use(Operand
::Move(Place
::from(result
))))
122 ExprKind
::Cast { source }
=> {
123 let source
= unpack
!(block
= this
.as_operand(block
, scope
, source
));
124 block
.and(Rvalue
::Cast(CastKind
::Misc
, source
, expr
.ty
))
126 ExprKind
::Pointer { cast, source }
=> {
127 let source
= unpack
!(block
= this
.as_operand(block
, scope
, source
));
128 block
.and(Rvalue
::Cast(CastKind
::Pointer(cast
), source
, expr
.ty
))
130 ExprKind
::Array { fields }
=> {
131 // (*) We would (maybe) be closer to codegen if we
132 // handled this and other aggregate cases via
133 // `into()`, not `as_rvalue` -- in that case, instead
138 // dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
140 // we could just generate
145 // The problem is that then we would need to:
147 // (a) have a more complex mechanism for handling
149 // (b) distinguish the case where the type `Foo` has a
150 // destructor, in which case creating an instance
151 // as a whole "arms" the destructor, and you can't
152 // write individual fields; and,
153 // (c) handle the case where the type Foo has no
154 // fields. We don't want `let x: ();` to compile
155 // to the same MIR as `let x = ();`.
157 // first process the set of fields
158 let el_ty
= expr
.ty
.sequence_element_type(this
.hir
.tcx());
159 let fields
: Vec
<_
> = fields
161 .map(|f
| unpack
!(block
= this
.as_operand(block
, scope
, f
)))
164 block
.and(Rvalue
::Aggregate(box AggregateKind
::Array(el_ty
), fields
))
166 ExprKind
::Tuple { fields }
=> {
168 // first process the set of fields
169 let fields
: Vec
<_
> = fields
171 .map(|f
| unpack
!(block
= this
.as_operand(block
, scope
, f
)))
174 block
.and(Rvalue
::Aggregate(box AggregateKind
::Tuple
, fields
))
176 ExprKind
::Closure { closure_id, substs, upvars, movability }
=> {
178 let operands
: Vec
<_
> = upvars
181 let upvar
= this
.hir
.mirror(upvar
);
182 match Category
::of(&upvar
.kind
) {
183 // Use as_place to avoid creating a temporary when
184 // moving a variable into a closure, so that
185 // borrowck knows which variables to mark as being
186 // used as mut. This is OK here because the upvar
187 // expressions have no side effects and act on
189 // This occurs when capturing by copy/move, while
190 // by reference captures use as_operand
191 Some(Category
::Place
) => {
192 let place
= unpack
!(block
= this
.as_place(block
, upvar
));
193 this
.consume_by_copy_or_move(place
)
196 // Turn mutable borrow captures into unique
197 // borrow captures when capturing an immutable
198 // variable. This is sound because the mutation
199 // that caused the capture will cause an error.
203 BorrowKind
::Mut { allow_two_phase_borrow: false }
,
206 block
= this
.limit_capture_mutability(
207 upvar
.span
, upvar
.ty
, scope
, block
, arg
,
210 _
=> unpack
!(block
= this
.as_operand(block
, scope
, upvar
)),
216 let result
= match substs
{
217 UpvarSubsts
::Generator(substs
) => {
218 // We implicitly set the discriminant to 0. See
219 // librustc_mir/transform/deaggregator.rs for details.
220 let movability
= movability
.unwrap();
221 box AggregateKind
::Generator(closure_id
, substs
, movability
)
223 UpvarSubsts
::Closure(substs
) => box AggregateKind
::Closure(closure_id
, substs
),
225 block
.and(Rvalue
::Aggregate(result
, operands
))
227 ExprKind
::Assign { .. }
| ExprKind
::AssignOp { .. }
=> {
228 block
= unpack
!(this
.stmt_expr(block
, expr
, None
));
229 block
.and(Rvalue
::Use(Operand
::Constant(box Constant
{
232 literal
: ty
::Const
::zero_sized(this
.hir
.tcx(), this
.hir
.tcx().types
.unit
),
235 ExprKind
::Yield { .. }
236 | ExprKind
::Literal { .. }
237 | ExprKind
::StaticRef { .. }
238 | ExprKind
::Block { .. }
239 | ExprKind
::Match { .. }
240 | ExprKind
::NeverToAny { .. }
241 | ExprKind
::Use { .. }
242 | ExprKind
::Borrow { .. }
243 | ExprKind
::AddressOf { .. }
244 | ExprKind
::Adt { .. }
245 | ExprKind
::Loop { .. }
246 | ExprKind
::LogicalOp { .. }
247 | ExprKind
::Call { .. }
248 | ExprKind
::Field { .. }
249 | ExprKind
::Deref { .. }
250 | ExprKind
::Index { .. }
251 | ExprKind
::VarRef { .. }
253 | ExprKind
::Break { .. }
254 | ExprKind
::Continue { .. }
255 | ExprKind
::Return { .. }
256 | ExprKind
::InlineAsm { .. }
257 | ExprKind
::LlvmInlineAsm { .. }
258 | ExprKind
::PlaceTypeAscription { .. }
259 | ExprKind
::ValueTypeAscription { .. }
=> {
260 // these do not have corresponding `Rvalue` variants,
261 // so make an operand and then return that
262 debug_assert
!(match Category
::of(&expr
.kind
) {
263 Some(Category
::Rvalue(RvalueFunc
::AsRvalue
)) => false,
266 let operand
= unpack
!(block
= this
.as_operand(block
, scope
, expr
));
267 block
.and(Rvalue
::Use(operand
))
272 crate fn build_binary_op(
274 mut block
: BasicBlock
,
280 ) -> BlockAnd
<Rvalue
<'tcx
>> {
281 let source_info
= self.source_info(span
);
282 let bool_ty
= self.hir
.bool_ty();
283 if self.hir
.check_overflow() && op
.is_checkable() && ty
.is_integral() {
284 let result_tup
= self.hir
.tcx().intern_tup(&[ty
, bool_ty
]);
285 let result_value
= self.temp(result_tup
, span
);
287 self.cfg
.push_assign(
291 Rvalue
::CheckedBinaryOp(op
, lhs
.to_copy(), rhs
.to_copy()),
293 let val_fld
= Field
::new(0);
294 let of_fld
= Field
::new(1);
296 let tcx
= self.hir
.tcx();
297 let val
= tcx
.mk_place_field(result_value
, val_fld
, ty
);
298 let of
= tcx
.mk_place_field(result_value
, of_fld
, bool_ty
);
300 let err
= AssertKind
::Overflow(op
, lhs
, rhs
);
302 block
= self.assert(block
, Operand
::Move(of
), false, err
, span
);
304 block
.and(Rvalue
::Use(Operand
::Move(val
)))
306 if ty
.is_integral() && (op
== BinOp
::Div
|| op
== BinOp
::Rem
) {
307 // Checking division and remainder is more complex, since we 1. always check
308 // and 2. there are two possible failure cases, divide-by-zero and overflow.
310 let zero_err
= if op
== BinOp
::Div
{
311 AssertKind
::DivisionByZero(lhs
.to_copy())
313 AssertKind
::RemainderByZero(lhs
.to_copy())
315 let overflow_err
= AssertKind
::Overflow(op
, lhs
.to_copy(), rhs
.to_copy());
318 let is_zero
= self.temp(bool_ty
, span
);
319 let zero
= self.zero_literal(span
, ty
);
320 self.cfg
.push_assign(
324 Rvalue
::BinaryOp(BinOp
::Eq
, rhs
.to_copy(), zero
),
327 block
= self.assert(block
, Operand
::Move(is_zero
), false, zero_err
, span
);
329 // We only need to check for the overflow in one case:
330 // MIN / -1, and only for signed values.
332 let neg_1
= self.neg_1_literal(span
, ty
);
333 let min
= self.minval_literal(span
, ty
);
335 let is_neg_1
= self.temp(bool_ty
, span
);
336 let is_min
= self.temp(bool_ty
, span
);
337 let of
= self.temp(bool_ty
, span
);
339 // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
341 self.cfg
.push_assign(
345 Rvalue
::BinaryOp(BinOp
::Eq
, rhs
.to_copy(), neg_1
),
347 self.cfg
.push_assign(
351 Rvalue
::BinaryOp(BinOp
::Eq
, lhs
.to_copy(), min
),
354 let is_neg_1
= Operand
::Move(is_neg_1
);
355 let is_min
= Operand
::Move(is_min
);
356 self.cfg
.push_assign(
360 Rvalue
::BinaryOp(BinOp
::BitAnd
, is_neg_1
, is_min
),
363 block
= self.assert(block
, Operand
::Move(of
), false, overflow_err
, span
);
367 block
.and(Rvalue
::BinaryOp(op
, lhs
, rhs
))
371 fn limit_capture_mutability(
375 temp_lifetime
: Option
<region
::Scope
>,
376 mut block
: BasicBlock
,
378 ) -> BlockAnd
<Operand
<'tcx
>> {
381 let source_info
= this
.source_info(upvar_span
);
382 let temp
= this
.local_decls
.push(LocalDecl
::new(upvar_ty
, upvar_span
));
384 this
.cfg
.push(block
, Statement { source_info, kind: StatementKind::StorageLive(temp) }
);
386 let arg_place
= unpack
!(block
= this
.as_place(block
, arg
));
388 let mutability
= match arg_place
.as_ref() {
389 PlaceRef { local, projection: &[] }
=> this
.local_decls
[local
].mutability
,
390 PlaceRef { local, projection: &[ProjectionElem::Deref] }
=> {
392 this
.local_decls
[local
].is_ref_for_guard(),
393 "Unexpected capture place",
395 this
.local_decls
[local
].mutability
399 projection
: &[ref proj_base @
.., ProjectionElem
::Field(upvar_index
, _
)],
404 &[ref proj_base @
.., ProjectionElem
::Field(upvar_index
, _
), ProjectionElem
::Deref
],
406 let place
= PlaceRef { local, projection: proj_base }
;
408 // Not projected from the implicit `self` in a closure.
410 match place
.local_or_deref_local() {
411 Some(local
) => local
== Local
::new(1),
414 "Unexpected capture place"
418 this
.upvar_mutbls
.len() > upvar_index
.index(),
419 "Unexpected capture place"
421 this
.upvar_mutbls
[upvar_index
.index()]
423 _
=> bug
!("Unexpected capture place"),
426 let borrow_kind
= match mutability
{
427 Mutability
::Not
=> BorrowKind
::Unique
,
428 Mutability
::Mut
=> BorrowKind
::Mut { allow_two_phase_borrow: false }
,
431 this
.cfg
.push_assign(
435 Rvalue
::Ref(this
.hir
.tcx().lifetimes
.re_erased
, borrow_kind
, arg_place
),
438 // In constants, temp_lifetime is None. We should not need to drop
439 // anything because no values with a destructor can be created in
440 // a constant at this time, even if the type may need dropping.
441 if let Some(temp_lifetime
) = temp_lifetime
{
442 this
.schedule_drop_storage_and_value(upvar_span
, temp_lifetime
, temp
);
445 block
.and(Operand
::Move(Place
::from(temp
)))
448 // Helper to get a `-1` value of the appropriate type
449 fn neg_1_literal(&mut self, span
: Span
, ty
: Ty
<'tcx
>) -> Operand
<'tcx
> {
450 let param_ty
= ty
::ParamEnv
::empty().and(ty
);
451 let bits
= self.hir
.tcx().layout_of(param_ty
).unwrap().size
.bits();
452 let n
= (!0u128) >> (128 - bits
);
453 let literal
= ty
::Const
::from_bits(self.hir
.tcx(), n
, param_ty
);
455 self.literal_operand(span
, literal
)
458 // Helper to get the minimum value of the appropriate type
459 fn minval_literal(&mut self, span
: Span
, ty
: Ty
<'tcx
>) -> Operand
<'tcx
> {
460 assert
!(ty
.is_signed());
461 let param_ty
= ty
::ParamEnv
::empty().and(ty
);
462 let bits
= self.hir
.tcx().layout_of(param_ty
).unwrap().size
.bits();
463 let n
= 1 << (bits
- 1);
464 let literal
= ty
::Const
::from_bits(self.hir
.tcx(), n
, param_ty
);
466 self.literal_operand(span
, literal
)