rustc_mir_transform/
lower_slice_len.rs

1//! This pass lowers calls to core::slice::len to just PtrMetadata op.
2//! It should run before inlining!
3
4use rustc_hir::def_id::DefId;
5use rustc_middle::mir::*;
6use rustc_middle::ty::TyCtxt;
7
8pub(super) struct LowerSliceLenCalls;
9
10impl<'tcx> crate::MirPass<'tcx> for LowerSliceLenCalls {
11    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
12        sess.mir_opt_level() > 0
13    }
14
15    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
16        let language_items = tcx.lang_items();
17        let Some(slice_len_fn_item_def_id) = language_items.slice_len_fn() else {
18            // there is no lang item to compare to :)
19            return;
20        };
21
22        // The one successor remains unchanged, so no need to invalidate
23        let basic_blocks = body.basic_blocks.as_mut_preserves_cfg();
24        for block in basic_blocks {
25            // lower `<[_]>::len` calls
26            lower_slice_len_call(block, slice_len_fn_item_def_id);
27        }
28    }
29
30    fn is_required(&self) -> bool {
31        false
32    }
33}
34
35fn lower_slice_len_call<'tcx>(block: &mut BasicBlockData<'tcx>, slice_len_fn_item_def_id: DefId) {
36    let terminator = block.terminator();
37    if let TerminatorKind::Call {
38        func,
39        args,
40        destination,
41        target: Some(bb),
42        call_source: CallSource::Normal,
43        ..
44    } = &terminator.kind
45        // some heuristics for fast rejection
46        && let [arg] = &args[..]
47        && let Some((fn_def_id, _)) = func.const_fn_def()
48        && fn_def_id == slice_len_fn_item_def_id
49    {
50        // perform modifications from something like:
51        //     _5 = core::slice::<impl [u8]>::len(move _6) -> bb1
52        // into:
53        //     _5 = PtrMetadata(move _6)
54        //     goto bb1
55
56        // make new RValue for Len
57        let r_value = Rvalue::UnaryOp(UnOp::PtrMetadata, arg.node.clone());
58        let len_statement_kind = StatementKind::Assign(Box::new((*destination, r_value)));
59        let add_statement =
60            Statement { kind: len_statement_kind, source_info: terminator.source_info };
61
62        // modify terminator into simple Goto
63        let new_terminator_kind = TerminatorKind::Goto { target: *bb };
64
65        block.statements.push(add_statement);
66        block.terminator_mut().kind = new_terminator_kind;
67    }
68}