1 //! Propagates constants for early reporting of statically known
6 use rustc_ast::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::interpret::{InterpResult, Scalar};
13 use rustc_middle::mir::visit::{
14 MutVisitor, MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor,
16 use rustc_middle::mir::{
17 AggregateKind, AssertKind, BasicBlock, BinOp, Body, ClearCrossCrate, Constant, Local,
18 LocalDecl, LocalKind, Location, Operand, Place, Rvalue, SourceInfo, SourceScope,
19 SourceScopeData, Statement, StatementKind, Terminator, TerminatorKind, UnOp, RETURN_PLACE,
21 use rustc_middle::ty::layout::{HasTyCtxt, LayoutError, TyAndLayout};
22 use rustc_middle::ty::subst::{InternalSubsts, Subst};
23 use rustc_middle::ty::{self, ConstInt, ConstKind, Instance, ParamEnv, Ty, TyCtxt, TypeFoldable};
24 use rustc_session::lint;
25 use rustc_span::{def_id::DefId, Span};
26 use rustc_target::abi::{HasDataLayout, LayoutOf, Size, TargetDataLayout};
27 use rustc_trait_selection::traits;
29 use crate::const_eval::error_to_const_error;
30 use crate::interpret::{
31 self, compile_time_machine, AllocId, Allocation, Frame, ImmTy, Immediate, InterpCx, LocalState,
32 LocalValue, MemPlace, Memory, MemoryKind, OpTy, Operand as InterpOperand, PlaceTy, Pointer,
33 ScalarMaybeUninit, StackPopCleanup,
35 use crate::transform::{MirPass, MirSource};
37 /// The maximum number of bytes that we'll allocate space for a return value.
38 const MAX_ALLOC_LIMIT: u64 = 1024;
40 /// Macro for machine-specific `InterpError` without allocation.
41 /// (These will never be shown to the user, but they help diagnose ICEs.)
42 macro_rules! throw_machine_stop_str {
44 // We make a new local type for it. The type itself does not carry any information,
45 // but its vtable (for the `MachineStopType` trait) does.
47 // Printing this type shows the desired string.
48 impl std::fmt::Display for Zst {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 impl rustc_middle::mir::interpret::MachineStopType for Zst {}
54 throw_machine_stop!(Zst)
60 impl<'tcx> MirPass<'tcx> for ConstProp {
61 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
62 // will be evaluated by miri and produce its errors there
63 if source.promoted.is_some() {
67 use rustc_middle::hir::map::blocks::FnLikeNode;
68 let hir_id = tcx.hir().as_local_hir_id(source.def_id().expect_local());
70 let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
71 let is_assoc_const = tcx.def_kind(source.def_id()) == DefKind::AssocConst;
73 // Only run const prop on functions, methods, closures and associated constants
74 if !is_fn_like && !is_assoc_const {
75 // skip anon_const/statics/consts because they'll be evaluated by miri anyway
76 trace!("ConstProp skipped for {:?}", source.def_id());
80 let is_generator = tcx.type_of(source.def_id()).is_generator();
81 // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
82 // computing their layout.
84 trace!("ConstProp skipped for generator {:?}", source.def_id());
88 // Check if it's even possible to satisfy the 'where' clauses
90 // This branch will never be taken for any normal function.
91 // However, it's possible to `#!feature(trivial_bounds)]` to write
92 // a function with impossible to satisfy clauses, e.g.:
93 // `fn foo() where String: Copy {}`
95 // We don't usually need to worry about this kind of case,
96 // since we would get a compilation error if the user tried
97 // to call it. However, since we can do const propagation
98 // even without any calls to the function, we need to make
99 // sure that it even makes sense to try to evaluate the body.
100 // If there are unsatisfiable where clauses, then all bets are
101 // off, and we just give up.
103 // We manually filter the predicates, skipping anything that's not
104 // "global". We are in a potentially generic context
105 // (e.g. we are evaluating a function without substituting generic
106 // parameters, so this filtering serves two purposes:
108 // 1. We skip evaluating any predicates that we would
109 // never be able prove are unsatisfiable (e.g. `<T as Foo>`
110 // 2. We avoid trying to normalize predicates involving generic
111 // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
112 // the normalization code (leading to cycle errors), since
113 // it's usually never invoked in this way.
115 .predicates_of(source.def_id())
118 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
119 if traits::impossible_predicates(
121 traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
123 trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", source.def_id());
127 trace!("ConstProp starting for {:?}", source.def_id());
129 let dummy_body = &Body::new(
130 body.basic_blocks().clone(),
131 body.source_scopes.clone(),
132 body.local_decls.clone(),
136 tcx.def_span(source.def_id()),
140 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
141 // constants, instead of just checking for const-folding succeeding.
142 // That would require an uniform one-def no-mutation analysis
143 // and RPO (or recursing when needing the value of a local).
144 let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx, source);
145 optimization_finder.visit_body(body);
147 trace!("ConstProp done for {:?}", source.def_id());
151 struct ConstPropMachine<'mir, 'tcx> {
152 /// The virtual call stack.
153 stack: Vec<Frame<'mir, 'tcx, (), ()>>,
154 /// `OnlyInsideOwnBlock` locals that were written in the current block get erased at the end.
155 written_only_inside_own_block_locals: FxHashSet<Local>,
156 /// Locals that need to be cleared after every block terminates.
157 only_propagate_inside_block_locals: BitSet<Local>,
160 impl<'mir, 'tcx> ConstPropMachine<'mir, 'tcx> {
161 fn new(only_propagate_inside_block_locals: BitSet<Local>) -> Self {
164 written_only_inside_own_block_locals: Default::default(),
165 only_propagate_inside_block_locals,
170 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx> {
171 compile_time_machine!(<'mir, 'tcx>);
173 type MemoryExtra = ();
175 fn find_mir_or_eval_fn(
176 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
177 _instance: ty::Instance<'tcx>,
178 _args: &[OpTy<'tcx>],
179 _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
180 _unwind: Option<BasicBlock>,
181 ) -> InterpResult<'tcx, Option<&'mir Body<'tcx>>> {
186 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
187 _instance: ty::Instance<'tcx>,
188 _args: &[OpTy<'tcx>],
189 _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
190 _unwind: Option<BasicBlock>,
191 ) -> InterpResult<'tcx> {
192 throw_machine_stop_str!("calling intrinsics isn't supported in ConstProp")
196 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
197 _msg: &rustc_middle::mir::AssertMessage<'tcx>,
198 _unwind: Option<rustc_middle::mir::BasicBlock>,
199 ) -> InterpResult<'tcx> {
200 bug!("panics terminators are not evaluated in ConstProp")
203 fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> {
204 throw_unsup!(ReadPointerAsBytes)
208 _ecx: &InterpCx<'mir, 'tcx, Self>,
212 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
213 // We can't do this because aliasing of memory can differ between const eval and llvm
214 throw_machine_stop_str!("pointer arithmetic or comparisons aren't supported in ConstProp")
218 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
219 _dest: PlaceTy<'tcx>,
220 ) -> InterpResult<'tcx> {
221 throw_machine_stop_str!("can't const prop heap allocations")
225 _ecx: &InterpCx<'mir, 'tcx, Self>,
226 frame: &Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>,
228 ) -> InterpResult<'tcx, InterpOperand<Self::PointerTag>> {
229 let l = &frame.locals[local];
231 if l.value == LocalValue::Uninitialized {
232 throw_machine_stop_str!("tried to access an uninitialized local")
238 fn access_local_mut<'a>(
239 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
242 ) -> InterpResult<'tcx, Result<&'a mut LocalValue<Self::PointerTag>, MemPlace<Self::PointerTag>>>
244 if frame == 0 && ecx.machine.only_propagate_inside_block_locals.contains(local) {
245 ecx.machine.written_only_inside_own_block_locals.insert(local);
247 ecx.machine.stack[frame].locals[local].access_mut()
250 fn before_access_global(
253 allocation: &Allocation<Self::PointerTag, Self::AllocExtra>,
254 _static_def_id: Option<DefId>,
256 ) -> InterpResult<'tcx> {
258 throw_machine_stop_str!("can't write to global");
260 // If the static allocation is mutable, then we can't const prop it as its content
261 // might be different at runtime.
262 if allocation.mutability == Mutability::Mut {
263 throw_machine_stop_str!("can't access mutable globals in ConstProp");
271 ecx: &'a InterpCx<'mir, 'tcx, Self>,
272 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
278 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
279 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
280 &mut ecx.machine.stack
284 /// Finds optimization opportunities on the MIR.
285 struct ConstPropagator<'mir, 'tcx> {
286 ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
288 can_const_prop: IndexVec<Local, ConstPropMode>,
289 param_env: ParamEnv<'tcx>,
290 // FIXME(eddyb) avoid cloning these two fields more than once,
291 // by accessing them through `ecx` instead.
292 source_scopes: IndexVec<SourceScope, SourceScopeData>,
293 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
294 // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
295 // the last known `SourceInfo` here and just keep revisiting it.
296 source_info: Option<SourceInfo>,
299 impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
301 type TyAndLayout = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
303 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
304 self.tcx.layout_of(self.param_env.and(ty))
308 impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
310 fn data_layout(&self) -> &TargetDataLayout {
311 &self.tcx.data_layout
315 impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
317 fn tcx(&self) -> TyCtxt<'tcx> {
322 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
325 dummy_body: &'mir Body<'tcx>,
327 source: MirSource<'tcx>,
328 ) -> ConstPropagator<'mir, 'tcx> {
329 let def_id = source.def_id();
330 let substs = &InternalSubsts::identity_for_item(tcx, def_id);
331 let param_env = tcx.param_env(def_id).with_reveal_all();
333 let span = tcx.def_span(def_id);
334 let can_const_prop = CanConstProp::check(body);
335 let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
336 for (l, mode) in can_const_prop.iter_enumerated() {
337 if *mode == ConstPropMode::OnlyInsideOwnBlock {
338 only_propagate_inside_block_locals.insert(l);
341 let mut ecx = InterpCx::new(
345 ConstPropMachine::new(only_propagate_inside_block_locals),
350 .layout_of(body.return_ty().subst(tcx, substs))
352 // Don't bother allocating memory for ZST types which have no values
353 // or for large values.
354 .filter(|ret_layout| {
355 !ret_layout.is_zst() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
357 .map(|ret_layout| ecx.allocate(ret_layout, MemoryKind::Stack));
359 ecx.push_stack_frame(
360 Instance::new(def_id, substs),
363 StackPopCleanup::None { cleanup: false },
365 .expect("failed to push initial stack frame");
372 // FIXME(eddyb) avoid cloning these two fields more than once,
373 // by accessing them through `ecx` instead.
374 source_scopes: body.source_scopes.clone(),
375 //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
376 local_decls: body.local_decls.clone(),
381 fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
382 let op = match self.ecx.eval_place_to_op(place, None) {
385 trace!("get_const failed: {}", e);
390 // Try to read the local as an immediate so that if it is representable as a scalar, we can
391 // handle it as such, but otherwise, just return the value as is.
392 Some(match self.ecx.try_read_immediate(op) {
393 Ok(Ok(imm)) => imm.into(),
398 /// Remove `local` from the pool of `Locals`. Allows writing to them,
399 /// but not reading from them anymore.
400 fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
401 ecx.frame_mut().locals[local] =
402 LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
405 fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
406 match &self.source_scopes[source_info.scope].local_data {
407 ClearCrossCrate::Set(data) => Some(data.lint_root),
408 ClearCrossCrate::Clear => None,
412 fn use_ecx<F, T>(&mut self, f: F) -> Option<T>
414 F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
417 Ok(val) => Some(val),
419 // Some errors shouldn't come up because creating them causes
420 // an allocation, which we should avoid. When that happens,
421 // dedicated error variants should be introduced instead.
423 !error.kind.allocates(),
424 "const-prop encountered allocating error: {}",
432 /// Returns the value, if any, of evaluating `c`.
433 fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
434 // FIXME we need to revisit this for #67176
439 match self.ecx.eval_const_to_op(c.literal, None) {
442 let tcx = self.ecx.tcx.at(c.span);
443 let err = error_to_const_error(&self.ecx, error, Some(c.span));
444 if let Some(lint_root) = self.lint_root(source_info) {
445 let lint_only = match c.literal.val {
446 // Promoteds must lint and not error as the user didn't ask for them
447 ConstKind::Unevaluated(_, _, Some(_)) => true,
448 // Out of backwards compatibility we cannot report hard errors in unused
449 // generic functions using associated constants of the generic parameters.
450 _ => c.literal.needs_subst(),
453 // Out of backwards compatibility we cannot report hard errors in unused
454 // generic functions using associated constants of the generic parameters.
455 err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
457 err.report_as_error(tcx, "erroneous constant used");
460 err.report_as_error(tcx, "erroneous constant used");
467 /// Returns the value, if any, of evaluating `place`.
468 fn eval_place(&mut self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
469 trace!("eval_place(place={:?})", place);
470 self.use_ecx(|this| this.ecx.eval_place_to_op(place, None))
473 /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
474 /// or `eval_place`, depending on the variant of `Operand` used.
475 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
477 Operand::Constant(ref c) => self.eval_constant(c, source_info),
478 Operand::Move(place) | Operand::Copy(place) => self.eval_place(place),
482 fn report_assert_as_lint(
484 lint: &'static lint::Lint,
485 source_info: SourceInfo,
486 message: &'static str,
487 panic: AssertKind<impl std::fmt::Debug>,
489 let lint_root = self.lint_root(source_info)?;
490 self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
491 let mut err = lint.build(message);
492 err.span_label(source_info.span, format!("{:?}", panic));
502 source_info: SourceInfo,
504 if let (val, true) = self.use_ecx(|this| {
505 let val = this.ecx.read_immediate(this.ecx.eval_operand(arg, None)?)?;
506 let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, val)?;
509 // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
510 // appropriate to use.
511 assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
512 self.report_assert_as_lint(
513 lint::builtin::ARITHMETIC_OVERFLOW,
515 "this arithmetic operation will overflow",
516 AssertKind::OverflowNeg(val.to_const_int()),
526 left: &Operand<'tcx>,
527 right: &Operand<'tcx>,
528 source_info: SourceInfo,
531 self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(right, None)?))?;
532 let l = self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(left, None)?));
533 // Check for exceeding shifts *even if* we cannot evaluate the LHS.
534 if op == BinOp::Shr || op == BinOp::Shl {
535 // We need the type of the LHS. We cannot use `place_layout` as that is the type
536 // of the result, which for checked binops is not the same!
537 let left_ty = left.ty(&self.local_decls, self.tcx);
538 let left_size = self.ecx.layout_of(left_ty).ok()?.size;
539 let right_size = r.layout.size;
540 let r_bits = r.to_scalar().ok();
541 // This is basically `force_bits`.
542 let r_bits = r_bits.and_then(|r| r.to_bits_or_ptr(right_size, &self.tcx).ok());
543 if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
544 debug!("check_binary_op: reporting assert for {:?}", source_info);
545 self.report_assert_as_lint(
546 lint::builtin::ARITHMETIC_OVERFLOW,
548 "this arithmetic operation will overflow",
549 AssertKind::Overflow(
552 Some(l) => l.to_const_int(),
553 // Invent a dummy value, the diagnostic ignores it anyway
554 None => ConstInt::new(
558 left_ty.is_ptr_sized_integral(),
569 // The remaining operators are handled through `overflowing_binary_op`.
570 if self.use_ecx(|this| {
571 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, l, r)?;
574 self.report_assert_as_lint(
575 lint::builtin::ARITHMETIC_OVERFLOW,
577 "this arithmetic operation will overflow",
578 AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
585 fn propagate_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
587 Operand::Copy(l) | Operand::Move(l) => {
588 if let Some(value) = self.get_const(l) {
589 if self.should_const_prop(value) {
590 // FIXME(felix91gr): this code only handles `Scalar` cases.
591 // For now, we're not handling `ScalarPair` cases because
592 // doing so here would require a lot of code duplication.
593 // We should hopefully generalize `Operand` handling into a fn,
594 // and use it to do const-prop here and everywhere else
595 // where it makes sense.
596 if let interpret::Operand::Immediate(interpret::Immediate::Scalar(
597 ScalarMaybeUninit::Scalar(scalar),
600 *operand = self.operand_from_scalar(
603 self.source_info.unwrap().span,
609 Operand::Constant(ref mut ct) => self.visit_constant(ct, location),
615 rvalue: &Rvalue<'tcx>,
616 place_layout: TyAndLayout<'tcx>,
617 source_info: SourceInfo,
620 // #66397: Don't try to eval into large places as that can cause an OOM
621 if place_layout.size >= Size::from_bytes(MAX_ALLOC_LIMIT) {
625 // Perform any special handling for specific Rvalue types.
626 // Generally, checks here fall into one of two categories:
627 // 1. Additional checking to provide useful lints to the user
628 // - In this case, we will do some validation and then fall through to the
629 // end of the function which evals the assignment.
630 // 2. Working around bugs in other parts of the compiler
631 // - In this case, we'll return `None` from this function to stop evaluation.
633 // Additional checking: give lints to the user if an overflow would occur.
634 // We do this here and not in the `Assert` terminator as that terminator is
635 // only sometimes emitted (overflow checks can be disabled), but we want to always
637 Rvalue::UnaryOp(op, arg) => {
638 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
639 self.check_unary_op(*op, arg, source_info)?;
641 Rvalue::BinaryOp(op, left, right) => {
642 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
643 self.check_binary_op(*op, left, right, source_info)?;
645 Rvalue::CheckedBinaryOp(op, left, right) => {
647 "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
652 self.check_binary_op(*op, left, right, source_info)?;
655 // Do not try creating references (#67862)
656 Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
657 trace!("skipping AddressOf | Ref for {:?}", place);
659 // This may be creating mutable references or immutable references to cells.
660 // If that happens, the pointed to value could be mutated via that reference.
661 // Since we aren't tracking references, the const propagator loses track of what
662 // value the local has right now.
663 // Thus, all locals that have their reference taken
664 // must not take part in propagation.
665 Self::remove_const(&mut self.ecx, place.local);
669 Rvalue::ThreadLocalRef(def_id) => {
670 trace!("skipping ThreadLocalRef({:?})", def_id);
675 // There's no other checking to do at this time.
676 Rvalue::Aggregate(..)
681 | Rvalue::Discriminant(..)
682 | Rvalue::NullaryOp(..) => {}
685 // FIXME we need to revisit this for #67176
686 if rvalue.needs_subst() {
690 self.use_ecx(|this| {
691 trace!("calling eval_rvalue_into_place(rvalue = {:?}, place = {:?})", rvalue, place);
692 this.ecx.eval_rvalue_into_place(rvalue, place)?;
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 {
702 literal: ty::Const::from_scalar(self.tcx, scalar, ty),
706 fn replace_with_const(
708 rval: &mut Rvalue<'tcx>,
710 source_info: SourceInfo,
712 if let Rvalue::Use(Operand::Constant(c)) = rval {
713 if !matches!(c.literal.val, ConstKind::Unevaluated(..)) {
714 trace!("skipping replace of Rvalue::Use({:?} because it is already a const", c);
719 trace!("attepting to replace {:?} with {:?}", rval, value);
720 if let Err(e) = self.ecx.const_validate_operand(
723 // FIXME: is ref tracking too expensive?
724 &mut interpret::RefTracking::empty(),
725 /*may_ref_to_static*/ true,
727 trace!("validation error, attempt failed: {:?}", e);
731 // FIXME> figure out what to do when try_read_immediate fails
732 let imm = self.use_ecx(|this| this.ecx.try_read_immediate(value));
734 if let Some(Ok(imm)) = imm {
736 interpret::Immediate::Scalar(ScalarMaybeUninit::Scalar(scalar)) => {
737 *rval = Rvalue::Use(self.operand_from_scalar(
743 Immediate::ScalarPair(
744 ScalarMaybeUninit::Scalar(one),
745 ScalarMaybeUninit::Scalar(two),
747 // Found a value represented as a pair. For now only do cont-prop if type of
748 // Rvalue is also a pair with two scalars. The more general case is more
749 // complicated to implement so we'll do it later.
750 // FIXME: implement the general case stated above ^.
751 let ty = &value.layout.ty.kind;
752 // Only do it for tuples
753 if let ty::Tuple(substs) = ty {
754 // Only do it if tuple is also a pair with two scalars
755 if substs.len() == 2 {
756 let opt_ty1_ty2 = self.use_ecx(|this| {
757 let ty1 = substs[0].expect_ty();
758 let ty2 = substs[1].expect_ty();
759 let ty_is_scalar = |ty| {
760 this.ecx.layout_of(ty).ok().map(|layout| layout.abi.is_scalar())
763 if ty_is_scalar(ty1) && ty_is_scalar(ty2) {
770 if let Some(Some((ty1, ty2))) = opt_ty1_ty2 {
771 *rval = Rvalue::Aggregate(
772 Box::new(AggregateKind::Tuple),
774 self.operand_from_scalar(one, ty1, source_info.span),
775 self.operand_from_scalar(two, ty2, source_info.span),
787 /// Returns `true` if and only if this `op` should be const-propagated into.
788 fn should_const_prop(&mut self, op: OpTy<'tcx>) -> bool {
789 let mir_opt_level = self.tcx.sess.opts.debugging_opts.mir_opt_level;
791 if mir_opt_level == 0 {
796 interpret::Operand::Immediate(Immediate::Scalar(ScalarMaybeUninit::Scalar(s))) => {
799 interpret::Operand::Immediate(Immediate::ScalarPair(
800 ScalarMaybeUninit::Scalar(l),
801 ScalarMaybeUninit::Scalar(r),
802 )) => l.is_bits() && r.is_bits(),
808 /// The mode that `ConstProp` is allowed to run in for a given `Local`.
809 #[derive(Clone, Copy, Debug, PartialEq)]
811 /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
813 /// The `Local` can only be propagated into and from its own block.
815 /// The `Local` can be propagated into but reads cannot be propagated.
817 /// The `Local` cannot be part of propagation at all. Any statement
818 /// referencing it either for reading or writing will not get propagated.
822 struct CanConstProp {
823 can_const_prop: IndexVec<Local, ConstPropMode>,
824 // False at the beginning. Once set, no more assignments are allowed to that local.
825 found_assignment: BitSet<Local>,
826 // Cache of locals' information
827 local_kinds: IndexVec<Local, LocalKind>,
831 /// Returns true if `local` can be propagated
832 fn check(body: &Body<'_>) -> IndexVec<Local, ConstPropMode> {
833 let mut cpv = CanConstProp {
834 can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
835 found_assignment: BitSet::new_empty(body.local_decls.len()),
836 local_kinds: IndexVec::from_fn_n(
837 |local| body.local_kind(local),
838 body.local_decls.len(),
841 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
842 // Cannot use args at all
843 // Cannot use locals because if x < y { y - x } else { x - y } would
845 // FIXME(oli-obk): lint variables until they are used in a condition
846 // FIXME(oli-obk): lint if return value is constant
847 if cpv.local_kinds[local] == LocalKind::Arg {
848 *val = ConstPropMode::OnlyPropagateInto;
850 "local {:?} can't be const propagated because it's a function argument",
853 } else if cpv.local_kinds[local] == LocalKind::Var {
854 *val = ConstPropMode::OnlyInsideOwnBlock;
856 "local {:?} will only be propagated inside its block, because it's a user variable",
861 cpv.visit_body(&body);
866 impl<'tcx> Visitor<'tcx> for CanConstProp {
867 fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
868 use rustc_middle::mir::visit::PlaceContext::*;
870 // Projections are fine, because `&mut foo.x` will be caught by
871 // `MutatingUseContext::Borrow` elsewhere.
872 MutatingUse(MutatingUseContext::Projection)
873 // These are just stores, where the storing is not propagatable, but there may be later
874 // mutations of the same local via `Store`
875 | MutatingUse(MutatingUseContext::Call)
876 // Actual store that can possibly even propagate a value
877 | MutatingUse(MutatingUseContext::Store) => {
878 if !self.found_assignment.insert(local) {
879 match &mut self.can_const_prop[local] {
880 // If the local can only get propagated in its own block, then we don't have
881 // to worry about multiple assignments, as we'll nuke the const state at the
882 // end of the block anyway, and inside the block we overwrite previous
883 // states as applicable.
884 ConstPropMode::OnlyInsideOwnBlock => {}
885 ConstPropMode::NoPropagation => {}
886 ConstPropMode::OnlyPropagateInto => {}
887 other @ ConstPropMode::FullConstProp => {
889 "local {:?} can't be propagated because of multiple assignments",
892 *other = ConstPropMode::OnlyPropagateInto;
897 // Reading constants is allowed an arbitrary number of times
898 NonMutatingUse(NonMutatingUseContext::Copy)
899 | NonMutatingUse(NonMutatingUseContext::Move)
900 | NonMutatingUse(NonMutatingUseContext::Inspect)
901 | NonMutatingUse(NonMutatingUseContext::Projection)
904 // These could be propagated with a smarter analysis or just some careful thinking about
905 // whether they'd be fine right now.
906 MutatingUse(MutatingUseContext::AsmOutput)
907 | MutatingUse(MutatingUseContext::Yield)
908 | MutatingUse(MutatingUseContext::Drop)
909 | MutatingUse(MutatingUseContext::Retag)
910 // These can't ever be propagated under any scheme, as we can't reason about indirect
912 | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
913 | NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
914 | NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
915 | NonMutatingUse(NonMutatingUseContext::AddressOf)
916 | MutatingUse(MutatingUseContext::Borrow)
917 | MutatingUse(MutatingUseContext::AddressOf) => {
918 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
919 self.can_const_prop[local] = ConstPropMode::NoPropagation;
925 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
926 fn tcx(&self) -> TyCtxt<'tcx> {
930 fn visit_body(&mut self, body: &mut Body<'tcx>) {
931 for (bb, data) in body.basic_blocks_mut().iter_enumerated_mut() {
932 self.visit_basic_block_data(bb, data);
936 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
937 // Only const prop copies and moves on `mir_opt_level=3` as doing so
938 // currently increases compile time.
939 if self.tcx.sess.opts.debugging_opts.mir_opt_level < 3 {
940 self.super_operand(operand, location)
942 self.propagate_operand(operand, location)
946 fn visit_constant(&mut self, constant: &mut Constant<'tcx>, location: Location) {
947 trace!("visit_constant: {:?}", constant);
948 self.super_constant(constant, location);
949 self.eval_constant(constant, self.source_info.unwrap());
952 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
953 trace!("visit_statement: {:?}", statement);
954 let source_info = statement.source_info;
955 self.source_info = Some(source_info);
956 if let StatementKind::Assign(box (place, ref mut rval)) = statement.kind {
957 let place_ty: Ty<'tcx> = place.ty(&self.local_decls, self.tcx).ty;
958 if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
959 let can_const_prop = self.can_const_prop[place.local];
960 if let Some(()) = self.const_prop(rval, place_layout, source_info, place) {
961 // This will return None if the above `const_prop` invocation only "wrote" a
962 // type whose creation requires no write. E.g. a generator whose initial state
963 // consists solely of uninitialized memory (so it doesn't capture any locals).
964 if let Some(value) = self.get_const(place) {
965 if self.should_const_prop(value) {
966 trace!("replacing {:?} with {:?}", rval, value);
967 self.replace_with_const(rval, value, source_info);
968 if can_const_prop == ConstPropMode::FullConstProp
969 || can_const_prop == ConstPropMode::OnlyInsideOwnBlock
971 trace!("propagated into {:?}", place);
975 match can_const_prop {
976 ConstPropMode::OnlyInsideOwnBlock => {
978 "found local restricted to its block. \
979 Will remove it from const-prop after block is finished. Local: {:?}",
983 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
984 trace!("can't propagate into {:?}", place);
985 if place.local != RETURN_PLACE {
986 Self::remove_const(&mut self.ecx, place.local);
989 ConstPropMode::FullConstProp => {}
992 // Const prop failed, so erase the destination, ensuring that whatever happens
993 // from here on, does not know about the previous value.
994 // This is important in case we have
997 // x = SOME_MUTABLE_STATIC;
998 // // x must now be undefined
1000 // FIXME: we overzealously erase the entire local, because that's easier to
1003 "propagation into {:?} failed.
1004 Nuking the entire site from orbit, it's the only way to be sure",
1007 Self::remove_const(&mut self.ecx, place.local);
1011 "cannot propagate into {:?}, because the type of the local is generic.",
1014 Self::remove_const(&mut self.ecx, place.local);
1017 match statement.kind {
1018 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
1019 let frame = self.ecx.frame_mut();
1020 frame.locals[local].value =
1021 if let StatementKind::StorageLive(_) = statement.kind {
1022 LocalValue::Uninitialized
1031 self.super_statement(statement, location);
1034 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
1035 let source_info = terminator.source_info;
1036 self.source_info = Some(source_info);
1037 self.super_terminator(terminator, location);
1038 match &mut terminator.kind {
1039 TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
1040 if let Some(value) = self.eval_operand(&cond, source_info) {
1041 trace!("assertion on {:?} should be {:?}", value, expected);
1042 let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
1043 let value_const = self.ecx.read_scalar(value).unwrap();
1044 if expected != value_const {
1049 impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
1050 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1052 Self::Val(val) => val.fmt(fmt),
1053 Self::Underscore => fmt.write_str("_"),
1057 let mut eval_to_int = |op| {
1058 // This can be `None` if the lhs wasn't const propagated and we just
1059 // triggered the assert on the value of the rhs.
1060 match self.eval_operand(op, source_info) {
1062 DbgVal::Val(self.ecx.read_immediate(op).unwrap().to_const_int())
1064 None => DbgVal::Underscore,
1067 let msg = match msg {
1068 AssertKind::DivisionByZero(op) => {
1069 Some(AssertKind::DivisionByZero(eval_to_int(op)))
1071 AssertKind::RemainderByZero(op) => {
1072 Some(AssertKind::RemainderByZero(eval_to_int(op)))
1074 AssertKind::BoundsCheck { ref len, ref index } => {
1075 let len = eval_to_int(len);
1076 let index = eval_to_int(index);
1077 Some(AssertKind::BoundsCheck { len, index })
1079 // Overflow is are already covered by checks on the binary operators.
1080 AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
1081 // Need proper const propagator for these.
1084 // Poison all places this operand references so that further code
1085 // doesn't use the invalid value
1087 Operand::Move(ref place) | Operand::Copy(ref place) => {
1088 Self::remove_const(&mut self.ecx, place.local);
1090 Operand::Constant(_) => {}
1092 if let Some(msg) = msg {
1093 self.report_assert_as_lint(
1094 lint::builtin::UNCONDITIONAL_PANIC,
1096 "this operation will panic at runtime",
1101 if self.should_const_prop(value) {
1102 if let ScalarMaybeUninit::Scalar(scalar) = value_const {
1103 *cond = self.operand_from_scalar(
1105 self.tcx.types.bool,
1113 TerminatorKind::SwitchInt { ref mut discr, .. } => {
1114 // FIXME: This is currently redundant with `visit_operand`, but sadly
1115 // always visiting operands currently causes a perf regression in LLVM codegen, so
1116 // `visit_operand` currently only runs for propagates places for `mir_opt_level=3`.
1117 self.propagate_operand(discr, location)
1119 // None of these have Operands to const-propagate.
1120 TerminatorKind::Goto { .. }
1121 | TerminatorKind::Resume
1122 | TerminatorKind::Abort
1123 | TerminatorKind::Return
1124 | TerminatorKind::Unreachable
1125 | TerminatorKind::Drop { .. }
1126 | TerminatorKind::DropAndReplace { .. }
1127 | TerminatorKind::Yield { .. }
1128 | TerminatorKind::GeneratorDrop
1129 | TerminatorKind::FalseEdge { .. }
1130 | TerminatorKind::FalseUnwind { .. }
1131 | TerminatorKind::InlineAsm { .. } => {}
1132 // Every argument in our function calls have already been propagated in `visit_operand`.
1134 // NOTE: because LLVM codegen gives performance regressions with it, so this is gated
1135 // on `mir_opt_level=3`.
1136 TerminatorKind::Call { .. } => {}
1139 // We remove all Locals which are restricted in propagation to their containing blocks and
1140 // which were modified in the current block.
1141 // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
1142 let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
1143 for &local in locals.iter() {
1144 Self::remove_const(&mut self.ecx, local);
1147 // Put it back so we reuse the heap of the storage
1148 self.ecx.machine.written_only_inside_own_block_locals = locals;
1149 if cfg!(debug_assertions) {
1150 // Ensure we are correctly erasing locals with the non-debug-assert logic.
1151 for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
1153 self.get_const(local.into()).is_none()
1155 .layout_of(self.local_decls[local].ty)
1156 .map_or(true, |layout| layout.is_zst())