]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/instcombine.rs
Auto merge of #84944 - lcnr:obligation-dedup, r=jackh726
[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 && self.should_combine(source_info, rvalue) {
81                     *rvalue = new;
82                 }
83             }
84
85             _ => {}
86         }
87     }
88
89     fn try_eval_bool(&self, a: &Operand<'_>) -> Option<bool> {
90         let a = a.constant()?;
91         if a.literal.ty().is_bool() { a.literal.try_to_bool() } else { None }
92     }
93
94     /// Transform "&(*a)" ==> "a".
95     fn combine_ref_deref(&self, source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
96         if let Rvalue::Ref(_, _, place) = rvalue {
97             if let Some((base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
98                 if let ty::Ref(_, _, Mutability::Not) =
99                     base.ty(self.local_decls, self.tcx).ty.kind()
100                 {
101                     // The dereferenced place must have type `&_`, so that we don't copy `&mut _`.
102                 } else {
103                     return;
104                 }
105
106                 if !self.should_combine(source_info, rvalue) {
107                     return;
108                 }
109
110                 *rvalue = Rvalue::Use(Operand::Copy(Place {
111                     local: base.local,
112                     projection: self.tcx.intern_place_elems(base.projection),
113                 }));
114             }
115         }
116     }
117
118     /// Transform "Len([_; N])" ==> "N".
119     fn combine_len(&self, source_info: &SourceInfo, rvalue: &mut Rvalue<'tcx>) {
120         if let Rvalue::Len(ref place) = *rvalue {
121             let place_ty = place.ty(self.local_decls, self.tcx).ty;
122             if let ty::Array(_, len) = *place_ty.kind() {
123                 if !self.should_combine(source_info, rvalue) {
124                     return;
125                 }
126
127                 let constant =
128                     Constant { span: source_info.span, literal: len.into(), user_ty: None };
129                 *rvalue = Rvalue::Use(Operand::Constant(Box::new(constant)));
130             }
131         }
132     }
133 }