1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A number of passes which remove various redundancies in the CFG.
13 //! The `SimplifyCfg` pass gets rid of unnecessary blocks in the CFG, whereas the `SimplifyLocals`
14 //! gets rid of all the unnecessary local variable declarations.
16 //! The `SimplifyLocals` pass is kinda expensive and therefore not very suitable to be run often.
17 //! Most of the passes should not care or be impacted in meaningful ways due to extra locals
18 //! either, so running the pass once, right before translation, should suffice.
20 //! On the other side of the spectrum, the `SimplifyCfg` pass is considerably cheap to run, thus
21 //! one should run it after every pass which may modify CFG in significant ways. This pass must
22 //! also be run before any analysis passes because it removes dead blocks, and some of these can be
25 //! The cause of this typing issue is typeck allowing most blocks whose end is not reachable have
26 //! an arbitrary return type, rather than having the usual () return type (as a note, typeck's
27 //! notion of reachability is in fact slightly weaker than MIR CFG reachability - see #31617). A
28 //! standard example of the situation is:
32 //! let _a: char = { return; };
36 //! Here the block (`{ return; }`) has the return type `char`, rather than `()`, but the MIR we
37 //! naively generate still contains the `_a = ()` write in the unreachable block "after" the
40 use rustc_data_structures::bitvec::BitVector;
41 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
42 use rustc::ty::TyCtxt;
44 use rustc::mir::transform::{MirPass, MirSource, Pass};
45 use rustc::mir::visit::{MutVisitor, Visitor, LvalueContext};
48 pub struct SimplifyCfg<'a> { label: &'a str }
50 impl<'a> SimplifyCfg<'a> {
51 pub fn new(label: &'a str) -> Self {
52 SimplifyCfg { label: label }
56 pub fn simplify_cfg(mir: &mut Mir) {
57 CfgSimplifier::new(mir).simplify();
58 remove_dead_blocks(mir);
60 // FIXME: Should probably be moved into some kind of pass manager
61 mir.basic_blocks_mut().raw.shrink_to_fit();
64 impl<'l, 'tcx> MirPass<'tcx> for SimplifyCfg<'l> {
65 fn run_pass<'a>(&mut self, _tcx: TyCtxt<'a, 'tcx, 'tcx>, _src: MirSource, mir: &mut Mir<'tcx>) {
66 debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, mir);
71 impl<'l> Pass for SimplifyCfg<'l> {
72 fn disambiguator<'a>(&'a self) -> Option<Box<fmt::Display+'a>> {
73 Some(Box::new(self.label))
76 // avoid calling `type_name` - it contains `<'static>`
77 fn name(&self) -> ::std::borrow::Cow<'static, str> { "SimplifyCfg".into() }
80 pub struct CfgSimplifier<'a, 'tcx: 'a> {
81 basic_blocks: &'a mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
82 pred_count: IndexVec<BasicBlock, u32>
85 impl<'a, 'tcx: 'a> CfgSimplifier<'a, 'tcx> {
86 pub fn new(mir: &'a mut Mir<'tcx>) -> Self {
87 let mut pred_count = IndexVec::from_elem(0u32, mir.basic_blocks());
89 // we can't use mir.predecessors() here because that counts
90 // dead blocks, which we don't want to.
91 pred_count[START_BLOCK] = 1;
93 for (_, data) in traversal::preorder(mir) {
94 if let Some(ref term) = data.terminator {
95 for &tgt in term.successors().iter() {
101 let basic_blocks = mir.basic_blocks_mut();
104 basic_blocks: basic_blocks,
105 pred_count: pred_count
109 pub fn simplify(mut self) {
111 let mut changed = false;
113 for bb in (0..self.basic_blocks.len()).map(BasicBlock::new) {
114 if self.pred_count[bb] == 0 {
118 debug!("simplifying {:?}", bb);
120 let mut terminator = self.basic_blocks[bb].terminator.take()
121 .expect("invalid terminator state");
123 for successor in terminator.successors_mut() {
124 self.collapse_goto_chain(successor, &mut changed);
127 let mut new_stmts = vec![];
128 let mut inner_changed = true;
129 while inner_changed {
130 inner_changed = false;
131 inner_changed |= self.simplify_branch(&mut terminator);
132 inner_changed |= self.merge_successor(&mut new_stmts, &mut terminator);
133 changed |= inner_changed;
136 self.basic_blocks[bb].statements.extend(new_stmts);
137 self.basic_blocks[bb].terminator = Some(terminator);
139 changed |= inner_changed;
142 if !changed { break }
148 // Collapse a goto chain starting from `start`
149 fn collapse_goto_chain(&mut self, start: &mut BasicBlock, changed: &mut bool) {
150 let mut terminator = match self.basic_blocks[*start] {
153 terminator: ref mut terminator @ Some(Terminator {
154 kind: TerminatorKind::Goto { .. }, ..
156 } if statements.is_empty() => terminator.take(),
157 // if `terminator` is None, this means we are in a loop. In that
158 // case, let all the loop collapse to its entry.
162 let target = match terminator {
163 Some(Terminator { kind: TerminatorKind::Goto { ref mut target }, .. }) => {
164 self.collapse_goto_chain(target, changed);
169 self.basic_blocks[*start].terminator = terminator;
171 debug!("collapsing goto chain from {:?} to {:?}", *start, target);
173 *changed |= *start != target;
175 if self.pred_count[*start] == 1 {
176 // This is the last reference to *start, so the pred-count to
177 // to target is moved into the current block.
178 self.pred_count[*start] = 0;
180 self.pred_count[target] += 1;
181 self.pred_count[*start] -= 1;
187 // merge a block with 1 `goto` predecessor to its parent
188 fn merge_successor(&mut self,
189 new_stmts: &mut Vec<Statement<'tcx>>,
190 terminator: &mut Terminator<'tcx>)
193 let target = match terminator.kind {
194 TerminatorKind::Goto { target }
195 if self.pred_count[target] == 1
200 debug!("merging block {:?} into {:?}", target, terminator);
201 *terminator = match self.basic_blocks[target].terminator.take() {
202 Some(terminator) => terminator,
204 // unreachable loop - this should not be possible, as we
205 // don't strand blocks, but handle it correctly.
209 new_stmts.extend(self.basic_blocks[target].statements.drain(..));
210 self.pred_count[target] = 0;
215 // turn a branch with all successors identical to a goto
216 fn simplify_branch(&mut self, terminator: &mut Terminator<'tcx>) -> bool {
217 match terminator.kind {
218 TerminatorKind::SwitchInt { .. } => {},
223 let successors = terminator.successors();
224 if let Some(&first_succ) = terminator.successors().get(0) {
225 if successors.iter().all(|s| *s == first_succ) {
226 self.pred_count[first_succ] -= (successors.len()-1) as u32;
236 debug!("simplifying branch {:?}", terminator);
237 terminator.kind = TerminatorKind::Goto { target: first_succ };
241 fn strip_nops(&mut self) {
242 for blk in self.basic_blocks.iter_mut() {
243 blk.statements.retain(|stmt| if let StatementKind::Nop = stmt.kind {
252 pub fn remove_dead_blocks(mir: &mut Mir) {
253 let mut seen = BitVector::new(mir.basic_blocks().len());
254 for (bb, _) in traversal::preorder(mir) {
255 seen.insert(bb.index());
258 let basic_blocks = mir.basic_blocks_mut();
260 let num_blocks = basic_blocks.len();
261 let mut replacements : Vec<_> = (0..num_blocks).map(BasicBlock::new).collect();
262 let mut used_blocks = 0;
263 for alive_index in seen.iter() {
264 replacements[alive_index] = BasicBlock::new(used_blocks);
265 if alive_index != used_blocks {
266 // Swap the next alive block data with the current available slot. Since alive_index is
267 // non-decreasing this is a valid operation.
268 basic_blocks.raw.swap(alive_index, used_blocks);
272 basic_blocks.raw.truncate(used_blocks);
274 for block in basic_blocks {
275 for target in block.terminator_mut().successors_mut() {
276 *target = replacements[target.index()];
282 pub struct SimplifyLocals;
284 impl Pass for SimplifyLocals {
285 fn name(&self) -> ::std::borrow::Cow<'static, str> { "SimplifyLocals".into() }
288 impl<'tcx> MirPass<'tcx> for SimplifyLocals {
289 fn run_pass<'a>(&mut self, _: TyCtxt<'a, 'tcx, 'tcx>, _: MirSource, mir: &mut Mir<'tcx>) {
290 let mut marker = DeclMarker { locals: BitVector::new(mir.local_decls.len()) };
291 marker.visit_mir(mir);
292 // Return pointer and arguments are always live
293 marker.locals.insert(0);
294 for idx in mir.args_iter() {
295 marker.locals.insert(idx.index());
297 let map = make_local_map(&mut mir.local_decls, marker.locals);
298 // Update references to all vars and tmps now
299 LocalUpdater { map: map }.visit_mir(mir);
300 mir.local_decls.shrink_to_fit();
304 /// Construct the mapping while swapping out unused stuff out from the `vec`.
305 fn make_local_map<'tcx, I: Idx, V>(vec: &mut IndexVec<I, V>, mask: BitVector) -> Vec<usize> {
306 let mut map: Vec<usize> = ::std::iter::repeat(!0).take(vec.len()).collect();
308 for alive_index in mask.iter() {
309 map[alive_index] = used;
310 if alive_index != used {
311 vec.swap(alive_index, used);
320 pub locals: BitVector,
323 impl<'tcx> Visitor<'tcx> for DeclMarker {
324 fn visit_lvalue(&mut self, lval: &Lvalue<'tcx>, ctx: LvalueContext<'tcx>, loc: Location) {
325 if ctx == LvalueContext::StorageLive || ctx == LvalueContext::StorageDead {
326 // ignore these altogether, they get removed along with their otherwise unused decls.
329 if let Lvalue::Local(ref v) = *lval {
330 self.locals.insert(v.index());
332 self.super_lvalue(lval, ctx, loc);
336 struct LocalUpdater {
340 impl<'tcx> MutVisitor<'tcx> for LocalUpdater {
341 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
342 // Remove unnecessary StorageLive and StorageDead annotations.
343 data.statements.retain(|stmt| {
345 StatementKind::StorageLive(ref lval) | StatementKind::StorageDead(ref lval) => {
347 Lvalue::Local(l) => self.map[l.index()] != !0,
354 self.super_basic_block_data(block, data);
356 fn visit_lvalue(&mut self, lval: &mut Lvalue<'tcx>, ctx: LvalueContext<'tcx>, loc: Location) {
358 Lvalue::Local(ref mut l) => *l = Local::new(self.map[l.index()]),
361 self.super_lvalue(lval, ctx, loc);