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