Skip to main content

rustc_mir_transform/
known_panics_lint.rs

1//! A lint that checks for known panics like overflows, division by zero,
2//! out-of-bound access etc. Uses const propagation to determine the values of
3//! operands during checks.
4
5use std::fmt::Debug;
6
7use rustc_abi::{BackendRepr, FieldIdx, HasDataLayout, Size, TargetDataLayout, VariantIdx};
8use rustc_attr_ir::find_attr;
9use rustc_const_eval::const_eval::DummyMachine;
10use rustc_const_eval::interpret::{ImmTy, InterpCx, InterpResult, Projectable, Scalar, interp_ok};
11use rustc_data_structures::fx::FxHashSet;
12use rustc_hir::HirId;
13use rustc_hir::def::DefKind;
14use rustc_index::IndexVec;
15use rustc_index::bit_set::DenseBitSet;
16use rustc_lint_defs::builtin::UNCONDITIONAL_PANIC;
17use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
18use rustc_middle::mir::*;
19use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout};
20use rustc_middle::ty::{
21    self, ConstInt, GenericArgKind, GenericParamDefKind, ScalarInt, Ty, TyCtxt, TypeVisitableExt,
22    Unnormalized,
23};
24use rustc_span::{Span, bug};
25use tracing::{debug, instrument, trace};
26
27use crate::diagnostics::{AssertLint, AssertLintKind, ConstNIsZero};
28
29pub(super) struct KnownPanicsLint;
30
31impl<'tcx> crate::MirLint<'tcx> for KnownPanicsLint {
32    fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
33        if body.tainted_by_errors.is_some() {
34            return;
35        }
36
37        let def_id = body.source.def_id().expect_local();
38        let def_kind = tcx.def_kind(def_id);
39        let is_fn_like = def_kind.is_fn_like();
40        let is_assoc_const = def_kind == DefKind::AssocConst;
41
42        // Only run const prop on functions, methods, closures and associated constants
43        if !is_fn_like && !is_assoc_const {
44            // skip anon_const/statics/consts because they'll be evaluated by miri anyway
45            trace!("KnownPanicsLint skipped for {:?}", def_id);
46            return;
47        }
48
49        // FIXME(welseywiser) const prop doesn't work on coroutines because of query cycles
50        // computing their layout.
51        if tcx.is_coroutine(def_id.to_def_id()) {
52            trace!("KnownPanicsLint skipped for coroutine {:?}", def_id);
53            return;
54        }
55
56        trace!("KnownPanicsLint starting for {:?}", def_id);
57
58        let mut linter = ConstPropagator::new(body, tcx);
59        linter.visit_body(body);
60
61        trace!("KnownPanicsLint done for {:?}", def_id);
62    }
63}
64
65/// Visits MIR nodes, performs const propagation
66/// and runs lint checks as it goes
67struct ConstPropagator<'mir, 'tcx> {
68    ecx: InterpCx<'tcx, DummyMachine>,
69    tcx: TyCtxt<'tcx>,
70    typing_env: ty::TypingEnv<'tcx>,
71    worklist: Vec<BasicBlock>,
72    visited_blocks: DenseBitSet<BasicBlock>,
73    locals: IndexVec<Local, Value<'tcx>>,
74    body: &'mir Body<'tcx>,
75    written_only_inside_own_block_locals: FxHashSet<Local>,
76    can_const_prop: IndexVec<Local, ConstPropMode>,
77}
78
79#[derive(Debug, Clone)]
80enum Value<'tcx> {
81    Immediate(ImmTy<'tcx>),
82    Aggregate { variant: VariantIdx, fields: IndexVec<FieldIdx, Value<'tcx>> },
83    Uninit,
84}
85
86impl<'tcx> From<ImmTy<'tcx>> for Value<'tcx> {
87    fn from(v: ImmTy<'tcx>) -> Self {
88        Self::Immediate(v)
89    }
90}
91
92impl<'tcx> Value<'tcx> {
93    fn project(
94        &self,
95        proj: &[PlaceElem<'tcx>],
96        prop: &ConstPropagator<'_, 'tcx>,
97    ) -> Option<&Value<'tcx>> {
98        let mut this = self;
99        for proj in proj {
100            this = match (*proj, this) {
101                (PlaceElem::Field(idx, _), Value::Aggregate { fields, .. }) => {
102                    fields.get(idx).unwrap_or(&Value::Uninit)
103                }
104                (PlaceElem::Index(idx), Value::Aggregate { fields, .. }) => {
105                    let idx = prop.get_const(idx.into())?.immediate()?;
106                    let idx = prop.ecx.read_target_usize(idx).discard_err()?.try_into().ok()?;
107                    if idx <= FieldIdx::MAX_AS_U32 {
108                        fields.get(FieldIdx::from_u32(idx)).unwrap_or(&Value::Uninit)
109                    } else {
110                        return None;
111                    }
112                }
113                (
114                    PlaceElem::ConstantIndex { offset, min_length: _, from_end: false },
115                    Value::Aggregate { fields, .. },
116                ) => fields
117                    .get(FieldIdx::from_u32(offset.try_into().ok()?))
118                    .unwrap_or(&Value::Uninit),
119                _ => return None,
120            };
121        }
122        Some(this)
123    }
124
125    fn project_mut(&mut self, proj: &[PlaceElem<'_>]) -> Option<&mut Value<'tcx>> {
126        let mut this = self;
127        for proj in proj {
128            this = match (proj, this) {
129                (PlaceElem::Field(idx, _), Value::Aggregate { fields, .. }) => {
130                    fields.ensure_contains_elem(*idx, || Value::Uninit)
131                }
132                (PlaceElem::Field(..), val @ Value::Uninit) => {
133                    *val =
134                        Value::Aggregate { variant: VariantIdx::ZERO, fields: Default::default() };
135                    val.project_mut(&[*proj])?
136                }
137                _ => return None,
138            };
139        }
140        Some(this)
141    }
142
143    fn immediate(&self) -> Option<&ImmTy<'tcx>> {
144        match self {
145            Value::Immediate(op) => Some(op),
146            _ => None,
147        }
148    }
149}
150
151impl<'tcx> LayoutOfHelpers<'tcx> for ConstPropagator<'_, 'tcx> {
152    type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
153
154    #[inline]
155    fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
156        err
157    }
158}
159
160impl HasDataLayout for ConstPropagator<'_, '_> {
161    #[inline]
162    fn data_layout(&self) -> &TargetDataLayout {
163        &self.tcx.data_layout
164    }
165}
166
167impl<'tcx> ty::layout::HasTyCtxt<'tcx> for ConstPropagator<'_, 'tcx> {
168    #[inline]
169    fn tcx(&self) -> TyCtxt<'tcx> {
170        self.tcx
171    }
172}
173
174impl<'tcx> ty::layout::HasTypingEnv<'tcx> for ConstPropagator<'_, 'tcx> {
175    #[inline]
176    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
177        self.typing_env
178    }
179}
180
181impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
182    fn new(body: &'mir Body<'tcx>, tcx: TyCtxt<'tcx>) -> ConstPropagator<'mir, 'tcx> {
183        let def_id = body.source.def_id();
184        let typing_env = body.typing_env(tcx);
185        let can_const_prop = CanConstProp::check(tcx, typing_env, body);
186        let ecx = InterpCx::new(tcx, tcx.def_span(def_id), typing_env, DummyMachine);
187
188        ConstPropagator {
189            ecx,
190            tcx,
191            typing_env,
192            worklist: vec![START_BLOCK],
193            visited_blocks: DenseBitSet::new_empty(body.basic_blocks.len()),
194            locals: IndexVec::from_elem_n(Value::Uninit, body.local_decls.len()),
195            body,
196            can_const_prop,
197            written_only_inside_own_block_locals: Default::default(),
198        }
199    }
200
201    fn local_decls(&self) -> &'mir LocalDecls<'tcx> {
202        &self.body.local_decls
203    }
204
205    fn get_const(&self, place: Place<'tcx>) -> Option<&Value<'tcx>> {
206        self.locals[place.local].project(&place.projection, self)
207    }
208
209    /// Remove `local` from the pool of `Locals`. Allows writing to them,
210    /// but not reading from them anymore.
211    fn remove_const(&mut self, local: Local) {
212        self.locals[local] = Value::Uninit;
213        self.written_only_inside_own_block_locals.remove(&local);
214    }
215
216    fn access_mut(&mut self, place: &Place<'_>) -> Option<&mut Value<'tcx>> {
217        match self.can_const_prop[place.local] {
218            ConstPropMode::NoPropagation => return None,
219            ConstPropMode::OnlyInsideOwnBlock => {
220                self.written_only_inside_own_block_locals.insert(place.local);
221            }
222            ConstPropMode::FullConstProp => {}
223        }
224        self.locals[place.local].project_mut(place.projection)
225    }
226
227    fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
228        source_info.scope.lint_root(&self.body.source_scopes)
229    }
230
231    fn use_ecx<F, T>(&mut self, f: F) -> Option<T>
232    where
233        F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
234    {
235        f(self)
236            .inspect_err_info(|err| {
237                trace!("InterpCx operation failed: {:?}", err);
238                // Some errors shouldn't come up because creating them causes
239                // an allocation, which we should avoid. When that happens,
240                // dedicated error variants should be introduced instead.
241                assert!(
242                    !err.kind().formatted_string(),
243                    "known panics lint encountered formatting error: {}",
244                    err.to_string(),
245                );
246            })
247            .discard_err()
248    }
249
250    /// Returns the value, if any, of evaluating `c`.
251    fn eval_constant(&mut self, c: &ConstOperand<'tcx>) -> Option<ImmTy<'tcx>> {
252        // FIXME we need to revisit this for #67176
253        if c.has_param() {
254            return None;
255        }
256
257        // Normalization needed b/c known panics lint runs in
258        // `mir_drops_elaborated_and_const_checked`, which happens before
259        // optimized MIR. Only after optimizing the MIR can we guarantee
260        // that the `PostAnalysisNormalize` pass has happened and that the body's consts
261        // are normalized, so any call to resolve before that needs to be
262        // manually normalized.
263        let val = self
264            .tcx
265            .try_normalize_erasing_regions(self.typing_env, Unnormalized::new_wip(c.const_))
266            .ok()?;
267
268        self.use_ecx(|this| this.ecx.eval_mir_constant(&val, c.span, None))?
269            .as_mplace_or_imm()
270            .right()
271    }
272
273    /// Returns the value, if any, of evaluating `place`.
274    #[instrument(level = "trace", skip(self), ret)]
275    fn eval_place(&mut self, place: Place<'tcx>) -> Option<ImmTy<'tcx>> {
276        match self.get_const(place)? {
277            Value::Immediate(imm) => Some(imm.clone()),
278            Value::Aggregate { .. } => None,
279            Value::Uninit => None,
280        }
281    }
282
283    /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
284    /// or `eval_place`, depending on the variant of `Operand` used.
285    fn eval_operand(&mut self, op: &Operand<'tcx>) -> Option<ImmTy<'tcx>> {
286        match *op {
287            Operand::RuntimeChecks(_) => None,
288            Operand::Constant(ref c) => self.eval_constant(c),
289            Operand::Move(place) | Operand::Copy(place) => self.eval_place(place),
290        }
291    }
292
293    fn report_assert_as_lint(
294        &self,
295        location: Location,
296        lint_kind: AssertLintKind,
297        assert_kind: AssertKind<impl Debug>,
298    ) {
299        let source_info = self.body.source_info(location);
300        if let Some(lint_root) = self.lint_root(*source_info) {
301            let span = source_info.span;
302            self.tcx.emit_node_span_lint(
303                lint_kind.lint(),
304                lint_root,
305                span,
306                AssertLint { span, assert_kind, lint_kind },
307            );
308        }
309    }
310
311    fn check_unary_op(&mut self, op: UnOp, arg: &Operand<'tcx>, location: Location) -> Option<()> {
312        let arg = self.eval_operand(arg)?;
313        // The only operator that can overflow is `Neg`.
314        if op == UnOp::Neg && arg.layout.ty.is_integral() {
315            // Compute this as `0 - arg` so we can use `SubWithOverflow` to check for overflow.
316            let (arg, overflow) = self.use_ecx(|this| {
317                let arg = this.ecx.read_immediate(&arg)?;
318                let (_res, overflow) = this
319                    .ecx
320                    .binary_op(BinOp::SubWithOverflow, &ImmTy::from_int(0, arg.layout), &arg)?
321                    .to_scalar_pair();
322                interp_ok((arg, overflow.to_bool()?))
323            })?;
324            if overflow {
325                self.report_assert_as_lint(
326                    location,
327                    AssertLintKind::ArithmeticOverflow,
328                    AssertKind::OverflowNeg(arg.to_const_int()),
329                );
330                return None;
331            }
332        }
333
334        Some(())
335    }
336
337    fn check_binary_op(
338        &mut self,
339        op: BinOp,
340        left: &Operand<'tcx>,
341        right: &Operand<'tcx>,
342        location: Location,
343    ) -> Option<()> {
344        let r =
345            self.eval_operand(right).and_then(|r| self.use_ecx(|this| this.ecx.read_immediate(&r)));
346        let l =
347            self.eval_operand(left).and_then(|l| self.use_ecx(|this| this.ecx.read_immediate(&l)));
348        // Check for exceeding shifts *even if* we cannot evaluate the LHS.
349        if matches!(op, BinOp::Shr | BinOp::Shl) {
350            let r = r.clone()?;
351            // We need the type of the LHS. We cannot use `place_layout` as that is the type
352            // of the result, which for checked binops is not the same!
353            let left_ty = left.ty(self.local_decls(), self.tcx);
354            let left_size = self.ecx.layout_of(left_ty).ok()?.size;
355            let right_size = r.layout.size;
356            let r_bits = r.to_scalar().to_bits(right_size).discard_err();
357            if r_bits.is_some_and(|b| b >= left_size.bits() as u128) {
358                debug!("check_binary_op: reporting assert for {:?}", location);
359                let panic = AssertKind::Overflow(
360                    op,
361                    // Invent a dummy value, the diagnostic ignores it anyway
362                    ConstInt::new(
363                        ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
364                        left_ty.is_signed(),
365                        left_ty.is_ptr_sized_integral(),
366                    ),
367                    r.to_const_int(),
368                );
369                self.report_assert_as_lint(location, AssertLintKind::ArithmeticOverflow, panic);
370                return None;
371            }
372        }
373
374        // Div/Rem are handled via the assertions they trigger.
375        // But for Add/Sub/Mul, those assertions only exist in debug builds, and we want to
376        // lint in release builds as well, so we check on the operation instead.
377        // So normalize to the "overflowing" operator, and then ensure that it
378        // actually is an overflowing operator.
379        let op = op.wrapping_to_overflowing().unwrap_or(op);
380        // The remaining operators are handled through `wrapping_to_overflowing`.
381        if let (Some(l), Some(r)) = (l, r)
382            && l.layout.ty.is_integral()
383            && op.is_overflowing()
384            && self.use_ecx(|this| {
385                let (_res, overflow) = this.ecx.binary_op(op, &l, &r)?.to_scalar_pair();
386                overflow.to_bool()
387            })?
388        {
389            self.report_assert_as_lint(
390                location,
391                AssertLintKind::ArithmeticOverflow,
392                AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
393            );
394            return None;
395        }
396
397        Some(())
398    }
399
400    fn check_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) -> Option<()> {
401        // Perform any special handling for specific Rvalue types.
402        // Generally, checks here fall into one of two categories:
403        //   1. Additional checking to provide useful lints to the user
404        //        - In this case, we will do some validation and then fall through to the
405        //          end of the function which evals the assignment.
406        //   2. Working around bugs in other parts of the compiler
407        //        - In this case, we'll return `None` from this function to stop evaluation.
408        match rvalue {
409            // Additional checking: give lints to the user if an overflow would occur.
410            // We do this here and not in the `Assert` terminator as that terminator is
411            // only sometimes emitted (overflow checks can be disabled), but we want to always
412            // lint.
413            Rvalue::UnaryOp(op, arg) => {
414                trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
415                self.check_unary_op(*op, arg, location)?;
416            }
417            Rvalue::BinaryOp(op, (left, right)) => {
418                trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
419                self.check_binary_op(*op, left, right, location)?;
420            }
421
422            // Do not try creating references (#67862)
423            Rvalue::RawPtr(_, place) | Rvalue::Ref(_, _, place) | Rvalue::Reborrow(_, _, place) => {
424                trace!("skipping RawPtr | Ref | Reborrow for {:?}", place);
425
426                // This may be creating mutable references or immutable references to cells.
427                // If that happens, the pointed to value could be mutated via that reference.
428                // Since we aren't tracking references, the const propagator loses track of what
429                // value the local has right now.
430                // Thus, all locals that have their reference taken
431                // must not take part in propagation.
432                self.remove_const(place.local);
433
434                return None;
435            }
436            Rvalue::ThreadLocalRef(def_id) => {
437                trace!("skipping ThreadLocalRef({:?})", def_id);
438
439                return None;
440            }
441
442            // There's no other checking to do at this time.
443            Rvalue::Aggregate(..)
444            | Rvalue::Use(..)
445            | Rvalue::CopyForDeref(..)
446            | Rvalue::Repeat(..)
447            | Rvalue::Cast(..)
448            | Rvalue::Discriminant(..)
449            | Rvalue::WrapUnsafeBinder(..) => {}
450        }
451
452        // FIXME we need to revisit this for #67176
453        if rvalue.has_param() {
454            return None;
455        }
456        if !rvalue.ty(self.local_decls(), self.tcx).is_sized(self.tcx, self.typing_env) {
457            // the interpreter doesn't support unsized locals (only unsized arguments),
458            // but rustc does (in a kinda broken way), so we have to skip them here
459            return None;
460        }
461
462        Some(())
463    }
464
465    fn check_assertion(
466        &mut self,
467        expected: bool,
468        msg: &AssertKind<Operand<'tcx>>,
469        cond: &Operand<'tcx>,
470        location: Location,
471    ) {
472        let Some(value) = &self.eval_operand(cond) else { return };
473        trace!("assertion on {:?} should be {:?}", value, expected);
474
475        let expected = Scalar::from_bool(expected);
476        let Some(value_const) = self.use_ecx(|this| this.ecx.read_scalar(value)) else { return };
477
478        if expected != value_const {
479            // Poison all places this operand references so that further code
480            // doesn't use the invalid value
481            if let Some(place) = cond.place() {
482                self.remove_const(place.local);
483            }
484
485            enum DbgVal<T> {
486                Val(T),
487                Underscore,
488            }
489            impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
490                fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
491                    match self {
492                        Self::Val(val) => val.fmt(fmt),
493                        Self::Underscore => fmt.write_str("_"),
494                    }
495                }
496            }
497            let mut eval_to_int = |op| {
498                // This can be `None` if the lhs wasn't const propagated and we just
499                // triggered the assert on the value of the rhs.
500                self.eval_operand(op)
501                    .and_then(|op| self.ecx.read_immediate(&op).discard_err())
502                    .map_or(DbgVal::Underscore, |op| DbgVal::Val(op.to_const_int()))
503            };
504            let msg = match msg {
505                AssertKind::DivisionByZero(op) => AssertKind::DivisionByZero(eval_to_int(op)),
506                AssertKind::RemainderByZero(op) => AssertKind::RemainderByZero(eval_to_int(op)),
507                AssertKind::Overflow(bin_op @ (BinOp::Div | BinOp::Rem), op1, op2) => {
508                    // Division overflow is *UB* in the MIR, and different than the
509                    // other overflow checks.
510                    AssertKind::Overflow(*bin_op, eval_to_int(op1), eval_to_int(op2))
511                }
512                AssertKind::BoundsCheck { len, index } => {
513                    let len = eval_to_int(len);
514                    let index = eval_to_int(index);
515                    AssertKind::BoundsCheck { len, index }
516                }
517                // Remaining overflow errors are already covered by checks on the binary operators.
518                AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => return,
519                // Need proper const propagator for these.
520                _ => return,
521            };
522            self.report_assert_as_lint(location, AssertLintKind::UnconditionalPanic, msg);
523        }
524    }
525
526    fn ensure_not_propagated(&self, local: Local) {
527        if cfg!(debug_assertions) {
528            let val = self.get_const(local.into());
529            assert!(
530                matches!(val, Some(Value::Uninit))
531                    || self
532                        .layout_of(self.local_decls()[local].ty)
533                        .map_or(true, |layout| layout.is_zst()),
534                "failed to remove values for `{local:?}`, value={val:?}",
535            )
536        }
537    }
538
539    #[instrument(level = "trace", skip(self), ret)]
540    fn eval_rvalue(&mut self, rvalue: &Rvalue<'tcx>, dest: &Place<'tcx>) -> Option<()> {
541        if !dest.projection.is_empty() {
542            return None;
543        }
544        use rustc_middle::mir::Rvalue::*;
545        let layout = self.ecx.layout_of(dest.ty(self.body, self.tcx).ty).ok()?;
546        trace!(?layout);
547
548        let val: Value<'_> = match *rvalue {
549            ThreadLocalRef(_) => return None,
550
551            Use(ref operand, _) | WrapUnsafeBinder(ref operand, _) => {
552                self.eval_operand(operand)?.into()
553            }
554
555            CopyForDeref(place) | Reborrow(_, _, place) => self.eval_place(place)?.into(),
556
557            BinaryOp(bin_op, (ref left, ref right)) => {
558                let left = self.eval_operand(left)?;
559                let left = self.use_ecx(|this| this.ecx.read_immediate(&left))?;
560
561                let right = self.eval_operand(right)?;
562                let right = self.use_ecx(|this| this.ecx.read_immediate(&right))?;
563
564                let val = self.use_ecx(|this| this.ecx.binary_op(bin_op, &left, &right))?;
565                if matches!(val.layout.backend_repr, BackendRepr::ScalarPair { .. }) {
566                    // FIXME `Value` should properly support pairs in `Immediate`... but currently
567                    // it does not.
568                    let (val, overflow) = val.to_pair(&self.ecx);
569                    Value::Aggregate {
570                        variant: VariantIdx::ZERO,
571                        fields: [val.into(), overflow.into()].into_iter().collect(),
572                    }
573                } else {
574                    val.into()
575                }
576            }
577
578            UnaryOp(un_op, ref operand) => {
579                let operand = self.eval_operand(operand)?;
580                let val = self.use_ecx(|this| this.ecx.read_immediate(&operand))?;
581
582                let val = self.use_ecx(|this| this.ecx.unary_op(un_op, &val))?;
583                val.into()
584            }
585
586            Aggregate(ref kind, ref fields) => Value::Aggregate {
587                fields: fields
588                    .iter()
589                    .map(|field| self.eval_operand(field).map_or(Value::Uninit, Value::Immediate))
590                    .collect(),
591                variant: match **kind {
592                    AggregateKind::Adt(_, variant, _, _, _) => variant,
593                    AggregateKind::Array(_)
594                    | AggregateKind::Tuple
595                    | AggregateKind::RawPtr(_, _)
596                    | AggregateKind::Closure(_, _)
597                    | AggregateKind::Coroutine(_, _)
598                    | AggregateKind::CoroutineClosure(_, _) => VariantIdx::ZERO,
599                },
600            },
601
602            Repeat(ref op, n) => {
603                trace!(?op, ?n);
604                return None;
605            }
606
607            Ref(..) | RawPtr(..) => return None,
608
609            Cast(ref kind, ref value, to) => match kind {
610                CastKind::IntToInt | CastKind::IntToFloat => {
611                    let value = self.eval_operand(value)?;
612                    let value = self.ecx.read_immediate(&value).discard_err()?;
613                    let to = self.ecx.layout_of(to).ok()?;
614                    let res = self.ecx.int_to_int_or_float(&value, to).discard_err()?;
615                    res.into()
616                }
617                CastKind::FloatToFloat | CastKind::FloatToInt => {
618                    let value = self.eval_operand(value)?;
619                    let value = self.ecx.read_immediate(&value).discard_err()?;
620                    let to = self.ecx.layout_of(to).ok()?;
621                    let res = self.ecx.float_to_float_or_int(&value, to).discard_err()?;
622                    res.into()
623                }
624                CastKind::Transmute | CastKind::Subtype => {
625                    let value = self.eval_operand(value)?;
626                    let to = self.ecx.layout_of(to).ok()?;
627                    // `offset` for immediates only supports scalar/scalar-pair ABIs,
628                    // so bail out if the target is not one.
629                    match (value.layout.backend_repr, to.backend_repr) {
630                        (BackendRepr::Scalar(..), BackendRepr::Scalar(..)) => {}
631                        (BackendRepr::ScalarPair { .. }, BackendRepr::ScalarPair { .. }) => {}
632                        _ => return None,
633                    }
634
635                    value.offset(Size::ZERO, to, &self.ecx).discard_err()?.into()
636                }
637                _ => return None,
638            },
639
640            Discriminant(place) => {
641                let variant = match self.get_const(place)? {
642                    Value::Immediate(op) => {
643                        let op = op.clone();
644                        self.use_ecx(|this| this.ecx.read_discriminant(&op))?
645                    }
646                    Value::Aggregate { variant, .. } => *variant,
647                    Value::Uninit => return None,
648                };
649                let imm = self.use_ecx(|this| {
650                    this.ecx.discriminant_for_variant(
651                        place.ty(this.local_decls(), this.tcx).ty,
652                        variant,
653                    )
654                })?;
655                imm.into()
656            }
657        };
658        trace!(?val);
659
660        *self.access_mut(dest)? = val;
661
662        Some(())
663    }
664}
665
666impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> {
667    fn visit_body(&mut self, body: &Body<'tcx>) {
668        while let Some(bb) = self.worklist.pop() {
669            if !self.visited_blocks.insert(bb) {
670                continue;
671            }
672
673            let data = &body.basic_blocks[bb];
674            self.visit_basic_block_data(bb, data);
675        }
676    }
677
678    fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
679        self.super_operand(operand, location);
680    }
681
682    fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, location: Location) {
683        trace!("visit_const_operand: {:?}", constant);
684        self.super_const_operand(constant, location);
685        self.eval_constant(constant);
686    }
687
688    fn visit_assign(&mut self, place: &Place<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
689        self.super_assign(place, rvalue, location);
690
691        let Some(()) = self.check_rvalue(rvalue, location) else { return };
692
693        match self.can_const_prop[place.local] {
694            // Do nothing if the place is indirect.
695            _ if place.is_indirect() => {}
696            ConstPropMode::NoPropagation => self.ensure_not_propagated(place.local),
697            ConstPropMode::OnlyInsideOwnBlock | ConstPropMode::FullConstProp => {
698                if self.eval_rvalue(rvalue, place).is_none() {
699                    // Const prop failed, so erase the destination, ensuring that whatever happens
700                    // from here on, does not know about the previous value.
701                    // This is important in case we have
702                    // ```rust
703                    // let mut x = 42;
704                    // x = SOME_MUTABLE_STATIC;
705                    // // x must now be uninit
706                    // ```
707                    // FIXME: we overzealously erase the entire local, because that's easier to
708                    // implement.
709                    trace!(
710                        "propagation into {:?} failed.
711                        Nuking the entire site from orbit, it's the only way to be sure",
712                        place,
713                    );
714                    self.remove_const(place.local);
715                }
716            }
717        }
718    }
719
720    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
721        trace!("visit_statement: {:?}", statement);
722
723        // We want to evaluate operands before any change to the assigned-to value,
724        // so we recurse first.
725        self.super_statement(statement, location);
726
727        match statement.kind {
728            StatementKind::SetDiscriminant { ref place, variant_index } => {
729                match self.can_const_prop[place.local] {
730                    // Do nothing if the place is indirect.
731                    _ if place.is_indirect() => {}
732                    ConstPropMode::NoPropagation => self.ensure_not_propagated(place.local),
733                    ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
734                        match self.access_mut(place) {
735                            Some(Value::Aggregate { variant, .. }) => *variant = variant_index,
736                            _ => self.remove_const(place.local),
737                        }
738                    }
739                }
740            }
741            StatementKind::StorageLive(local) => {
742                self.remove_const(local);
743            }
744            StatementKind::StorageDead(local) => {
745                self.remove_const(local);
746            }
747            _ => {}
748        }
749    }
750
751    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
752        self.super_terminator(terminator, location);
753        match &terminator.kind {
754            TerminatorKind::Assert { expected, msg, cond, .. } => {
755                self.check_assertion(*expected, msg, cond, location);
756            }
757            TerminatorKind::SwitchInt { discr, targets } => {
758                if let Some(ref value) = self.eval_operand(discr)
759                    && let Some(value_const) = self.use_ecx(|this| this.ecx.read_scalar(value))
760                    && let Some(constant) = value_const.to_bits(value_const.size()).discard_err()
761                {
762                    // We managed to evaluate the discriminant, so we know we only need to visit
763                    // one target.
764                    let target = targets.target_for_value(constant);
765                    self.worklist.push(target);
766                    return;
767                }
768                // We failed to evaluate the discriminant, fallback to visiting all successors.
769            }
770            TerminatorKind::Call { func, args: _, .. } => {
771                if let Some((def_id, generic_args)) = func.const_fn_def() {
772                    for (index, arg) in generic_args.iter().enumerate() {
773                        if let GenericArgKind::Const(ct) = arg.kind() {
774                            let generics = self.tcx.generics_of(def_id);
775                            let param_def = generics.param_at(index, self.tcx);
776
777                            if let GenericParamDefKind::Const { .. } = param_def.kind
778                                && find_attr!(self.tcx, param_def.def_id, LintPanicsWhenZero)
779                                && let Some(0) = ct.try_to_target_usize(self.tcx)
780                            {
781                                // We managed to figure-out that the value of a
782                                // `#[lint::panics_when_zero]` const-generic parameter is zero.
783                                //
784                                // Let's report it as an unconditional panic.
785                                let source_info = self.body.source_info(location);
786                                if let Some(lint_root) = self.lint_root(*source_info) {
787                                    self.tcx.emit_node_span_lint(
788                                        UNCONDITIONAL_PANIC,
789                                        lint_root,
790                                        source_info.span,
791                                        ConstNIsZero {
792                                            const_param_span: source_info.span,
793                                            const_param_name: param_def.name,
794                                        },
795                                    );
796                                }
797                            }
798                        }
799                    }
800                }
801            }
802            // None of these have Operands to const-propagate.
803            TerminatorKind::Goto { .. }
804            | TerminatorKind::UnwindResume
805            | TerminatorKind::UnwindTerminate(_)
806            | TerminatorKind::Return
807            | TerminatorKind::TailCall { .. }
808            | TerminatorKind::Unreachable
809            | TerminatorKind::Drop { .. }
810            | TerminatorKind::Yield { .. }
811            | TerminatorKind::CoroutineDrop
812            | TerminatorKind::FalseEdge { .. }
813            | TerminatorKind::FalseUnwind { .. }
814            | TerminatorKind::InlineAsm { .. } => {}
815        }
816
817        self.worklist.extend(terminator.successors());
818    }
819
820    fn visit_basic_block_data(&mut self, block: BasicBlock, data: &BasicBlockData<'tcx>) {
821        self.super_basic_block_data(block, data);
822
823        // We remove all Locals which are restricted in propagation to their containing blocks and
824        // which were modified in the current block.
825        // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
826        let mut written_only_inside_own_block_locals =
827            std::mem::take(&mut self.written_only_inside_own_block_locals);
828
829        // This loop can get very hot for some bodies: it check each local in each bb.
830        // To avoid this quadratic behaviour, we only clear the locals that were modified inside
831        // the current block.
832        // The order in which we remove consts does not matter.
833        #[allow(rustc::potential_query_instability)]
834        for local in written_only_inside_own_block_locals.drain() {
835            debug_assert_eq!(self.can_const_prop[local], ConstPropMode::OnlyInsideOwnBlock);
836            self.remove_const(local);
837        }
838        self.written_only_inside_own_block_locals = written_only_inside_own_block_locals;
839
840        if cfg!(debug_assertions) {
841            for (local, &mode) in self.can_const_prop.iter_enumerated() {
842                match mode {
843                    ConstPropMode::FullConstProp => {}
844                    ConstPropMode::NoPropagation | ConstPropMode::OnlyInsideOwnBlock => {
845                        self.ensure_not_propagated(local);
846                    }
847                }
848            }
849        }
850    }
851}
852
853/// The maximum number of bytes that we'll allocate space for a local or the return value.
854/// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
855/// Severely regress performance.
856const MAX_ALLOC_LIMIT: u64 = 1024;
857
858/// The mode that `ConstProp` is allowed to run in for a given `Local`.
859#[derive(Clone, Copy, Debug, PartialEq)]
860enum ConstPropMode {
861    /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
862    FullConstProp,
863    /// The `Local` can only be propagated into and from its own block.
864    OnlyInsideOwnBlock,
865    /// The `Local` cannot be part of propagation at all. Any statement
866    /// referencing it either for reading or writing will not get propagated.
867    NoPropagation,
868}
869
870/// A visitor that determines locals in a MIR body
871/// that can be const propagated
872struct CanConstProp {
873    can_const_prop: IndexVec<Local, ConstPropMode>,
874    // False at the beginning. Once set, no more assignments are allowed to that local.
875    found_assignment: DenseBitSet<Local>,
876}
877
878impl CanConstProp {
879    /// Returns true if `local` can be propagated
880    fn check<'tcx>(
881        tcx: TyCtxt<'tcx>,
882        typing_env: ty::TypingEnv<'tcx>,
883        body: &Body<'tcx>,
884    ) -> IndexVec<Local, ConstPropMode> {
885        let mut cpv = CanConstProp {
886            can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
887            found_assignment: DenseBitSet::new_empty(body.local_decls.len()),
888        };
889        for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
890            let ty = body.local_decls[local].ty;
891            if ty.is_async_drop_in_place_coroutine(tcx) {
892                // No const propagation for async drop coroutine (AsyncDropGlue).
893                // Otherwise, tcx.layout_of(typing_env.as_query_input(ty)) will be called
894                // (early layout request for async drop coroutine) to calculate layout size.
895                // Layout for `async_drop_in_place<T>::{closure}` may only be known with known T.
896                *val = ConstPropMode::NoPropagation;
897                continue;
898            } else if ty.is_union() {
899                // Unions are incompatible with the current implementation of
900                // const prop because Rust has no concept of an active
901                // variant of a union
902                *val = ConstPropMode::NoPropagation;
903            } else {
904                match tcx.layout_of(typing_env.as_query_input(ty)) {
905                    Ok(layout) if layout.size < Size::from_bytes(MAX_ALLOC_LIMIT) => {}
906                    // Either the layout fails to compute, then we can't use this local anyway
907                    // or the local is too large, then we don't want to.
908                    _ => {
909                        *val = ConstPropMode::NoPropagation;
910                        continue;
911                    }
912                }
913            }
914        }
915        // Consider that arguments are assigned on entry.
916        for arg in body.args_iter() {
917            cpv.found_assignment.insert(arg);
918        }
919        cpv.visit_body(body);
920        cpv.can_const_prop
921    }
922}
923
924impl<'tcx> Visitor<'tcx> for CanConstProp {
925    fn visit_place(&mut self, place: &Place<'tcx>, mut context: PlaceContext, loc: Location) {
926        use rustc_middle::mir::visit::PlaceContext::*;
927
928        // Dereferencing just read the address of `place.local`.
929        if place.projection.first() == Some(&PlaceElem::Deref) {
930            context = NonMutatingUse(NonMutatingUseContext::Copy);
931        }
932
933        self.visit_local(place.local, context, loc);
934        self.visit_projection(place.as_ref(), context, loc);
935    }
936
937    fn visit_local(&mut self, local: Local, context: PlaceContext, _: Location) {
938        use rustc_middle::mir::visit::PlaceContext::*;
939        match context {
940            // These are just stores, where the storing is not propagatable, but there may be later
941            // mutations of the same local via `Store`
942            | MutatingUse(MutatingUseContext::Call)
943            | MutatingUse(MutatingUseContext::AsmOutput)
944            // Actual store that can possibly even propagate a value
945            | MutatingUse(MutatingUseContext::Store)
946            | MutatingUse(MutatingUseContext::SetDiscriminant) => {
947                if !self.found_assignment.insert(local) {
948                    match &mut self.can_const_prop[local] {
949                        // If the local can only get propagated in its own block, then we don't have
950                        // to worry about multiple assignments, as we'll nuke the const state at the
951                        // end of the block anyway, and inside the block we overwrite previous
952                        // states as applicable.
953                        ConstPropMode::OnlyInsideOwnBlock => {}
954                        ConstPropMode::NoPropagation => {}
955                        other @ ConstPropMode::FullConstProp => {
956                            trace!(
957                                "local {:?} can't be propagated because of multiple assignments. Previous state: {:?}",
958                                local, other,
959                            );
960                            *other = ConstPropMode::OnlyInsideOwnBlock;
961                        }
962                    }
963                }
964            }
965            // Reading constants is allowed an arbitrary number of times
966            NonMutatingUse(NonMutatingUseContext::Copy)
967            | NonMutatingUse(NonMutatingUseContext::Move)
968            | NonMutatingUse(NonMutatingUseContext::Inspect)
969            | NonMutatingUse(NonMutatingUseContext::PlaceMention)
970            | NonUse(_) => {}
971
972            // These could be propagated with a smarter analysis or just some careful thinking about
973            // whether they'd be fine right now.
974            MutatingUse(MutatingUseContext::Yield)
975            | MutatingUse(MutatingUseContext::Drop)
976            // These can't ever be propagated under any scheme, as we can't reason about indirect
977            // mutation.
978            | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
979            | NonMutatingUse(NonMutatingUseContext::FakeBorrow)
980            | NonMutatingUse(NonMutatingUseContext::RawBorrow)
981            | MutatingUse(MutatingUseContext::Borrow)
982            | MutatingUse(MutatingUseContext::RawBorrow) => {
983                trace!("local {:?} can't be propagated because it's used: {:?}", local, context);
984                self.can_const_prop[local] = ConstPropMode::NoPropagation;
985            }
986            MutatingUse(MutatingUseContext::Projection)
987            | NonMutatingUse(NonMutatingUseContext::Projection) => {
988                bug!("visit_place should not pass {context:?} for {local:?}")
989            }
990        }
991    }
992}