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(
350                    Operand::Constant(Box::new(ConstOperand {
351                        span: expr_span,
352                        user_ty: None,
353                        const_: Const::zero_sized(this.tcx.types.unit),
354                    })),
355                    WithRetag::Yes,
356                ))
357            }
358
359            ExprKind::Literal { .. }
360            | ExprKind::NamedConst { .. }
361            | ExprKind::NonHirLiteral { .. }
362            | ExprKind::ZstLiteral { .. }
363            | ExprKind::ConstParam { .. }
364            | ExprKind::ConstBlock { .. }
365            | ExprKind::StaticRef { .. } => {
366                let constant = this.as_constant(expr);
367                block.and(Rvalue::Use(Operand::Constant(Box::new(constant)), WithRetag::Yes))
368            }
369
370            ExprKind::WrapUnsafeBinder { source } => {
371                let source = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, source, LocalInfo::Boring,
            NeedsTemporary::Maybe);
    block = b;
    v
}unpack!(
372                    block = this.as_operand(
373                        block,
374                        scope,
375                        source,
376                        LocalInfo::Boring,
377                        NeedsTemporary::Maybe
378                    )
379                );
380                block.and(Rvalue::WrapUnsafeBinder(source, expr.ty))
381            }
382
383            ExprKind::Yield { .. }
384            | ExprKind::Block { .. }
385            | ExprKind::Match { .. }
386            | ExprKind::If { .. }
387            | ExprKind::NeverToAny { .. }
388            | ExprKind::Use { .. }
389            | ExprKind::Borrow { .. }
390            | ExprKind::RawBorrow { .. }
391            | ExprKind::Adt { .. }
392            | ExprKind::Loop { .. }
393            | ExprKind::LoopMatch { .. }
394            | ExprKind::LogicalOp { .. }
395            | ExprKind::Call { .. }
396            | ExprKind::Field { .. }
397            | ExprKind::Let { .. }
398            | ExprKind::Deref { .. }
399            | ExprKind::Index { .. }
400            | ExprKind::VarRef { .. }
401            | ExprKind::UpvarRef { .. }
402            | ExprKind::Break { .. }
403            | ExprKind::Continue { .. }
404            | ExprKind::ConstContinue { .. }
405            | ExprKind::Return { .. }
406            | ExprKind::Become { .. }
407            | ExprKind::InlineAsm { .. }
408            | ExprKind::PlaceTypeAscription { .. }
409            | ExprKind::ValueTypeAscription { .. }
410            | ExprKind::PlaceUnwrapUnsafeBinder { .. }
411            | ExprKind::ValueUnwrapUnsafeBinder { .. } => {
412                // these do not have corresponding `Rvalue` variants,
413                // so make an operand and then return that
414                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!(
415                    Category::of(&expr.kind),
416                    Some(Category::Rvalue(RvalueFunc::AsRvalue) | Category::Constant)
417                ));
418                let operand = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, expr_id, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
419                    block = this.as_operand(
420                        block,
421                        scope,
422                        expr_id,
423                        LocalInfo::Boring,
424                        NeedsTemporary::No,
425                    )
426                );
427                block.and(Rvalue::Use(operand, WithRetag::Yes))
428            }
429
430            ExprKind::ByUse { expr, span: _ } => {
431                let operand = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, expr, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
432                    block =
433                        this.as_operand(block, scope, expr, LocalInfo::Boring, NeedsTemporary::No)
434                );
435                block.and(Rvalue::Use(operand, WithRetag::Yes))
436            }
437        }
438    }
439
440    pub(crate) fn build_binary_op(
441        &mut self,
442        mut block: BasicBlock,
443        op: BinOp,
444        span: Span,
445        ty: Ty<'tcx>,
446        lhs: Operand<'tcx>,
447        rhs: Operand<'tcx>,
448    ) -> BlockAnd<Rvalue<'tcx>> {
449        let source_info = self.source_info(span);
450        let bool_ty = self.tcx.types.bool;
451        let rvalue = match op {
452            BinOp::Add | BinOp::Sub | BinOp::Mul if self.check_overflow && ty.is_integral() => {
453                let result_tup = Ty::new_tup(self.tcx, &[ty, bool_ty]);
454                let result_value = self.temp(result_tup, span);
455
456                let op_with_overflow = op.wrapping_to_overflowing().unwrap();
457
458                self.cfg.push_assign(
459                    block,
460                    source_info,
461                    result_value,
462                    Rvalue::BinaryOp(op_with_overflow, Box::new((lhs.to_copy(), rhs.to_copy()))),
463                );
464                let val_fld = FieldIdx::ZERO;
465                let of_fld = FieldIdx::new(1);
466
467                let tcx = self.tcx;
468                let val = tcx.mk_place_field(result_value, val_fld, ty);
469                let of = tcx.mk_place_field(result_value, of_fld, bool_ty);
470
471                let err = AssertKind::Overflow(op, lhs, rhs);
472                block = self.assert(block, Operand::Move(of), false, err, span);
473
474                Rvalue::Use(Operand::Move(val), WithRetag::Yes)
475            }
476            BinOp::Shl | BinOp::Shr if self.check_overflow && ty.is_integral() => {
477                // For an unsigned RHS, the shift is in-range for `rhs < bits`.
478                // For a signed RHS, `IntToInt` cast to the equivalent unsigned
479                // type and do that same comparison.
480                // A negative value will be *at least* 128 after the cast (that's i8::MIN),
481                // and 128 is an overflowing shift amount for all our currently existing types,
482                // so this cast can never make us miss an overflow.
483                let (lhs_size, _) = ty.int_size_and_signed(self.tcx);
484                if !(lhs_size.bits() <= 128) {
    ::core::panicking::panic("assertion failed: lhs_size.bits() <= 128")
};assert!(lhs_size.bits() <= 128);
485                let rhs_ty = rhs.ty(&self.local_decls, self.tcx);
486                let (rhs_size, _) = rhs_ty.int_size_and_signed(self.tcx);
487
488                let (unsigned_rhs, unsigned_ty) = match rhs_ty.kind() {
489                    ty::Uint(_) => (rhs.to_copy(), rhs_ty),
490                    ty::Int(int_width) => {
491                        let uint_ty = Ty::new_uint(self.tcx, int_width.to_unsigned());
492                        let rhs_temp = self.temp(uint_ty, span);
493                        self.cfg.push_assign(
494                            block,
495                            source_info,
496                            rhs_temp,
497                            Rvalue::Cast(CastKind::IntToInt, rhs.to_copy(), uint_ty),
498                        );
499                        (Operand::Move(rhs_temp), uint_ty)
500                    }
501                    _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("only integers are shiftable")));
}unreachable!("only integers are shiftable"),
502                };
503
504                // This can't overflow because the largest shiftable types are 128-bit,
505                // which fits in `u8`, the smallest possible `unsigned_ty`.
506                let lhs_bits = Operand::const_from_scalar(
507                    self.tcx,
508                    unsigned_ty,
509                    Scalar::from_uint(lhs_size.bits(), rhs_size),
510                    span,
511                );
512
513                let inbounds = self.temp(bool_ty, span);
514                self.cfg.push_assign(
515                    block,
516                    source_info,
517                    inbounds,
518                    Rvalue::BinaryOp(BinOp::Lt, Box::new((unsigned_rhs, lhs_bits))),
519                );
520
521                let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
522                block = self.assert(block, Operand::Move(inbounds), true, overflow_err, span);
523                Rvalue::BinaryOp(op, Box::new((lhs, rhs)))
524            }
525            BinOp::Div | BinOp::Rem if ty.is_integral() => {
526                // Checking division and remainder is more complex, since we 1. always check
527                // and 2. there are two possible failure cases, divide-by-zero and overflow.
528
529                let zero_err = if op == BinOp::Div {
530                    AssertKind::DivisionByZero(lhs.to_copy())
531                } else {
532                    AssertKind::RemainderByZero(lhs.to_copy())
533                };
534                let overflow_err = AssertKind::Overflow(op, lhs.to_copy(), rhs.to_copy());
535
536                // Check for / 0
537                let is_zero = self.temp(bool_ty, span);
538                let zero = self.zero_literal(span, ty);
539                self.cfg.push_assign(
540                    block,
541                    source_info,
542                    is_zero,
543                    Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), zero))),
544                );
545
546                block = self.assert(block, Operand::Move(is_zero), false, zero_err, span);
547
548                // We only need to check for the overflow in one case:
549                // MIN / -1, and only for signed values.
550                if ty.is_signed() {
551                    let neg_1 = self.neg_1_literal(span, ty);
552                    let min = self.minval_literal(span, ty);
553
554                    let is_neg_1 = self.temp(bool_ty, span);
555                    let is_min = self.temp(bool_ty, span);
556                    let of = self.temp(bool_ty, span);
557
558                    // this does (rhs == -1) & (lhs == MIN). It could short-circuit instead
559
560                    self.cfg.push_assign(
561                        block,
562                        source_info,
563                        is_neg_1,
564                        Rvalue::BinaryOp(BinOp::Eq, Box::new((rhs.to_copy(), neg_1))),
565                    );
566                    self.cfg.push_assign(
567                        block,
568                        source_info,
569                        is_min,
570                        Rvalue::BinaryOp(BinOp::Eq, Box::new((lhs.to_copy(), min))),
571                    );
572
573                    let is_neg_1 = Operand::Move(is_neg_1);
574                    let is_min = Operand::Move(is_min);
575                    self.cfg.push_assign(
576                        block,
577                        source_info,
578                        of,
579                        Rvalue::BinaryOp(BinOp::BitAnd, Box::new((is_neg_1, is_min))),
580                    );
581
582                    block = self.assert(block, Operand::Move(of), false, overflow_err, span);
583                }
584
585                Rvalue::BinaryOp(op, Box::new((lhs, rhs)))
586            }
587            _ => Rvalue::BinaryOp(op, Box::new((lhs, rhs))),
588        };
589        block.and(rvalue)
590    }
591
592    /// Recursively inspect a THIR expression and probe through unsizing
593    /// operations that can be const-folded today.
594    fn check_constness(&self, mut kind: &'a ExprKind<'tcx>) -> bool {
595        loop {
596            {
    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:596",
                        "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(596u32),
                        ::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");
597            match kind {
598                &ExprKind::ValueTypeAscription { source: eid, user_ty: _, user_ty_span: _ }
599                | &ExprKind::Use { source: eid }
600                | &ExprKind::PointerCoercion {
601                    cast: PointerCoercion::Unsize,
602                    source: eid,
603                    is_from_as_cast: _,
604                }
605                | &ExprKind::Scope { region_scope: _, hir_id: _, value: eid } => {
606                    kind = &self.thir[eid].kind
607                }
608                _ => return #[allow(non_exhaustive_omitted_patterns)] match Category::of(&kind) {
    Some(Category::Constant) => true,
    _ => false,
}matches!(Category::of(&kind), Some(Category::Constant)),
609            }
610        }
611    }
612
613    fn build_zero_repeat(
614        &mut self,
615        mut block: BasicBlock,
616        value: ExprId,
617        scope: TempLifetime,
618        outer_source_info: SourceInfo,
619    ) -> BlockAnd<Rvalue<'tcx>> {
620        let this = self; // See "LET_THIS_SELF".
621        let value_expr = &this.thir[value];
622        let elem_ty = value_expr.ty;
623        if this.check_constness(&value_expr.kind) {
624            // Repeating a const does nothing
625        } else {
626            // For a non-const, we may need to generate an appropriate `Drop`
627            let value_operand = {
    let BlockAnd(b, v) =
        this.as_operand(block, scope, value, LocalInfo::Boring,
            NeedsTemporary::No);
    block = b;
    v
}unpack!(
628                block = this.as_operand(block, scope, value, LocalInfo::Boring, NeedsTemporary::No)
629            );
630            if let Operand::Move(to_drop) = value_operand {
631                let success = this.cfg.start_new_block();
632                this.cfg.terminate(
633                    block,
634                    outer_source_info,
635                    TerminatorKind::Drop {
636                        place: to_drop,
637                        target: success,
638                        unwind: UnwindAction::Continue,
639                        replace: false,
640                        drop: None,
641                        async_fut: None,
642                    },
643                );
644                this.diverge_from(block);
645                block = success;
646            }
647            this.record_operands_moved(&[Spanned { node: value_operand, span: DUMMY_SP }]);
648        }
649        block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), IndexVec::new()))
650    }
651
652    fn limit_capture_mutability(
653        &mut self,
654        upvar_span: Span,
655        upvar_ty: Ty<'tcx>,
656        temp_lifetime: Option<region::Scope>,
657        mut block: BasicBlock,
658        arg: ExprId,
659    ) -> BlockAnd<Operand<'tcx>> {
660        let this = self; // See "LET_THIS_SELF".
661
662        let source_info = this.source_info(upvar_span);
663        let temp = this.local_decls.push(LocalDecl::new(upvar_ty, upvar_span));
664
665        this.cfg.push(block, Statement::new(source_info, StatementKind::StorageLive(temp)));
666
667        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));
668
669        let mutability = match arg_place_builder.base() {
670            // We are capturing a path that starts off a local variable in the parent.
671            // The mutability of the current capture is same as the mutability
672            // of the local declaration in the parent.
673            PlaceBase::Local(local) => this.local_decls[local].mutability,
674            // Parent is a closure and we are capturing a path that is captured
675            // by the parent itself. The mutability of the current capture
676            // is same as that of the capture in the parent closure.
677            PlaceBase::Upvar { .. } => {
678                let enclosing_upvars_resolved = arg_place_builder.to_place(this);
679
680                match enclosing_upvars_resolved.as_ref() {
681                    PlaceRef {
682                        local,
683                        projection: &[ProjectionElem::Field(upvar_index, _), ..],
684                    }
685                    | PlaceRef {
686                        local,
687                        projection:
688                            &[ProjectionElem::Deref, ProjectionElem::Field(upvar_index, _), ..],
689                    } => {
690                        // Not in a closure
691                        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!(
692                            local == ty::CAPTURE_STRUCT_LOCAL,
693                            "Expected local to be Local(1), found {local:?}"
694                        );
695                        // Not in a closure
696                        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!(
697                            this.upvars.len() > upvar_index.index(),
698                            "Unexpected capture place, upvars={:#?}, upvar_index={:?}",
699                            this.upvars,
700                            upvar_index
701                        );
702                        this.upvars[upvar_index.index()].mutability
703                    }
704                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Unexpected capture place"))bug!("Unexpected capture place"),
705                }
706            }
707        };
708
709        let borrow_kind = match mutability {
710            Mutability::Not => BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture },
711            Mutability::Mut => BorrowKind::Mut { kind: MutBorrowKind::Default },
712        };
713
714        let arg_place = arg_place_builder.to_place(this);
715
716        this.cfg.push_assign(
717            block,
718            source_info,
719            Place::from(temp),
720            Rvalue::Ref(this.tcx.lifetimes.re_erased, borrow_kind, arg_place),
721        );
722
723        // This can be `None` if the expression's temporary scope was extended so that it can be
724        // borrowed by a `const` or `static`. In that case, it's never dropped.
725        if let Some(temp_lifetime) = temp_lifetime {
726            this.schedule_drop_storage_and_value(upvar_span, temp_lifetime, temp);
727        }
728
729        block.and(Operand::Move(Place::from(temp)))
730    }
731
732    // Helper to get a `-1` value of the appropriate type
733    fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
734        let typing_env = ty::TypingEnv::fully_monomorphized();
735        let size = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size;
736        let literal = Const::from_bits(self.tcx, size.unsigned_int_max(), typing_env, ty);
737
738        self.literal_operand(span, literal)
739    }
740
741    // Helper to get the minimum value of the appropriate type
742    fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
743        if !ty.is_signed() {
    ::core::panicking::panic("assertion failed: ty.is_signed()")
};assert!(ty.is_signed());
744        let typing_env = ty::TypingEnv::fully_monomorphized();
745        let bits = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size.bits();
746        let n = 1 << (bits - 1);
747        let literal = Const::from_bits(self.tcx, n, typing_env, ty);
748
749        self.literal_operand(span, literal)
750    }
751}