]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/simplify.rs
perf(mir): Reserve enough space for the merged blocks before appending
[rust.git] / src / librustc_mir / transform / simplify.rs
1 //! A number of passes which remove various redundancies in the CFG.
2 //!
3 //! The `SimplifyCfg` pass gets rid of unnecessary blocks in the CFG, whereas the `SimplifyLocals`
4 //! gets rid of all the unnecessary local variable declarations.
5 //!
6 //! The `SimplifyLocals` pass is kinda expensive and therefore not very suitable to be run often.
7 //! Most of the passes should not care or be impacted in meaningful ways due to extra locals
8 //! either, so running the pass once, right before codegen, should suffice.
9 //!
10 //! On the other side of the spectrum, the `SimplifyCfg` pass is considerably cheap to run, thus
11 //! one should run it after every pass which may modify CFG in significant ways. This pass must
12 //! also be run before any analysis passes because it removes dead blocks, and some of these can be
13 //! ill-typed.
14 //!
15 //! The cause of this typing issue is typeck allowing most blocks whose end is not reachable have
16 //! an arbitrary return type, rather than having the usual () return type (as a note, typeck's
17 //! notion of reachability is in fact slightly weaker than MIR CFG reachability - see #31617). A
18 //! standard example of the situation is:
19 //!
20 //! ```rust
21 //!   fn example() {
22 //!       let _a: char = { return; };
23 //!   }
24 //! ```
25 //!
26 //! Here the block (`{ return; }`) has the return type `char`, rather than `()`, but the MIR we
27 //! naively generate still contains the `_a = ()` write in the unreachable block "after" the
28 //! return.
29
30 use crate::transform::{MirPass, MirSource};
31 use rustc::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
32 use rustc::mir::*;
33 use rustc::ty::{self, TyCtxt};
34 use rustc_index::bit_set::BitSet;
35 use rustc_index::vec::{Idx, IndexVec};
36 use std::borrow::Cow;
37
38 pub struct SimplifyCfg {
39     label: String,
40 }
41
42 impl SimplifyCfg {
43     pub fn new(label: &str) -> Self {
44         SimplifyCfg { label: format!("SimplifyCfg-{}", label) }
45     }
46 }
47
48 pub fn simplify_cfg(body: &mut BodyAndCache<'_>) {
49     CfgSimplifier::new(body).simplify();
50     remove_dead_blocks(body);
51
52     // FIXME: Should probably be moved into some kind of pass manager
53     body.basic_blocks_mut().raw.shrink_to_fit();
54 }
55
56 impl<'tcx> MirPass<'tcx> for SimplifyCfg {
57     fn name(&self) -> Cow<'_, str> {
58         Cow::Borrowed(&self.label)
59     }
60
61     fn run_pass(&self, _tcx: TyCtxt<'tcx>, _src: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>) {
62         debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, body);
63         simplify_cfg(body);
64     }
65 }
66
67 pub struct CfgSimplifier<'a, 'tcx> {
68     basic_blocks: &'a mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
69     pred_count: IndexVec<BasicBlock, u32>,
70 }
71
72 impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> {
73     pub fn new(body: &'a mut BodyAndCache<'tcx>) -> Self {
74         let mut pred_count = IndexVec::from_elem(0u32, body.basic_blocks());
75
76         // we can't use mir.predecessors() here because that counts
77         // dead blocks, which we don't want to.
78         pred_count[START_BLOCK] = 1;
79
80         for (_, data) in traversal::preorder(body) {
81             if let Some(ref term) = data.terminator {
82                 for &tgt in term.successors() {
83                     pred_count[tgt] += 1;
84                 }
85             }
86         }
87
88         let basic_blocks = body.basic_blocks_mut();
89
90         CfgSimplifier { basic_blocks, pred_count }
91     }
92
93     pub fn simplify(mut self) {
94         self.strip_nops();
95
96         let mut start = START_BLOCK;
97
98         let mut merged_blocks = Vec::new();
99         loop {
100             let mut changed = false;
101
102             self.collapse_goto_chain(&mut start, &mut changed);
103
104             for bb in self.basic_blocks.indices() {
105                 if self.pred_count[bb] == 0 {
106                     continue;
107                 }
108
109                 debug!("simplifying {:?}", bb);
110
111                 let mut terminator =
112                     self.basic_blocks[bb].terminator.take().expect("invalid terminator state");
113
114                 for successor in terminator.successors_mut() {
115                     self.collapse_goto_chain(successor, &mut changed);
116                 }
117
118                 let mut inner_changed = true;
119                 while inner_changed {
120                     inner_changed = false;
121                     inner_changed |= self.simplify_branch(&mut terminator);
122                     inner_changed |= self.merge_successor(&mut merged_blocks, &mut terminator);
123                     changed |= inner_changed;
124                 }
125
126                 let merged_block_count =
127                     merged_blocks.iter().map(|&i| self.basic_blocks[i].statements.len()).sum();
128
129                 if merged_block_count > 0 {
130                     let mut statements = std::mem::take(&mut self.basic_blocks[bb].statements);
131                     statements.reserve(merged_block_count);
132                     for &from in &merged_blocks {
133                         statements.append(&mut self.basic_blocks[from].statements);
134                     }
135                     self.basic_blocks[bb].statements = statements;
136                 }
137                 merged_blocks.clear();
138
139                 self.basic_blocks[bb].terminator = Some(terminator);
140
141                 changed |= inner_changed;
142             }
143
144             if !changed {
145                 break;
146             }
147         }
148
149         if start != START_BLOCK {
150             debug_assert!(self.pred_count[START_BLOCK] == 0);
151             self.basic_blocks.swap(START_BLOCK, start);
152             self.pred_count.swap(START_BLOCK, start);
153
154             // pred_count == 1 if the start block has no predecessor _blocks_.
155             if self.pred_count[START_BLOCK] > 1 {
156                 for (bb, data) in self.basic_blocks.iter_enumerated_mut() {
157                     if self.pred_count[bb] == 0 {
158                         continue;
159                     }
160
161                     for target in data.terminator_mut().successors_mut() {
162                         if *target == start {
163                             *target = START_BLOCK;
164                         }
165                     }
166                 }
167             }
168         }
169     }
170
171     // Collapse a goto chain starting from `start`
172     fn collapse_goto_chain(&mut self, start: &mut BasicBlock, changed: &mut bool) {
173         let mut terminator = match self.basic_blocks[*start] {
174             BasicBlockData {
175                 ref statements,
176                 terminator:
177                     ref mut terminator @ Some(Terminator { kind: TerminatorKind::Goto { .. }, .. }),
178                 ..
179             } if statements.is_empty() => terminator.take(),
180             // if `terminator` is None, this means we are in a loop. In that
181             // case, let all the loop collapse to its entry.
182             _ => return,
183         };
184
185         let target = match terminator {
186             Some(Terminator { kind: TerminatorKind::Goto { ref mut target }, .. }) => {
187                 self.collapse_goto_chain(target, changed);
188                 *target
189             }
190             _ => unreachable!(),
191         };
192         self.basic_blocks[*start].terminator = terminator;
193
194         debug!("collapsing goto chain from {:?} to {:?}", *start, target);
195
196         *changed |= *start != target;
197
198         if self.pred_count[*start] == 1 {
199             // This is the last reference to *start, so the pred-count to
200             // to target is moved into the current block.
201             self.pred_count[*start] = 0;
202         } else {
203             self.pred_count[target] += 1;
204             self.pred_count[*start] -= 1;
205         }
206
207         *start = target;
208     }
209
210     // merge a block with 1 `goto` predecessor to its parent
211     fn merge_successor(
212         &mut self,
213         merged_blocks: &mut Vec<BasicBlock>,
214         terminator: &mut Terminator<'tcx>,
215     ) -> bool {
216         let target = match terminator.kind {
217             TerminatorKind::Goto { target } if self.pred_count[target] == 1 => target,
218             _ => return false,
219         };
220
221         debug!("merging block {:?} into {:?}", target, terminator);
222         *terminator = match self.basic_blocks[target].terminator.take() {
223             Some(terminator) => terminator,
224             None => {
225                 // unreachable loop - this should not be possible, as we
226                 // don't strand blocks, but handle it correctly.
227                 return false;
228             }
229         };
230
231         merged_blocks.push(target);
232         self.pred_count[target] = 0;
233
234         true
235     }
236
237     // turn a branch with all successors identical to a goto
238     fn simplify_branch(&mut self, terminator: &mut Terminator<'tcx>) -> bool {
239         match terminator.kind {
240             TerminatorKind::SwitchInt { .. } => {}
241             _ => return false,
242         };
243
244         let first_succ = {
245             if let Some(&first_succ) = terminator.successors().nth(0) {
246                 if terminator.successors().all(|s| *s == first_succ) {
247                     let count = terminator.successors().count();
248                     self.pred_count[first_succ] -= (count - 1) as u32;
249                     first_succ
250                 } else {
251                     return false;
252                 }
253             } else {
254                 return false;
255             }
256         };
257
258         debug!("simplifying branch {:?}", terminator);
259         terminator.kind = TerminatorKind::Goto { target: first_succ };
260         true
261     }
262
263     fn strip_nops(&mut self) {
264         for blk in self.basic_blocks.iter_mut() {
265             blk.statements
266                 .retain(|stmt| if let StatementKind::Nop = stmt.kind { false } else { true })
267         }
268     }
269 }
270
271 pub fn remove_dead_blocks(body: &mut BodyAndCache<'_>) {
272     let mut seen = BitSet::new_empty(body.basic_blocks().len());
273     for (bb, _) in traversal::preorder(body) {
274         seen.insert(bb.index());
275     }
276
277     let basic_blocks = body.basic_blocks_mut();
278
279     let num_blocks = basic_blocks.len();
280     let mut replacements: Vec<_> = (0..num_blocks).map(BasicBlock::new).collect();
281     let mut used_blocks = 0;
282     for alive_index in seen.iter() {
283         replacements[alive_index] = BasicBlock::new(used_blocks);
284         if alive_index != used_blocks {
285             // Swap the next alive block data with the current available slot. Since
286             // alive_index is non-decreasing this is a valid operation.
287             basic_blocks.raw.swap(alive_index, used_blocks);
288         }
289         used_blocks += 1;
290     }
291     basic_blocks.raw.truncate(used_blocks);
292
293     for block in basic_blocks {
294         for target in block.terminator_mut().successors_mut() {
295             *target = replacements[target.index()];
296         }
297     }
298 }
299
300 pub struct SimplifyLocals;
301
302 impl<'tcx> MirPass<'tcx> for SimplifyLocals {
303     fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>) {
304         trace!("running SimplifyLocals on {:?}", source);
305         let locals = {
306             let read_only_cache = read_only!(body);
307             let mut marker = DeclMarker { locals: BitSet::new_empty(body.local_decls.len()), body };
308             marker.visit_body(read_only_cache);
309             // Return pointer and arguments are always live
310             marker.locals.insert(RETURN_PLACE);
311             for arg in body.args_iter() {
312                 marker.locals.insert(arg);
313             }
314
315             marker.locals
316         };
317
318         let map = make_local_map(&mut body.local_decls, locals);
319         // Update references to all vars and tmps now
320         LocalUpdater { map, tcx }.visit_body(body);
321         body.local_decls.shrink_to_fit();
322     }
323 }
324
325 /// Construct the mapping while swapping out unused stuff out from the `vec`.
326 fn make_local_map<V>(
327     vec: &mut IndexVec<Local, V>,
328     mask: BitSet<Local>,
329 ) -> IndexVec<Local, Option<Local>> {
330     let mut map: IndexVec<Local, Option<Local>> = IndexVec::from_elem(None, &*vec);
331     let mut used = Local::new(0);
332     for alive_index in mask.iter() {
333         map[alive_index] = Some(used);
334         if alive_index != used {
335             vec.swap(alive_index, used);
336         }
337         used.increment_by(1);
338     }
339     vec.truncate(used.index());
340     map
341 }
342
343 struct DeclMarker<'a, 'tcx> {
344     pub locals: BitSet<Local>,
345     pub body: &'a Body<'tcx>,
346 }
347
348 impl<'a, 'tcx> Visitor<'tcx> for DeclMarker<'a, 'tcx> {
349     fn visit_local(&mut self, local: &Local, ctx: PlaceContext, location: Location) {
350         // Ignore storage markers altogether, they get removed along with their otherwise unused
351         // decls.
352         // FIXME: Extend this to all non-uses.
353         if ctx.is_storage_marker() {
354             return;
355         }
356
357         // Ignore stores of constants because `ConstProp` and `CopyProp` can remove uses of many
358         // of these locals. However, if the local is still needed, then it will be referenced in
359         // another place and we'll mark it as being used there.
360         if ctx == PlaceContext::MutatingUse(MutatingUseContext::Store)
361             || ctx == PlaceContext::MutatingUse(MutatingUseContext::Projection)
362         {
363             let block = &self.body.basic_blocks()[location.block];
364             if location.statement_index != block.statements.len() {
365                 let stmt = &block.statements[location.statement_index];
366
367                 if let StatementKind::Assign(box (p, Rvalue::Use(Operand::Constant(c)))) =
368                     &stmt.kind
369                 {
370                     match c.literal.val {
371                         // Keep assignments from unevaluated constants around, since the evaluation
372                         // may report errors, even if the use of the constant is dead code.
373                         ty::ConstKind::Unevaluated(..) => {}
374                         _ => {
375                             if !p.is_indirect() {
376                                 trace!("skipping store of const value {:?} to {:?}", c, p);
377                                 return;
378                             }
379                         }
380                     }
381                 }
382             }
383         }
384
385         self.locals.insert(*local);
386     }
387 }
388
389 struct LocalUpdater<'tcx> {
390     map: IndexVec<Local, Option<Local>>,
391     tcx: TyCtxt<'tcx>,
392 }
393
394 impl<'tcx> MutVisitor<'tcx> for LocalUpdater<'tcx> {
395     fn tcx(&self) -> TyCtxt<'tcx> {
396         self.tcx
397     }
398
399     fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
400         // Remove unnecessary StorageLive and StorageDead annotations.
401         data.statements.retain(|stmt| match &stmt.kind {
402             StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => self.map[*l].is_some(),
403             StatementKind::Assign(box (place, _)) => self.map[place.local].is_some(),
404             _ => true,
405         });
406         self.super_basic_block_data(block, data);
407     }
408
409     fn visit_local(&mut self, l: &mut Local, _: PlaceContext, _: Location) {
410         *l = self.map[*l].unwrap();
411     }
412
413     fn process_projection_elem(&mut self, elem: &PlaceElem<'tcx>) -> Option<PlaceElem<'tcx>> {
414         match elem {
415             PlaceElem::Index(local) => Some(PlaceElem::Index(self.map[*local].unwrap())),
416             _ => None,
417         }
418     }
419 }