1 //! A constant propagation optimization pass based on dataflow analysis.
3 //! Currently, this pass only propagates scalar values.
5 use rustc_const_eval::interpret::{ConstValue, ImmTy, Immediate, InterpCx, Scalar};
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_middle::mir::visit::{MutVisitor, Visitor};
8 use rustc_middle::mir::*;
9 use rustc_middle::ty::{self, Ty, TyCtxt};
10 use rustc_mir_dataflow::value_analysis::{Map, State, TrackElem, ValueAnalysis, ValueOrPlace};
11 use rustc_mir_dataflow::{lattice::FlatSet, Analysis, ResultsVisitor, SwitchIntEdgeEffects};
12 use rustc_span::DUMMY_SP;
16 // These constants are somewhat random guesses and have not been optimized.
17 // If `tcx.sess.mir_opt_level() >= 4`, we ignore the limits (this can become very expensive).
18 const BLOCK_LIMIT: usize = 100;
19 const PLACE_LIMIT: usize = 100;
21 pub struct DataflowConstProp;
23 impl<'tcx> MirPass<'tcx> for DataflowConstProp {
24 fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
25 sess.mir_opt_level() >= 3
28 #[instrument(skip_all level = "debug")]
29 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
30 if tcx.sess.mir_opt_level() < 4 && body.basic_blocks.len() > BLOCK_LIMIT {
31 debug!("aborted dataflow const prop due too many basic blocks");
35 // Decide which places to track during the analysis.
36 let map = Map::from_filter(tcx, body, Ty::is_scalar);
38 // We want to have a somewhat linear runtime w.r.t. the number of statements/terminators.
39 // Let's call this number `n`. Dataflow analysis has `O(h*n)` transfer function
40 // applications, where `h` is the height of the lattice. Because the height of our lattice
41 // is linear w.r.t. the number of tracked places, this is `O(tracked_places * n)`. However,
42 // because every transfer function application could traverse the whole map, this becomes
43 // `O(num_nodes * tracked_places * n)` in terms of time complexity. Since the number of
44 // map nodes is strongly correlated to the number of tracked places, this becomes more or
45 // less `O(n)` if we place a constant limit on the number of tracked places.
46 if tcx.sess.mir_opt_level() < 4 && map.tracked_places() > PLACE_LIMIT {
47 debug!("aborted dataflow const prop due to too many tracked places");
51 // Perform the actual dataflow analysis.
52 let analysis = ConstAnalysis::new(tcx, body, map);
53 let results = debug_span!("analyze")
54 .in_scope(|| analysis.wrap().into_engine(tcx, body).iterate_to_fixpoint());
56 // Collect results and patch the body afterwards.
57 let mut visitor = CollectAndPatch::new(tcx, &results.analysis.0.map);
58 debug_span!("collect").in_scope(|| results.visit_reachable_with(body, &mut visitor));
59 debug_span!("patch").in_scope(|| visitor.visit_body(body));
63 struct ConstAnalysis<'tcx> {
66 ecx: InterpCx<'tcx, 'tcx, DummyMachine>,
67 param_env: ty::ParamEnv<'tcx>,
70 impl<'tcx> ValueAnalysis<'tcx> for ConstAnalysis<'tcx> {
71 type Value = FlatSet<ScalarTy<'tcx>>;
73 const NAME: &'static str = "ConstAnalysis";
75 fn map(&self) -> &Map {
82 rvalue: &Rvalue<'tcx>,
83 state: &mut State<Self::Value>,
86 Rvalue::CheckedBinaryOp(op, box (left, right)) => {
87 let target = self.map().find(target.as_ref());
88 if let Some(target) = target {
89 // We should not track any projections other than
90 // what is overwritten below, but just in case...
91 state.flood_idx(target, self.map());
94 let value_target = target
95 .and_then(|target| self.map().apply(target, TrackElem::Field(0_u32.into())));
96 let overflow_target = target
97 .and_then(|target| self.map().apply(target, TrackElem::Field(1_u32.into())));
99 if value_target.is_some() || overflow_target.is_some() {
100 let (val, overflow) = self.binary_op(state, *op, left, right);
102 if let Some(value_target) = value_target {
103 state.assign_idx(value_target, ValueOrPlace::Value(val), self.map());
105 if let Some(overflow_target) = overflow_target {
106 let overflow = match overflow {
107 FlatSet::Top => FlatSet::Top,
108 FlatSet::Elem(overflow) => {
110 // Overflow cannot be reliably propagated. See: https://github.com/rust-lang/rust/pull/101168#issuecomment-1288091446
113 self.wrap_scalar(Scalar::from_bool(false), self.tcx.types.bool)
116 FlatSet::Bottom => FlatSet::Bottom,
120 ValueOrPlace::Value(overflow),
126 _ => self.super_assign(target, rvalue, state),
132 rvalue: &Rvalue<'tcx>,
133 state: &mut State<Self::Value>,
134 ) -> ValueOrPlace<Self::Value> {
137 kind @ (CastKind::IntToInt
138 | CastKind::FloatToInt
139 | CastKind::FloatToFloat
140 | CastKind::IntToFloat),
143 ) => match self.eval_operand(operand, state) {
144 FlatSet::Elem(op) => match kind {
145 CastKind::IntToInt | CastKind::IntToFloat => {
146 self.ecx.int_to_int_or_float(&op, *ty)
148 CastKind::FloatToInt | CastKind::FloatToFloat => {
149 self.ecx.float_to_float_or_int(&op, *ty)
153 .map(|result| ValueOrPlace::Value(self.wrap_immediate(result, *ty)))
154 .unwrap_or(ValueOrPlace::top()),
155 _ => ValueOrPlace::top(),
157 Rvalue::BinaryOp(op, box (left, right)) => {
158 // Overflows must be ignored here.
159 let (val, _overflow) = self.binary_op(state, *op, left, right);
160 ValueOrPlace::Value(val)
162 Rvalue::UnaryOp(op, operand) => match self.eval_operand(operand, state) {
163 FlatSet::Elem(value) => self
165 .unary_op(*op, &value)
166 .map(|val| ValueOrPlace::Value(self.wrap_immty(val)))
167 .unwrap_or(ValueOrPlace::Value(FlatSet::Top)),
168 FlatSet::Bottom => ValueOrPlace::Value(FlatSet::Bottom),
169 FlatSet::Top => ValueOrPlace::Value(FlatSet::Top),
171 _ => self.super_rvalue(rvalue, state),
177 constant: &Constant<'tcx>,
178 _state: &mut State<Self::Value>,
182 .eval(self.tcx, self.param_env)
184 .map(|value| FlatSet::Elem(ScalarTy(value, constant.ty())))
185 .unwrap_or(FlatSet::Top)
188 fn handle_switch_int(
190 discr: &Operand<'tcx>,
191 apply_edge_effects: &mut impl SwitchIntEdgeEffects<State<Self::Value>>,
193 // FIXME: The dataflow framework only provides the state if we call `apply()`, which makes
194 // this more inefficient than it has to be.
195 let mut discr_value = None;
196 let mut handled = false;
197 apply_edge_effects.apply(|state, target| {
198 let discr_value = match discr_value {
199 Some(value) => value,
201 let value = match self.handle_operand(discr, state) {
202 ValueOrPlace::Value(value) => value,
203 ValueOrPlace::Place(place) => state.get_idx(place, self.map()),
205 let result = match value {
206 FlatSet::Top => FlatSet::Top,
207 FlatSet::Elem(ScalarTy(scalar, _)) => {
208 let int = scalar.assert_int();
209 FlatSet::Elem(int.assert_bits(int.size()))
211 FlatSet::Bottom => FlatSet::Bottom,
213 discr_value = Some(result);
218 let FlatSet::Elem(choice) = discr_value else {
219 // Do nothing if we don't know which branch will be taken.
223 if target.value.map(|n| n == choice).unwrap_or(!handled) {
224 // Branch is taken. Has no effect on state.
227 // Branch is not taken.
228 state.mark_unreachable();
234 #[derive(Clone, PartialEq, Eq)]
235 struct ScalarTy<'tcx>(Scalar, Ty<'tcx>);
237 impl<'tcx> std::fmt::Debug for ScalarTy<'tcx> {
238 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239 // This is used for dataflow visualization, so we return something more concise.
240 std::fmt::Display::fmt(&ConstantKind::Val(ConstValue::Scalar(self.0), self.1), f)
244 impl<'tcx> ConstAnalysis<'tcx> {
245 pub fn new(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, map: Map) -> Self {
246 let param_env = tcx.param_env(body.source.def_id());
250 ecx: InterpCx::new(tcx, DUMMY_SP, param_env, DummyMachine),
251 param_env: param_env,
257 state: &mut State<FlatSet<ScalarTy<'tcx>>>,
259 left: &Operand<'tcx>,
260 right: &Operand<'tcx>,
261 ) -> (FlatSet<ScalarTy<'tcx>>, FlatSet<bool>) {
262 let left = self.eval_operand(left, state);
263 let right = self.eval_operand(right, state);
264 match (left, right) {
265 (FlatSet::Elem(left), FlatSet::Elem(right)) => {
266 match self.ecx.overflowing_binary_op(op, &left, &right) {
267 Ok((val, overflow, ty)) => (self.wrap_scalar(val, ty), FlatSet::Elem(overflow)),
268 _ => (FlatSet::Top, FlatSet::Top),
271 (FlatSet::Bottom, _) | (_, FlatSet::Bottom) => (FlatSet::Bottom, FlatSet::Bottom),
273 // Could attempt some algebraic simplifcations here.
274 (FlatSet::Top, FlatSet::Top)
282 state: &mut State<FlatSet<ScalarTy<'tcx>>>,
283 ) -> FlatSet<ImmTy<'tcx>> {
284 let value = match self.handle_operand(op, state) {
285 ValueOrPlace::Value(value) => value,
286 ValueOrPlace::Place(place) => state.get_idx(place, &self.map),
289 FlatSet::Top => FlatSet::Top,
290 FlatSet::Elem(ScalarTy(scalar, ty)) => self
292 .layout_of(self.param_env.and(ty))
293 .map(|layout| FlatSet::Elem(ImmTy::from_scalar(scalar, layout)))
294 .unwrap_or(FlatSet::Top),
295 FlatSet::Bottom => FlatSet::Bottom,
299 fn wrap_scalar(&self, scalar: Scalar, ty: Ty<'tcx>) -> FlatSet<ScalarTy<'tcx>> {
300 FlatSet::Elem(ScalarTy(scalar, ty))
303 fn wrap_immediate(&self, imm: Immediate, ty: Ty<'tcx>) -> FlatSet<ScalarTy<'tcx>> {
305 Immediate::Scalar(scalar) => self.wrap_scalar(scalar, ty),
310 fn wrap_immty(&self, val: ImmTy<'tcx>) -> FlatSet<ScalarTy<'tcx>> {
311 self.wrap_immediate(*val, val.layout.ty)
315 struct CollectAndPatch<'tcx, 'map> {
319 /// For a given MIR location, this stores the values of the operands used by that location. In
320 /// particular, this is before the effect, such that the operands of `_1 = _1 + _2` are
321 /// properly captured. (This may become UB soon, but it is currently emitted even by safe code.)
322 before_effect: FxHashMap<(Location, Place<'tcx>), ScalarTy<'tcx>>,
324 /// Stores the assigned values for assignments where the Rvalue is constant.
325 assignments: FxHashMap<Location, ScalarTy<'tcx>>,
328 impl<'tcx, 'map> CollectAndPatch<'tcx, 'map> {
329 fn new(tcx: TyCtxt<'tcx>, map: &'map Map) -> Self {
330 Self { tcx, map, before_effect: FxHashMap::default(), assignments: FxHashMap::default() }
333 fn make_operand(&self, scalar: ScalarTy<'tcx>) -> Operand<'tcx> {
334 Operand::Constant(Box::new(Constant {
337 literal: ConstantKind::Val(ConstValue::Scalar(scalar.0), scalar.1),
342 impl<'mir, 'tcx, 'map> ResultsVisitor<'mir, 'tcx> for CollectAndPatch<'tcx, 'map> {
343 type FlowState = State<FlatSet<ScalarTy<'tcx>>>;
345 fn visit_statement_before_primary_effect(
347 state: &Self::FlowState,
348 statement: &'mir Statement<'tcx>,
351 match &statement.kind {
352 StatementKind::Assign(box (_, rvalue)) => {
353 OperandCollector { state, visitor: self }.visit_rvalue(rvalue, location);
359 fn visit_statement_after_primary_effect(
361 state: &Self::FlowState,
362 statement: &'mir Statement<'tcx>,
365 match statement.kind {
366 StatementKind::Assign(box (_, Rvalue::Use(Operand::Constant(_)))) => {
367 // Don't overwrite the assignment if it already uses a constant (to keep the span).
369 StatementKind::Assign(box (place, _)) => match state.get(place.as_ref(), self.map) {
371 FlatSet::Elem(value) => {
372 self.assignments.insert(location, value);
375 // This assignment is either unreachable, or an uninitialized value is assigned.
382 fn visit_terminator_before_primary_effect(
384 state: &Self::FlowState,
385 terminator: &'mir Terminator<'tcx>,
388 OperandCollector { state, visitor: self }.visit_terminator(terminator, location);
392 impl<'tcx, 'map> MutVisitor<'tcx> for CollectAndPatch<'tcx, 'map> {
393 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
397 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
398 if let Some(value) = self.assignments.get(&location) {
399 match &mut statement.kind {
400 StatementKind::Assign(box (_, rvalue)) => {
401 *rvalue = Rvalue::Use(self.make_operand(value.clone()));
403 _ => bug!("found assignment info for non-assign statement"),
406 self.super_statement(statement, location);
410 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
412 Operand::Copy(place) | Operand::Move(place) => {
413 if let Some(value) = self.before_effect.get(&(location, *place)) {
414 *operand = self.make_operand(value.clone());
422 struct OperandCollector<'tcx, 'map, 'a> {
423 state: &'a State<FlatSet<ScalarTy<'tcx>>>,
424 visitor: &'a mut CollectAndPatch<'tcx, 'map>,
427 impl<'tcx, 'map, 'a> Visitor<'tcx> for OperandCollector<'tcx, 'map, 'a> {
428 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
430 Operand::Copy(place) | Operand::Move(place) => {
431 match self.state.get(place.as_ref(), self.visitor.map) {
433 FlatSet::Elem(value) => {
434 self.visitor.before_effect.insert((location, *place), value);
436 FlatSet::Bottom => (),
446 impl<'mir, 'tcx> rustc_const_eval::interpret::Machine<'mir, 'tcx> for DummyMachine {
447 rustc_const_eval::interpret::compile_time_machine!(<'mir, 'tcx>);
449 const PANIC_ON_ALLOC_FAIL: bool = true;
451 fn enforce_alignment(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
455 fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
459 fn find_mir_or_eval_fn(
460 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
461 _instance: ty::Instance<'tcx>,
462 _abi: rustc_target::spec::abi::Abi,
463 _args: &[rustc_const_eval::interpret::OpTy<'tcx, Self::Provenance>],
464 _destination: &rustc_const_eval::interpret::PlaceTy<'tcx, Self::Provenance>,
465 _target: Option<BasicBlock>,
466 _unwind: rustc_const_eval::interpret::StackPopUnwind,
467 ) -> interpret::InterpResult<'tcx, Option<(&'mir Body<'tcx>, ty::Instance<'tcx>)>> {
472 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
473 _instance: ty::Instance<'tcx>,
474 _args: &[rustc_const_eval::interpret::OpTy<'tcx, Self::Provenance>],
475 _destination: &rustc_const_eval::interpret::PlaceTy<'tcx, Self::Provenance>,
476 _target: Option<BasicBlock>,
477 _unwind: rustc_const_eval::interpret::StackPopUnwind,
478 ) -> interpret::InterpResult<'tcx> {
483 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
484 _msg: &rustc_middle::mir::AssertMessage<'tcx>,
485 _unwind: Option<BasicBlock>,
486 ) -> interpret::InterpResult<'tcx> {
491 _ecx: &InterpCx<'mir, 'tcx, Self>,
493 _left: &rustc_const_eval::interpret::ImmTy<'tcx, Self::Provenance>,
494 _right: &rustc_const_eval::interpret::ImmTy<'tcx, Self::Provenance>,
495 ) -> interpret::InterpResult<'tcx, (interpret::Scalar<Self::Provenance>, bool, Ty<'tcx>)> {
496 throw_unsup!(Unsupported("".into()))
500 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
501 _ptr: interpret::Pointer<Self::Provenance>,
502 ) -> interpret::InterpResult<'tcx> {
507 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
508 _frame: rustc_const_eval::interpret::Frame<'mir, 'tcx, Self::Provenance>,
509 ) -> interpret::InterpResult<
511 rustc_const_eval::interpret::Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>,
517 _ecx: &'a InterpCx<'mir, 'tcx, Self>,
518 ) -> &'a [rustc_const_eval::interpret::Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>]
524 _ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
526 rustc_const_eval::interpret::Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>,