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 let mut merged_blocks = Vec::new();
100 let mut changed = false;
102 self.collapse_goto_chain(&mut start, &mut changed);
104 for bb in self.basic_blocks.indices() {
105 if self.pred_count[bb] == 0 {
109 debug!("simplifying {:?}", bb);
112 self.basic_blocks[bb].terminator.take().expect("invalid terminator state");
114 for successor in terminator.successors_mut() {
115 self.collapse_goto_chain(successor, &mut changed);
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;
126 let merged_block_count =
127 merged_blocks.iter().map(|&i| self.basic_blocks[i].statements.len()).sum();
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);
135 self.basic_blocks[bb].statements = statements;
137 merged_blocks.clear();
139 self.basic_blocks[bb].terminator = Some(terminator);
141 changed |= inner_changed;
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);
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 {
161 for target in data.terminator_mut().successors_mut() {
162 if *target == start {
163 *target = START_BLOCK;
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] {
177 ref mut terminator @ Some(Terminator { kind: TerminatorKind::Goto { .. }, .. }),
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.
185 let target = match terminator {
186 Some(Terminator { kind: TerminatorKind::Goto { ref mut target }, .. }) => {
187 self.collapse_goto_chain(target, changed);
192 self.basic_blocks[*start].terminator = terminator;
194 debug!("collapsing goto chain from {:?} to {:?}", *start, target);
196 *changed |= *start != target;
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;
203 self.pred_count[target] += 1;
204 self.pred_count[*start] -= 1;
210 // merge a block with 1 `goto` predecessor to its parent
213 merged_blocks: &mut Vec<BasicBlock>,
214 terminator: &mut Terminator<'tcx>,
216 let target = match terminator.kind {
217 TerminatorKind::Goto { target } if self.pred_count[target] == 1 => target,
221 debug!("merging block {:?} into {:?}", target, terminator);
222 *terminator = match self.basic_blocks[target].terminator.take() {
223 Some(terminator) => terminator,
225 // unreachable loop - this should not be possible, as we
226 // don't strand blocks, but handle it correctly.
231 merged_blocks.push(target);
232 self.pred_count[target] = 0;
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 { .. } => {}
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;
258 debug!("simplifying branch {:?}", terminator);
259 terminator.kind = TerminatorKind::Goto { target: first_succ };
263 fn strip_nops(&mut self) {
264 for blk in self.basic_blocks.iter_mut() {
266 .retain(|stmt| if let StatementKind::Nop = stmt.kind { false } else { true })
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());
277 let basic_blocks = body.basic_blocks_mut();
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);
291 basic_blocks.raw.truncate(used_blocks);
293 for block in basic_blocks {
294 for target in block.terminator_mut().successors_mut() {
295 *target = replacements[target.index()];
300 pub struct SimplifyLocals;
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);
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);
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();
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>,
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);
337 used.increment_by(1);
339 vec.truncate(used.index());
343 struct DeclMarker<'a, 'tcx> {
344 pub locals: BitSet<Local>,
345 pub body: &'a Body<'tcx>,
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
352 // FIXME: Extend this to all non-uses.
353 if ctx.is_storage_marker() {
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)
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];
367 if let StatementKind::Assign(box (p, Rvalue::Use(Operand::Constant(c)))) =
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(..) => {}
375 if !p.is_indirect() {
376 trace!("skipping store of const value {:?} to {:?}", c, p);
385 self.locals.insert(*local);
389 struct LocalUpdater<'tcx> {
390 map: IndexVec<Local, Option<Local>>,
394 impl<'tcx> MutVisitor<'tcx> for LocalUpdater<'tcx> {
395 fn tcx(&self) -> TyCtxt<'tcx> {
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(),
406 self.super_basic_block_data(block, data);
409 fn visit_local(&mut self, l: &mut Local, _: PlaceContext, _: Location) {
410 *l = self.map[*l].unwrap();
413 fn process_projection_elem(&mut self, elem: &PlaceElem<'tcx>) -> Option<PlaceElem<'tcx>> {
415 PlaceElem::Index(local) => Some(PlaceElem::Index(self.map[*local].unwrap())),