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_index::bit_set::BitSet;
32 use rustc_index::vec::{Idx, IndexVec};
33 use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
34 use rustc_middle::mir::*;
35 use rustc_middle::ty::TyCtxt;
36 use smallvec::SmallVec;
39 pub struct SimplifyCfg {
44 pub fn new(label: &str) -> Self {
45 SimplifyCfg { label: format!("SimplifyCfg-{}", label) }
49 pub fn simplify_cfg(body: &mut Body<'_>) {
50 CfgSimplifier::new(body).simplify();
51 remove_dead_blocks(body);
53 // FIXME: Should probably be moved into some kind of pass manager
54 body.basic_blocks_mut().raw.shrink_to_fit();
57 impl<'tcx> MirPass<'tcx> for SimplifyCfg {
58 fn name(&self) -> Cow<'_, str> {
59 Cow::Borrowed(&self.label)
62 fn run_pass(&self, _tcx: TyCtxt<'tcx>, _src: MirSource<'tcx>, body: &mut Body<'tcx>) {
63 debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, body);
68 pub struct CfgSimplifier<'a, 'tcx> {
69 basic_blocks: &'a mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
70 pred_count: IndexVec<BasicBlock, u32>,
73 impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> {
74 pub fn new(body: &'a mut Body<'tcx>) -> Self {
75 let mut pred_count = IndexVec::from_elem(0u32, body.basic_blocks());
77 // we can't use mir.predecessors() here because that counts
78 // dead blocks, which we don't want to.
79 pred_count[START_BLOCK] = 1;
81 for (_, data) in traversal::preorder(body) {
82 if let Some(ref term) = data.terminator {
83 for &tgt in term.successors() {
89 let basic_blocks = body.basic_blocks_mut();
91 CfgSimplifier { basic_blocks, pred_count }
94 pub fn simplify(mut self) {
97 let mut start = START_BLOCK;
99 // Vec of the blocks that should be merged. We store the indices here, instead of the
100 // statements itself to avoid moving the (relatively) large statements twice.
101 // We do not push the statements directly into the target block (`bb`) as that is slower
102 // due to additional reallocations
103 let mut merged_blocks = Vec::new();
105 let mut changed = false;
107 self.collapse_goto_chain(&mut start, &mut changed);
109 for bb in self.basic_blocks.indices() {
110 if self.pred_count[bb] == 0 {
114 debug!("simplifying {:?}", bb);
117 self.basic_blocks[bb].terminator.take().expect("invalid terminator state");
119 for successor in terminator.successors_mut() {
120 self.collapse_goto_chain(successor, &mut changed);
123 let mut inner_changed = true;
124 merged_blocks.clear();
125 while inner_changed {
126 inner_changed = false;
127 inner_changed |= self.simplify_branch(&mut terminator);
128 inner_changed |= self.merge_successor(&mut merged_blocks, &mut terminator);
129 changed |= inner_changed;
132 let statements_to_merge =
133 merged_blocks.iter().map(|&i| self.basic_blocks[i].statements.len()).sum();
135 if statements_to_merge > 0 {
136 let mut statements = std::mem::take(&mut self.basic_blocks[bb].statements);
137 statements.reserve(statements_to_merge);
138 for &from in &merged_blocks {
139 statements.append(&mut self.basic_blocks[from].statements);
141 self.basic_blocks[bb].statements = statements;
144 self.basic_blocks[bb].terminator = Some(terminator);
152 if start != START_BLOCK {
153 debug_assert!(self.pred_count[START_BLOCK] == 0);
154 self.basic_blocks.swap(START_BLOCK, start);
155 self.pred_count.swap(START_BLOCK, start);
157 // pred_count == 1 if the start block has no predecessor _blocks_.
158 if self.pred_count[START_BLOCK] > 1 {
159 for (bb, data) in self.basic_blocks.iter_enumerated_mut() {
160 if self.pred_count[bb] == 0 {
164 for target in data.terminator_mut().successors_mut() {
165 if *target == start {
166 *target = START_BLOCK;
174 /// This function will return `None` if
175 /// * the block has statements
176 /// * the block has a terminator other than `goto`
177 /// * the block has no terminator (meaning some other part of the current optimization stole it)
178 fn take_terminator_if_simple_goto(&mut self, bb: BasicBlock) -> Option<Terminator<'tcx>> {
179 match self.basic_blocks[bb] {
183 ref mut terminator @ Some(Terminator { kind: TerminatorKind::Goto { .. }, .. }),
185 } if statements.is_empty() => terminator.take(),
186 // if `terminator` is None, this means we are in a loop. In that
187 // case, let all the loop collapse to its entry.
192 /// Collapse a goto chain starting from `start`
193 fn collapse_goto_chain(&mut self, start: &mut BasicBlock, changed: &mut bool) {
194 // Using `SmallVec` here, because in some logs on libcore oli-obk saw many single-element
195 // goto chains. We should probably benchmark different sizes.
196 let mut terminators: SmallVec<[_; 1]> = Default::default();
197 let mut current = *start;
198 while let Some(terminator) = self.take_terminator_if_simple_goto(current) {
199 let target = match terminator {
200 Terminator { kind: TerminatorKind::Goto { target }, .. } => target,
203 terminators.push((current, terminator));
208 while let Some((current, mut terminator)) = terminators.pop() {
209 let target = match terminator {
210 Terminator { kind: TerminatorKind::Goto { ref mut target }, .. } => target,
213 *changed |= *target != last;
215 debug!("collapsing goto chain from {:?} to {:?}", current, target);
217 if self.pred_count[current] == 1 {
218 // This is the last reference to current, so the pred-count to
219 // to target is moved into the current block.
220 self.pred_count[current] = 0;
222 self.pred_count[*target] += 1;
223 self.pred_count[current] -= 1;
225 self.basic_blocks[current].terminator = Some(terminator);
229 // merge a block with 1 `goto` predecessor to its parent
232 merged_blocks: &mut Vec<BasicBlock>,
233 terminator: &mut Terminator<'tcx>,
235 let target = match terminator.kind {
236 TerminatorKind::Goto { target } if self.pred_count[target] == 1 => target,
240 debug!("merging block {:?} into {:?}", target, terminator);
241 *terminator = match self.basic_blocks[target].terminator.take() {
242 Some(terminator) => terminator,
244 // unreachable loop - this should not be possible, as we
245 // don't strand blocks, but handle it correctly.
250 merged_blocks.push(target);
251 self.pred_count[target] = 0;
256 // turn a branch with all successors identical to a goto
257 fn simplify_branch(&mut self, terminator: &mut Terminator<'tcx>) -> bool {
258 match terminator.kind {
259 TerminatorKind::SwitchInt { .. } => {}
264 if let Some(&first_succ) = terminator.successors().next() {
265 if terminator.successors().all(|s| *s == first_succ) {
266 let count = terminator.successors().count();
267 self.pred_count[first_succ] -= (count - 1) as u32;
277 debug!("simplifying branch {:?}", terminator);
278 terminator.kind = TerminatorKind::Goto { target: first_succ };
282 fn strip_nops(&mut self) {
283 for blk in self.basic_blocks.iter_mut() {
285 .retain(|stmt| if let StatementKind::Nop = stmt.kind { false } else { true })
290 pub fn remove_dead_blocks(body: &mut Body<'_>) {
291 let mut seen = BitSet::new_empty(body.basic_blocks().len());
292 for (bb, _) in traversal::preorder(body) {
293 seen.insert(bb.index());
296 let basic_blocks = body.basic_blocks_mut();
298 let num_blocks = basic_blocks.len();
299 let mut replacements: Vec<_> = (0..num_blocks).map(BasicBlock::new).collect();
300 let mut used_blocks = 0;
301 for alive_index in seen.iter() {
302 replacements[alive_index] = BasicBlock::new(used_blocks);
303 if alive_index != used_blocks {
304 // Swap the next alive block data with the current available slot. Since
305 // alive_index is non-decreasing this is a valid operation.
306 basic_blocks.raw.swap(alive_index, used_blocks);
310 basic_blocks.raw.truncate(used_blocks);
312 for block in basic_blocks {
313 for target in block.terminator_mut().successors_mut() {
314 *target = replacements[target.index()];
319 pub struct SimplifyLocals;
321 impl<'tcx> MirPass<'tcx> for SimplifyLocals {
322 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
323 trace!("running SimplifyLocals on {:?}", source);
325 // First, we're going to get a count of *actual* uses for every `Local`.
326 // Take a look at `DeclMarker::visit_local()` to see exactly what is ignored.
327 let mut used_locals = {
328 let mut marker = DeclMarker::new(body);
329 marker.visit_body(&body);
334 let arg_count = body.arg_count;
336 // Next, we're going to remove any `Local` with zero actual uses. When we remove those
337 // `Locals`, we're also going to subtract any uses of other `Locals` from the `used_locals`
338 // count. For example, if we removed `_2 = discriminant(_1)`, then we'll subtract one from
339 // `use_counts[_1]`. That in turn might make `_1` unused, so we loop until we hit a
340 // fixedpoint where there are no more unused locals.
342 let mut remove_statements = RemoveStatements::new(&mut used_locals, arg_count, tcx);
343 remove_statements.visit_body(body);
345 if !remove_statements.modified {
350 // Finally, we'll actually do the work of shrinking `body.local_decls` and remapping the `Local`s.
351 let map = make_local_map(&mut body.local_decls, used_locals, arg_count);
353 // Only bother running the `LocalUpdater` if we actually found locals to remove.
354 if map.iter().any(Option::is_none) {
355 // Update references to all vars and tmps now
356 let mut updater = LocalUpdater { map, tcx };
357 updater.visit_body(body);
359 body.local_decls.shrink_to_fit();
364 /// Construct the mapping while swapping out unused stuff out from the `vec`.
365 fn make_local_map<V>(
366 local_decls: &mut IndexVec<Local, V>,
367 used_locals: IndexVec<Local, usize>,
369 ) -> IndexVec<Local, Option<Local>> {
370 let mut map: IndexVec<Local, Option<Local>> = IndexVec::from_elem(None, &*local_decls);
371 let mut used = Local::new(0);
372 for (alive_index, count) in used_locals.iter_enumerated() {
373 // The `RETURN_PLACE` and arguments are always live.
374 if alive_index.as_usize() > arg_count && *count == 0 {
378 map[alive_index] = Some(used);
379 if alive_index != used {
380 local_decls.swap(alive_index, used);
382 used.increment_by(1);
384 local_decls.truncate(used.index());
388 struct DeclMarker<'a, 'tcx> {
389 pub local_counts: IndexVec<Local, usize>,
390 pub body: &'a Body<'tcx>,
393 impl<'a, 'tcx> DeclMarker<'a, 'tcx> {
394 pub fn new(body: &'a Body<'tcx>) -> Self {
395 Self { local_counts: IndexVec::from_elem(0, &body.local_decls), body }
399 impl<'a, 'tcx> Visitor<'tcx> for DeclMarker<'a, 'tcx> {
400 fn visit_local(&mut self, local: &Local, ctx: PlaceContext, location: Location) {
401 // Ignore storage markers altogether, they get removed along with their otherwise unused
403 // FIXME: Extend this to all non-uses.
404 if ctx.is_storage_marker() {
408 // Ignore stores of constants because `ConstProp` and `CopyProp` can remove uses of many
409 // of these locals. However, if the local is still needed, then it will be referenced in
410 // another place and we'll mark it as being used there.
411 if ctx == PlaceContext::MutatingUse(MutatingUseContext::Store)
412 || ctx == PlaceContext::MutatingUse(MutatingUseContext::Projection)
414 let block = &self.body.basic_blocks()[location.block];
415 if location.statement_index != block.statements.len() {
416 let stmt = &block.statements[location.statement_index];
418 if let StatementKind::Assign(box (dest, rvalue)) = &stmt.kind {
419 if !dest.is_indirect() && dest.local == *local {
420 let can_skip = match rvalue {
422 | Rvalue::Discriminant(_)
423 | Rvalue::BinaryOp(_, _, _)
424 | Rvalue::CheckedBinaryOp(_, _, _)
425 | Rvalue::Repeat(_, _)
426 | Rvalue::AddressOf(_, _)
428 | Rvalue::UnaryOp(_, _)
429 | Rvalue::Aggregate(_, _) => true,
435 trace!("skipping store of {:?} to {:?}", rvalue, dest);
443 self.local_counts[*local] += 1;
447 struct StatementDeclMarker<'a, 'tcx> {
448 used_locals: &'a mut IndexVec<Local, usize>,
449 statement: &'a Statement<'tcx>,
452 impl<'a, 'tcx> StatementDeclMarker<'a, 'tcx> {
454 used_locals: &'a mut IndexVec<Local, usize>,
455 statement: &'a Statement<'tcx>,
457 Self { used_locals, statement }
461 impl<'a, 'tcx> Visitor<'tcx> for StatementDeclMarker<'a, 'tcx> {
462 fn visit_local(&mut self, local: &Local, context: PlaceContext, _location: Location) {
463 // Skip the lvalue for assignments
464 if let StatementKind::Assign(box (p, _)) = self.statement.kind {
465 if p.local == *local && context.is_place_assignment() {
470 let use_count = &mut self.used_locals[*local];
471 // If this is the local we're removing...
478 struct RemoveStatements<'a, 'tcx> {
479 used_locals: &'a mut IndexVec<Local, usize>,
485 impl<'a, 'tcx> RemoveStatements<'a, 'tcx> {
487 used_locals: &'a mut IndexVec<Local, usize>,
491 Self { used_locals, arg_count, tcx, modified: false }
494 fn keep_local(&self, l: Local) -> bool {
495 trace!("keep_local({:?}): count: {:?}", l, self.used_locals[l]);
496 l.as_usize() <= self.arg_count || self.used_locals[l] != 0
500 impl<'a, 'tcx> MutVisitor<'tcx> for RemoveStatements<'a, 'tcx> {
501 fn tcx(&self) -> TyCtxt<'tcx> {
505 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
506 // Remove unnecessary StorageLive and StorageDead annotations.
508 data.statements.retain(|stmt| {
509 let keep = match &stmt.kind {
510 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
513 StatementKind::Assign(box (place, _)) => self.keep_local(place.local),
518 trace!("removing statement {:?}", stmt);
519 self.modified = true;
521 let mut visitor = StatementDeclMarker::new(self.used_locals, stmt);
522 visitor.visit_statement(stmt, Location { block, statement_index: i });
530 self.super_basic_block_data(block, data);
534 struct LocalUpdater<'tcx> {
535 map: IndexVec<Local, Option<Local>>,
539 impl<'tcx> MutVisitor<'tcx> for LocalUpdater<'tcx> {
540 fn tcx(&self) -> TyCtxt<'tcx> {
544 fn visit_local(&mut self, l: &mut Local, _: PlaceContext, _: Location) {
545 *l = self.map[*l].unwrap();