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