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