]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/const_prop.rs
Auto merge of #91403 - cjgillot:inherit-async, r=oli-obk
[rust.git] / compiler / rustc_mir_transform / src / const_prop.rs
1 //! Propagates constants for early reporting of statically known
2 //! assertion failures
3
4 use std::cell::Cell;
5
6 use rustc_ast::Mutability;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_hir::def::DefKind;
9 use rustc_hir::HirId;
10 use rustc_index::bit_set::BitSet;
11 use rustc_index::vec::IndexVec;
12 use rustc_middle::mir::visit::{
13     MutVisitor, MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor,
14 };
15 use rustc_middle::mir::{
16     AssertKind, BasicBlock, BinOp, Body, Constant, ConstantKind, Local, LocalDecl, LocalKind,
17     Location, Operand, Place, Rvalue, SourceInfo, SourceScope, SourceScopeData, Statement,
18     StatementKind, Terminator, TerminatorKind, UnOp, RETURN_PLACE,
19 };
20 use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout};
21 use rustc_middle::ty::subst::{InternalSubsts, Subst};
22 use rustc_middle::ty::{
23     self, ConstInt, ConstKind, Instance, ParamEnv, ScalarInt, Ty, TyCtxt, TypeFoldable,
24 };
25 use rustc_session::lint;
26 use rustc_span::{def_id::DefId, Span};
27 use rustc_target::abi::{HasDataLayout, Size, TargetDataLayout};
28 use rustc_target::spec::abi::Abi;
29 use rustc_trait_selection::traits;
30
31 use crate::MirPass;
32 use rustc_const_eval::const_eval::ConstEvalErr;
33 use rustc_const_eval::interpret::{
34     self, compile_time_machine, AllocId, Allocation, ConstValue, CtfeValidationMode, Frame, ImmTy,
35     Immediate, InterpCx, InterpResult, LocalState, LocalValue, MemPlace, MemoryKind, OpTy,
36     Operand as InterpOperand, PlaceTy, Scalar, ScalarMaybeUninit, StackPopCleanup, StackPopUnwind,
37 };
38
39 /// The maximum number of bytes that we'll allocate space for a local or the return value.
40 /// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
41 /// Severely regress performance.
42 const MAX_ALLOC_LIMIT: u64 = 1024;
43
44 /// Macro for machine-specific `InterpError` without allocation.
45 /// (These will never be shown to the user, but they help diagnose ICEs.)
46 macro_rules! throw_machine_stop_str {
47     ($($tt:tt)*) => {{
48         // We make a new local type for it. The type itself does not carry any information,
49         // but its vtable (for the `MachineStopType` trait) does.
50         struct Zst;
51         // Printing this type shows the desired string.
52         impl std::fmt::Display for Zst {
53             fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54                 write!(f, $($tt)*)
55             }
56         }
57         impl rustc_middle::mir::interpret::MachineStopType for Zst {}
58         throw_machine_stop!(Zst)
59     }};
60 }
61
62 pub struct ConstProp;
63
64 impl<'tcx> MirPass<'tcx> for ConstProp {
65     fn is_enabled(&self, _sess: &rustc_session::Session) -> bool {
66         // FIXME(#70073): Unlike the other passes in "optimizations", this one emits errors, so it
67         // runs even when MIR optimizations are disabled. We should separate the lint out from the
68         // transform and move the lint as early in the pipeline as possible.
69         true
70     }
71
72     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
73         // will be evaluated by miri and produce its errors there
74         if body.source.promoted.is_some() {
75             return;
76         }
77
78         let def_id = body.source.def_id().expect_local();
79         let is_fn_like = tcx.hir().get_by_def_id(def_id).fn_kind().is_some();
80         let is_assoc_const = tcx.def_kind(def_id) == DefKind::AssocConst;
81
82         // Only run const prop on functions, methods, closures and associated constants
83         if !is_fn_like && !is_assoc_const {
84             // skip anon_const/statics/consts because they'll be evaluated by miri anyway
85             trace!("ConstProp skipped for {:?}", def_id);
86             return;
87         }
88
89         let is_generator = tcx.type_of(def_id.to_def_id()).is_generator();
90         // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
91         // computing their layout.
92         if is_generator {
93             trace!("ConstProp skipped for generator {:?}", def_id);
94             return;
95         }
96
97         // Check if it's even possible to satisfy the 'where' clauses
98         // for this item.
99         // This branch will never be taken for any normal function.
100         // However, it's possible to `#!feature(trivial_bounds)]` to write
101         // a function with impossible to satisfy clauses, e.g.:
102         // `fn foo() where String: Copy {}`
103         //
104         // We don't usually need to worry about this kind of case,
105         // since we would get a compilation error if the user tried
106         // to call it. However, since we can do const propagation
107         // even without any calls to the function, we need to make
108         // sure that it even makes sense to try to evaluate the body.
109         // If there are unsatisfiable where clauses, then all bets are
110         // off, and we just give up.
111         //
112         // We manually filter the predicates, skipping anything that's not
113         // "global". We are in a potentially generic context
114         // (e.g. we are evaluating a function without substituting generic
115         // parameters, so this filtering serves two purposes:
116         //
117         // 1. We skip evaluating any predicates that we would
118         // never be able prove are unsatisfiable (e.g. `<T as Foo>`
119         // 2. We avoid trying to normalize predicates involving generic
120         // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
121         // the normalization code (leading to cycle errors), since
122         // it's usually never invoked in this way.
123         let predicates = tcx
124             .predicates_of(def_id.to_def_id())
125             .predicates
126             .iter()
127             .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
128         if traits::impossible_predicates(
129             tcx,
130             traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
131         ) {
132             trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", def_id);
133             return;
134         }
135
136         trace!("ConstProp starting for {:?}", def_id);
137
138         let dummy_body = &Body::new(
139             body.source,
140             body.basic_blocks().clone(),
141             body.source_scopes.clone(),
142             body.local_decls.clone(),
143             Default::default(),
144             body.arg_count,
145             Default::default(),
146             body.span,
147             body.generator_kind(),
148             body.tainted_by_errors,
149         );
150
151         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
152         // constants, instead of just checking for const-folding succeeding.
153         // That would require a uniform one-def no-mutation analysis
154         // and RPO (or recursing when needing the value of a local).
155         let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx);
156         optimization_finder.visit_body(body);
157
158         trace!("ConstProp done for {:?}", def_id);
159     }
160 }
161
162 struct ConstPropMachine<'mir, 'tcx> {
163     /// The virtual call stack.
164     stack: Vec<Frame<'mir, 'tcx>>,
165     /// `OnlyInsideOwnBlock` locals that were written in the current block get erased at the end.
166     written_only_inside_own_block_locals: FxHashSet<Local>,
167     /// Locals that need to be cleared after every block terminates.
168     only_propagate_inside_block_locals: BitSet<Local>,
169     can_const_prop: IndexVec<Local, ConstPropMode>,
170 }
171
172 impl ConstPropMachine<'_, '_> {
173     fn new(
174         only_propagate_inside_block_locals: BitSet<Local>,
175         can_const_prop: IndexVec<Local, ConstPropMode>,
176     ) -> Self {
177         Self {
178             stack: Vec::new(),
179             written_only_inside_own_block_locals: Default::default(),
180             only_propagate_inside_block_locals,
181             can_const_prop,
182         }
183     }
184 }
185
186 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx> {
187     compile_time_machine!(<'mir, 'tcx>);
188     const PANIC_ON_ALLOC_FAIL: bool = true; // all allocations are small (see `MAX_ALLOC_LIMIT`)
189
190     type MemoryKind = !;
191
192     type MemoryExtra = ();
193
194     fn load_mir(
195         _ecx: &InterpCx<'mir, 'tcx, Self>,
196         _instance: ty::InstanceDef<'tcx>,
197     ) -> InterpResult<'tcx, &'tcx Body<'tcx>> {
198         throw_machine_stop_str!("calling functions isn't supported in ConstProp")
199     }
200
201     fn find_mir_or_eval_fn(
202         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
203         _instance: ty::Instance<'tcx>,
204         _abi: Abi,
205         _args: &[OpTy<'tcx>],
206         _ret: Option<(&PlaceTy<'tcx>, BasicBlock)>,
207         _unwind: StackPopUnwind,
208     ) -> InterpResult<'tcx, Option<(&'mir Body<'tcx>, ty::Instance<'tcx>)>> {
209         Ok(None)
210     }
211
212     fn call_intrinsic(
213         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
214         _instance: ty::Instance<'tcx>,
215         _args: &[OpTy<'tcx>],
216         _ret: Option<(&PlaceTy<'tcx>, BasicBlock)>,
217         _unwind: StackPopUnwind,
218     ) -> InterpResult<'tcx> {
219         throw_machine_stop_str!("calling intrinsics isn't supported in ConstProp")
220     }
221
222     fn assert_panic(
223         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
224         _msg: &rustc_middle::mir::AssertMessage<'tcx>,
225         _unwind: Option<rustc_middle::mir::BasicBlock>,
226     ) -> InterpResult<'tcx> {
227         bug!("panics terminators are not evaluated in ConstProp")
228     }
229
230     fn binary_ptr_op(
231         _ecx: &InterpCx<'mir, 'tcx, Self>,
232         _bin_op: BinOp,
233         _left: &ImmTy<'tcx>,
234         _right: &ImmTy<'tcx>,
235     ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
236         // We can't do this because aliasing of memory can differ between const eval and llvm
237         throw_machine_stop_str!("pointer arithmetic or comparisons aren't supported in ConstProp")
238     }
239
240     fn access_local(
241         _ecx: &InterpCx<'mir, 'tcx, Self>,
242         frame: &Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>,
243         local: Local,
244     ) -> InterpResult<'tcx, InterpOperand<Self::PointerTag>> {
245         let l = &frame.locals[local];
246
247         if l.value == LocalValue::Uninitialized {
248             throw_machine_stop_str!("tried to access an uninitialized local")
249         }
250
251         l.access()
252     }
253
254     fn access_local_mut<'a>(
255         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
256         frame: usize,
257         local: Local,
258     ) -> InterpResult<'tcx, Result<&'a mut LocalValue<Self::PointerTag>, MemPlace<Self::PointerTag>>>
259     {
260         if ecx.machine.can_const_prop[local] == ConstPropMode::NoPropagation {
261             throw_machine_stop_str!("tried to write to a local that is marked as not propagatable")
262         }
263         if frame == 0 && ecx.machine.only_propagate_inside_block_locals.contains(local) {
264             trace!(
265                 "mutating local {:?} which is restricted to its block. \
266                 Will remove it from const-prop after block is finished.",
267                 local
268             );
269             ecx.machine.written_only_inside_own_block_locals.insert(local);
270         }
271         ecx.machine.stack[frame].locals[local].access_mut()
272     }
273
274     fn before_access_global(
275         _memory_extra: &(),
276         _alloc_id: AllocId,
277         allocation: &Allocation<Self::PointerTag, Self::AllocExtra>,
278         _static_def_id: Option<DefId>,
279         is_write: bool,
280     ) -> InterpResult<'tcx> {
281         if is_write {
282             throw_machine_stop_str!("can't write to global");
283         }
284         // If the static allocation is mutable, then we can't const prop it as its content
285         // might be different at runtime.
286         if allocation.mutability == Mutability::Mut {
287             throw_machine_stop_str!("can't access mutable globals in ConstProp");
288         }
289
290         Ok(())
291     }
292
293     #[inline(always)]
294     fn init_frame_extra(
295         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
296         frame: Frame<'mir, 'tcx>,
297     ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
298         Ok(frame)
299     }
300
301     #[inline(always)]
302     fn stack<'a>(
303         ecx: &'a InterpCx<'mir, 'tcx, Self>,
304     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
305         &ecx.machine.stack
306     }
307
308     #[inline(always)]
309     fn stack_mut<'a>(
310         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
311     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
312         &mut ecx.machine.stack
313     }
314 }
315
316 /// Finds optimization opportunities on the MIR.
317 struct ConstPropagator<'mir, 'tcx> {
318     ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
319     tcx: TyCtxt<'tcx>,
320     param_env: ParamEnv<'tcx>,
321     // FIXME(eddyb) avoid cloning these two fields more than once,
322     // by accessing them through `ecx` instead.
323     source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
324     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
325     // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
326     // the last known `SourceInfo` here and just keep revisiting it.
327     source_info: Option<SourceInfo>,
328 }
329
330 impl<'tcx> LayoutOfHelpers<'tcx> for ConstPropagator<'_, 'tcx> {
331     type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
332
333     #[inline]
334     fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
335         err
336     }
337 }
338
339 impl HasDataLayout for ConstPropagator<'_, '_> {
340     #[inline]
341     fn data_layout(&self) -> &TargetDataLayout {
342         &self.tcx.data_layout
343     }
344 }
345
346 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for ConstPropagator<'_, 'tcx> {
347     #[inline]
348     fn tcx(&self) -> TyCtxt<'tcx> {
349         self.tcx
350     }
351 }
352
353 impl<'tcx> ty::layout::HasParamEnv<'tcx> for ConstPropagator<'_, 'tcx> {
354     #[inline]
355     fn param_env(&self) -> ty::ParamEnv<'tcx> {
356         self.param_env
357     }
358 }
359
360 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
361     fn new(
362         body: &Body<'tcx>,
363         dummy_body: &'mir Body<'tcx>,
364         tcx: TyCtxt<'tcx>,
365     ) -> ConstPropagator<'mir, 'tcx> {
366         let def_id = body.source.def_id();
367         let substs = &InternalSubsts::identity_for_item(tcx, def_id);
368         let param_env = tcx.param_env_reveal_all_normalized(def_id);
369
370         let span = tcx.def_span(def_id);
371         // FIXME: `CanConstProp::check` computes the layout of all locals, return those layouts
372         // so we can write them to `ecx.frame_mut().locals.layout, reducing the duplication in
373         // `layout_of` query invocations.
374         let can_const_prop = CanConstProp::check(tcx, param_env, body);
375         let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
376         for (l, mode) in can_const_prop.iter_enumerated() {
377             if *mode == ConstPropMode::OnlyInsideOwnBlock {
378                 only_propagate_inside_block_locals.insert(l);
379             }
380         }
381         let mut ecx = InterpCx::new(
382             tcx,
383             span,
384             param_env,
385             ConstPropMachine::new(only_propagate_inside_block_locals, can_const_prop),
386             (),
387         );
388
389         let ret = ecx
390             .layout_of(body.return_ty().subst(tcx, substs))
391             .ok()
392             // Don't bother allocating memory for ZST types which have no values
393             // or for large values.
394             .filter(|ret_layout| {
395                 !ret_layout.is_zst() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
396             })
397             .map(|ret_layout| {
398                 ecx.allocate(ret_layout, MemoryKind::Stack)
399                     .expect("couldn't perform small allocation")
400                     .into()
401             });
402
403         ecx.push_stack_frame(
404             Instance::new(def_id, substs),
405             dummy_body,
406             ret.as_ref(),
407             StackPopCleanup::Root { cleanup: false },
408         )
409         .expect("failed to push initial stack frame");
410
411         ConstPropagator {
412             ecx,
413             tcx,
414             param_env,
415             // FIXME(eddyb) avoid cloning these two fields more than once,
416             // by accessing them through `ecx` instead.
417             source_scopes: body.source_scopes.clone(),
418             //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
419             local_decls: body.local_decls.clone(),
420             source_info: None,
421         }
422     }
423
424     fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
425         let op = match self.ecx.eval_place_to_op(place, None) {
426             Ok(op) => op,
427             Err(e) => {
428                 trace!("get_const failed: {}", e);
429                 return None;
430             }
431         };
432
433         // Try to read the local as an immediate so that if it is representable as a scalar, we can
434         // handle it as such, but otherwise, just return the value as is.
435         Some(match self.ecx.try_read_immediate(&op) {
436             Ok(Ok(imm)) => imm.into(),
437             _ => op,
438         })
439     }
440
441     /// Remove `local` from the pool of `Locals`. Allows writing to them,
442     /// but not reading from them anymore.
443     fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
444         ecx.frame_mut().locals[local] =
445             LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
446     }
447
448     fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
449         source_info.scope.lint_root(&self.source_scopes)
450     }
451
452     fn use_ecx<F, T>(&mut self, f: F) -> Option<T>
453     where
454         F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
455     {
456         match f(self) {
457             Ok(val) => Some(val),
458             Err(error) => {
459                 trace!("InterpCx operation failed: {:?}", error);
460                 // Some errors shouldn't come up because creating them causes
461                 // an allocation, which we should avoid. When that happens,
462                 // dedicated error variants should be introduced instead.
463                 assert!(
464                     !error.kind().formatted_string(),
465                     "const-prop encountered formatting error: {}",
466                     error
467                 );
468                 None
469             }
470         }
471     }
472
473     /// Returns the value, if any, of evaluating `c`.
474     fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
475         // FIXME we need to revisit this for #67176
476         if c.needs_subst() {
477             return None;
478         }
479
480         match self.ecx.mir_const_to_op(&c.literal, None) {
481             Ok(op) => Some(op),
482             Err(error) => {
483                 let tcx = self.ecx.tcx.at(c.span);
484                 let err = ConstEvalErr::new(&self.ecx, error, Some(c.span));
485                 if let Some(lint_root) = self.lint_root(source_info) {
486                     let lint_only = match c.literal {
487                         ConstantKind::Ty(ct) => match ct.val {
488                             // Promoteds must lint and not error as the user didn't ask for them
489                             ConstKind::Unevaluated(ty::Unevaluated {
490                                 def: _,
491                                 substs: _,
492                                 promoted: Some(_),
493                             }) => true,
494                             // Out of backwards compatibility we cannot report hard errors in unused
495                             // generic functions using associated constants of the generic parameters.
496                             _ => c.literal.needs_subst(),
497                         },
498                         ConstantKind::Val(_, ty) => ty.needs_subst(),
499                     };
500                     if lint_only {
501                         // Out of backwards compatibility we cannot report hard errors in unused
502                         // generic functions using associated constants of the generic parameters.
503                         err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
504                     } else {
505                         err.report_as_error(tcx, "erroneous constant used");
506                     }
507                 } else {
508                     err.report_as_error(tcx, "erroneous constant used");
509                 }
510                 None
511             }
512         }
513     }
514
515     /// Returns the value, if any, of evaluating `place`.
516     fn eval_place(&mut self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
517         trace!("eval_place(place={:?})", place);
518         self.use_ecx(|this| this.ecx.eval_place_to_op(place, None))
519     }
520
521     /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
522     /// or `eval_place`, depending on the variant of `Operand` used.
523     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
524         match *op {
525             Operand::Constant(ref c) => self.eval_constant(c, source_info),
526             Operand::Move(place) | Operand::Copy(place) => self.eval_place(place),
527         }
528     }
529
530     fn report_assert_as_lint(
531         &self,
532         lint: &'static lint::Lint,
533         source_info: SourceInfo,
534         message: &'static str,
535         panic: AssertKind<impl std::fmt::Debug>,
536     ) {
537         if let Some(lint_root) = self.lint_root(source_info) {
538             self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
539                 let mut err = lint.build(message);
540                 err.span_label(source_info.span, format!("{:?}", panic));
541                 err.emit()
542             });
543         }
544     }
545
546     fn check_unary_op(
547         &mut self,
548         op: UnOp,
549         arg: &Operand<'tcx>,
550         source_info: SourceInfo,
551     ) -> Option<()> {
552         if let (val, true) = self.use_ecx(|this| {
553             let val = this.ecx.read_immediate(&this.ecx.eval_operand(arg, None)?)?;
554             let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, &val)?;
555             Ok((val, overflow))
556         })? {
557             // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
558             // appropriate to use.
559             assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
560             self.report_assert_as_lint(
561                 lint::builtin::ARITHMETIC_OVERFLOW,
562                 source_info,
563                 "this arithmetic operation will overflow",
564                 AssertKind::OverflowNeg(val.to_const_int()),
565             );
566             return None;
567         }
568
569         Some(())
570     }
571
572     fn check_binary_op(
573         &mut self,
574         op: BinOp,
575         left: &Operand<'tcx>,
576         right: &Operand<'tcx>,
577         source_info: SourceInfo,
578     ) -> Option<()> {
579         let r = self.use_ecx(|this| this.ecx.read_immediate(&this.ecx.eval_operand(right, None)?));
580         let l = self.use_ecx(|this| this.ecx.read_immediate(&this.ecx.eval_operand(left, None)?));
581         // Check for exceeding shifts *even if* we cannot evaluate the LHS.
582         if op == BinOp::Shr || op == BinOp::Shl {
583             let r = r?;
584             // We need the type of the LHS. We cannot use `place_layout` as that is the type
585             // of the result, which for checked binops is not the same!
586             let left_ty = left.ty(&self.local_decls, self.tcx);
587             let left_size = self.ecx.layout_of(left_ty).ok()?.size;
588             let right_size = r.layout.size;
589             let r_bits = r.to_scalar().ok();
590             let r_bits = r_bits.and_then(|r| r.to_bits(right_size).ok());
591             if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
592                 debug!("check_binary_op: reporting assert for {:?}", source_info);
593                 self.report_assert_as_lint(
594                     lint::builtin::ARITHMETIC_OVERFLOW,
595                     source_info,
596                     "this arithmetic operation will overflow",
597                     AssertKind::Overflow(
598                         op,
599                         match l {
600                             Some(l) => l.to_const_int(),
601                             // Invent a dummy value, the diagnostic ignores it anyway
602                             None => ConstInt::new(
603                                 ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
604                                 left_ty.is_signed(),
605                                 left_ty.is_ptr_sized_integral(),
606                             ),
607                         },
608                         r.to_const_int(),
609                     ),
610                 );
611                 return None;
612             }
613         }
614
615         if let (Some(l), Some(r)) = (&l, &r) {
616             // The remaining operators are handled through `overflowing_binary_op`.
617             if self.use_ecx(|this| {
618                 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, l, r)?;
619                 Ok(overflow)
620             })? {
621                 self.report_assert_as_lint(
622                     lint::builtin::ARITHMETIC_OVERFLOW,
623                     source_info,
624                     "this arithmetic operation will overflow",
625                     AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
626                 );
627                 return None;
628             }
629         }
630         Some(())
631     }
632
633     fn propagate_operand(&mut self, operand: &mut Operand<'tcx>) {
634         match *operand {
635             Operand::Copy(l) | Operand::Move(l) => {
636                 if let Some(value) = self.get_const(l) {
637                     if self.should_const_prop(&value) {
638                         // FIXME(felix91gr): this code only handles `Scalar` cases.
639                         // For now, we're not handling `ScalarPair` cases because
640                         // doing so here would require a lot of code duplication.
641                         // We should hopefully generalize `Operand` handling into a fn,
642                         // and use it to do const-prop here and everywhere else
643                         // where it makes sense.
644                         if let interpret::Operand::Immediate(interpret::Immediate::Scalar(
645                             ScalarMaybeUninit::Scalar(scalar),
646                         )) = *value
647                         {
648                             *operand = self.operand_from_scalar(
649                                 scalar,
650                                 value.layout.ty,
651                                 self.source_info.unwrap().span,
652                             );
653                         }
654                     }
655                 }
656             }
657             Operand::Constant(_) => (),
658         }
659     }
660
661     fn const_prop(
662         &mut self,
663         rvalue: &Rvalue<'tcx>,
664         source_info: SourceInfo,
665         place: Place<'tcx>,
666     ) -> Option<()> {
667         // Perform any special handling for specific Rvalue types.
668         // Generally, checks here fall into one of two categories:
669         //   1. Additional checking to provide useful lints to the user
670         //        - In this case, we will do some validation and then fall through to the
671         //          end of the function which evals the assignment.
672         //   2. Working around bugs in other parts of the compiler
673         //        - In this case, we'll return `None` from this function to stop evaluation.
674         match rvalue {
675             // Additional checking: give lints to the user if an overflow would occur.
676             // We do this here and not in the `Assert` terminator as that terminator is
677             // only sometimes emitted (overflow checks can be disabled), but we want to always
678             // lint.
679             Rvalue::UnaryOp(op, arg) => {
680                 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
681                 self.check_unary_op(*op, arg, source_info)?;
682             }
683             Rvalue::BinaryOp(op, box (left, right)) => {
684                 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
685                 self.check_binary_op(*op, left, right, source_info)?;
686             }
687             Rvalue::CheckedBinaryOp(op, box (left, right)) => {
688                 trace!(
689                     "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
690                     op,
691                     left,
692                     right
693                 );
694                 self.check_binary_op(*op, left, right, source_info)?;
695             }
696
697             // Do not try creating references (#67862)
698             Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
699                 trace!("skipping AddressOf | Ref for {:?}", place);
700
701                 // This may be creating mutable references or immutable references to cells.
702                 // If that happens, the pointed to value could be mutated via that reference.
703                 // Since we aren't tracking references, the const propagator loses track of what
704                 // value the local has right now.
705                 // Thus, all locals that have their reference taken
706                 // must not take part in propagation.
707                 Self::remove_const(&mut self.ecx, place.local);
708
709                 return None;
710             }
711             Rvalue::ThreadLocalRef(def_id) => {
712                 trace!("skipping ThreadLocalRef({:?})", def_id);
713
714                 return None;
715             }
716
717             // There's no other checking to do at this time.
718             Rvalue::Aggregate(..)
719             | Rvalue::Use(..)
720             | Rvalue::Repeat(..)
721             | Rvalue::Len(..)
722             | Rvalue::Cast(..)
723             | Rvalue::ShallowInitBox(..)
724             | Rvalue::Discriminant(..)
725             | Rvalue::NullaryOp(..) => {}
726         }
727
728         // FIXME we need to revisit this for #67176
729         if rvalue.needs_subst() {
730             return None;
731         }
732
733         if self.tcx.sess.mir_opt_level() >= 4 {
734             self.eval_rvalue_with_identities(rvalue, place)
735         } else {
736             self.use_ecx(|this| this.ecx.eval_rvalue_into_place(rvalue, place))
737         }
738     }
739
740     // Attempt to use albegraic identities to eliminate constant expressions
741     fn eval_rvalue_with_identities(
742         &mut self,
743         rvalue: &Rvalue<'tcx>,
744         place: Place<'tcx>,
745     ) -> Option<()> {
746         self.use_ecx(|this| match rvalue {
747             Rvalue::BinaryOp(op, box (left, right))
748             | Rvalue::CheckedBinaryOp(op, box (left, right)) => {
749                 let l = this.ecx.eval_operand(left, None);
750                 let r = this.ecx.eval_operand(right, None);
751
752                 let const_arg = match (l, r) {
753                     (Ok(ref x), Err(_)) | (Err(_), Ok(ref x)) => this.ecx.read_immediate(x)?,
754                     (Err(e), Err(_)) => return Err(e),
755                     (Ok(_), Ok(_)) => return this.ecx.eval_rvalue_into_place(rvalue, place),
756                 };
757
758                 let arg_value = const_arg.to_scalar()?.to_bits(const_arg.layout.size)?;
759                 let dest = this.ecx.eval_place(place)?;
760
761                 match op {
762                     BinOp::BitAnd if arg_value == 0 => this.ecx.write_immediate(*const_arg, &dest),
763                     BinOp::BitOr
764                         if arg_value == const_arg.layout.size.truncate(u128::MAX)
765                             || (const_arg.layout.ty.is_bool() && arg_value == 1) =>
766                     {
767                         this.ecx.write_immediate(*const_arg, &dest)
768                     }
769                     BinOp::Mul if const_arg.layout.ty.is_integral() && arg_value == 0 => {
770                         if let Rvalue::CheckedBinaryOp(_, _) = rvalue {
771                             let val = Immediate::ScalarPair(
772                                 const_arg.to_scalar()?.into(),
773                                 Scalar::from_bool(false).into(),
774                             );
775                             this.ecx.write_immediate(val, &dest)
776                         } else {
777                             this.ecx.write_immediate(*const_arg, &dest)
778                         }
779                     }
780                     _ => this.ecx.eval_rvalue_into_place(rvalue, place),
781                 }
782             }
783             _ => this.ecx.eval_rvalue_into_place(rvalue, place),
784         })
785     }
786
787     /// Creates a new `Operand::Constant` from a `Scalar` value
788     fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
789         Operand::Constant(Box::new(Constant {
790             span,
791             user_ty: None,
792             literal: ty::Const::from_scalar(self.tcx, scalar, ty).into(),
793         }))
794     }
795
796     fn replace_with_const(
797         &mut self,
798         rval: &mut Rvalue<'tcx>,
799         value: &OpTy<'tcx>,
800         source_info: SourceInfo,
801     ) {
802         if let Rvalue::Use(Operand::Constant(c)) = rval {
803             match c.literal {
804                 ConstantKind::Ty(c) if matches!(c.val, ConstKind::Unevaluated(..)) => {}
805                 _ => {
806                     trace!("skipping replace of Rvalue::Use({:?} because it is already a const", c);
807                     return;
808                 }
809             }
810         }
811
812         trace!("attempting to replace {:?} with {:?}", rval, value);
813         if let Err(e) = self.ecx.const_validate_operand(
814             value,
815             vec![],
816             // FIXME: is ref tracking too expensive?
817             // FIXME: what is the point of ref tracking if we do not even check the tracked refs?
818             &mut interpret::RefTracking::empty(),
819             CtfeValidationMode::Regular,
820         ) {
821             trace!("validation error, attempt failed: {:?}", e);
822             return;
823         }
824
825         // FIXME> figure out what to do when try_read_immediate fails
826         let imm = self.use_ecx(|this| this.ecx.try_read_immediate(value));
827
828         if let Some(Ok(imm)) = imm {
829             match *imm {
830                 interpret::Immediate::Scalar(ScalarMaybeUninit::Scalar(scalar)) => {
831                     *rval = Rvalue::Use(self.operand_from_scalar(
832                         scalar,
833                         value.layout.ty,
834                         source_info.span,
835                     ));
836                 }
837                 Immediate::ScalarPair(
838                     ScalarMaybeUninit::Scalar(_),
839                     ScalarMaybeUninit::Scalar(_),
840                 ) => {
841                     // Found a value represented as a pair. For now only do const-prop if the type
842                     // of `rvalue` is also a tuple with two scalars.
843                     // FIXME: enable the general case stated above ^.
844                     let ty = &value.layout.ty;
845                     // Only do it for tuples
846                     if let ty::Tuple(substs) = ty.kind() {
847                         // Only do it if tuple is also a pair with two scalars
848                         if substs.len() == 2 {
849                             let alloc = self.use_ecx(|this| {
850                                 let ty1 = substs[0].expect_ty();
851                                 let ty2 = substs[1].expect_ty();
852                                 let ty_is_scalar = |ty| {
853                                     this.ecx.layout_of(ty).ok().map(|layout| layout.abi.is_scalar())
854                                         == Some(true)
855                                 };
856                                 if ty_is_scalar(ty1) && ty_is_scalar(ty2) {
857                                     let alloc = this
858                                         .ecx
859                                         .intern_with_temp_alloc(value.layout, |ecx, dest| {
860                                             ecx.write_immediate(*imm, dest)
861                                         })
862                                         .unwrap();
863                                     Ok(Some(alloc))
864                                 } else {
865                                     Ok(None)
866                                 }
867                             });
868
869                             if let Some(Some(alloc)) = alloc {
870                                 // Assign entire constant in a single statement.
871                                 // We can't use aggregates, as we run after the aggregate-lowering `MirPhase`.
872                                 *rval = Rvalue::Use(Operand::Constant(Box::new(Constant {
873                                     span: source_info.span,
874                                     user_ty: None,
875                                     literal: self
876                                         .ecx
877                                         .tcx
878                                         .mk_const(ty::Const {
879                                             ty,
880                                             val: ty::ConstKind::Value(ConstValue::ByRef {
881                                                 alloc,
882                                                 offset: Size::ZERO,
883                                             }),
884                                         })
885                                         .into(),
886                                 })));
887                             }
888                         }
889                     }
890                 }
891                 // Scalars or scalar pairs that contain undef values are assumed to not have
892                 // successfully evaluated and are thus not propagated.
893                 _ => {}
894             }
895         }
896     }
897
898     /// Returns `true` if and only if this `op` should be const-propagated into.
899     fn should_const_prop(&mut self, op: &OpTy<'tcx>) -> bool {
900         let mir_opt_level = self.tcx.sess.mir_opt_level();
901
902         if mir_opt_level == 0 {
903             return false;
904         }
905
906         if !self.tcx.consider_optimizing(|| format!("ConstantPropagation - OpTy: {:?}", op)) {
907             return false;
908         }
909
910         match **op {
911             interpret::Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Scalar(s))) => {
912                 s.try_to_int().is_ok()
913             }
914             interpret::Operand::Immediate(Immediate::ScalarPair(
915                 ScalarMaybeUninit::Scalar(l),
916                 ScalarMaybeUninit::Scalar(r),
917             )) => l.try_to_int().is_ok() && r.try_to_int().is_ok(),
918             _ => false,
919         }
920     }
921 }
922
923 /// The mode that `ConstProp` is allowed to run in for a given `Local`.
924 #[derive(Clone, Copy, Debug, PartialEq)]
925 enum ConstPropMode {
926     /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
927     FullConstProp,
928     /// The `Local` can only be propagated into and from its own block.
929     OnlyInsideOwnBlock,
930     /// The `Local` can be propagated into but reads cannot be propagated.
931     OnlyPropagateInto,
932     /// The `Local` cannot be part of propagation at all. Any statement
933     /// referencing it either for reading or writing will not get propagated.
934     NoPropagation,
935 }
936
937 struct CanConstProp {
938     can_const_prop: IndexVec<Local, ConstPropMode>,
939     // False at the beginning. Once set, no more assignments are allowed to that local.
940     found_assignment: BitSet<Local>,
941     // Cache of locals' information
942     local_kinds: IndexVec<Local, LocalKind>,
943 }
944
945 impl CanConstProp {
946     /// Returns true if `local` can be propagated
947     fn check<'tcx>(
948         tcx: TyCtxt<'tcx>,
949         param_env: ParamEnv<'tcx>,
950         body: &Body<'tcx>,
951     ) -> IndexVec<Local, ConstPropMode> {
952         let mut cpv = CanConstProp {
953             can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
954             found_assignment: BitSet::new_empty(body.local_decls.len()),
955             local_kinds: IndexVec::from_fn_n(
956                 |local| body.local_kind(local),
957                 body.local_decls.len(),
958             ),
959         };
960         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
961             let ty = body.local_decls[local].ty;
962             match tcx.layout_of(param_env.and(ty)) {
963                 Ok(layout) if layout.size < Size::from_bytes(MAX_ALLOC_LIMIT) => {}
964                 // Either the layout fails to compute, then we can't use this local anyway
965                 // or the local is too large, then we don't want to.
966                 _ => {
967                     *val = ConstPropMode::NoPropagation;
968                     continue;
969                 }
970             }
971             // Cannot use args at all
972             // Cannot use locals because if x < y { y - x } else { x - y } would
973             //        lint for x != y
974             // FIXME(oli-obk): lint variables until they are used in a condition
975             // FIXME(oli-obk): lint if return value is constant
976             if cpv.local_kinds[local] == LocalKind::Arg {
977                 *val = ConstPropMode::OnlyPropagateInto;
978                 trace!(
979                     "local {:?} can't be const propagated because it's a function argument",
980                     local
981                 );
982             } else if cpv.local_kinds[local] == LocalKind::Var {
983                 *val = ConstPropMode::OnlyInsideOwnBlock;
984                 trace!(
985                     "local {:?} will only be propagated inside its block, because it's a user variable",
986                     local
987                 );
988             }
989         }
990         cpv.visit_body(&body);
991         cpv.can_const_prop
992     }
993 }
994
995 impl Visitor<'_> for CanConstProp {
996     fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
997         use rustc_middle::mir::visit::PlaceContext::*;
998         match context {
999             // Projections are fine, because `&mut foo.x` will be caught by
1000             // `MutatingUseContext::Borrow` elsewhere.
1001             MutatingUse(MutatingUseContext::Projection)
1002             // These are just stores, where the storing is not propagatable, but there may be later
1003             // mutations of the same local via `Store`
1004             | MutatingUse(MutatingUseContext::Call)
1005             | MutatingUse(MutatingUseContext::AsmOutput)
1006             // Actual store that can possibly even propagate a value
1007             | MutatingUse(MutatingUseContext::Store) => {
1008                 if !self.found_assignment.insert(local) {
1009                     match &mut self.can_const_prop[local] {
1010                         // If the local can only get propagated in its own block, then we don't have
1011                         // to worry about multiple assignments, as we'll nuke the const state at the
1012                         // end of the block anyway, and inside the block we overwrite previous
1013                         // states as applicable.
1014                         ConstPropMode::OnlyInsideOwnBlock => {}
1015                         ConstPropMode::NoPropagation => {}
1016                         ConstPropMode::OnlyPropagateInto => {}
1017                         other @ ConstPropMode::FullConstProp => {
1018                             trace!(
1019                                 "local {:?} can't be propagated because of multiple assignments. Previous state: {:?}",
1020                                 local, other,
1021                             );
1022                             *other = ConstPropMode::OnlyInsideOwnBlock;
1023                         }
1024                     }
1025                 }
1026             }
1027             // Reading constants is allowed an arbitrary number of times
1028             NonMutatingUse(NonMutatingUseContext::Copy)
1029             | NonMutatingUse(NonMutatingUseContext::Move)
1030             | NonMutatingUse(NonMutatingUseContext::Inspect)
1031             | NonMutatingUse(NonMutatingUseContext::Projection)
1032             | NonUse(_) => {}
1033
1034             // These could be propagated with a smarter analysis or just some careful thinking about
1035             // whether they'd be fine right now.
1036             MutatingUse(MutatingUseContext::Yield)
1037             | MutatingUse(MutatingUseContext::Drop)
1038             | MutatingUse(MutatingUseContext::Retag)
1039             // These can't ever be propagated under any scheme, as we can't reason about indirect
1040             // mutation.
1041             | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
1042             | NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
1043             | NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
1044             | NonMutatingUse(NonMutatingUseContext::AddressOf)
1045             | MutatingUse(MutatingUseContext::Borrow)
1046             | MutatingUse(MutatingUseContext::AddressOf) => {
1047                 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
1048                 self.can_const_prop[local] = ConstPropMode::NoPropagation;
1049             }
1050         }
1051     }
1052 }
1053
1054 impl<'tcx> MutVisitor<'tcx> for ConstPropagator<'_, 'tcx> {
1055     fn tcx(&self) -> TyCtxt<'tcx> {
1056         self.tcx
1057     }
1058
1059     fn visit_body(&mut self, body: &mut Body<'tcx>) {
1060         for (bb, data) in body.basic_blocks_mut().iter_enumerated_mut() {
1061             self.visit_basic_block_data(bb, data);
1062         }
1063     }
1064
1065     fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1066         self.super_operand(operand, location);
1067
1068         // Only const prop copies and moves on `mir_opt_level=3` as doing so
1069         // currently slightly increases compile time in some cases.
1070         if self.tcx.sess.mir_opt_level() >= 3 {
1071             self.propagate_operand(operand)
1072         }
1073     }
1074
1075     fn visit_constant(&mut self, constant: &mut Constant<'tcx>, location: Location) {
1076         trace!("visit_constant: {:?}", constant);
1077         self.super_constant(constant, location);
1078         self.eval_constant(constant, self.source_info.unwrap());
1079     }
1080
1081     fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1082         trace!("visit_statement: {:?}", statement);
1083         let source_info = statement.source_info;
1084         self.source_info = Some(source_info);
1085         if let StatementKind::Assign(box (place, ref mut rval)) = statement.kind {
1086             let can_const_prop = self.ecx.machine.can_const_prop[place.local];
1087             if let Some(()) = self.const_prop(rval, source_info, place) {
1088                 // This will return None if the above `const_prop` invocation only "wrote" a
1089                 // type whose creation requires no write. E.g. a generator whose initial state
1090                 // consists solely of uninitialized memory (so it doesn't capture any locals).
1091                 if let Some(ref value) = self.get_const(place) {
1092                     if self.should_const_prop(value) {
1093                         trace!("replacing {:?} with {:?}", rval, value);
1094                         self.replace_with_const(rval, value, source_info);
1095                         if can_const_prop == ConstPropMode::FullConstProp
1096                             || can_const_prop == ConstPropMode::OnlyInsideOwnBlock
1097                         {
1098                             trace!("propagated into {:?}", place);
1099                         }
1100                     }
1101                 }
1102                 match can_const_prop {
1103                     ConstPropMode::OnlyInsideOwnBlock => {
1104                         trace!(
1105                             "found local restricted to its block. \
1106                                 Will remove it from const-prop after block is finished. Local: {:?}",
1107                             place.local
1108                         );
1109                     }
1110                     ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1111                         trace!("can't propagate into {:?}", place);
1112                         if place.local != RETURN_PLACE {
1113                             Self::remove_const(&mut self.ecx, place.local);
1114                         }
1115                     }
1116                     ConstPropMode::FullConstProp => {}
1117                 }
1118             } else {
1119                 // Const prop failed, so erase the destination, ensuring that whatever happens
1120                 // from here on, does not know about the previous value.
1121                 // This is important in case we have
1122                 // ```rust
1123                 // let mut x = 42;
1124                 // x = SOME_MUTABLE_STATIC;
1125                 // // x must now be uninit
1126                 // ```
1127                 // FIXME: we overzealously erase the entire local, because that's easier to
1128                 // implement.
1129                 trace!(
1130                     "propagation into {:?} failed.
1131                         Nuking the entire site from orbit, it's the only way to be sure",
1132                     place,
1133                 );
1134                 Self::remove_const(&mut self.ecx, place.local);
1135             }
1136         } else {
1137             match statement.kind {
1138                 StatementKind::SetDiscriminant { ref place, .. } => {
1139                     match self.ecx.machine.can_const_prop[place.local] {
1140                         ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
1141                             if self.use_ecx(|this| this.ecx.statement(statement)).is_some() {
1142                                 trace!("propped discriminant into {:?}", place);
1143                             } else {
1144                                 Self::remove_const(&mut self.ecx, place.local);
1145                             }
1146                         }
1147                         ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
1148                             Self::remove_const(&mut self.ecx, place.local);
1149                         }
1150                     }
1151                 }
1152                 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
1153                     let frame = self.ecx.frame_mut();
1154                     frame.locals[local].value =
1155                         if let StatementKind::StorageLive(_) = statement.kind {
1156                             LocalValue::Uninitialized
1157                         } else {
1158                             LocalValue::Dead
1159                         };
1160                 }
1161                 _ => {}
1162             }
1163         }
1164
1165         self.super_statement(statement, location);
1166     }
1167
1168     fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1169         let source_info = terminator.source_info;
1170         self.source_info = Some(source_info);
1171         self.super_terminator(terminator, location);
1172         match &mut terminator.kind {
1173             TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
1174                 if let Some(ref value) = self.eval_operand(&cond, source_info) {
1175                     trace!("assertion on {:?} should be {:?}", value, expected);
1176                     let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
1177                     let value_const = self.ecx.read_scalar(&value).unwrap();
1178                     if expected != value_const {
1179                         enum DbgVal<T> {
1180                             Val(T),
1181                             Underscore,
1182                         }
1183                         impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
1184                             fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1185                                 match self {
1186                                     Self::Val(val) => val.fmt(fmt),
1187                                     Self::Underscore => fmt.write_str("_"),
1188                                 }
1189                             }
1190                         }
1191                         let mut eval_to_int = |op| {
1192                             // This can be `None` if the lhs wasn't const propagated and we just
1193                             // triggered the assert on the value of the rhs.
1194                             self.eval_operand(op, source_info).map_or(DbgVal::Underscore, |op| {
1195                                 DbgVal::Val(self.ecx.read_immediate(&op).unwrap().to_const_int())
1196                             })
1197                         };
1198                         let msg = match msg {
1199                             AssertKind::DivisionByZero(op) => {
1200                                 Some(AssertKind::DivisionByZero(eval_to_int(op)))
1201                             }
1202                             AssertKind::RemainderByZero(op) => {
1203                                 Some(AssertKind::RemainderByZero(eval_to_int(op)))
1204                             }
1205                             AssertKind::BoundsCheck { ref len, ref index } => {
1206                                 let len = eval_to_int(len);
1207                                 let index = eval_to_int(index);
1208                                 Some(AssertKind::BoundsCheck { len, index })
1209                             }
1210                             // Overflow is are already covered by checks on the binary operators.
1211                             AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
1212                             // Need proper const propagator for these.
1213                             _ => None,
1214                         };
1215                         // Poison all places this operand references so that further code
1216                         // doesn't use the invalid value
1217                         match cond {
1218                             Operand::Move(ref place) | Operand::Copy(ref place) => {
1219                                 Self::remove_const(&mut self.ecx, place.local);
1220                             }
1221                             Operand::Constant(_) => {}
1222                         }
1223                         if let Some(msg) = msg {
1224                             self.report_assert_as_lint(
1225                                 lint::builtin::UNCONDITIONAL_PANIC,
1226                                 source_info,
1227                                 "this operation will panic at runtime",
1228                                 msg,
1229                             );
1230                         }
1231                     } else {
1232                         if self.should_const_prop(value) {
1233                             if let ScalarMaybeUninit::Scalar(scalar) = value_const {
1234                                 *cond = self.operand_from_scalar(
1235                                     scalar,
1236                                     self.tcx.types.bool,
1237                                     source_info.span,
1238                                 );
1239                             }
1240                         }
1241                     }
1242                 }
1243             }
1244             TerminatorKind::SwitchInt { ref mut discr, .. } => {
1245                 // FIXME: This is currently redundant with `visit_operand`, but sadly
1246                 // always visiting operands currently causes a perf regression in LLVM codegen, so
1247                 // `visit_operand` currently only runs for propagates places for `mir_opt_level=4`.
1248                 self.propagate_operand(discr)
1249             }
1250             // None of these have Operands to const-propagate.
1251             TerminatorKind::Goto { .. }
1252             | TerminatorKind::Resume
1253             | TerminatorKind::Abort
1254             | TerminatorKind::Return
1255             | TerminatorKind::Unreachable
1256             | TerminatorKind::Drop { .. }
1257             | TerminatorKind::DropAndReplace { .. }
1258             | TerminatorKind::Yield { .. }
1259             | TerminatorKind::GeneratorDrop
1260             | TerminatorKind::FalseEdge { .. }
1261             | TerminatorKind::FalseUnwind { .. }
1262             | TerminatorKind::InlineAsm { .. } => {}
1263             // Every argument in our function calls have already been propagated in `visit_operand`.
1264             //
1265             // NOTE: because LLVM codegen gives slight performance regressions with it, so this is
1266             // gated on `mir_opt_level=3`.
1267             TerminatorKind::Call { .. } => {}
1268         }
1269
1270         // We remove all Locals which are restricted in propagation to their containing blocks and
1271         // which were modified in the current block.
1272         // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
1273         let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
1274         for &local in locals.iter() {
1275             Self::remove_const(&mut self.ecx, local);
1276         }
1277         locals.clear();
1278         // Put it back so we reuse the heap of the storage
1279         self.ecx.machine.written_only_inside_own_block_locals = locals;
1280         if cfg!(debug_assertions) {
1281             // Ensure we are correctly erasing locals with the non-debug-assert logic.
1282             for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
1283                 assert!(
1284                     self.get_const(local.into()).is_none()
1285                         || self
1286                             .layout_of(self.local_decls[local].ty)
1287                             .map_or(true, |layout| layout.is_zst())
1288                 )
1289             }
1290         }
1291     }
1292 }