rustc_mir_transform/
instsimplify.rs

1//! Performs various peephole optimizations.
2
3use rustc_abi::ExternAbi;
4use rustc_ast::attr;
5use rustc_hir::LangItem;
6use rustc_middle::bug;
7use rustc_middle::mir::*;
8use rustc_middle::ty::layout::ValidityRequirement;
9use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, layout};
10use rustc_span::{DUMMY_SP, Symbol, sym};
11
12use crate::simplify::simplify_duplicate_switch_targets;
13
14pub(super) enum InstSimplify {
15    BeforeInline,
16    AfterSimplifyCfg,
17}
18
19impl<'tcx> crate::MirPass<'tcx> for InstSimplify {
20    fn name(&self) -> &'static str {
21        match self {
22            InstSimplify::BeforeInline => "InstSimplify-before-inline",
23            InstSimplify::AfterSimplifyCfg => "InstSimplify-after-simplifycfg",
24        }
25    }
26
27    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
28        sess.mir_opt_level() > 0
29    }
30
31    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
32        let ctx = InstSimplifyContext {
33            tcx,
34            local_decls: &body.local_decls,
35            typing_env: body.typing_env(tcx),
36        };
37        let preserve_ub_checks =
38            attr::contains_name(tcx.hir_krate_attrs(), sym::rustc_preserve_ub_checks);
39        for block in body.basic_blocks.as_mut() {
40            for statement in block.statements.iter_mut() {
41                let StatementKind::Assign(box (.., rvalue)) = &mut statement.kind else {
42                    continue;
43                };
44
45                if !preserve_ub_checks {
46                    ctx.simplify_ub_check(rvalue);
47                }
48                ctx.simplify_bool_cmp(rvalue);
49                ctx.simplify_ref_deref(rvalue);
50                ctx.simplify_ptr_aggregate(rvalue);
51                ctx.simplify_cast(rvalue);
52                ctx.simplify_repeated_aggregate(rvalue);
53                ctx.simplify_repeat_once(rvalue);
54            }
55
56            let terminator = block.terminator.as_mut().unwrap();
57            ctx.simplify_primitive_clone(terminator, &mut block.statements);
58            ctx.simplify_align_of_slice_val(terminator, &mut block.statements);
59            ctx.simplify_intrinsic_assert(terminator);
60            ctx.simplify_nounwind_call(terminator);
61            simplify_duplicate_switch_targets(terminator);
62        }
63    }
64
65    fn is_required(&self) -> bool {
66        false
67    }
68}
69
70struct InstSimplifyContext<'a, 'tcx> {
71    tcx: TyCtxt<'tcx>,
72    local_decls: &'a LocalDecls<'tcx>,
73    typing_env: ty::TypingEnv<'tcx>,
74}
75
76impl<'tcx> InstSimplifyContext<'_, 'tcx> {
77    /// Transform aggregates like [0, 0, 0, 0, 0] into [0; 5].
78    /// GVN can also do this optimization, but GVN is only run at mir-opt-level 2 so having this in
79    /// InstSimplify helps unoptimized builds.
80    fn simplify_repeated_aggregate(&self, rvalue: &mut Rvalue<'tcx>) {
81        let Rvalue::Aggregate(box AggregateKind::Array(_), fields) = &*rvalue else {
82            return;
83        };
84        if fields.len() < 5 {
85            return;
86        }
87        let (first, rest) = fields[..].split_first().unwrap();
88        let Operand::Constant(first) = first else {
89            return;
90        };
91        let Ok(first_val) = first.const_.eval(self.tcx, self.typing_env, first.span) else {
92            return;
93        };
94        if rest.iter().all(|field| {
95            let Operand::Constant(field) = field else {
96                return false;
97            };
98            let field = field.const_.eval(self.tcx, self.typing_env, field.span);
99            field == Ok(first_val)
100        }) {
101            let len = ty::Const::from_target_usize(self.tcx, fields.len().try_into().unwrap());
102            *rvalue = Rvalue::Repeat(Operand::Constant(first.clone()), len);
103        }
104    }
105
106    /// Transform boolean comparisons into logical operations.
107    fn simplify_bool_cmp(&self, rvalue: &mut Rvalue<'tcx>) {
108        let Rvalue::BinaryOp(op @ (BinOp::Eq | BinOp::Ne), box (a, b)) = &*rvalue else { return };
109        *rvalue = match (op, self.try_eval_bool(a), self.try_eval_bool(b)) {
110            // Transform "Eq(a, true)" ==> "a"
111            (BinOp::Eq, _, Some(true)) => Rvalue::Use(a.clone()),
112
113            // Transform "Ne(a, false)" ==> "a"
114            (BinOp::Ne, _, Some(false)) => Rvalue::Use(a.clone()),
115
116            // Transform "Eq(true, b)" ==> "b"
117            (BinOp::Eq, Some(true), _) => Rvalue::Use(b.clone()),
118
119            // Transform "Ne(false, b)" ==> "b"
120            (BinOp::Ne, Some(false), _) => Rvalue::Use(b.clone()),
121
122            // Transform "Eq(false, b)" ==> "Not(b)"
123            (BinOp::Eq, Some(false), _) => Rvalue::UnaryOp(UnOp::Not, b.clone()),
124
125            // Transform "Ne(true, b)" ==> "Not(b)"
126            (BinOp::Ne, Some(true), _) => Rvalue::UnaryOp(UnOp::Not, b.clone()),
127
128            // Transform "Eq(a, false)" ==> "Not(a)"
129            (BinOp::Eq, _, Some(false)) => Rvalue::UnaryOp(UnOp::Not, a.clone()),
130
131            // Transform "Ne(a, true)" ==> "Not(a)"
132            (BinOp::Ne, _, Some(true)) => Rvalue::UnaryOp(UnOp::Not, a.clone()),
133
134            _ => return,
135        };
136    }
137
138    fn try_eval_bool(&self, a: &Operand<'_>) -> Option<bool> {
139        let a = a.constant()?;
140        if a.const_.ty().is_bool() { a.const_.try_to_bool() } else { None }
141    }
142
143    /// Transform `&(*a)` ==> `a`.
144    fn simplify_ref_deref(&self, rvalue: &mut Rvalue<'tcx>) {
145        if let Rvalue::Ref(_, _, place) | Rvalue::RawPtr(_, place) = rvalue
146            && let Some((base, ProjectionElem::Deref)) = place.as_ref().last_projection()
147            && rvalue.ty(self.local_decls, self.tcx) == base.ty(self.local_decls, self.tcx).ty
148        {
149            *rvalue = Rvalue::Use(Operand::Copy(Place {
150                local: base.local,
151                projection: self.tcx.mk_place_elems(base.projection),
152            }));
153        }
154    }
155
156    /// Transform `Aggregate(RawPtr, [p, ()])` ==> `Cast(PtrToPtr, p)`.
157    fn simplify_ptr_aggregate(&self, rvalue: &mut Rvalue<'tcx>) {
158        if let Rvalue::Aggregate(box AggregateKind::RawPtr(pointee_ty, mutability), fields) = rvalue
159            && let meta_ty = fields.raw[1].ty(self.local_decls, self.tcx)
160            && meta_ty.is_unit()
161        {
162            // The mutable borrows we're holding prevent printing `rvalue` here
163            let mut fields = std::mem::take(fields);
164            let _meta = fields.pop().unwrap();
165            let data = fields.pop().unwrap();
166            let ptr_ty = Ty::new_ptr(self.tcx, *pointee_ty, *mutability);
167            *rvalue = Rvalue::Cast(CastKind::PtrToPtr, data, ptr_ty);
168        }
169    }
170
171    fn simplify_ub_check(&self, rvalue: &mut Rvalue<'tcx>) {
172        let Rvalue::NullaryOp(NullOp::UbChecks, _) = *rvalue else { return };
173
174        let const_ = Const::from_bool(self.tcx, self.tcx.sess.ub_checks());
175        let constant = ConstOperand { span: DUMMY_SP, const_, user_ty: None };
176        *rvalue = Rvalue::Use(Operand::Constant(Box::new(constant)));
177    }
178
179    fn simplify_cast(&self, rvalue: &mut Rvalue<'tcx>) {
180        let Rvalue::Cast(kind, operand, cast_ty) = rvalue else { return };
181
182        let operand_ty = operand.ty(self.local_decls, self.tcx);
183        if operand_ty == *cast_ty {
184            *rvalue = Rvalue::Use(operand.clone());
185        } else if *kind == CastKind::Transmute
186            // Transmuting an integer to another integer is just a signedness cast
187            && let (ty::Int(int), ty::Uint(uint)) | (ty::Uint(uint), ty::Int(int)) =
188                (operand_ty.kind(), cast_ty.kind())
189            && int.bit_width() == uint.bit_width()
190        {
191            // The width check isn't strictly necessary, as different widths
192            // are UB and thus we'd be allowed to turn it into a cast anyway.
193            // But let's keep the UB around for codegen to exploit later.
194            // (If `CastKind::Transmute` ever becomes *not* UB for mismatched sizes,
195            // then the width check is necessary for big-endian correctness.)
196            *kind = CastKind::IntToInt;
197        }
198    }
199
200    /// Simplify `[x; 1]` to just `[x]`.
201    fn simplify_repeat_once(&self, rvalue: &mut Rvalue<'tcx>) {
202        if let Rvalue::Repeat(operand, count) = rvalue
203            && let Some(1) = count.try_to_target_usize(self.tcx)
204        {
205            *rvalue = Rvalue::Aggregate(
206                Box::new(AggregateKind::Array(operand.ty(self.local_decls, self.tcx))),
207                [operand.clone()].into(),
208            );
209        }
210    }
211
212    fn simplify_primitive_clone(
213        &self,
214        terminator: &mut Terminator<'tcx>,
215        statements: &mut Vec<Statement<'tcx>>,
216    ) {
217        let TerminatorKind::Call {
218            func, args, destination, target: Some(destination_block), ..
219        } = &terminator.kind
220        else {
221            return;
222        };
223
224        // It's definitely not a clone if there are multiple arguments
225        let [arg] = &args[..] else { return };
226
227        // Only bother looking more if it's easy to know what we're calling
228        let Some((fn_def_id, ..)) = func.const_fn_def() else { return };
229
230        // These types are easily available from locals, so check that before
231        // doing DefId lookups to figure out what we're actually calling.
232        let arg_ty = arg.node.ty(self.local_decls, self.tcx);
233
234        let ty::Ref(_region, inner_ty, Mutability::Not) = *arg_ty.kind() else { return };
235
236        if !self.tcx.is_lang_item(fn_def_id, LangItem::CloneFn)
237            || !inner_ty.is_trivially_pure_clone_copy()
238        {
239            return;
240        }
241
242        let Some(arg_place) = arg.node.place() else { return };
243
244        statements.push(Statement::new(
245            terminator.source_info,
246            StatementKind::Assign(Box::new((
247                *destination,
248                Rvalue::Use(Operand::Copy(
249                    arg_place.project_deeper(&[ProjectionElem::Deref], self.tcx),
250                )),
251            ))),
252        ));
253        terminator.kind = TerminatorKind::Goto { target: *destination_block };
254    }
255
256    // Convert `align_of_val::<[T]>(ptr)` to `align_of::<T>()`, since the
257    // alignment of a slice doesn't actually depend on metadata at all
258    // and the element type is always `Sized`.
259    //
260    // This is here so it can run after inlining, where it's more useful.
261    // (LowerIntrinsics is done in cleanup, before the optimization passes.)
262    fn simplify_align_of_slice_val(
263        &self,
264        terminator: &mut Terminator<'tcx>,
265        statements: &mut Vec<Statement<'tcx>>,
266    ) {
267        if let TerminatorKind::Call {
268            func, args, destination, target: Some(destination_block), ..
269        } = &terminator.kind
270            && args.len() == 1
271            && let Some((fn_def_id, generics)) = func.const_fn_def()
272            && self.tcx.is_intrinsic(fn_def_id, sym::align_of_val)
273            && let ty::Slice(elem_ty) = *generics.type_at(0).kind()
274        {
275            statements.push(Statement::new(
276                terminator.source_info,
277                StatementKind::Assign(Box::new((
278                    *destination,
279                    Rvalue::NullaryOp(NullOp::AlignOf, elem_ty),
280                ))),
281            ));
282            terminator.kind = TerminatorKind::Goto { target: *destination_block };
283        }
284    }
285
286    fn simplify_nounwind_call(&self, terminator: &mut Terminator<'tcx>) {
287        let TerminatorKind::Call { ref func, ref mut unwind, .. } = terminator.kind else {
288            return;
289        };
290
291        let Some((def_id, _)) = func.const_fn_def() else {
292            return;
293        };
294
295        let body_ty = self.tcx.type_of(def_id).skip_binder();
296        let body_abi = match body_ty.kind() {
297            ty::FnDef(..) => body_ty.fn_sig(self.tcx).abi(),
298            ty::Closure(..) => ExternAbi::RustCall,
299            ty::Coroutine(..) => ExternAbi::Rust,
300            _ => bug!("unexpected body ty: {body_ty:?}"),
301        };
302
303        if !layout::fn_can_unwind(self.tcx, Some(def_id), body_abi) {
304            *unwind = UnwindAction::Unreachable;
305        }
306    }
307
308    fn simplify_intrinsic_assert(&self, terminator: &mut Terminator<'tcx>) {
309        let TerminatorKind::Call { ref func, target: ref mut target @ Some(target_block), .. } =
310            terminator.kind
311        else {
312            return;
313        };
314        let func_ty = func.ty(self.local_decls, self.tcx);
315        let Some((intrinsic_name, args)) = resolve_rust_intrinsic(self.tcx, func_ty) else {
316            return;
317        };
318        // The intrinsics we are interested in have one generic parameter
319        let [arg, ..] = args[..] else { return };
320
321        let known_is_valid =
322            intrinsic_assert_panics(self.tcx, self.typing_env, arg, intrinsic_name);
323        match known_is_valid {
324            // We don't know the layout or it's not validity assertion at all, don't touch it
325            None => {}
326            Some(true) => {
327                // If we know the assert panics, indicate to later opts that the call diverges
328                *target = None;
329            }
330            Some(false) => {
331                // If we know the assert does not panic, turn the call into a Goto
332                terminator.kind = TerminatorKind::Goto { target: target_block };
333            }
334        }
335    }
336}
337
338fn intrinsic_assert_panics<'tcx>(
339    tcx: TyCtxt<'tcx>,
340    typing_env: ty::TypingEnv<'tcx>,
341    arg: ty::GenericArg<'tcx>,
342    intrinsic_name: Symbol,
343) -> Option<bool> {
344    let requirement = ValidityRequirement::from_intrinsic(intrinsic_name)?;
345    let ty = arg.expect_ty();
346    Some(!tcx.check_validity_requirement((requirement, typing_env.as_query_input(ty))).ok()?)
347}
348
349fn resolve_rust_intrinsic<'tcx>(
350    tcx: TyCtxt<'tcx>,
351    func_ty: Ty<'tcx>,
352) -> Option<(Symbol, GenericArgsRef<'tcx>)> {
353    let ty::FnDef(def_id, args) = *func_ty.kind() else { return None };
354    let intrinsic = tcx.intrinsic(def_id)?;
355    Some((intrinsic.name, args))
356}