1 //! Propagates constants for early reporting of statically known
6 use rustc_ast::Mutability;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_hir::def::DefKind;
10 use rustc_index::bit_set::BitSet;
11 use rustc_index::vec::IndexVec;
12 use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
13 use rustc_middle::mir::{
14 AssertKind, BasicBlock, BinOp, Body, Constant, ConstantKind, Local, LocalDecl, LocalKind,
15 Location, Operand, Place, Rvalue, SourceInfo, SourceScope, SourceScopeData, Statement,
16 StatementKind, Terminator, TerminatorKind, UnOp, RETURN_PLACE,
18 use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout};
19 use rustc_middle::ty::subst::{InternalSubsts, Subst};
20 use rustc_middle::ty::{
21 self, ConstInt, ConstKind, EarlyBinder, Instance, ParamEnv, ScalarInt, Ty, TyCtxt,
24 use rustc_session::lint;
25 use rustc_span::{def_id::DefId, Span};
26 use rustc_target::abi::{HasDataLayout, Size, TargetDataLayout};
27 use rustc_target::spec::abi::Abi as CallAbi;
28 use rustc_trait_selection::traits;
31 use rustc_const_eval::const_eval::ConstEvalErr;
32 use rustc_const_eval::interpret::{
33 self, compile_time_machine, AllocId, ConstAllocation, Frame, ImmTy, InterpCx, InterpResult,
34 LocalState, LocalValue, MemoryKind, OpTy, PlaceTy, Pointer, Scalar, ScalarMaybeUninit,
35 StackPopCleanup, StackPopUnwind,
38 /// The maximum number of bytes that we'll allocate space for a local or the return value.
39 /// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
40 /// Severely regress performance.
41 const MAX_ALLOC_LIMIT: u64 = 1024;
43 /// Macro for machine-specific `InterpError` without allocation.
44 /// (These will never be shown to the user, but they help diagnose ICEs.)
45 macro_rules! throw_machine_stop_str {
47 // We make a new local type for it. The type itself does not carry any information,
48 // but its vtable (for the `MachineStopType` trait) does.
50 // Printing this type shows the desired string.
51 impl std::fmt::Display for Zst {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 impl rustc_middle::mir::interpret::MachineStopType for Zst {}
57 throw_machine_stop!(Zst)
63 impl<'tcx> MirLint<'tcx> for ConstProp {
64 fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
65 // will be evaluated by miri and produce its errors there
66 if body.source.promoted.is_some() {
70 let def_id = body.source.def_id().expect_local();
71 let is_fn_like = tcx.def_kind(def_id).is_fn_like();
72 let is_assoc_const = tcx.def_kind(def_id) == DefKind::AssocConst;
74 // Only run const prop on functions, methods, closures and associated constants
75 if !is_fn_like && !is_assoc_const {
76 // skip anon_const/statics/consts because they'll be evaluated by miri anyway
77 trace!("ConstProp skipped for {:?}", def_id);
81 let is_generator = tcx.type_of(def_id.to_def_id()).is_generator();
82 // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
83 // computing their layout.
85 trace!("ConstProp skipped for generator {:?}", def_id);
89 // Check if it's even possible to satisfy the 'where' clauses
91 // This branch will never be taken for any normal function.
92 // However, it's possible to `#!feature(trivial_bounds)]` to write
93 // a function with impossible to satisfy clauses, e.g.:
94 // `fn foo() where String: Copy {}`
96 // We don't usually need to worry about this kind of case,
97 // since we would get a compilation error if the user tried
98 // to call it. However, since we can do const propagation
99 // even without any calls to the function, we need to make
100 // sure that it even makes sense to try to evaluate the body.
101 // If there are unsatisfiable where clauses, then all bets are
102 // off, and we just give up.
104 // We manually filter the predicates, skipping anything that's not
105 // "global". We are in a potentially generic context
106 // (e.g. we are evaluating a function without substituting generic
107 // parameters, so this filtering serves two purposes:
109 // 1. We skip evaluating any predicates that we would
110 // never be able prove are unsatisfiable (e.g. `<T as Foo>`
111 // 2. We avoid trying to normalize predicates involving generic
112 // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
113 // the normalization code (leading to cycle errors), since
114 // it's usually never invoked in this way.
116 .predicates_of(def_id.to_def_id())
119 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
120 if traits::impossible_predicates(
122 traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
124 trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", def_id);
128 trace!("ConstProp starting for {:?}", def_id);
130 let dummy_body = &Body::new(
132 body.basic_blocks().clone(),
133 body.source_scopes.clone(),
134 body.local_decls.clone(),
139 body.generator_kind(),
140 body.tainted_by_errors,
143 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
144 // constants, instead of just checking for const-folding succeeding.
145 // That would require a uniform one-def no-mutation analysis
146 // and RPO (or recursing when needing the value of a local).
147 let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx);
148 optimization_finder.visit_body(body);
150 trace!("ConstProp done for {:?}", def_id);
154 struct ConstPropMachine<'mir, 'tcx> {
155 /// The virtual call stack.
156 stack: Vec<Frame<'mir, 'tcx>>,
157 /// `OnlyInsideOwnBlock` locals that were written in the current block get erased at the end.
158 written_only_inside_own_block_locals: FxHashSet<Local>,
159 /// Locals that need to be cleared after every block terminates.
160 only_propagate_inside_block_locals: BitSet<Local>,
161 can_const_prop: IndexVec<Local, ConstPropMode>,
164 impl ConstPropMachine<'_, '_> {
166 only_propagate_inside_block_locals: BitSet<Local>,
167 can_const_prop: IndexVec<Local, ConstPropMode>,
171 written_only_inside_own_block_locals: Default::default(),
172 only_propagate_inside_block_locals,
178 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx> {
179 compile_time_machine!(<'mir, 'tcx>);
180 const PANIC_ON_ALLOC_FAIL: bool = true; // all allocations are small (see `MAX_ALLOC_LIMIT`)
185 _ecx: &InterpCx<'mir, 'tcx, Self>,
186 _instance: ty::InstanceDef<'tcx>,
187 ) -> InterpResult<'tcx, &'tcx Body<'tcx>> {
188 throw_machine_stop_str!("calling functions isn't supported in ConstProp")
191 fn find_mir_or_eval_fn(
192 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
193 _instance: ty::Instance<'tcx>,
195 _args: &[OpTy<'tcx>],
196 _destination: &PlaceTy<'tcx>,
197 _target: Option<BasicBlock>,
198 _unwind: StackPopUnwind,
199 ) -> InterpResult<'tcx, Option<(&'mir Body<'tcx>, ty::Instance<'tcx>)>> {
204 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
205 _instance: ty::Instance<'tcx>,
206 _args: &[OpTy<'tcx>],
207 _destination: &PlaceTy<'tcx>,
208 _target: Option<BasicBlock>,
209 _unwind: StackPopUnwind,
210 ) -> InterpResult<'tcx> {
211 throw_machine_stop_str!("calling intrinsics isn't supported in ConstProp")
215 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
216 _msg: &rustc_middle::mir::AssertMessage<'tcx>,
217 _unwind: Option<rustc_middle::mir::BasicBlock>,
218 ) -> InterpResult<'tcx> {
219 bug!("panics terminators are not evaluated in ConstProp")
223 _ecx: &InterpCx<'mir, 'tcx, Self>,
226 _right: &ImmTy<'tcx>,
227 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
228 // We can't do this because aliasing of memory can differ between const eval and llvm
229 throw_machine_stop_str!("pointer arithmetic or comparisons aren't supported in ConstProp")
233 frame: &'a Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>,
235 ) -> InterpResult<'tcx, &'a interpret::Operand<Self::PointerTag>> {
236 let l = &frame.locals[local];
240 LocalValue::Live(interpret::Operand::Immediate(interpret::Immediate::Uninit))
242 // For us "uninit" means "we don't know its value, might be initiailized or not".
244 throw_machine_stop_str!("tried to access a local with unknown value")
250 fn access_local_mut<'a>(
251 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
254 ) -> InterpResult<'tcx, &'a mut interpret::Operand<Self::PointerTag>> {
255 if ecx.machine.can_const_prop[local] == ConstPropMode::NoPropagation {
256 throw_machine_stop_str!("tried to write to a local that is marked as not propagatable")
258 if frame == 0 && ecx.machine.only_propagate_inside_block_locals.contains(local) {
260 "mutating local {:?} which is restricted to its block. \
261 Will remove it from const-prop after block is finished.",
264 ecx.machine.written_only_inside_own_block_locals.insert(local);
266 ecx.machine.stack[frame].locals[local].access_mut()
269 fn before_access_global(
273 alloc: ConstAllocation<'tcx, Self::PointerTag, Self::AllocExtra>,
274 _static_def_id: Option<DefId>,
276 ) -> InterpResult<'tcx> {
278 throw_machine_stop_str!("can't write to global");
280 // If the static allocation is mutable, then we can't const prop it as its content
281 // might be different at runtime.
282 if alloc.inner().mutability == Mutability::Mut {
283 throw_machine_stop_str!("can't access mutable globals in ConstProp");
291 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
292 _ptr: Pointer<AllocId>,
293 ) -> InterpResult<'tcx> {
294 throw_machine_stop_str!("exposing pointers isn't supported in ConstProp")
299 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
300 frame: Frame<'mir, 'tcx>,
301 ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
307 ecx: &'a InterpCx<'mir, 'tcx, Self>,
308 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
314 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
315 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
316 &mut ecx.machine.stack
320 /// Finds optimization opportunities on the MIR.
321 struct ConstPropagator<'mir, 'tcx> {
322 ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
324 param_env: ParamEnv<'tcx>,
325 source_scopes: &'mir IndexVec<SourceScope, SourceScopeData<'tcx>>,
326 local_decls: &'mir IndexVec<Local, LocalDecl<'tcx>>,
327 // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
328 // the last known `SourceInfo` here and just keep revisiting it.
329 source_info: Option<SourceInfo>,
332 impl<'tcx> LayoutOfHelpers<'tcx> for ConstPropagator<'_, 'tcx> {
333 type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
336 fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
341 impl HasDataLayout for ConstPropagator<'_, '_> {
343 fn data_layout(&self) -> &TargetDataLayout {
344 &self.tcx.data_layout
348 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for ConstPropagator<'_, 'tcx> {
350 fn tcx(&self) -> TyCtxt<'tcx> {
355 impl<'tcx> ty::layout::HasParamEnv<'tcx> for ConstPropagator<'_, 'tcx> {
357 fn param_env(&self) -> ty::ParamEnv<'tcx> {
362 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
365 dummy_body: &'mir Body<'tcx>,
367 ) -> ConstPropagator<'mir, 'tcx> {
368 let def_id = body.source.def_id();
369 let substs = &InternalSubsts::identity_for_item(tcx, def_id);
370 let param_env = tcx.param_env_reveal_all_normalized(def_id);
372 let can_const_prop = CanConstProp::check(tcx, param_env, body);
373 let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
374 for (l, mode) in can_const_prop.iter_enumerated() {
375 if *mode == ConstPropMode::OnlyInsideOwnBlock {
376 only_propagate_inside_block_locals.insert(l);
379 let mut ecx = InterpCx::new(
381 tcx.def_span(def_id),
383 ConstPropMachine::new(only_propagate_inside_block_locals, can_const_prop),
387 .layout_of(EarlyBinder(body.return_ty()).subst(tcx, substs))
389 // Don't bother allocating memory for large values.
390 // I don't know how return types can seem to be unsized but this happens in the
391 // `type/type-unsatisfiable.rs` test.
392 .filter(|ret_layout| {
393 !ret_layout.is_unsized() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
395 .unwrap_or_else(|| ecx.layout_of(tcx.types.unit).unwrap());
398 .allocate(ret_layout, MemoryKind::Stack)
399 .expect("couldn't perform small allocation")
402 ecx.push_stack_frame(
403 Instance::new(def_id, substs),
406 StackPopCleanup::Root { cleanup: false },
408 .expect("failed to push initial stack frame");
414 source_scopes: &dummy_body.source_scopes,
415 local_decls: &dummy_body.local_decls,
420 fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
421 let op = match self.ecx.eval_place_to_op(place, None) {
424 trace!("get_const failed: {}", e);
429 // Try to read the local as an immediate so that if it is representable as a scalar, we can
430 // handle it as such, but otherwise, just return the value as is.
431 Some(match self.ecx.read_immediate_raw(&op, /*force*/ false) {
432 Ok(Ok(imm)) => imm.into(),
437 /// Remove `local` from the pool of `Locals`. Allows writing to them,
438 /// but not reading from them anymore.
439 fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
440 ecx.frame_mut().locals[local] = LocalState {
441 value: LocalValue::Live(interpret::Operand::Immediate(interpret::Immediate::Uninit)),
442 layout: Cell::new(None),
446 fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
447 source_info.scope.lint_root(self.source_scopes)
450 fn use_ecx<F, T>(&mut self, source_info: SourceInfo, f: F) -> Option<T>
452 F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
454 // Overwrite the PC -- whatever the interpreter does to it does not make any sense anyway.
455 self.ecx.frame_mut().loc = Err(source_info.span);
457 Ok(val) => Some(val),
459 trace!("InterpCx operation failed: {:?}", error);
460 // Some errors shouldn't come up because creating them causes
461 // an allocation, which we should avoid. When that happens,
462 // dedicated error variants should be introduced instead.
464 !error.kind().formatted_string(),
465 "const-prop encountered formatting error: {}",
473 /// Returns the value, if any, of evaluating `c`.
474 fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
475 // FIXME we need to revisit this for #67176
480 match self.ecx.mir_const_to_op(&c.literal, None) {
483 let tcx = self.ecx.tcx.at(c.span);
484 let err = ConstEvalErr::new(&self.ecx, error, Some(c.span));
485 if let Some(lint_root) = self.lint_root(source_info) {
486 let lint_only = match c.literal {
487 ConstantKind::Ty(ct) => match ct.kind() {
488 // Promoteds must lint and not error as the user didn't ask for them
489 ConstKind::Unevaluated(ty::Unevaluated {
494 // Out of backwards compatibility we cannot report hard errors in unused
495 // generic functions using associated constants of the generic parameters.
496 _ => c.literal.needs_subst(),
498 ConstantKind::Val(_, ty) => ty.needs_subst(),
501 // Out of backwards compatibility we cannot report hard errors in unused
502 // generic functions using associated constants of the generic parameters.
503 err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
505 err.report_as_error(tcx, "erroneous constant used");
508 err.report_as_error(tcx, "erroneous constant used");
515 /// Returns the value, if any, of evaluating `place`.
516 fn eval_place(&mut self, place: Place<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
517 trace!("eval_place(place={:?})", place);
518 self.use_ecx(source_info, |this| this.ecx.eval_place_to_op(place, None))
521 /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
522 /// or `eval_place`, depending on the variant of `Operand` used.
523 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
525 Operand::Constant(ref c) => self.eval_constant(c, source_info),
526 Operand::Move(place) | Operand::Copy(place) => self.eval_place(place, source_info),
530 fn report_assert_as_lint(
532 lint: &'static lint::Lint,
533 source_info: SourceInfo,
534 message: &'static str,
535 panic: AssertKind<impl std::fmt::Debug>,
537 if let Some(lint_root) = self.lint_root(source_info) {
538 self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
539 let mut err = lint.build(message);
540 err.span_label(source_info.span, format!("{:?}", panic));
550 source_info: SourceInfo,
552 if let (val, true) = self.use_ecx(source_info, |this| {
553 let val = this.ecx.read_immediate(&this.ecx.eval_operand(arg, None)?)?;
554 let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, &val)?;
557 // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
558 // appropriate to use.
559 assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
560 self.report_assert_as_lint(
561 lint::builtin::ARITHMETIC_OVERFLOW,
563 "this arithmetic operation will overflow",
564 AssertKind::OverflowNeg(val.to_const_int()),
575 left: &Operand<'tcx>,
576 right: &Operand<'tcx>,
577 source_info: SourceInfo,
579 let r = self.use_ecx(source_info, |this| {
580 this.ecx.read_immediate(&this.ecx.eval_operand(right, None)?)
582 let l = self.use_ecx(source_info, |this| {
583 this.ecx.read_immediate(&this.ecx.eval_operand(left, None)?)
585 // Check for exceeding shifts *even if* we cannot evaluate the LHS.
586 if op == BinOp::Shr || op == BinOp::Shl {
588 // We need the type of the LHS. We cannot use `place_layout` as that is the type
589 // of the result, which for checked binops is not the same!
590 let left_ty = left.ty(self.local_decls, self.tcx);
591 let left_size = self.ecx.layout_of(left_ty).ok()?.size;
592 let right_size = r.layout.size;
593 let r_bits = r.to_scalar().ok();
594 let r_bits = r_bits.and_then(|r| r.to_bits(right_size).ok());
595 if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
596 debug!("check_binary_op: reporting assert for {:?}", source_info);
597 self.report_assert_as_lint(
598 lint::builtin::ARITHMETIC_OVERFLOW,
600 "this arithmetic operation will overflow",
601 AssertKind::Overflow(
604 Some(l) => l.to_const_int(),
605 // Invent a dummy value, the diagnostic ignores it anyway
606 None => ConstInt::new(
607 ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
609 left_ty.is_ptr_sized_integral(),
619 if let (Some(l), Some(r)) = (&l, &r) {
620 // The remaining operators are handled through `overflowing_binary_op`.
621 if self.use_ecx(source_info, |this| {
622 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, l, r)?;
625 self.report_assert_as_lint(
626 lint::builtin::ARITHMETIC_OVERFLOW,
628 "this arithmetic operation will overflow",
629 AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
639 rvalue: &Rvalue<'tcx>,
640 source_info: SourceInfo,
643 // Perform any special handling for specific Rvalue types.
644 // Generally, checks here fall into one of two categories:
645 // 1. Additional checking to provide useful lints to the user
646 // - In this case, we will do some validation and then fall through to the
647 // end of the function which evals the assignment.
648 // 2. Working around bugs in other parts of the compiler
649 // - In this case, we'll return `None` from this function to stop evaluation.
651 // Additional checking: give lints to the user if an overflow would occur.
652 // We do this here and not in the `Assert` terminator as that terminator is
653 // only sometimes emitted (overflow checks can be disabled), but we want to always
655 Rvalue::UnaryOp(op, arg) => {
656 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
657 self.check_unary_op(*op, arg, source_info)?;
659 Rvalue::BinaryOp(op, box (left, right)) => {
660 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
661 self.check_binary_op(*op, left, right, source_info)?;
663 Rvalue::CheckedBinaryOp(op, box (left, right)) => {
665 "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
670 self.check_binary_op(*op, left, right, source_info)?;
673 // Do not try creating references (#67862)
674 Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
675 trace!("skipping AddressOf | Ref for {:?}", place);
677 // This may be creating mutable references or immutable references to cells.
678 // If that happens, the pointed to value could be mutated via that reference.
679 // Since we aren't tracking references, the const propagator loses track of what
680 // value the local has right now.
681 // Thus, all locals that have their reference taken
682 // must not take part in propagation.
683 Self::remove_const(&mut self.ecx, place.local);
687 Rvalue::ThreadLocalRef(def_id) => {
688 trace!("skipping ThreadLocalRef({:?})", def_id);
693 // There's no other checking to do at this time.
694 Rvalue::Aggregate(..)
696 | Rvalue::CopyForDeref(..)
700 | Rvalue::ShallowInitBox(..)
701 | Rvalue::Discriminant(..)
702 | Rvalue::NullaryOp(..) => {}
705 // FIXME we need to revisit this for #67176
706 if rvalue.needs_subst() {
710 self.use_ecx(source_info, |this| this.ecx.eval_rvalue_into_place(rvalue, place))
714 /// The mode that `ConstProp` is allowed to run in for a given `Local`.
715 #[derive(Clone, Copy, Debug, PartialEq)]
717 /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
719 /// The `Local` can only be propagated into and from its own block.
721 /// The `Local` can be propagated into but reads cannot be propagated.
723 /// The `Local` cannot be part of propagation at all. Any statement
724 /// referencing it either for reading or writing will not get propagated.
728 struct CanConstProp {
729 can_const_prop: IndexVec<Local, ConstPropMode>,
730 // False at the beginning. Once set, no more assignments are allowed to that local.
731 found_assignment: BitSet<Local>,
732 // Cache of locals' information
733 local_kinds: IndexVec<Local, LocalKind>,
737 /// Returns true if `local` can be propagated
740 param_env: ParamEnv<'tcx>,
742 ) -> IndexVec<Local, ConstPropMode> {
743 let mut cpv = CanConstProp {
744 can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
745 found_assignment: BitSet::new_empty(body.local_decls.len()),
746 local_kinds: IndexVec::from_fn_n(
747 |local| body.local_kind(local),
748 body.local_decls.len(),
751 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
752 let ty = body.local_decls[local].ty;
753 match tcx.layout_of(param_env.and(ty)) {
754 Ok(layout) if layout.size < Size::from_bytes(MAX_ALLOC_LIMIT) => {}
755 // Either the layout fails to compute, then we can't use this local anyway
756 // or the local is too large, then we don't want to.
758 *val = ConstPropMode::NoPropagation;
762 // Cannot use args at all
763 // Cannot use locals because if x < y { y - x } else { x - y } would
765 // FIXME(oli-obk): lint variables until they are used in a condition
766 // FIXME(oli-obk): lint if return value is constant
767 if cpv.local_kinds[local] == LocalKind::Arg {
768 *val = ConstPropMode::OnlyPropagateInto;
770 "local {:?} can't be const propagated because it's a function argument",
773 } else if cpv.local_kinds[local] == LocalKind::Var {
774 *val = ConstPropMode::OnlyInsideOwnBlock;
776 "local {:?} will only be propagated inside its block, because it's a user variable",
781 cpv.visit_body(&body);
786 impl Visitor<'_> for CanConstProp {
787 fn visit_local(&mut self, local: Local, context: PlaceContext, _: Location) {
788 use rustc_middle::mir::visit::PlaceContext::*;
790 // Projections are fine, because `&mut foo.x` will be caught by
791 // `MutatingUseContext::Borrow` elsewhere.
792 MutatingUse(MutatingUseContext::Projection)
793 // These are just stores, where the storing is not propagatable, but there may be later
794 // mutations of the same local via `Store`
795 | MutatingUse(MutatingUseContext::Call)
796 | MutatingUse(MutatingUseContext::AsmOutput)
797 | MutatingUse(MutatingUseContext::Deinit)
798 // Actual store that can possibly even propagate a value
799 | MutatingUse(MutatingUseContext::SetDiscriminant)
800 | MutatingUse(MutatingUseContext::Store) => {
801 if !self.found_assignment.insert(local) {
802 match &mut self.can_const_prop[local] {
803 // If the local can only get propagated in its own block, then we don't have
804 // to worry about multiple assignments, as we'll nuke the const state at the
805 // end of the block anyway, and inside the block we overwrite previous
806 // states as applicable.
807 ConstPropMode::OnlyInsideOwnBlock => {}
808 ConstPropMode::NoPropagation => {}
809 ConstPropMode::OnlyPropagateInto => {}
810 other @ ConstPropMode::FullConstProp => {
812 "local {:?} can't be propagated because of multiple assignments. Previous state: {:?}",
815 *other = ConstPropMode::OnlyInsideOwnBlock;
820 // Reading constants is allowed an arbitrary number of times
821 NonMutatingUse(NonMutatingUseContext::Copy)
822 | NonMutatingUse(NonMutatingUseContext::Move)
823 | NonMutatingUse(NonMutatingUseContext::Inspect)
824 | NonMutatingUse(NonMutatingUseContext::Projection)
827 // These could be propagated with a smarter analysis or just some careful thinking about
828 // whether they'd be fine right now.
829 MutatingUse(MutatingUseContext::Yield)
830 | MutatingUse(MutatingUseContext::Drop)
831 | MutatingUse(MutatingUseContext::Retag)
832 // These can't ever be propagated under any scheme, as we can't reason about indirect
834 | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
835 | NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
836 | NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
837 | NonMutatingUse(NonMutatingUseContext::AddressOf)
838 | MutatingUse(MutatingUseContext::Borrow)
839 | MutatingUse(MutatingUseContext::AddressOf) => {
840 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
841 self.can_const_prop[local] = ConstPropMode::NoPropagation;
847 impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> {
848 fn visit_body(&mut self, body: &Body<'tcx>) {
849 for (bb, data) in body.basic_blocks().iter_enumerated() {
850 self.visit_basic_block_data(bb, data);
854 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
855 self.super_operand(operand, location);
858 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
859 trace!("visit_constant: {:?}", constant);
860 self.super_constant(constant, location);
861 self.eval_constant(constant, self.source_info.unwrap());
864 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
865 trace!("visit_statement: {:?}", statement);
866 let source_info = statement.source_info;
867 self.source_info = Some(source_info);
868 if let StatementKind::Assign(box (place, ref rval)) = statement.kind {
869 let can_const_prop = self.ecx.machine.can_const_prop[place.local];
870 if let Some(()) = self.const_prop(rval, source_info, place) {
871 match can_const_prop {
872 ConstPropMode::OnlyInsideOwnBlock => {
874 "found local restricted to its block. \
875 Will remove it from const-prop after block is finished. Local: {:?}",
879 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
880 trace!("can't propagate into {:?}", place);
881 if place.local != RETURN_PLACE {
882 Self::remove_const(&mut self.ecx, place.local);
885 ConstPropMode::FullConstProp => {}
888 // Const prop failed, so erase the destination, ensuring that whatever happens
889 // from here on, does not know about the previous value.
890 // This is important in case we have
893 // x = SOME_MUTABLE_STATIC;
894 // // x must now be uninit
896 // FIXME: we overzealously erase the entire local, because that's easier to
899 "propagation into {:?} failed.
900 Nuking the entire site from orbit, it's the only way to be sure",
903 Self::remove_const(&mut self.ecx, place.local);
906 match statement.kind {
907 StatementKind::SetDiscriminant { ref place, .. } => {
908 match self.ecx.machine.can_const_prop[place.local] {
909 ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
911 .use_ecx(source_info, |this| this.ecx.statement(statement))
914 trace!("propped discriminant into {:?}", place);
916 Self::remove_const(&mut self.ecx, place.local);
919 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
920 Self::remove_const(&mut self.ecx, place.local);
924 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
925 let frame = self.ecx.frame_mut();
926 frame.locals[local].value =
927 if let StatementKind::StorageLive(_) = statement.kind {
928 LocalValue::Live(interpret::Operand::Immediate(
929 interpret::Immediate::Uninit,
939 self.super_statement(statement, location);
942 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
943 let source_info = terminator.source_info;
944 self.source_info = Some(source_info);
945 self.super_terminator(terminator, location);
946 match &terminator.kind {
947 TerminatorKind::Assert { expected, ref msg, ref cond, .. } => {
948 if let Some(ref value) = self.eval_operand(&cond, source_info) {
949 trace!("assertion on {:?} should be {:?}", value, expected);
950 let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
951 let value_const = self.ecx.read_scalar(&value).unwrap();
952 if expected != value_const {
957 impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
958 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
960 Self::Val(val) => val.fmt(fmt),
961 Self::Underscore => fmt.write_str("_"),
965 let mut eval_to_int = |op| {
966 // This can be `None` if the lhs wasn't const propagated and we just
967 // triggered the assert on the value of the rhs.
968 self.eval_operand(op, source_info).map_or(DbgVal::Underscore, |op| {
969 DbgVal::Val(self.ecx.read_immediate(&op).unwrap().to_const_int())
972 let msg = match msg {
973 AssertKind::DivisionByZero(op) => {
974 Some(AssertKind::DivisionByZero(eval_to_int(op)))
976 AssertKind::RemainderByZero(op) => {
977 Some(AssertKind::RemainderByZero(eval_to_int(op)))
979 AssertKind::Overflow(bin_op @ (BinOp::Div | BinOp::Rem), op1, op2) => {
980 // Division overflow is *UB* in the MIR, and different than the
981 // other overflow checks.
982 Some(AssertKind::Overflow(
988 AssertKind::BoundsCheck { ref len, ref index } => {
989 let len = eval_to_int(len);
990 let index = eval_to_int(index);
991 Some(AssertKind::BoundsCheck { len, index })
993 // Remaining overflow errors are already covered by checks on the binary operators.
994 AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
995 // Need proper const propagator for these.
998 // Poison all places this operand references so that further code
999 // doesn't use the invalid value
1001 Operand::Move(ref place) | Operand::Copy(ref place) => {
1002 Self::remove_const(&mut self.ecx, place.local);
1004 Operand::Constant(_) => {}
1006 if let Some(msg) = msg {
1007 self.report_assert_as_lint(
1008 lint::builtin::UNCONDITIONAL_PANIC,
1010 "this operation will panic at runtime",
1017 // None of these have Operands to const-propagate.
1018 TerminatorKind::Goto { .. }
1019 | TerminatorKind::Resume
1020 | TerminatorKind::Abort
1021 | TerminatorKind::Return
1022 | TerminatorKind::Unreachable
1023 | TerminatorKind::Drop { .. }
1024 | TerminatorKind::DropAndReplace { .. }
1025 | TerminatorKind::Yield { .. }
1026 | TerminatorKind::GeneratorDrop
1027 | TerminatorKind::FalseEdge { .. }
1028 | TerminatorKind::FalseUnwind { .. }
1029 | TerminatorKind::SwitchInt { .. }
1030 | TerminatorKind::Call { .. }
1031 | TerminatorKind::InlineAsm { .. } => {}
1034 // We remove all Locals which are restricted in propagation to their containing blocks and
1035 // which were modified in the current block.
1036 // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
1037 let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
1038 for &local in locals.iter() {
1039 Self::remove_const(&mut self.ecx, local);
1042 // Put it back so we reuse the heap of the storage
1043 self.ecx.machine.written_only_inside_own_block_locals = locals;
1044 if cfg!(debug_assertions) {
1045 // Ensure we are correctly erasing locals with the non-debug-assert logic.
1046 for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
1048 self.get_const(local.into()).is_none()
1050 .layout_of(self.local_decls[local].ty)
1051 .map_or(true, |layout| layout.is_zst())