1 //! Propagates constants for early reporting of statically known
4 use crate::const_prop::CanConstProp;
5 use crate::const_prop::ConstPropMachine;
6 use crate::const_prop::ConstPropMode;
8 use rustc_const_eval::interpret::Immediate;
9 use rustc_const_eval::interpret::{
10 self, InterpCx, InterpResult, LocalState, LocalValue, MemoryKind, OpTy, Scalar, StackPopCleanup,
12 use rustc_hir::def::DefKind;
14 use rustc_index::bit_set::BitSet;
15 use rustc_index::vec::IndexVec;
16 use rustc_middle::mir::visit::Visitor;
17 use rustc_middle::mir::{
18 AssertKind, BinOp, Body, Constant, Local, LocalDecl, Location, Operand, Place, Rvalue,
19 SourceInfo, SourceScope, SourceScopeData, Statement, StatementKind, Terminator, TerminatorKind,
22 use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout};
23 use rustc_middle::ty::InternalSubsts;
24 use rustc_middle::ty::{self, ConstInt, Instance, ParamEnv, ScalarInt, Ty, TyCtxt, TypeVisitable};
25 use rustc_session::lint;
27 use rustc_target::abi::{HasDataLayout, Size, TargetDataLayout};
28 use rustc_trait_selection::traits;
31 /// The maximum number of bytes that we'll allocate space for a local or the return value.
32 /// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
33 /// Severely regress performance.
34 const MAX_ALLOC_LIMIT: u64 = 1024;
37 impl<'tcx> MirLint<'tcx> for ConstProp {
38 fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
39 // will be evaluated by miri and produce its errors there
40 if body.source.promoted.is_some() {
44 let def_id = body.source.def_id().expect_local();
45 let is_fn_like = tcx.def_kind(def_id).is_fn_like();
46 let is_assoc_const = tcx.def_kind(def_id) == DefKind::AssocConst;
48 // Only run const prop on functions, methods, closures and associated constants
49 if !is_fn_like && !is_assoc_const {
50 // skip anon_const/statics/consts because they'll be evaluated by miri anyway
51 trace!("ConstProp skipped for {:?}", def_id);
55 let is_generator = tcx.type_of(def_id.to_def_id()).is_generator();
56 // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
57 // computing their layout.
59 trace!("ConstProp skipped for generator {:?}", def_id);
63 // Check if it's even possible to satisfy the 'where' clauses
65 // This branch will never be taken for any normal function.
66 // However, it's possible to `#!feature(trivial_bounds)]` to write
67 // a function with impossible to satisfy clauses, e.g.:
68 // `fn foo() where String: Copy {}`
70 // We don't usually need to worry about this kind of case,
71 // since we would get a compilation error if the user tried
72 // to call it. However, since we can do const propagation
73 // even without any calls to the function, we need to make
74 // sure that it even makes sense to try to evaluate the body.
75 // If there are unsatisfiable where clauses, then all bets are
76 // off, and we just give up.
78 // We manually filter the predicates, skipping anything that's not
79 // "global". We are in a potentially generic context
80 // (e.g. we are evaluating a function without substituting generic
81 // parameters, so this filtering serves two purposes:
83 // 1. We skip evaluating any predicates that we would
84 // never be able prove are unsatisfiable (e.g. `<T as Foo>`
85 // 2. We avoid trying to normalize predicates involving generic
86 // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
87 // the normalization code (leading to cycle errors), since
88 // it's usually never invoked in this way.
90 .predicates_of(def_id.to_def_id())
93 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
94 if traits::impossible_predicates(
96 traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
98 trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", def_id);
102 trace!("ConstProp starting for {:?}", def_id);
104 let dummy_body = &Body::new(
106 (*body.basic_blocks).clone(),
107 body.source_scopes.clone(),
108 body.local_decls.clone(),
113 body.generator_kind(),
114 body.tainted_by_errors,
117 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
118 // constants, instead of just checking for const-folding succeeding.
119 // That would require a uniform one-def no-mutation analysis
120 // and RPO (or recursing when needing the value of a local).
121 let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx);
122 optimization_finder.visit_body(body);
124 trace!("ConstProp done for {:?}", def_id);
128 /// Finds optimization opportunities on the MIR.
129 struct ConstPropagator<'mir, 'tcx> {
130 ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
132 param_env: ParamEnv<'tcx>,
133 source_scopes: &'mir IndexVec<SourceScope, SourceScopeData<'tcx>>,
134 local_decls: &'mir IndexVec<Local, LocalDecl<'tcx>>,
135 // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
136 // the last known `SourceInfo` here and just keep revisiting it.
137 source_info: Option<SourceInfo>,
140 impl<'tcx> LayoutOfHelpers<'tcx> for ConstPropagator<'_, 'tcx> {
141 type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
144 fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
149 impl HasDataLayout for ConstPropagator<'_, '_> {
151 fn data_layout(&self) -> &TargetDataLayout {
152 &self.tcx.data_layout
156 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for ConstPropagator<'_, 'tcx> {
158 fn tcx(&self) -> TyCtxt<'tcx> {
163 impl<'tcx> ty::layout::HasParamEnv<'tcx> for ConstPropagator<'_, 'tcx> {
165 fn param_env(&self) -> ty::ParamEnv<'tcx> {
170 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
173 dummy_body: &'mir Body<'tcx>,
175 ) -> ConstPropagator<'mir, 'tcx> {
176 let def_id = body.source.def_id();
177 let substs = &InternalSubsts::identity_for_item(tcx, def_id);
178 let param_env = tcx.param_env_reveal_all_normalized(def_id);
180 let can_const_prop = CanConstProp::check(tcx, param_env, body);
181 let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
182 for (l, mode) in can_const_prop.iter_enumerated() {
183 if *mode == ConstPropMode::OnlyInsideOwnBlock {
184 only_propagate_inside_block_locals.insert(l);
187 let mut ecx = InterpCx::new(
189 tcx.def_span(def_id),
191 ConstPropMachine::new(only_propagate_inside_block_locals, can_const_prop),
195 .layout_of(body.bound_return_ty().subst(tcx, substs))
197 // Don't bother allocating memory for large values.
198 // I don't know how return types can seem to be unsized but this happens in the
199 // `type/type-unsatisfiable.rs` test.
200 .filter(|ret_layout| {
201 ret_layout.is_sized() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
203 .unwrap_or_else(|| ecx.layout_of(tcx.types.unit).unwrap());
206 .allocate(ret_layout, MemoryKind::Stack)
207 .expect("couldn't perform small allocation")
210 ecx.push_stack_frame(
211 Instance::new(def_id, substs),
214 StackPopCleanup::Root { cleanup: false },
216 .expect("failed to push initial stack frame");
222 source_scopes: &dummy_body.source_scopes,
223 local_decls: &dummy_body.local_decls,
228 fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
229 let op = match self.ecx.eval_place_to_op(place, None) {
231 if matches!(*op, interpret::Operand::Immediate(Immediate::Uninit)) {
232 // Make sure nobody accidentally uses this value.
238 trace!("get_const failed: {}", e);
243 // Try to read the local as an immediate so that if it is representable as a scalar, we can
244 // handle it as such, but otherwise, just return the value as is.
245 Some(match self.ecx.read_immediate_raw(&op) {
246 Ok(Ok(imm)) => imm.into(),
251 /// Remove `local` from the pool of `Locals`. Allows writing to them,
252 /// but not reading from them anymore.
253 fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
254 ecx.frame_mut().locals[local] = LocalState {
255 value: LocalValue::Live(interpret::Operand::Immediate(interpret::Immediate::Uninit)),
256 layout: Cell::new(None),
260 fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
261 source_info.scope.lint_root(self.source_scopes)
264 fn use_ecx<F, T>(&mut self, source_info: SourceInfo, f: F) -> Option<T>
266 F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
268 // Overwrite the PC -- whatever the interpreter does to it does not make any sense anyway.
269 self.ecx.frame_mut().loc = Err(source_info.span);
271 Ok(val) => Some(val),
273 trace!("InterpCx operation failed: {:?}", error);
274 // Some errors shouldn't come up because creating them causes
275 // an allocation, which we should avoid. When that happens,
276 // dedicated error variants should be introduced instead.
278 !error.kind().formatted_string(),
279 "const-prop encountered formatting error: {}",
287 /// Returns the value, if any, of evaluating `c`.
288 fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
289 // FIXME we need to revisit this for #67176
294 self.use_ecx(source_info, |this| this.ecx.eval_mir_constant(&c.literal, Some(c.span), None))
297 /// Returns the value, if any, of evaluating `place`.
298 fn eval_place(&mut self, place: Place<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
299 trace!("eval_place(place={:?})", place);
300 self.use_ecx(source_info, |this| this.ecx.eval_place_to_op(place, None))
303 /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
304 /// or `eval_place`, depending on the variant of `Operand` used.
305 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
307 Operand::Constant(ref c) => self.eval_constant(c, source_info),
308 Operand::Move(place) | Operand::Copy(place) => self.eval_place(place, source_info),
312 fn report_assert_as_lint(
314 lint: &'static lint::Lint,
315 source_info: SourceInfo,
316 message: &'static str,
317 panic: AssertKind<impl std::fmt::Debug>,
319 if let Some(lint_root) = self.lint_root(source_info) {
320 self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, message, |lint| {
321 lint.span_label(source_info.span, format!("{:?}", panic))
330 source_info: SourceInfo,
332 if let (val, true) = self.use_ecx(source_info, |this| {
333 let val = this.ecx.read_immediate(&this.ecx.eval_operand(arg, None)?)?;
334 let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, &val)?;
337 // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
338 // appropriate to use.
339 assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
340 self.report_assert_as_lint(
341 lint::builtin::ARITHMETIC_OVERFLOW,
343 "this arithmetic operation will overflow",
344 AssertKind::OverflowNeg(val.to_const_int()),
355 left: &Operand<'tcx>,
356 right: &Operand<'tcx>,
357 source_info: SourceInfo,
359 let r = self.use_ecx(source_info, |this| {
360 this.ecx.read_immediate(&this.ecx.eval_operand(right, None)?)
362 let l = self.use_ecx(source_info, |this| {
363 this.ecx.read_immediate(&this.ecx.eval_operand(left, None)?)
365 // Check for exceeding shifts *even if* we cannot evaluate the LHS.
366 if op == BinOp::Shr || op == BinOp::Shl {
368 // We need the type of the LHS. We cannot use `place_layout` as that is the type
369 // of the result, which for checked binops is not the same!
370 let left_ty = left.ty(self.local_decls, self.tcx);
371 let left_size = self.ecx.layout_of(left_ty).ok()?.size;
372 let right_size = r.layout.size;
373 let r_bits = r.to_scalar().to_bits(right_size).ok();
374 if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
375 debug!("check_binary_op: reporting assert for {:?}", source_info);
376 self.report_assert_as_lint(
377 lint::builtin::ARITHMETIC_OVERFLOW,
379 "this arithmetic operation will overflow",
380 AssertKind::Overflow(
383 Some(l) => l.to_const_int(),
384 // Invent a dummy value, the diagnostic ignores it anyway
385 None => ConstInt::new(
386 ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
388 left_ty.is_ptr_sized_integral(),
398 if let (Some(l), Some(r)) = (l, r) {
399 // The remaining operators are handled through `overflowing_binary_op`.
400 if self.use_ecx(source_info, |this| {
401 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, &l, &r)?;
404 self.report_assert_as_lint(
405 lint::builtin::ARITHMETIC_OVERFLOW,
407 "this arithmetic operation will overflow",
408 AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
418 rvalue: &Rvalue<'tcx>,
419 source_info: SourceInfo,
422 // Perform any special handling for specific Rvalue types.
423 // Generally, checks here fall into one of two categories:
424 // 1. Additional checking to provide useful lints to the user
425 // - In this case, we will do some validation and then fall through to the
426 // end of the function which evals the assignment.
427 // 2. Working around bugs in other parts of the compiler
428 // - In this case, we'll return `None` from this function to stop evaluation.
430 // Additional checking: give lints to the user if an overflow would occur.
431 // We do this here and not in the `Assert` terminator as that terminator is
432 // only sometimes emitted (overflow checks can be disabled), but we want to always
434 Rvalue::UnaryOp(op, arg) => {
435 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
436 self.check_unary_op(*op, arg, source_info)?;
438 Rvalue::BinaryOp(op, box (left, right)) => {
439 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
440 self.check_binary_op(*op, left, right, source_info)?;
442 Rvalue::CheckedBinaryOp(op, box (left, right)) => {
444 "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
449 self.check_binary_op(*op, left, right, source_info)?;
452 // Do not try creating references (#67862)
453 Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
454 trace!("skipping AddressOf | Ref for {:?}", place);
456 // This may be creating mutable references or immutable references to cells.
457 // If that happens, the pointed to value could be mutated via that reference.
458 // Since we aren't tracking references, the const propagator loses track of what
459 // value the local has right now.
460 // Thus, all locals that have their reference taken
461 // must not take part in propagation.
462 Self::remove_const(&mut self.ecx, place.local);
466 Rvalue::ThreadLocalRef(def_id) => {
467 trace!("skipping ThreadLocalRef({:?})", def_id);
472 // There's no other checking to do at this time.
473 Rvalue::Aggregate(..)
475 | Rvalue::CopyForDeref(..)
479 | Rvalue::ShallowInitBox(..)
480 | Rvalue::Discriminant(..)
481 | Rvalue::NullaryOp(..) => {}
484 // FIXME we need to revisit this for #67176
485 if rvalue.needs_subst() {
489 .ty(&self.ecx.frame().body.local_decls, *self.ecx.tcx)
490 .is_sized(*self.ecx.tcx, self.param_env)
492 // the interpreter doesn't support unsized locals (only unsized arguments),
493 // but rustc does (in a kinda broken way), so we have to skip them here
497 self.use_ecx(source_info, |this| this.ecx.eval_rvalue_into_place(rvalue, place))
501 impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> {
502 fn visit_body(&mut self, body: &Body<'tcx>) {
503 for (bb, data) in body.basic_blocks.iter_enumerated() {
504 self.visit_basic_block_data(bb, data);
508 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
509 self.super_operand(operand, location);
512 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
513 trace!("visit_constant: {:?}", constant);
514 self.super_constant(constant, location);
515 self.eval_constant(constant, self.source_info.unwrap());
518 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
519 trace!("visit_statement: {:?}", statement);
520 let source_info = statement.source_info;
521 self.source_info = Some(source_info);
522 if let StatementKind::Assign(box (place, ref rval)) = statement.kind {
523 let can_const_prop = self.ecx.machine.can_const_prop[place.local];
524 if let Some(()) = self.const_prop(rval, source_info, place) {
525 match can_const_prop {
526 ConstPropMode::OnlyInsideOwnBlock => {
528 "found local restricted to its block. \
529 Will remove it from const-prop after block is finished. Local: {:?}",
533 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
534 trace!("can't propagate into {:?}", place);
535 if place.local != RETURN_PLACE {
536 Self::remove_const(&mut self.ecx, place.local);
539 ConstPropMode::FullConstProp => {}
542 // Const prop failed, so erase the destination, ensuring that whatever happens
543 // from here on, does not know about the previous value.
544 // This is important in case we have
547 // x = SOME_MUTABLE_STATIC;
548 // // x must now be uninit
550 // FIXME: we overzealously erase the entire local, because that's easier to
553 "propagation into {:?} failed.
554 Nuking the entire site from orbit, it's the only way to be sure",
557 Self::remove_const(&mut self.ecx, place.local);
560 match statement.kind {
561 StatementKind::SetDiscriminant { ref place, .. } => {
562 match self.ecx.machine.can_const_prop[place.local] {
563 ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
565 .use_ecx(source_info, |this| this.ecx.statement(statement))
568 trace!("propped discriminant into {:?}", place);
570 Self::remove_const(&mut self.ecx, place.local);
573 ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
574 Self::remove_const(&mut self.ecx, place.local);
578 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
579 let frame = self.ecx.frame_mut();
580 frame.locals[local].value =
581 if let StatementKind::StorageLive(_) = statement.kind {
582 LocalValue::Live(interpret::Operand::Immediate(
583 interpret::Immediate::Uninit,
593 self.super_statement(statement, location);
596 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
597 let source_info = terminator.source_info;
598 self.source_info = Some(source_info);
599 self.super_terminator(terminator, location);
600 match &terminator.kind {
601 TerminatorKind::Assert { expected, ref msg, ref cond, .. } => {
602 if let Some(ref value) = self.eval_operand(&cond, source_info) {
603 trace!("assertion on {:?} should be {:?}", value, expected);
604 let expected = Scalar::from_bool(*expected);
605 let Ok(value_const) = self.ecx.read_scalar(&value) else {
606 // FIXME should be used use_ecx rather than a local match... but we have
607 // quite a few of these read_scalar/read_immediate that need fixing.
610 if expected != value_const {
615 impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
616 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
618 Self::Val(val) => val.fmt(fmt),
619 Self::Underscore => fmt.write_str("_"),
623 let mut eval_to_int = |op| {
624 // This can be `None` if the lhs wasn't const propagated and we just
625 // triggered the assert on the value of the rhs.
626 self.eval_operand(op, source_info)
627 .and_then(|op| self.ecx.read_immediate(&op).ok())
628 .map_or(DbgVal::Underscore, |op| DbgVal::Val(op.to_const_int()))
630 let msg = match msg {
631 AssertKind::DivisionByZero(op) => {
632 Some(AssertKind::DivisionByZero(eval_to_int(op)))
634 AssertKind::RemainderByZero(op) => {
635 Some(AssertKind::RemainderByZero(eval_to_int(op)))
637 AssertKind::Overflow(bin_op @ (BinOp::Div | BinOp::Rem), op1, op2) => {
638 // Division overflow is *UB* in the MIR, and different than the
639 // other overflow checks.
640 Some(AssertKind::Overflow(
646 AssertKind::BoundsCheck { ref len, ref index } => {
647 let len = eval_to_int(len);
648 let index = eval_to_int(index);
649 Some(AssertKind::BoundsCheck { len, index })
651 // Remaining overflow errors are already covered by checks on the binary operators.
652 AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
653 // Need proper const propagator for these.
656 // Poison all places this operand references so that further code
657 // doesn't use the invalid value
659 Operand::Move(ref place) | Operand::Copy(ref place) => {
660 Self::remove_const(&mut self.ecx, place.local);
662 Operand::Constant(_) => {}
664 if let Some(msg) = msg {
665 self.report_assert_as_lint(
666 lint::builtin::UNCONDITIONAL_PANIC,
668 "this operation will panic at runtime",
675 // None of these have Operands to const-propagate.
676 TerminatorKind::Goto { .. }
677 | TerminatorKind::Resume
678 | TerminatorKind::Abort
679 | TerminatorKind::Return
680 | TerminatorKind::Unreachable
681 | TerminatorKind::Drop { .. }
682 | TerminatorKind::DropAndReplace { .. }
683 | TerminatorKind::Yield { .. }
684 | TerminatorKind::GeneratorDrop
685 | TerminatorKind::FalseEdge { .. }
686 | TerminatorKind::FalseUnwind { .. }
687 | TerminatorKind::SwitchInt { .. }
688 | TerminatorKind::Call { .. }
689 | TerminatorKind::InlineAsm { .. } => {}
692 // We remove all Locals which are restricted in propagation to their containing blocks and
693 // which were modified in the current block.
694 // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
695 let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
696 for &local in locals.iter() {
697 Self::remove_const(&mut self.ecx, local);
700 // Put it back so we reuse the heap of the storage
701 self.ecx.machine.written_only_inside_own_block_locals = locals;
702 if cfg!(debug_assertions) {
703 // Ensure we are correctly erasing locals with the non-debug-assert logic.
704 for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
706 self.get_const(local.into()).is_none()
708 .layout_of(self.local_decls[local].ty)
709 .map_or(true, |layout| layout.is_zst())