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