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