Skip to main content

rustc_mir_transform/
early_otherwise_branch.rs

1use std::fmt::Debug;
2
3use rustc_index::bit_set::DenseBitSet;
4use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, VisitPlacesWith, Visitor};
5use rustc_middle::mir::*;
6use rustc_middle::ty::{self, Ty, TyCtxt};
7use tracing::trace;
8
9use super::simplify::simplify_cfg;
10use super::ssa::SsaLocals;
11use crate::PassPolicy;
12use crate::patch::MirPatch;
13
14/// This pass optimizes something like
15/// ```ignore (syntax-highlighting-only)
16/// let x: Option<()>;
17/// let y: Option<()>;
18/// match (x,y) {
19///     (Some(_), Some(_)) => {0},
20///     (None, None) => {2},
21///     _ => {1}
22/// }
23/// ```
24/// into something like
25/// ```ignore (syntax-highlighting-only)
26/// let x: Option<()>;
27/// let y: Option<()>;
28/// let discriminant_x = std::mem::discriminant(x);
29/// let discriminant_y = std::mem::discriminant(y);
30/// if discriminant_x == discriminant_y {
31///     match x {
32///         Some(_) => 0,
33///         None => 2,
34///     }
35/// } else {
36///     1
37/// }
38/// ```
39///
40/// Specifically, it looks for instances of control flow like this:
41/// ```text
42///
43///     =================
44///     |      BB1      |
45///     |---------------|                  ============================
46///     |     ...       |         /------> |            BBC           |
47///     |---------------|         |        |--------------------------|
48///     |  switchInt(Q) |         |        |   _cl = discriminant(P)  |
49///     |       c       | --------/        |--------------------------|
50///     |       d       | -------\         |       switchInt(_cl)     |
51///     |      ...      |        |         |            c             | ---> BBC.2
52///     |    otherwise  | --\    |    /--- |         otherwise        |
53///     =================   |    |    |    ============================
54///                         |    |    |
55///     =================   |    |    |
56///     |      BBU      | <-|    |    |    ============================
57///     |---------------|        \-------> |            BBD           |
58///     |---------------|             |    |--------------------------|
59///     |  unreachable  |             |    |   _dl = discriminant(P)  |
60///     =================             |    |--------------------------|
61///                                   |    |       switchInt(_dl)     |
62///     =================             |    |            d             | ---> BBD.2
63///     |      BB9      | <--------------- |         otherwise        |
64///     |---------------|                  ============================
65///     |      ...      |
66///     =================
67/// ```
68/// Where the `otherwise` branch on `BB1` is permitted to either go to `BBU`. In the
69/// code:
70///  - `BB1` is `parent` and `BBC, BBD` are children
71///  - `P` is `child_place`
72///  - `child_ty` is the type of `_cl`.
73///  - `Q` is `parent_op`.
74///  - `parent_ty` is the type of `Q`.
75///  - `BB9` is `destination`
76/// All this is then transformed into:
77/// ```text
78///
79///     =======================
80///     |          BB1        |
81///     |---------------------|                  ============================
82///     |          ...        |         /------> |           BBEq           |
83///     | _s = discriminant(P)|         |        |--------------------------|
84///     | _t = Ne(Q, _s)      |         |        |--------------------------|
85///     |---------------------|         |        |       switchInt(Q)       |
86///     |     switchInt(_t)   |         |        |            c             | ---> BBC.2
87///     |        false        | --------/        |            d             | ---> BBD.2
88///     |       otherwise     |       /--------- |         otherwise        |
89///     =======================       |          ============================
90///                                   |
91///     =================             |
92///     |      BB9      | <-----------/
93///     |---------------|
94///     |      ...      |
95///     =================
96/// ```
97pub(super) struct EarlyOtherwiseBranch;
98
99impl<'tcx> crate::MirPass<'tcx> for EarlyOtherwiseBranch {
100    fn policy(&self, ctx: &crate::PassCtx<'_>) -> PassPolicy {
101        PassPolicy::optional(ctx.mir_opt_level() >= 2)
102    }
103
104    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
105        trace!("running EarlyOtherwiseBranch on {:?}", body.source);
106
107        let mut should_cleanup = false;
108        // The transform only writes fresh temporaries, so argument facts survive CFG changes.
109        let mut unchanged_arguments = None;
110
111        // Also consider newly generated bbs in the same pass
112        for parent in body.basic_blocks.indices() {
113            let bbs = &*body.basic_blocks;
114            let Some(opt_data) = evaluate_candidate(tcx, body, parent, &mut unchanged_arguments)
115            else {
116                continue;
117            };
118
119            trace!("SUCCESS: found optimization possibility to apply: {opt_data:?}");
120
121            should_cleanup = true;
122
123            let TerminatorKind::SwitchInt { discr: parent_op, targets: parent_targets } =
124                &bbs[parent].terminator().kind
125            else {
126                unreachable!()
127            };
128            // Always correct since we can only switch on `Copy` types
129            let parent_op = parent_op.to_copy();
130            let parent_ty = parent_op.ty(body.local_decls(), tcx);
131            let statements_before = bbs[parent].statements.len();
132            let parent_end = Location { block: parent, statement_index: statements_before };
133
134            let mut patch = MirPatch::new(body);
135
136            let second_operand = if opt_data.need_hoist_discriminant {
137                // create temp to store second discriminant in, `_s` in example above
138                let second_discriminant_temp =
139                    patch.new_temp(opt_data.child_ty, opt_data.child_source.span);
140
141                // create assignment of discriminant
142                patch.add_assign(
143                    parent_end,
144                    Place::from(second_discriminant_temp),
145                    Rvalue::Discriminant(opt_data.child_place),
146                );
147                Operand::Move(Place::from(second_discriminant_temp))
148            } else {
149                Operand::Copy(opt_data.child_place)
150            };
151
152            // create temp to store inequality comparison between the two discriminants, `_t` in
153            // example above
154            let nequal = BinOp::Ne;
155            let comp_res_type = nequal.ty(tcx, parent_ty, opt_data.child_ty);
156            let comp_temp = patch.new_temp(comp_res_type, opt_data.child_source.span);
157
158            // create inequality comparison
159            let comp_rvalue =
160                Rvalue::BinaryOp(nequal, Box::new((parent_op.clone(), second_operand)));
161            patch.add_statement(
162                parent_end,
163                StatementKind::Assign(Box::new((Place::from(comp_temp), comp_rvalue))),
164            );
165
166            let eq_new_targets = parent_targets.iter().map(|(value, child)| {
167                let TerminatorKind::SwitchInt { targets, .. } = &bbs[child].terminator().kind
168                else {
169                    unreachable!()
170                };
171                (value, targets.target_for_value(value))
172            });
173            // The otherwise either is the same target branch or an unreachable.
174            let eq_targets = SwitchTargets::new(eq_new_targets, parent_targets.otherwise());
175
176            // Create `bbEq` in example above
177            let eq_switch = BasicBlockData::new(
178                Terminator {
179                    source_info: bbs[parent].terminator().source_info,
180                    kind: TerminatorKind::SwitchInt {
181                        // switch on the first discriminant, so we can mark the second one as dead
182                        discr: parent_op,
183                        targets: eq_targets,
184                    },
185                },
186                bbs[parent].is_cleanup,
187            );
188
189            let eq_bb = patch.new_block(eq_switch);
190
191            // Jump to it on the basis of the inequality comparison
192            let true_case = opt_data.destination;
193            let false_case = eq_bb;
194            patch.patch_terminator(
195                parent,
196                TerminatorKind::if_(Operand::Move(Place::from(comp_temp)), true_case, false_case),
197            );
198
199            patch.apply(body);
200        }
201
202        // Since this optimization adds new basic blocks and invalidates others,
203        // clean up the cfg to make it nicer for other passes
204        if should_cleanup {
205            simplify_cfg(tcx, body);
206        }
207    }
208}
209
210#[derive(Debug)]
211struct OptimizationData<'tcx> {
212    destination: BasicBlock,
213    child_place: Place<'tcx>,
214    child_ty: Ty<'tcx>,
215    child_source: SourceInfo,
216    need_hoist_discriminant: bool,
217}
218
219fn evaluate_candidate<'tcx>(
220    tcx: TyCtxt<'tcx>,
221    body: &Body<'tcx>,
222    parent: BasicBlock,
223    unchanged_arguments: &mut Option<UnchangedArguments>,
224) -> Option<OptimizationData<'tcx>> {
225    let bbs = &body.basic_blocks;
226    // NB: If this BB is a cleanup, we may need to figure out what else needs to be handled.
227    if bbs[parent].is_cleanup {
228        return None;
229    }
230    let TerminatorKind::SwitchInt { targets, discr: parent_discr } = &bbs[parent].terminator().kind
231    else {
232        return None;
233    };
234    let parent_ty = parent_discr.ty(body.local_decls(), tcx);
235    let (_, child) = targets.iter().next()?;
236
237    let Terminator {
238        kind: TerminatorKind::SwitchInt { targets: child_targets, discr: child_discr },
239        source_info,
240    } = bbs[child].terminator()
241    else {
242        return None;
243    };
244    let child_ty = child_discr.ty(body.local_decls(), tcx);
245    if child_ty != parent_ty {
246        return None;
247    }
248
249    // For now, we only handle:
250    // ```
251    // bb4: {
252    //     _8 = discriminant((_3.1: Enum1));
253    //    switchInt(move _8) -> [2: bb7, otherwise: bb1];
254    // }
255    // ```
256    // and
257    // ```
258    // bb2: {
259    //     switchInt((_3.1: u64)) -> [1: bb5, otherwise: bb1];
260    // }
261    // ```
262    if bbs[child].statements.len() > 1 {
263        return None;
264    }
265
266    // When thie BB has exactly one statement, this statement should be discriminant.
267    let need_hoist_discriminant = bbs[child].statements.len() == 1;
268    let otherwise_is_empty_unreachable = bbs[targets.otherwise()].is_empty_unreachable();
269    let child_place = if need_hoist_discriminant {
270        // Handle:
271        // ```
272        // bb4: {
273        //     _8 = discriminant((_3.1: Enum1));
274        //    switchInt(move _8) -> [2: bb7, otherwise: bb1];
275        // }
276        // ```
277        let [
278            Statement {
279                kind: StatementKind::Assign((_, Rvalue::Discriminant(child_place))), ..
280            },
281        ] = bbs[child].statements.as_slice()
282        else {
283            return None;
284        };
285        *child_place
286    } else {
287        // Handle:
288        // ```
289        // bb2: {
290        //     switchInt((_3.1: u64)) -> [1: bb5, otherwise: bb1];
291        // }
292        // ```
293        let Operand::Copy(child_place) = child_discr else {
294            return None;
295        };
296        *child_place
297    };
298    let destination = if otherwise_is_empty_unreachable {
299        child_targets.otherwise()
300    } else {
301        targets.otherwise()
302    };
303
304    // Verify that the optimization is legal for each branch
305    for (value, child) in targets.iter() {
306        if !verify_candidate_branch(
307            &bbs[child],
308            value,
309            child_place,
310            destination,
311            need_hoist_discriminant,
312        ) {
313            return None;
314        }
315    }
316    // A stable address does not imply that the child place is initialized on the otherwise path.
317    // Keep discriminant hoisting restricted to exhaustive switches (#95162).
318    if !otherwise_is_empty_unreachable
319        && (need_hoist_discriminant
320            || !unchanged_arguments
321                .get_or_insert_with(|| UnchangedArguments::new(tcx, body))
322                .can_hoist(body, child_place))
323    {
324        return None;
325    }
326    Some(OptimizationData {
327        destination,
328        child_place,
329        child_ty,
330        child_source: *source_info,
331        need_hoist_discriminant,
332    })
333}
334
335fn verify_candidate_branch<'tcx>(
336    branch: &BasicBlockData<'tcx>,
337    value: u128,
338    place: Place<'tcx>,
339    destination: BasicBlock,
340    need_hoist_discriminant: bool,
341) -> bool {
342    // In order for the optimization to be correct, the terminator must be a `SwitchInt`.
343    let TerminatorKind::SwitchInt { discr: switch_op, targets } = &branch.terminator().kind else {
344        return false;
345    };
346    if need_hoist_discriminant {
347        // If we need hoist discriminant, the branch must have exactly one statement.
348        let [statement] = branch.statements.as_slice() else {
349            return false;
350        };
351        // The statement must assign the discriminant of `place`.
352        let StatementKind::Assign((discr_place, Rvalue::Discriminant(from_place))) = statement.kind
353        else {
354            return false;
355        };
356        if from_place != place {
357            return false;
358        }
359        // The assignment must invalidate a local that terminate on a `SwitchInt`.
360        if !discr_place.projection.is_empty() || *switch_op != Operand::Move(discr_place) {
361            return false;
362        }
363    } else {
364        // If we don't need hoist discriminant, the branch must not have any statements.
365        if !branch.statements.is_empty() {
366            return false;
367        }
368        // The place on `SwitchInt` must be the same.
369        if *switch_op != Operand::Copy(place) {
370            return false;
371        }
372    }
373    // It must fall through to `destination` if the switch misses.
374    if destination != targets.otherwise() {
375        return false;
376    }
377    // It must have exactly one branch for value `value` and have no more branches.
378    let mut iter = targets.iter();
379    let (Some((target_value, _)), None) = (iter.next(), iter.next()) else {
380        return false;
381    };
382    target_value == value
383}
384
385struct UnchangedArguments(DenseBitSet<Local>);
386
387impl UnchangedArguments {
388    fn new<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> Self {
389        let ssa = SsaLocals::new(tcx, body, body.typing_env(tcx));
390        let mut arguments = DenseBitSet::new_empty(body.local_decls.len());
391        for arg in body.args_iter() {
392            if ssa.is_ssa(arg) && !ssa.borrowed_locals().contains(arg) {
393                arguments.insert(arg);
394            }
395        }
396        // SSA does not track storage lifetimes or invalidate moved places.
397        VisitPlacesWith(|place: Place<'_>, context: PlaceContext| {
398            if matches!(context, PlaceContext::NonMutatingUse(NonMutatingUseContext::Move))
399                || context.is_storage_marker()
400            {
401                arguments.remove(place.local);
402            }
403        })
404        .visit_body(body);
405        Self(arguments)
406    }
407
408    fn can_hoist<'tcx>(&self, body: &Body<'tcx>, place: Place<'tcx>) -> bool {
409        // New temporaries added by this pass are outside the cached bitset.
410        if !self.0.contains_loose(place.local) {
411            return false;
412        }
413        let mut ty = body.local_decls[place.local].ty;
414        for elem in place.projection.iter() {
415            let ProjectionElem::Field(_, field_ty) = elem else {
416                return false;
417            };
418            // A valid union or enum need not have initialized bytes in every field.
419            let fields_are_valid = match ty.kind() {
420                ty::Tuple(_) => true,
421                ty::Adt(def, _) => def.is_struct(),
422                _ => false,
423            };
424            if !fields_are_valid {
425                return false;
426            }
427            ty = field_ty;
428        }
429        true
430    }
431}