Skip to main content

rustc_mir_build/builder/expr/
as_rvalue.rs

1//! See docs in `build/expr/mod.rs`.
2
3use rustc_abi::FieldIdx;
4use rustc_index::{Idx, IndexVec};
5use rustc_middle::bug;
6use rustc_middle::middle::region::{self, TempLifetime};
7use rustc_middle::mir::interpret::Scalar;
8use rustc_middle::mir::*;
9use rustc_middle::thir::*;
10use rustc_middle::ty::adjustment::PointerCoercion;
11use rustc_middle::ty::cast::{CastTy, mir_cast_kind};
12use rustc_middle::ty::util::IntTypeExt;
13use rustc_middle::ty::{self, Ty, UpvarArgs};
14use rustc_span::{DUMMY_SP, Span, Spanned};
15use tracing::debug;
16
17use crate::builder::expr::as_place::PlaceBase;
18use crate::builder::expr::category::{Category, RvalueFunc};
19use crate::builder::scope::LintLevel;
20use crate::builder::{BlockAnd, BlockAndExtension, Builder, NeedsTemporary};
21
22impl<'a, 'tcx> Builder<'a, 'tcx> {
23    /// Returns an rvalue suitable for use until the end of the current
24    /// scope expression.
25    ///
26    /// The operand returned from this function will *not be valid* after
27    /// an ExprKind::Scope is passed, so please do *not* return it from
28    /// functions to avoid bad miscompiles.
29    pub(crate) fn as_local_rvalue(
30        &mut self,
31        block: BasicBlock,
32        expr_id: ExprId,
33    ) -> BlockAnd<Rvalue<'tcx>> {
34        let local_scope = self.local_scope();
35        self.as_rvalue(
36            block,
37            TempLifetime { temp_lifetime: Some(local_scope), backwards_incompatible: None },
38            expr_id,
39        )
40    }
41
42    /// Compile `expr`, yielding an rvalue.
43    pub(crate) fn as_rvalue(
44        &mut self,
45        mut block: BasicBlock,
46        scope: TempLifetime,
47        expr_id: ExprId,
48    ) -> BlockAnd<Rvalue<'tcx>> {
49        let this = self; // See "LET_THIS_SELF".
50        let expr = &this.thir[expr_id];
51        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs:51",
                        "rustc_mir_build::builder::expr::as_rvalue",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs"),
                        ::tracing_core::__macro_support::Option::Some(51u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_rvalue"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("expr_as_rvalue(block={0:?}, scope={1:?}, expr={2:?})",
                                                    block, scope, expr) as &dyn Value))])
            });
    } else { ; }
};debug!("expr_as_rvalue(block={:?}, scope={:?}, expr={:?})", block, scope, expr);
52
53        let expr_span = expr.span;
54        let source_info = this.source_info(expr_span);
55
56        match expr.kind {
57            ExprKind::ThreadLocalRef(did) => block.and(Rvalue::ThreadLocalRef(did)),
58            ExprKind::Scope { region_scope, hir_id, value } => {
59                let region_scope = (region_scope, source_info);
60                this.in_scope(region_scope, LintLevel::Explicit(hir_id), |this| {
61                    this.as_rvalue(block, scope, value)
62                })
63            }
64            ExprKind::Repeat { value, count } => {
65                if Some(0) == count.try_to_target_usize(this.tcx) {
66                    this.build_zero_repeat(block, value, scope, source_info)
67                } else {
68                    let value_operand = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, value, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
69                        block = this.as_operand(
70                            block,
71                            scope,
72                            value,
73                            LocalInfo::Boring,
74                            NeedsTemporary::No
75                        )
76                    );
77                    block.and(Rvalue::Repeat(value_operand, count))
78                }
79            }
80            ExprKind::Binary { op, lhs, rhs } => {
81                let lhs = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, lhs, LocalInfo::Boring,
            NeedsTemporary::Maybe);
    block = b;
    v
}unpack!(
82                    block = this.as_operand(
83                        block,
84                        scope,
85                        lhs,
86                        LocalInfo::Boring,
87                        NeedsTemporary::Maybe
88                    )
89                );
90                let rhs = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, rhs, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
91                    block =
92                        this.as_operand(block, scope, rhs, LocalInfo::Boring, NeedsTemporary::No)
93                );
94                this.build_binary_op(block, op, expr_span, expr.ty, lhs, rhs)
95            }
96            ExprKind::Unary { op, arg } => {
97                let arg = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, arg, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
98                    block =
99                        this.as_operand(block, scope, arg, LocalInfo::Boring, NeedsTemporary::No)
100                );
101                // Check for -MIN on signed integers
102                if this.check_overflow && op == UnOp::Neg && expr.ty.is_signed() {
103                    let bool_ty = this.tcx.types.bool;
104
105                    let minval = this.minval_literal(expr_span, expr.ty);
106                    let is_min = this.temp(bool_ty, expr_span);
107
108                    this.cfg.push_assign(
109                        block,
110                        source_info,
111                        is_min,
112                        Rvalue::BinaryOp(BinOp::Eq, Box::new((arg.to_copy(), minval))),
113                    );
114
115                    block = this.assert(
116                        block,
117                        Operand::Move(is_min),
118                        false,
119                        AssertKind::OverflowNeg(arg.to_copy()),
120                        expr_span,
121                    );
122                }
123                block.and(Rvalue::UnaryOp(op, arg))
124            }
125            ExprKind::Cast { source } => {
126                let source_expr = &this.thir[source];
127
128                // Casting an enum to an integer is equivalent to computing the discriminant and casting the
129                // discriminant. Previously every backend had to repeat the logic for this operation. Now we
130                // create all the steps directly in MIR with operations all backends need to support anyway.
131                let (source, ty) = if let ty::Adt(adt_def, ..) = source_expr.ty.kind()
132                    && adt_def.is_enum()
133                {
134                    let discr_ty = adt_def.repr().discr_type().to_ty(this.tcx);
135                    let temp = {
    let BlockAnd(b, v) = this.as_temp(block, scope, source, Mutability::Not);
    block = b;
    v
}unpack!(block = this.as_temp(block, scope, source, Mutability::Not));
136                    let discr = this.temp(discr_ty, source_expr.span);
137                    this.cfg.push_assign(
138                        block,
139                        source_info,
140                        discr,
141                        Rvalue::Discriminant(temp.into()),
142                    );
143                    (Operand::Move(discr), discr_ty)
144                } else {
145                    let ty = source_expr.ty;
146                    let source = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, source, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
147                        block = this.as_operand(
148                            block,
149                            scope,
150                            source,
151                            LocalInfo::Boring,
152                            NeedsTemporary::No
153                        )
154                    );
155                    (source, ty)
156                };
157                let from_ty = CastTy::from_ty(ty);
158                let cast_ty = CastTy::from_ty(expr.ty);
159                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs:159",
                        "rustc_mir_build::builder::expr::as_rvalue",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs"),
                        ::tracing_core::__macro_support::Option::Some(159u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_rvalue"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("ExprKind::Cast from_ty={1:?}, cast_ty={0:?}/{2:?}",
                                                    expr.ty, from_ty, cast_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("ExprKind::Cast from_ty={from_ty:?}, cast_ty={:?}/{cast_ty:?}", expr.ty);
160                let cast_kind = mir_cast_kind(ty, expr.ty);
161                block.and(Rvalue::Cast(cast_kind, source, expr.ty))
162            }
163            ExprKind::PointerCoercion { cast, source, is_from_as_cast } => {
164                let source = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, source, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
165                    block = this.as_operand(
166                        block,
167                        scope,
168                        source,
169                        LocalInfo::Boring,
170                        NeedsTemporary::No
171                    )
172                );
173                let origin =
174                    if is_from_as_cast { CoercionSource::AsCast } else { CoercionSource::Implicit };
175                block.and(Rvalue::Cast(CastKind::PointerCoercion(cast, origin), source, expr.ty))
176            }
177            ExprKind::Array { ref fields } => {
178                // (*) We would (maybe) be closer to codegen if we
179                // handled this and other aggregate cases via
180                // `into()`, not `as_rvalue` -- in that case, instead
181                // of generating
182                //
183                //     let tmp1 = ...1;
184                //     let tmp2 = ...2;
185                //     dest = Rvalue::Aggregate(Foo, [tmp1, tmp2])
186                //
187                // we could just generate
188                //
189                //     dest.f = ...1;
190                //     dest.g = ...2;
191                //
192                // The problem is that then we would need to:
193                //
194                // (a) have a more complex mechanism for handling
195                //     partial cleanup;
196                // (b) distinguish the case where the type `Foo` has a
197                //     destructor, in which case creating an instance
198                //     as a whole "arms" the destructor, and you can't
199                //     write individual fields; and,
200                // (c) handle the case where the type Foo has no
201                //     fields. We don't want `let x: ();` to compile
202                //     to the same MIR as `let x = ();`.
203
204                // first process the set of fields
205                let el_ty = expr.ty.sequence_element_type(this.tcx);
206                let fields: IndexVec<FieldIdx, _> = fields
207                    .into_iter()
208                    .copied()
209                    .map(|f| {
210                        {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, f, LocalInfo::Boring,
            NeedsTemporary::Maybe);
    block = b;
    v
}unpack!(
211                            block = this.as_operand(
212                                block,
213                                scope,
214                                f,
215                                LocalInfo::Boring,
216                                NeedsTemporary::Maybe
217                            )
218                        )
219                    })
220                    .collect();
221
222                block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(el_ty)), fields))
223            }
224            ExprKind::Tuple { ref fields } => {
225                // see (*) above
226                // first process the set of fields
227                let fields: IndexVec<FieldIdx, _> = fields
228                    .into_iter()
229                    .copied()
230                    .map(|f| {
231                        {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, f, LocalInfo::Boring,
            NeedsTemporary::Maybe);
    block = b;
    v
}unpack!(
232                            block = this.as_operand(
233                                block,
234                                scope,
235                                f,
236                                LocalInfo::Boring,
237                                NeedsTemporary::Maybe
238                            )
239                        )
240                    })
241                    .collect();
242
243                block.and(Rvalue::Aggregate(Box::new(AggregateKind::Tuple), fields))
244            }
245            ExprKind::Closure(box ClosureExpr {
246                closure_id,
247                args,
248                ref upvars,
249                ref fake_reads,
250                movability: _,
251            }) => {
252                // Convert the closure fake reads, if any, from `ExprRef` to mir `Place`
253                // and push the fake reads.
254                // This must come before creating the operands. This is required in case
255                // there is a fake read and a borrow of the same path, since otherwise the
256                // fake read might interfere with the borrow. Consider an example like this
257                // one:
258                // ```
259                // let mut x = 0;
260                // let c = || {
261                //     &mut x; // mutable borrow of `x`
262                //     match x { _ => () } // fake read of `x`
263                // };
264                // ```
265                //
266                for (thir_place, cause, hir_id) in fake_reads.into_iter() {
267                    let place_builder = {
    let BlockAnd(b, v) = this.as_place_builder(block, *thir_place);
    block = b;
    v
}unpack!(block = this.as_place_builder(block, *thir_place));
268
269                    if let Some(mir_place) = place_builder.try_to_place(this) {
270                        this.cfg.push_fake_read(
271                            block,
272                            this.source_info(this.tcx.hir_span(*hir_id)),
273                            *cause,
274                            mir_place,
275                        );
276                    }
277                }
278
279                // see (*) above
280                let operands: IndexVec<FieldIdx, _> = upvars
281                    .into_iter()
282                    .copied()
283                    .map(|upvar| {
284                        let upvar_expr = &this.thir[upvar];
285                        match Category::of(&upvar_expr.kind) {
286                            // Use as_place to avoid creating a temporary when
287                            // moving a variable into a closure, so that
288                            // borrowck knows which variables to mark as being
289                            // used as mut. This is OK here because the upvar
290                            // expressions have no side effects and act on
291                            // disjoint places.
292                            // This occurs when capturing by copy/move, while
293                            // by reference captures use as_operand
294                            Some(Category::Place) => {
295                                let place = { let BlockAnd(b, v) = this.as_place(block, upvar); block = b; v }unpack!(block = this.as_place(block, upvar));
296                                this.consume_by_copy_or_move(place)
297                            }
298                            _ => {
299                                // Turn mutable borrow captures into unique
300                                // borrow captures when capturing an immutable
301                                // variable. This is sound because the mutation
302                                // that caused the capture will cause an error.
303                                match upvar_expr.kind {
304                                    ExprKind::Borrow {
305                                        borrow_kind:
306                                            BorrowKind::Mut { kind: MutBorrowKind::Default },
307                                        arg,
308                                    } => {
    let BlockAnd(b, v) =
        this.limit_capture_mutability(upvar_expr.span, upvar_expr.ty,
            scope.temp_lifetime, block, arg);
    block = b;
    v
}unpack!(
309                                        block = this.limit_capture_mutability(
310                                            upvar_expr.span,
311                                            upvar_expr.ty,
312                                            scope.temp_lifetime,
313                                            block,
314                                            arg,
315                                        )
316                                    ),
317                                    _ => {
318                                        {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, upvar, LocalInfo::Boring,
            NeedsTemporary::Maybe);
    block = b;
    v
}unpack!(
319                                            block = this.as_operand(
320                                                block,
321                                                scope,
322                                                upvar,
323                                                LocalInfo::Boring,
324                                                NeedsTemporary::Maybe
325                                            )
326                                        )
327                                    }
328                                }
329                            }
330                        }
331                    })
332                    .collect();
333
334                let result = match args {
335                    UpvarArgs::Coroutine(args) => {
336                        Box::new(AggregateKind::Coroutine(closure_id.to_def_id(), args))
337                    }
338                    UpvarArgs::Closure(args) => {
339                        Box::new(AggregateKind::Closure(closure_id.to_def_id(), args))
340                    }
341                    UpvarArgs::CoroutineClosure(args) => {
342                        Box::new(AggregateKind::CoroutineClosure(closure_id.to_def_id(), args))
343                    }
344                };
345                block.and(Rvalue::Aggregate(result, operands))
346            }
347            ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
348                block = this.stmt_expr(block, expr_id, None).into_block();
349                block.and(Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
350                    span: expr_span,
351                    user_ty: None,
352                    const_: Const::zero_sized(this.tcx.types.unit),
353                }))))
354            }
355
356            ExprKind::Literal { .. }
357            | ExprKind::NamedConst { .. }
358            | ExprKind::NonHirLiteral { .. }
359            | ExprKind::ZstLiteral { .. }
360            | ExprKind::ConstParam { .. }
361            | ExprKind::ConstBlock { .. }
362            | ExprKind::StaticRef { .. } => {
363                let constant = this.as_constant(expr);
364                block.and(Rvalue::Use(Operand::Constant(Box::new(constant))))
365            }
366
367            ExprKind::WrapUnsafeBinder { source } => {
368                let source = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, source, LocalInfo::Boring,
            NeedsTemporary::Maybe);
    block = b;
    v
}unpack!(
369                    block = this.as_operand(
370                        block,
371                        scope,
372                        source,
373                        LocalInfo::Boring,
374                        NeedsTemporary::Maybe
375                    )
376                );
377                block.and(Rvalue::WrapUnsafeBinder(source, expr.ty))
378            }
379
380            ExprKind::Yield { .. }
381            | ExprKind::Block { .. }
382            | ExprKind::Match { .. }
383            | ExprKind::If { .. }
384            | ExprKind::NeverToAny { .. }
385            | ExprKind::Use { .. }
386            | ExprKind::Borrow { .. }
387            | ExprKind::RawBorrow { .. }
388            | ExprKind::Adt { .. }
389            | ExprKind::Loop { .. }
390            | ExprKind::LoopMatch { .. }
391            | ExprKind::LogicalOp { .. }
392            | ExprKind::Call { .. }
393            | ExprKind::Field { .. }
394            | ExprKind::Let { .. }
395            | ExprKind::Deref { .. }
396            | ExprKind::Index { .. }
397            | ExprKind::VarRef { .. }
398            | ExprKind::UpvarRef { .. }
399            | ExprKind::Break { .. }
400            | ExprKind::Continue { .. }
401            | ExprKind::ConstContinue { .. }
402            | ExprKind::Return { .. }
403            | ExprKind::Become { .. }
404            | ExprKind::InlineAsm { .. }
405            | ExprKind::PlaceTypeAscription { .. }
406            | ExprKind::ValueTypeAscription { .. }
407            | ExprKind::PlaceUnwrapUnsafeBinder { .. }
408            | ExprKind::ValueUnwrapUnsafeBinder { .. } => {
409                // these do not have corresponding `Rvalue` variants,
410                // so make an operand and then return that
411                if true {
    if !!#[allow(non_exhaustive_omitted_patterns)] match Category::of(&expr.kind)
                    {
                    Some(Category::Rvalue(RvalueFunc::AsRvalue) |
                        Category::Constant) => true,
                    _ => false,
                } {
        ::core::panicking::panic("assertion failed: !matches!(Category::of(&expr.kind),\n        Some(Category::Rvalue(RvalueFunc::AsRvalue) | Category::Constant))")
    };
};debug_assert!(!matches!(
412                    Category::of(&expr.kind),
413                    Some(Category::Rvalue(RvalueFunc::AsRvalue) | Category::Constant)
414                ));
415                let operand = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, expr_id, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
416                    block = this.as_operand(
417                        block,
418                        scope,
419                        expr_id,
420                        LocalInfo::Boring,
421                        NeedsTemporary::No,
422                    )
423                );
424                block.and(Rvalue::Use(operand))
425            }
426
427            ExprKind::ByUse { expr, span: _ } => {
428                let operand = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, expr, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
429                    block =
430                        this.as_operand(block, scope, expr, LocalInfo::Boring, NeedsTemporary::No)
431                );
432                block.and(Rvalue::Use(operand))
433            }
434        }
435    }
436
437    pub(crate) fn build_binary_op(
438        &mut self,
439        mut block: BasicBlock,
440        op: BinOp,
441        span: Span,
442        ty: Ty<'tcx>,
443        lhs: Operand<'tcx>,
444        rhs: Operand<'tcx>,
445    ) -> BlockAnd<Rvalue<'tcx>> {
446        let source_info = self.source_info(span);
447        let bool_ty = self.tcx.types.bool;
448        let rvalue = match op {
449            BinOp::Add | BinOp::Sub | BinOp::Mul if self.check_overflow && ty.is_integral() => {
450                let result_tup = Ty::new_tup(self.tcx, &[ty, bool_ty]);
451                let result_value = self.temp(result_tup, span);
452
453                let op_with_overflow = op.wrapping_to_overflowing().unwrap();
454
455                self.cfg.push_assign(
456                    block,
457                    source_info,
458                    result_value,
459                    Rvalue::BinaryOp(op_with_overflow, Box::new((lhs.to_copy(), rhs.to_copy()))),
460                );
461                let val_fld = FieldIdx::ZERO;
462                let of_fld = FieldIdx::new(1);
463
464                let tcx = self.tcx;
465                let val = tcx.mk_place_field(result_value, val_fld, ty);
466                let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
467
468                let err = AssertKind::Overflow(op, lhs, rhs);
469                block = self.assert(block, Operand::Move(of), false, err, span);
470
471                Rvalue::Use(Operand::Move(val))
472            }
473            BinOp::Shl | BinOp::Shr if self.check_overflow && ty.is_integral() => {
474                // For an unsigned RHS, the shift is in-range for `rhs < bits`.
475                // For a signed RHS, `IntToInt` cast to the equivalent unsigned
476                // type and do that same comparison.
477                // A negative value will be *at least* 128 after the cast (that's i8::MIN),
478                // and 128 is an overflowing shift amount for all our currently existing types,
479                // so this cast can never make us miss an overflow.
480                let (lhs_size, _) = ty.int_size_and_signed(self.tcx);
481                if !(lhs_size.bits() <= 128) {
    ::core::panicking::panic("assertion failed: lhs_size.bits() <= 128")
};assert!(lhs_size.bits() <= 128);
482                let rhs_ty = rhs.ty(&self.local_decls, self.tcx);
483                let (rhs_size, _) = rhs_ty.int_size_and_signed(self.tcx);
484
485                let (unsigned_rhs, unsigned_ty) = match rhs_ty.kind() {
486                    ty::Uint(_) => (rhs.to_copy(), rhs_ty),
487                    ty::Int(int_width) => {
488                        let uint_ty = Ty::new_uint(self.tcx, int_width.to_unsigned());
489                        let rhs_temp = self.temp(uint_ty, span);
490                        self.cfg.push_assign(
491                            block,
492                            source_info,
493                            rhs_temp,
494                            Rvalue::Cast(CastKind::IntToInt, rhs.to_copy(), uint_ty),
495                        );
496                        (Operand::Move(rhs_temp), uint_ty)
497                    }
498                    _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("only integers are shiftable")));
}unreachable!("only integers are shiftable"),
499                };
500
501                // This can't overflow because the largest shiftable types are 128-bit,
502                // which fits in `u8`, the smallest possible `unsigned_ty`.
503                let lhs_bits = Operand::const_from_scalar(
504                    self.tcx,
505                    unsigned_ty,
506                    Scalar::from_uint(lhs_size.bits(), rhs_size),
507                    span,
508                );
509
510                let inbounds = self.temp(bool_ty, span);
511                self.cfg.push_assign(
512                    block,
513                    source_info,
514                    inbounds,
515                    Rvalue::BinaryOp(BinOp::Lt, Box::new((unsigned_rhs, lhs_bits))),
516                );
517
518                let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
519                block = self.assert(block, Operand::Move(inbounds), true, overflow_err, span);
520                Rvalue::BinaryOp(op, Box::new((lhs, rhs)))
521            }
522            BinOp::Div | BinOp::Rem if ty.is_integral() => {
523                // Checking division and remainder is more complex, since we 1. always check
524                // and 2. there are two possible failure cases, divide-by-zero and overflow.
525
526                let zero_err = if op == BinOp::Div {
527                    AssertKind::DivisionByZero(lhs.to_copy())
528                } else {
529                    AssertKind::RemainderByZero(lhs.to_copy())
530                };
531                let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
532
533                // Check for / 0
534                let is_zero = self.temp(bool_ty, span);
535                let zero = self.zero_literal(span, ty);
536                self.cfg.push_assign(
537                    block,
538                    source_info,
539                    is_zero,
540                    Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), zero))),
541                );
542
543                block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
544
545                // We only need to check for the overflow in one case:
546                // MIN / -1, and only for signed values.
547                if ty.is_signed() {
548                    let neg_1 = self.neg_1_literal(span, ty);
549                    let min = self.minval_literal(span, ty);
550
551                    let is_neg_1 = self.temp(bool_ty, span);
552                    let is_min = self.temp(bool_ty, span);
553                    let of = self.temp(bool_ty, span);
554
555                    // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
556
557                    self.cfg.push_assign(
558                        block,
559                        source_info,
560                        is_neg_1,
561                        Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), neg_1))),
562                    );
563                    self.cfg.push_assign(
564                        block,
565                        source_info,
566                        is_min,
567                        Rvalue::BinaryOp(BinOp::Eq, Box::new((lhs.to_copy(), min))),
568                    );
569
570                    let is_neg_1 = Operand::Move(is_neg_1);
571                    let is_min = Operand::Move(is_min);
572                    self.cfg.push_assign(
573                        block,
574                        source_info,
575                        of,
576                        Rvalue::BinaryOp(BinOp::BitAnd, Box::new((is_neg_1, is_min))),
577                    );
578
579                    block = self.assert(block, Operand::Move(of), false, overflow_err, span);
580                }
581
582                Rvalue::BinaryOp(op, Box::new((lhs, rhs)))
583            }
584            _ => Rvalue::BinaryOp(op, Box::new((lhs, rhs))),
585        };
586        block.and(rvalue)
587    }
588
589    /// Recursively inspect a THIR expression and probe through unsizing
590    /// operations that can be const-folded today.
591    fn check_constness(&self, mut kind: &'a ExprKind<'tcx>) -> bool {
592        loop {
593            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs:593",
                        "rustc_mir_build::builder::expr::as_rvalue",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs"),
                        ::tracing_core::__macro_support::Option::Some(593u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_rvalue"),
                        ::tracing_core::field::FieldSet::new(&["message", "kind"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("check_constness")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&kind) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?kind, "check_constness");
594            match kind {
595                &ExprKind::ValueTypeAscription { source: eid, user_ty: _, user_ty_span: _ }
596                | &ExprKind::Use { source: eid }
597                | &ExprKind::PointerCoercion {
598                    cast: PointerCoercion::Unsize,
599                    source: eid,
600                    is_from_as_cast: _,
601                }
602                | &ExprKind::Scope { region_scope: _, hir_id: _, value: eid } => {
603                    kind = &self.thir[eid].kind
604                }
605                _ => return #[allow(non_exhaustive_omitted_patterns)] match Category::of(&kind) {
    Some(Category::Constant) => true,
    _ => false,
}matches!(Category::of(&kind), Some(Category::Constant)),
606            }
607        }
608    }
609
610    fn build_zero_repeat(
611        &mut self,
612        mut block: BasicBlock,
613        value: ExprId,
614        scope: TempLifetime,
615        outer_source_info: SourceInfo,
616    ) -> BlockAnd<Rvalue<'tcx>> {
617        let this = self; // See "LET_THIS_SELF".
618        let value_expr = &this.thir[value];
619        let elem_ty = value_expr.ty;
620        if this.check_constness(&value_expr.kind) {
621            // Repeating a const does nothing
622        } else {
623            // For a non-const, we may need to generate an appropriate `Drop`
624            let value_operand = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, value, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
625                block = this.as_operand(block, scope, value, LocalInfo::Boring, NeedsTemporary::No)
626            );
627            if let Operand::Move(to_drop) = value_operand {
628                let success = this.cfg.start_new_block();
629                this.cfg.terminate(
630                    block,
631                    outer_source_info,
632                    TerminatorKind::Drop {
633                        place: to_drop,
634                        target: success,
635                        unwind: UnwindAction::Continue,
636                        replace: false,
637                        drop: None,
638                        async_fut: None,
639                    },
640                );
641                this.diverge_from(block);
642                block = success;
643            }
644            this.record_operands_moved(&[Spanned { node: value_operand, span: DUMMY_SP }]);
645        }
646        block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), IndexVec::new()))
647    }
648
649    fn limit_capture_mutability(
650        &mut self,
651        upvar_span: Span,
652        upvar_ty: Ty<'tcx>,
653        temp_lifetime: Option<region::Scope>,
654        mut block: BasicBlock,
655        arg: ExprId,
656    ) -> BlockAnd<Operand<'tcx>> {
657        let this = self; // See "LET_THIS_SELF".
658
659        let source_info = this.source_info(upvar_span);
660        let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
661
662        this.cfg.push(block, Statement::new(source_info, StatementKind::StorageLive(temp)));
663
664        let arg_place_builder = { let BlockAnd(b, v) = this.as_place_builder(block, arg); block = b; v }unpack!(block = this.as_place_builder(block, arg));
665
666        let mutability = match arg_place_builder.base() {
667            // We are capturing a path that starts off a local variable in the parent.
668            // The mutability of the current capture is same as the mutability
669            // of the local declaration in the parent.
670            PlaceBase::Local(local) => this.local_decls[local].mutability,
671            // Parent is a closure and we are capturing a path that is captured
672            // by the parent itself. The mutability of the current capture
673            // is same as that of the capture in the parent closure.
674            PlaceBase::Upvar { .. } => {
675                let enclosing_upvars_resolved = arg_place_builder.to_place(this);
676
677                match enclosing_upvars_resolved.as_ref() {
678                    PlaceRef {
679                        local,
680                        projection: &[ProjectionElem::Field(upvar_index, _), ..],
681                    }
682                    | PlaceRef {
683                        local,
684                        projection:
685                            &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
686                    } => {
687                        // Not in a closure
688                        if true {
    if !(local == ty::CAPTURE_STRUCT_LOCAL) {
        {
            ::core::panicking::panic_fmt(format_args!("Expected local to be Local(1), found {0:?}",
                    local));
        }
    };
};debug_assert!(
689                            local == ty::CAPTURE_STRUCT_LOCAL,
690                            "Expected local to be Local(1), found {local:?}"
691                        );
692                        // Not in a closure
693                        if true {
    if !(this.upvars.len() > upvar_index.index()) {
        {
            ::core::panicking::panic_fmt(format_args!("Unexpected capture place, upvars={0:#?}, upvar_index={1:?}",
                    this.upvars, upvar_index));
        }
    };
};debug_assert!(
694                            this.upvars.len() > upvar_index.index(),
695                            "Unexpected capture place, upvars={:#?}, upvar_index={:?}",
696                            this.upvars,
697                            upvar_index
698                        );
699                        this.upvars[upvar_index.index()].mutability
700                    }
701                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected capture place"))bug!("Unexpected capture place"),
702                }
703            }
704        };
705
706        let borrow_kind = match mutability {
707            Mutability::Not => BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
708            Mutability::Mut => BorrowKind::Mut { kind: MutBorrowKind::Default },
709        };
710
711        let arg_place = arg_place_builder.to_place(this);
712
713        this.cfg.push_assign(
714            block,
715            source_info,
716            Place::from(temp),
717            Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place),
718        );
719
720        // This can be `None` if the expression's temporary scope was extended so that it can be
721        // borrowed by a `const` or `static`. In that case, it's never dropped.
722        if let Some(temp_lifetime) = temp_lifetime {
723            this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
724        }
725
726        block.and(Operand::Move(Place::from(temp)))
727    }
728
729    // Helper to get a `-1` value of the appropriate type
730    fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
731        let typing_env = ty::TypingEnv::fully_monomorphized();
732        let size = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size;
733        let literal = Const::from_bits(self.tcx, size.unsigned_int_max(), typing_env, ty);
734
735        self.literal_operand(span, literal)
736    }
737
738    // Helper to get the minimum value of the appropriate type
739    fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
740        if !ty.is_signed() {
    ::core::panicking::panic("assertion failed: ty.is_signed()")
};assert!(ty.is_signed());
741        let typing_env = ty::TypingEnv::fully_monomorphized();
742        let bits = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size.bits();
743        let n = 1 << (bits - 1);
744        let literal = Const::from_bits(self.tcx, n, typing_env, ty);
745
746        self.literal_operand(span, literal)
747    }
748}