]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/instcombine.rs
Rollup merge of #92274 - woppopo:const_deallocate, r=oli-obk
[rust.git] / compiler / rustc_mir_transform / src / instcombine.rs
1 //! Performs various peephole optimizations.
2
3 use crate::MirPass;
4 use rustc_hir::Mutability;
5 use rustc_middle::mir::{
6     BinOp, Body, Constant, LocalDecls, Operand, Place, ProjectionElem, Rvalue, SourceInfo,
7     StatementKind, UnOp,
8 };
9 use rustc_middle::ty::{self, TyCtxt};
10
11 pub struct InstCombine;
12
13 impl<'tcx> MirPass<'tcx> for InstCombine {
14     fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
15         sess.mir_opt_level() > 0
16     }
17
18     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
19         let (basic_blocks, local_decls) = body.basic_blocks_and_local_decls_mut();
20         let ctx = InstCombineContext { tcx, local_decls };
21         for block in basic_blocks.iter_mut() {
22             for statement in block.statements.iter_mut() {
23                 match statement.kind {
24                     StatementKind::Assign(box (_place, ref mut rvalue)) => {
25                         ctx.combine_bool_cmp(&statement.source_info, rvalue);
26                         ctx.combine_ref_deref(&statement.source_info, rvalue);
27                         ctx.combine_len(&statement.source_info, rvalue);
28                     }
29                     _ => {}
30                 }
31             }
32         }
33     }
34 }
35
36 struct InstCombineContext<'tcx, 'a> {
37     tcx: TyCtxt<'tcx>,
38     local_decls: &'a LocalDecls<'tcx>,
39 }
40
41 impl<'tcx> InstCombineContext<'tcx, '_> {
42     fn should_combine(&self, source_info: &SourceInfo, rvalue: &Rvalue<'tcx>) -> bool {
43         self.tcx.consider_optimizing(|| {
44             format!("InstCombine - Rvalue: {:?} SourceInfo: {:?}", rvalue, source_info)
45         })
46     }
47
48     /// Transform boolean comparisons into logical operations.
49     fn combine_bool_cmp(&self, source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
50         match rvalue {
51             Rvalue::BinaryOp(op @ (BinOp::Eq | BinOp::Ne), box (a, b)) => {
52                 let new = match (op, self.try_eval_bool(a), self.try_eval_bool(b)) {
53                     // Transform "Eq(a, true)" ==> "a"
54                     (BinOp::Eq, _, Some(true)) => Some(Rvalue::Use(a.clone())),
55
56                     // Transform "Ne(a, false)" ==> "a"
57                     (BinOp::Ne, _, Some(false)) => Some(Rvalue::Use(a.clone())),
58
59                     // Transform "Eq(true, b)" ==> "b"
60                     (BinOp::Eq, Some(true), _) => Some(Rvalue::Use(b.clone())),
61
62                     // Transform "Ne(false, b)" ==> "b"
63                     (BinOp::Ne, Some(false), _) => Some(Rvalue::Use(b.clone())),
64
65                     // Transform "Eq(false, b)" ==> "Not(b)"
66                     (BinOp::Eq, Some(false), _) => Some(Rvalue::UnaryOp(UnOp::Not, b.clone())),
67
68                     // Transform "Ne(true, b)" ==> "Not(b)"
69                     (BinOp::Ne, Some(true), _) => Some(Rvalue::UnaryOp(UnOp::Not, b.clone())),
70
71                     // Transform "Eq(a, false)" ==> "Not(a)"
72                     (BinOp::Eq, _, Some(false)) => Some(Rvalue::UnaryOp(UnOp::Not, a.clone())),
73
74                     // Transform "Ne(a, true)" ==> "Not(a)"
75                     (BinOp::Ne, _, Some(true)) => Some(Rvalue::UnaryOp(UnOp::Not, a.clone())),
76
77                     _ => None,
78                 };
79
80                 if let Some(new) = new {
81                     if self.should_combine(source_info, rvalue) {
82                         *rvalue = new;
83                     }
84                 }
85             }
86
87             _ => {}
88         }
89     }
90
91     fn try_eval_bool(&self, a: &Operand<'_>) -> Option<bool> {
92         let a = a.constant()?;
93         if a.literal.ty().is_bool() { a.literal.try_to_bool() } else { None }
94     }
95
96     /// Transform "&(*a)" ==> "a".
97     fn combine_ref_deref(&self, source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
98         if let Rvalue::Ref(_, _, place) = rvalue {
99             if let Some((base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
100                 if let ty::Ref(_, _, Mutability::Not) =
101                     base.ty(self.local_decls, self.tcx).ty.kind()
102                 {
103                     // The dereferenced place must have type `&_`, so that we don't copy `&mut _`.
104                 } else {
105                     return;
106                 }
107
108                 if !self.should_combine(source_info, rvalue) {
109                     return;
110                 }
111
112                 *rvalue = Rvalue::Use(Operand::Copy(Place {
113                     local: base.local,
114                     projection: self.tcx.intern_place_elems(base.projection),
115                 }));
116             }
117         }
118     }
119
120     /// Transform "Len([_; N])" ==> "N".
121     fn combine_len(&self, source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
122         if let Rvalue::Len(ref place) = *rvalue {
123             let place_ty = place.ty(self.local_decls, self.tcx).ty;
124             if let ty::Array(_, len) = *place_ty.kind() {
125                 if !self.should_combine(source_info, rvalue) {
126                     return;
127                 }
128
129                 let constant =
130                     Constant { span: source_info.span, literal: len.into(), user_ty: None };
131                 *rvalue = Rvalue::Use(Operand::Constant(Box::new(constant)));
132             }
133         }
134     }
135 }