1 //! A number of passes which remove various redundancies in the CFG.
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.
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.
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
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:
22 //! let _a: char = { return; };
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
30 use crate::transform::{MirPass, MirSource};
31 use rustc::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
33 use rustc::ty::{self, TyCtxt};
34 use rustc_index::bit_set::BitSet;
35 use rustc_index::vec::{Idx, IndexVec};
38 pub struct SimplifyCfg {
43 pub fn new(label: &str) -> Self {
44 SimplifyCfg { label: format!("SimplifyCfg-{}", label) }
48 pub fn simplify_cfg(body: &mut BodyAndCache<'_>) {
49 CfgSimplifier::new(body).simplify();
50 remove_dead_blocks(body);
52 // FIXME: Should probably be moved into some kind of pass manager
53 body.basic_blocks_mut().raw.shrink_to_fit();
56 impl<'tcx> MirPass<'tcx> for SimplifyCfg {
57 fn name(&self) -> Cow<'_, str> {
58 Cow::Borrowed(&self.label)
61 fn run_pass(&self, _tcx: TyCtxt<'tcx>, _src: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>) {
62 debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, body);
67 pub struct CfgSimplifier<'a, 'tcx> {
68 basic_blocks: &'a mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
69 pred_count: IndexVec<BasicBlock, u32>,
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());
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;
80 for (_, data) in traversal::preorder(body) {
81 if let Some(ref term) = data.terminator {
82 for &tgt in term.successors() {
88 let basic_blocks = body.basic_blocks_mut();
90 CfgSimplifier { basic_blocks, pred_count }
93 pub fn simplify(mut self) {
96 let mut start = START_BLOCK;
98 // Vec of the blocks that should be merged. We store the indices here, instead of the
99 // statements itself to avoid moving the (relatively) large statements twice.
100 // We do not push the statements directly into the target block (`bb`) as that is slower
101 // due to additional reallocations
102 let mut merged_blocks = Vec::new();
104 let mut changed = false;
106 self.collapse_goto_chain(&mut start, &mut changed);
108 for bb in self.basic_blocks.indices() {
109 if self.pred_count[bb] == 0 {
113 debug!("simplifying {:?}", bb);
116 self.basic_blocks[bb].terminator.take().expect("invalid terminator state");
118 for successor in terminator.successors_mut() {
119 self.collapse_goto_chain(successor, &mut changed);
122 let mut inner_changed = true;
123 merged_blocks.clear();
124 while inner_changed {
125 inner_changed = false;
126 inner_changed |= self.simplify_branch(&mut terminator);
127 inner_changed |= self.merge_successor(&mut merged_blocks, &mut terminator);
128 changed |= inner_changed;
131 let merged_block_count =
132 merged_blocks.iter().map(|&i| self.basic_blocks[i].statements.len()).sum();
134 if merged_block_count > 0 {
135 let mut statements = std::mem::take(&mut self.basic_blocks[bb].statements);
136 statements.reserve(merged_block_count);
137 for &from in &merged_blocks {
138 statements.append(&mut self.basic_blocks[from].statements);
140 self.basic_blocks[bb].statements = statements;
143 self.basic_blocks[bb].terminator = Some(terminator);
145 changed |= inner_changed;
153 if start != START_BLOCK {
154 debug_assert!(self.pred_count[START_BLOCK] == 0);
155 self.basic_blocks.swap(START_BLOCK, start);
156 self.pred_count.swap(START_BLOCK, start);
158 // pred_count == 1 if the start block has no predecessor _blocks_.
159 if self.pred_count[START_BLOCK] > 1 {
160 for (bb, data) in self.basic_blocks.iter_enumerated_mut() {
161 if self.pred_count[bb] == 0 {
165 for target in data.terminator_mut().successors_mut() {
166 if *target == start {
167 *target = START_BLOCK;
175 // Collapse a goto chain starting from `start`
176 fn collapse_goto_chain(&mut self, start: &mut BasicBlock, changed: &mut bool) {
177 let mut terminator = match self.basic_blocks[*start] {
181 ref mut terminator @ Some(Terminator { kind: TerminatorKind::Goto { .. }, .. }),
183 } if statements.is_empty() => terminator.take(),
184 // if `terminator` is None, this means we are in a loop. In that
185 // case, let all the loop collapse to its entry.
189 let target = match terminator {
190 Some(Terminator { kind: TerminatorKind::Goto { ref mut target }, .. }) => {
191 self.collapse_goto_chain(target, changed);
196 self.basic_blocks[*start].terminator = terminator;
198 debug!("collapsing goto chain from {:?} to {:?}", *start, target);
200 *changed |= *start != target;
202 if self.pred_count[*start] == 1 {
203 // This is the last reference to *start, so the pred-count to
204 // to target is moved into the current block.
205 self.pred_count[*start] = 0;
207 self.pred_count[target] += 1;
208 self.pred_count[*start] -= 1;
214 // merge a block with 1 `goto` predecessor to its parent
217 merged_blocks: &mut Vec<BasicBlock>,
218 terminator: &mut Terminator<'tcx>,
220 let target = match terminator.kind {
221 TerminatorKind::Goto { target } if self.pred_count[target] == 1 => target,
225 debug!("merging block {:?} into {:?}", target, terminator);
226 *terminator = match self.basic_blocks[target].terminator.take() {
227 Some(terminator) => terminator,
229 // unreachable loop - this should not be possible, as we
230 // don't strand blocks, but handle it correctly.
235 merged_blocks.push(target);
236 self.pred_count[target] = 0;
241 // turn a branch with all successors identical to a goto
242 fn simplify_branch(&mut self, terminator: &mut Terminator<'tcx>) -> bool {
243 match terminator.kind {
244 TerminatorKind::SwitchInt { .. } => {}
249 if let Some(&first_succ) = terminator.successors().nth(0) {
250 if terminator.successors().all(|s| *s == first_succ) {
251 let count = terminator.successors().count();
252 self.pred_count[first_succ] -= (count - 1) as u32;
262 debug!("simplifying branch {:?}", terminator);
263 terminator.kind = TerminatorKind::Goto { target: first_succ };
267 fn strip_nops(&mut self) {
268 for blk in self.basic_blocks.iter_mut() {
270 .retain(|stmt| if let StatementKind::Nop = stmt.kind { false } else { true })
275 pub fn remove_dead_blocks(body: &mut BodyAndCache<'_>) {
276 let mut seen = BitSet::new_empty(body.basic_blocks().len());
277 for (bb, _) in traversal::preorder(body) {
278 seen.insert(bb.index());
281 let basic_blocks = body.basic_blocks_mut();
283 let num_blocks = basic_blocks.len();
284 let mut replacements: Vec<_> = (0..num_blocks).map(BasicBlock::new).collect();
285 let mut used_blocks = 0;
286 for alive_index in seen.iter() {
287 replacements[alive_index] = BasicBlock::new(used_blocks);
288 if alive_index != used_blocks {
289 // Swap the next alive block data with the current available slot. Since
290 // alive_index is non-decreasing this is a valid operation.
291 basic_blocks.raw.swap(alive_index, used_blocks);
295 basic_blocks.raw.truncate(used_blocks);
297 for block in basic_blocks {
298 for target in block.terminator_mut().successors_mut() {
299 *target = replacements[target.index()];
304 pub struct SimplifyLocals;
306 impl<'tcx> MirPass<'tcx> for SimplifyLocals {
307 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>) {
308 trace!("running SimplifyLocals on {:?}", source);
310 let read_only_cache = read_only!(body);
311 let mut marker = DeclMarker { locals: BitSet::new_empty(body.local_decls.len()), body };
312 marker.visit_body(read_only_cache);
313 // Return pointer and arguments are always live
314 marker.locals.insert(RETURN_PLACE);
315 for arg in body.args_iter() {
316 marker.locals.insert(arg);
322 let map = make_local_map(&mut body.local_decls, locals);
323 // Update references to all vars and tmps now
324 LocalUpdater { map, tcx }.visit_body(body);
325 body.local_decls.shrink_to_fit();
329 /// Construct the mapping while swapping out unused stuff out from the `vec`.
330 fn make_local_map<V>(
331 vec: &mut IndexVec<Local, V>,
333 ) -> IndexVec<Local, Option<Local>> {
334 let mut map: IndexVec<Local, Option<Local>> = IndexVec::from_elem(None, &*vec);
335 let mut used = Local::new(0);
336 for alive_index in mask.iter() {
337 map[alive_index] = Some(used);
338 if alive_index != used {
339 vec.swap(alive_index, used);
341 used.increment_by(1);
343 vec.truncate(used.index());
347 struct DeclMarker<'a, 'tcx> {
348 pub locals: BitSet<Local>,
349 pub body: &'a Body<'tcx>,
352 impl<'a, 'tcx> Visitor<'tcx> for DeclMarker<'a, 'tcx> {
353 fn visit_local(&mut self, local: &Local, ctx: PlaceContext, location: Location) {
354 // Ignore storage markers altogether, they get removed along with their otherwise unused
356 // FIXME: Extend this to all non-uses.
357 if ctx.is_storage_marker() {
361 // Ignore stores of constants because `ConstProp` and `CopyProp` can remove uses of many
362 // of these locals. However, if the local is still needed, then it will be referenced in
363 // another place and we'll mark it as being used there.
364 if ctx == PlaceContext::MutatingUse(MutatingUseContext::Store)
365 || ctx == PlaceContext::MutatingUse(MutatingUseContext::Projection)
367 let block = &self.body.basic_blocks()[location.block];
368 if location.statement_index != block.statements.len() {
369 let stmt = &block.statements[location.statement_index];
371 if let StatementKind::Assign(box (p, Rvalue::Use(Operand::Constant(c)))) =
374 match c.literal.val {
375 // Keep assignments from unevaluated constants around, since the evaluation
376 // may report errors, even if the use of the constant is dead code.
377 ty::ConstKind::Unevaluated(..) => {}
379 if !p.is_indirect() {
380 trace!("skipping store of const value {:?} to {:?}", c, p);
389 self.locals.insert(*local);
393 struct LocalUpdater<'tcx> {
394 map: IndexVec<Local, Option<Local>>,
398 impl<'tcx> MutVisitor<'tcx> for LocalUpdater<'tcx> {
399 fn tcx(&self) -> TyCtxt<'tcx> {
403 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
404 // Remove unnecessary StorageLive and StorageDead annotations.
405 data.statements.retain(|stmt| match &stmt.kind {
406 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => self.map[*l].is_some(),
407 StatementKind::Assign(box (place, _)) => self.map[place.local].is_some(),
410 self.super_basic_block_data(block, data);
413 fn visit_local(&mut self, l: &mut Local, _: PlaceContext, _: Location) {
414 *l = self.map[*l].unwrap();
417 fn process_projection_elem(&mut self, elem: &PlaceElem<'tcx>) -> Option<PlaceElem<'tcx>> {
419 PlaceElem::Index(local) => Some(PlaceElem::Index(self.map[*local].unwrap())),