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