]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_mir/src/transform/simplify.rs
New upstream version 1.54.0+dfsg1
[rustc.git] / compiler / rustc_mir / src / transform / simplify.rs
CommitLineData
c30ab7b3 1//! A number of passes which remove various redundancies in the CFG.
3157f602 2//!
c30ab7b3
SL
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.
3157f602 5//!
c30ab7b3
SL
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
94b46f34 8//! either, so running the pass once, right before codegen, should suffice.
c30ab7b3
SL
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:
3157f602 19//!
3157f602
XL
20//! ```rust
21//! fn example() {
22//! let _a: char = { return; };
23//! }
24//! ```
25//!
c30ab7b3
SL
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.
3157f602 29
29967ef6 30use crate::transform::MirPass;
e74abb32 31use rustc_index::vec::{Idx, IndexVec};
17df50a5 32use rustc_middle::mir::coverage::*;
ba9703b0
XL
33use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
34use rustc_middle::mir::*;
f9f354fc 35use rustc_middle::ty::TyCtxt;
3dfed10e 36use smallvec::SmallVec;
cdc7bbd5
XL
37use std::borrow::Cow;
38use std::convert::TryInto;
92a42be0 39
dfeec247
XL
40pub struct SimplifyCfg {
41 label: String,
42}
a7813a04 43
7cac9316
XL
44impl SimplifyCfg {
45 pub fn new(label: &str) -> Self {
46 SimplifyCfg { label: format!("SimplifyCfg-{}", label) }
92a42be0 47 }
a7813a04
XL
48}
49
17df50a5 50pub fn simplify_cfg(tcx: TyCtxt<'tcx>, body: &mut Body<'_>) {
dc9dc135 51 CfgSimplifier::new(body).simplify();
17df50a5 52 remove_dead_blocks(tcx, body);
cc61c64b
XL
53
54 // FIXME: Should probably be moved into some kind of pass manager
dc9dc135 55 body.basic_blocks_mut().raw.shrink_to_fit();
cc61c64b
XL
56}
57
e1599b0c 58impl<'tcx> MirPass<'tcx> for SimplifyCfg {
416331ca 59 fn name(&self) -> Cow<'_, str> {
7cac9316 60 Cow::Borrowed(&self.label)
3157f602 61 }
3157f602 62
17df50a5 63 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
5869c6ff 64 debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, body.source);
17df50a5 65 simplify_cfg(tcx, body);
a7813a04 66 }
3157f602
XL
67}
68
dc9dc135 69pub struct CfgSimplifier<'a, 'tcx> {
3157f602 70 basic_blocks: &'a mut IndexVec<BasicBlock, BasicBlockData<'tcx>>,
dfeec247 71 pred_count: IndexVec<BasicBlock, u32>,
a7813a04
XL
72}
73
dc9dc135 74impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> {
f9f354fc 75 pub fn new(body: &'a mut Body<'tcx>) -> Self {
dc9dc135 76 let mut pred_count = IndexVec::from_elem(0u32, body.basic_blocks());
a7813a04 77
3157f602
XL
78 // we can't use mir.predecessors() here because that counts
79 // dead blocks, which we don't want to.
c30ab7b3
SL
80 pred_count[START_BLOCK] = 1;
81
dc9dc135 82 for (_, data) in traversal::preorder(body) {
3157f602 83 if let Some(ref term) = data.terminator {
83c7162d 84 for &tgt in term.successors() {
3157f602
XL
85 pred_count[tgt] += 1;
86 }
a7813a04
XL
87 }
88 }
3157f602 89
dc9dc135 90 let basic_blocks = body.basic_blocks_mut();
3157f602 91
dfeec247 92 CfgSimplifier { basic_blocks, pred_count }
a7813a04
XL
93 }
94
8bb4bdeb 95 pub fn simplify(mut self) {
3b2f2976
XL
96 self.strip_nops();
97
0731742a
XL
98 let mut start = START_BLOCK;
99
ba9703b0
XL
100 // Vec of the blocks that should be merged. We store the indices here, instead of the
101 // statements itself to avoid moving the (relatively) large statements twice.
102 // We do not push the statements directly into the target block (`bb`) as that is slower
103 // due to additional reallocations
104 let mut merged_blocks = Vec::new();
3157f602
XL
105 loop {
106 let mut changed = false;
107
0731742a
XL
108 self.collapse_goto_chain(&mut start, &mut changed);
109
110 for bb in self.basic_blocks.indices() {
3157f602 111 if self.pred_count[bb] == 0 {
dfeec247 112 continue;
a7813a04
XL
113 }
114
3157f602
XL
115 debug!("simplifying {:?}", bb);
116
dfeec247
XL
117 let mut terminator =
118 self.basic_blocks[bb].terminator.take().expect("invalid terminator state");
3157f602
XL
119
120 for successor in terminator.successors_mut() {
121 self.collapse_goto_chain(successor, &mut changed);
a7813a04
XL
122 }
123
3157f602 124 let mut inner_changed = true;
ba9703b0 125 merged_blocks.clear();
3157f602
XL
126 while inner_changed {
127 inner_changed = false;
128 inner_changed |= self.simplify_branch(&mut terminator);
ba9703b0 129 inner_changed |= self.merge_successor(&mut merged_blocks, &mut terminator);
3157f602 130 changed |= inner_changed;
92a42be0 131 }
92a42be0 132
ba9703b0
XL
133 let statements_to_merge =
134 merged_blocks.iter().map(|&i| self.basic_blocks[i].statements.len()).sum();
135
136 if statements_to_merge > 0 {
137 let mut statements = std::mem::take(&mut self.basic_blocks[bb].statements);
138 statements.reserve(statements_to_merge);
139 for &from in &merged_blocks {
140 statements.append(&mut self.basic_blocks[from].statements);
141 }
142 self.basic_blocks[bb].statements = statements;
143 }
144
145 self.basic_blocks[bb].terminator = Some(terminator);
a7813a04 146 }
92a42be0 147
dfeec247
XL
148 if !changed {
149 break;
150 }
a7813a04 151 }
0731742a
XL
152
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);
157
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 {
162 continue;
163 }
164
165 for target in data.terminator_mut().successors_mut() {
166 if *target == start {
167 *target = START_BLOCK;
168 }
169 }
170 }
171 }
172 }
a7813a04 173 }
a7813a04 174
3dfed10e
XL
175 /// This function will return `None` if
176 /// * the block has statements
177 /// * the block has a terminator other than `goto`
178 /// * the block has no terminator (meaning some other part of the current optimization stole it)
179 fn take_terminator_if_simple_goto(&mut self, bb: BasicBlock) -> Option<Terminator<'tcx>> {
180 match self.basic_blocks[bb] {
3157f602
XL
181 BasicBlockData {
182 ref statements,
dfeec247
XL
183 terminator:
184 ref mut terminator @ Some(Terminator { kind: TerminatorKind::Goto { .. }, .. }),
185 ..
3157f602
XL
186 } if statements.is_empty() => terminator.take(),
187 // if `terminator` is None, this means we are in a loop. In that
188 // case, let all the loop collapse to its entry.
3dfed10e
XL
189 _ => None,
190 }
191 }
3157f602 192
3dfed10e
XL
193 /// Collapse a goto chain starting from `start`
194 fn collapse_goto_chain(&mut self, start: &mut BasicBlock, changed: &mut bool) {
195 // Using `SmallVec` here, because in some logs on libcore oli-obk saw many single-element
196 // goto chains. We should probably benchmark different sizes.
197 let mut terminators: SmallVec<[_; 1]> = Default::default();
198 let mut current = *start;
199 while let Some(terminator) = self.take_terminator_if_simple_goto(current) {
200 let target = match terminator {
201 Terminator { kind: TerminatorKind::Goto { target }, .. } => target,
202 _ => unreachable!(),
203 };
204 terminators.push((current, terminator));
205 current = target;
206 }
207 let last = current;
208 *start = last;
209 while let Some((current, mut terminator)) = terminators.pop() {
210 let target = match terminator {
211 Terminator { kind: TerminatorKind::Goto { ref mut target }, .. } => target,
212 _ => unreachable!(),
213 };
214 *changed |= *target != last;
215 *target = last;
216 debug!("collapsing goto chain from {:?} to {:?}", current, target);
217
218 if self.pred_count[current] == 1 {
219 // This is the last reference to current, so the pred-count to
220 // to target is moved into the current block.
221 self.pred_count[current] = 0;
222 } else {
223 self.pred_count[*target] += 1;
224 self.pred_count[current] -= 1;
92a42be0 225 }
3dfed10e 226 self.basic_blocks[current].terminator = Some(terminator);
c30ab7b3 227 }
3157f602 228 }
7453a54e 229
3157f602 230 // merge a block with 1 `goto` predecessor to its parent
dfeec247
XL
231 fn merge_successor(
232 &mut self,
ba9703b0 233 merged_blocks: &mut Vec<BasicBlock>,
dfeec247
XL
234 terminator: &mut Terminator<'tcx>,
235 ) -> bool {
3157f602 236 let target = match terminator.kind {
dfeec247
XL
237 TerminatorKind::Goto { target } if self.pred_count[target] == 1 => target,
238 _ => return false,
3157f602
XL
239 };
240
241 debug!("merging block {:?} into {:?}", target, terminator);
242 *terminator = match self.basic_blocks[target].terminator.take() {
243 Some(terminator) => terminator,
244 None => {
245 // unreachable loop - this should not be possible, as we
246 // don't strand blocks, but handle it correctly.
dfeec247 247 return false;
3157f602
XL
248 }
249 };
ba9703b0
XL
250
251 merged_blocks.push(target);
3157f602 252 self.pred_count[target] = 0;
7453a54e 253
3157f602
XL
254 true
255 }
256
257 // turn a branch with all successors identical to a goto
258 fn simplify_branch(&mut self, terminator: &mut Terminator<'tcx>) -> bool {
259 match terminator.kind {
dfeec247
XL
260 TerminatorKind::SwitchInt { .. } => {}
261 _ => return false,
3157f602
XL
262 };
263
264 let first_succ = {
74b04a01 265 if let Some(&first_succ) = terminator.successors().next() {
83c7162d
XL
266 if terminator.successors().all(|s| *s == first_succ) {
267 let count = terminator.successors().count();
268 self.pred_count[first_succ] -= (count - 1) as u32;
3157f602
XL
269 first_succ
270 } else {
dfeec247 271 return false;
92a42be0 272 }
3157f602 273 } else {
dfeec247 274 return false;
92a42be0 275 }
3157f602
XL
276 };
277
278 debug!("simplifying branch {:?}", terminator);
279 terminator.kind = TerminatorKind::Goto { target: first_succ };
280 true
281 }
8bb4bdeb
XL
282
283 fn strip_nops(&mut self) {
284 for blk in self.basic_blocks.iter_mut() {
1b1a35ee 285 blk.statements.retain(|stmt| !matches!(stmt.kind, StatementKind::Nop))
8bb4bdeb
XL
286 }
287 }
3157f602
XL
288}
289
17df50a5 290pub fn remove_dead_blocks(tcx: TyCtxt<'tcx>, body: &mut Body<'_>) {
5869c6ff
XL
291 let reachable = traversal::reachable_as_bitset(body);
292 let num_blocks = body.basic_blocks().len();
293 if num_blocks == reachable.count() {
294 return;
3157f602
XL
295 }
296
dc9dc135 297 let basic_blocks = body.basic_blocks_mut();
dfeec247 298 let mut replacements: Vec<_> = (0..num_blocks).map(BasicBlock::new).collect();
3157f602 299 let mut used_blocks = 0;
5869c6ff
XL
300 for alive_index in reachable.iter() {
301 let alive_index = alive_index.index();
3157f602
XL
302 replacements[alive_index] = BasicBlock::new(used_blocks);
303 if alive_index != used_blocks {
60c5eb7d
XL
304 // Swap the next alive block data with the current available slot. Since
305 // alive_index is non-decreasing this is a valid operation.
3157f602 306 basic_blocks.raw.swap(alive_index, used_blocks);
92a42be0 307 }
3157f602
XL
308 used_blocks += 1;
309 }
17df50a5
XL
310
311 if tcx.sess.instrument_coverage() {
312 save_unreachable_coverage(basic_blocks, used_blocks);
313 }
314
3157f602 315 basic_blocks.raw.truncate(used_blocks);
92a42be0 316
3157f602
XL
317 for block in basic_blocks {
318 for target in block.terminator_mut().successors_mut() {
319 *target = replacements[target.index()];
92a42be0 320 }
92a42be0
SL
321 }
322}
c30ab7b3 323
17df50a5
XL
324/// Some MIR transforms can determine at compile time that a sequences of
325/// statements will never be executed, so they can be dropped from the MIR.
326/// For example, an `if` or `else` block that is guaranteed to never be executed
327/// because its condition can be evaluated at compile time, such as by const
328/// evaluation: `if false { ... }`.
329///
330/// Those statements are bypassed by redirecting paths in the CFG around the
331/// `dead blocks`; but with `-Z instrument-coverage`, the dead blocks usually
332/// include `Coverage` statements representing the Rust source code regions to
333/// be counted at runtime. Without these `Coverage` statements, the regions are
334/// lost, and the Rust source code will show no coverage information.
335///
336/// What we want to show in a coverage report is the dead code with coverage
337/// counts of `0`. To do this, we need to save the code regions, by injecting
338/// `Unreachable` coverage statements. These are non-executable statements whose
339/// code regions are still recorded in the coverage map, representing regions
340/// with `0` executions.
341fn save_unreachable_coverage(
342 basic_blocks: &mut IndexVec<BasicBlock, BasicBlockData<'_>>,
343 first_dead_block: usize,
344) {
345 let has_live_counters = basic_blocks.raw[0..first_dead_block].iter().any(|live_block| {
346 live_block.statements.iter().any(|statement| {
347 if let StatementKind::Coverage(coverage) = &statement.kind {
348 matches!(coverage.kind, CoverageKind::Counter { .. })
349 } else {
350 false
351 }
352 })
353 });
354 if !has_live_counters {
355 // If there are no live `Counter` `Coverage` statements anymore, don't
356 // move dead coverage to the `START_BLOCK`. Just allow the dead
357 // `Coverage` statements to be dropped with the dead blocks.
358 //
359 // The `generator::StateTransform` MIR pass can create atypical
360 // conditions, where all live `Counter`s are dropped from the MIR.
361 //
362 // At least one Counter per function is required by LLVM (and necessary,
363 // to add the `function_hash` to the counter's call to the LLVM
364 // intrinsic `instrprof.increment()`).
365 return;
366 }
367
368 // Retain coverage info for dead blocks, so coverage reports will still
369 // report `0` executions for the uncovered code regions.
370 let mut dropped_coverage = Vec::new();
371 for dead_block in basic_blocks.raw[first_dead_block..].iter() {
372 for statement in dead_block.statements.iter() {
373 if let StatementKind::Coverage(coverage) = &statement.kind {
374 if let Some(code_region) = &coverage.code_region {
375 dropped_coverage.push((statement.source_info, code_region.clone()));
376 }
377 }
378 }
379 }
380
381 let start_block = &mut basic_blocks[START_BLOCK];
382 for (source_info, code_region) in dropped_coverage {
383 start_block.statements.push(Statement {
384 source_info,
385 kind: StatementKind::Coverage(box Coverage {
386 kind: CoverageKind::Unreachable,
387 code_region: Some(code_region),
388 }),
389 })
390 }
391}
392
c30ab7b3
SL
393pub struct SimplifyLocals;
394
e1599b0c 395impl<'tcx> MirPass<'tcx> for SimplifyLocals {
29967ef6
XL
396 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
397 trace!("running SimplifyLocals on {:?}", body.source);
6a06907d
XL
398 simplify_locals(body, tcx);
399 }
400}
ba9703b0 401
6a06907d
XL
402pub fn simplify_locals<'tcx>(body: &mut Body<'tcx>, tcx: TyCtxt<'tcx>) {
403 // First, we're going to get a count of *actual* uses for every `Local`.
cdc7bbd5 404 let mut used_locals = UsedLocals::new(body);
ba9703b0 405
6a06907d
XL
406 // Next, we're going to remove any `Local` with zero actual uses. When we remove those
407 // `Locals`, we're also going to subtract any uses of other `Locals` from the `used_locals`
408 // count. For example, if we removed `_2 = discriminant(_1)`, then we'll subtract one from
409 // `use_counts[_1]`. That in turn might make `_1` unused, so we loop until we hit a
410 // fixedpoint where there are no more unused locals.
411 remove_unused_definitions(&mut used_locals, body);
ba9703b0 412
6a06907d 413 // Finally, we'll actually do the work of shrinking `body.local_decls` and remapping the `Local`s.
cdc7bbd5 414 let map = make_local_map(&mut body.local_decls, &used_locals);
ba9703b0 415
6a06907d
XL
416 // Only bother running the `LocalUpdater` if we actually found locals to remove.
417 if map.iter().any(Option::is_none) {
418 // Update references to all vars and tmps now
419 let mut updater = LocalUpdater { map, tcx };
420 updater.visit_body(body);
ba9703b0 421
6a06907d 422 body.local_decls.shrink_to_fit();
c30ab7b3
SL
423 }
424}
425
426/// Construct the mapping while swapping out unused stuff out from the `vec`.
cdc7bbd5 427fn make_local_map<V>(
ba9703b0 428 local_decls: &mut IndexVec<Local, V>,
cdc7bbd5 429 used_locals: &UsedLocals,
8faf50e0 430) -> IndexVec<Local, Option<Local>> {
cdc7bbd5 431 let mut map: IndexVec<Local, Option<Local>> = IndexVec::from_elem(None, &*local_decls);
8faf50e0 432 let mut used = Local::new(0);
29967ef6
XL
433
434 for alive_index in local_decls.indices() {
cdc7bbd5
XL
435 // `is_used` treats the `RETURN_PLACE` and arguments as used.
436 if !used_locals.is_used(alive_index) {
437 continue;
438 }
439
440 map[alive_index] = Some(used);
441 if alive_index != used {
442 local_decls.swap(alive_index, used);
c30ab7b3 443 }
cdc7bbd5 444 used.increment_by(1);
c30ab7b3 445 }
ba9703b0 446 local_decls.truncate(used.index());
c30ab7b3
SL
447 map
448}
449
29967ef6 450/// Keeps track of used & unused locals.
cdc7bbd5 451struct UsedLocals {
29967ef6 452 increment: bool,
cdc7bbd5 453 arg_count: u32,
29967ef6 454 use_count: IndexVec<Local, u32>,
c30ab7b3
SL
455}
456
cdc7bbd5 457impl UsedLocals {
29967ef6 458 /// Determines which locals are used & unused in the given body.
cdc7bbd5 459 fn new(body: &Body<'_>) -> Self {
29967ef6
XL
460 let mut this = Self {
461 increment: true,
cdc7bbd5 462 arg_count: body.arg_count.try_into().unwrap(),
29967ef6
XL
463 use_count: IndexVec::from_elem(0, &body.local_decls),
464 };
465 this.visit_body(body);
466 this
ba9703b0 467 }
ba9703b0 468
29967ef6 469 /// Checks if local is used.
cdc7bbd5
XL
470 ///
471 /// Return place and arguments are always considered used.
29967ef6
XL
472 fn is_used(&self, local: Local) -> bool {
473 trace!("is_used({:?}): use_count: {:?}", local, self.use_count[local]);
cdc7bbd5 474 local.as_u32() <= self.arg_count || self.use_count[local] != 0
29967ef6 475 }
e74abb32 476
29967ef6
XL
477 /// Updates the use counts to reflect the removal of given statement.
478 fn statement_removed(&mut self, statement: &Statement<'tcx>) {
479 self.increment = false;
e74abb32 480
29967ef6
XL
481 // The location of the statement is irrelevant.
482 let location = Location { block: START_BLOCK, statement_index: 0 };
483 self.visit_statement(statement, location);
c30ab7b3 484 }
ba9703b0 485
29967ef6
XL
486 /// Visits a left-hand side of an assignment.
487 fn visit_lhs(&mut self, place: &Place<'tcx>, location: Location) {
488 if place.is_indirect() {
489 // A use, not a definition.
490 self.visit_place(place, PlaceContext::MutatingUse(MutatingUseContext::Store), location);
491 } else {
cdc7bbd5
XL
492 // A definition. The base local itself is not visited, so this occurrence is not counted
493 // toward its use count. There might be other locals still, used in an indexing
494 // projection.
29967ef6 495 self.super_projection(
6a06907d 496 place.as_ref(),
29967ef6
XL
497 PlaceContext::MutatingUse(MutatingUseContext::Projection),
498 location,
499 );
500 }
ba9703b0
XL
501 }
502}
503
cdc7bbd5 504impl Visitor<'_> for UsedLocals {
29967ef6
XL
505 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
506 match statement.kind {
507 StatementKind::LlvmInlineAsm(..)
6a06907d 508 | StatementKind::CopyNonOverlapping(..)
29967ef6
XL
509 | StatementKind::Retag(..)
510 | StatementKind::Coverage(..)
511 | StatementKind::FakeRead(..)
512 | StatementKind::AscribeUserType(..) => {
513 self.super_statement(statement, location);
ba9703b0 514 }
ba9703b0 515
29967ef6 516 StatementKind::Nop => {}
ba9703b0 517
29967ef6 518 StatementKind::StorageLive(_local) | StatementKind::StorageDead(_local) => {}
c30ab7b3 519
29967ef6
XL
520 StatementKind::Assign(box (ref place, ref rvalue)) => {
521 self.visit_lhs(place, location);
522 self.visit_rvalue(rvalue, location);
523 }
ba9703b0 524
29967ef6
XL
525 StatementKind::SetDiscriminant { ref place, variant_index: _ } => {
526 self.visit_lhs(place, location);
527 }
528 }
ba9703b0 529 }
ba9703b0 530
cdc7bbd5 531 fn visit_local(&mut self, local: &Local, _ctx: PlaceContext, _location: Location) {
29967ef6
XL
532 if self.increment {
533 self.use_count[*local] += 1;
534 } else {
535 assert_ne!(self.use_count[*local], 0);
536 self.use_count[*local] -= 1;
537 }
e74abb32 538 }
29967ef6 539}
e74abb32 540
29967ef6 541/// Removes unused definitions. Updates the used locals to reflect the changes made.
cdc7bbd5 542fn remove_unused_definitions<'a, 'tcx>(used_locals: &'a mut UsedLocals, body: &mut Body<'tcx>) {
29967ef6
XL
543 // The use counts are updated as we remove the statements. A local might become unused
544 // during the retain operation, leading to a temporary inconsistency (storage statements or
545 // definitions referencing the local might remain). For correctness it is crucial that this
546 // computation reaches a fixed point.
547
548 let mut modified = true;
549 while modified {
550 modified = false;
551
552 for data in body.basic_blocks_mut() {
553 // Remove unnecessary StorageLive and StorageDead annotations.
554 data.statements.retain(|statement| {
555 let keep = match &statement.kind {
556 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
557 used_locals.is_used(*local)
558 }
559 StatementKind::Assign(box (place, _)) => used_locals.is_used(place.local),
ba9703b0 560
29967ef6
XL
561 StatementKind::SetDiscriminant { ref place, .. } => {
562 used_locals.is_used(place.local)
563 }
564 _ => true,
565 };
ba9703b0 566
29967ef6
XL
567 if !keep {
568 trace!("removing statement {:?}", statement);
569 modified = true;
570 used_locals.statement_removed(statement);
571 }
ba9703b0 572
29967ef6
XL
573 keep
574 });
575 }
c30ab7b3 576 }
ba9703b0 577}
e74abb32 578
ba9703b0
XL
579struct LocalUpdater<'tcx> {
580 map: IndexVec<Local, Option<Local>>,
581 tcx: TyCtxt<'tcx>,
582}
583
584impl<'tcx> MutVisitor<'tcx> for LocalUpdater<'tcx> {
585 fn tcx(&self) -> TyCtxt<'tcx> {
586 self.tcx
c30ab7b3 587 }
e74abb32 588
ba9703b0
XL
589 fn visit_local(&mut self, l: &mut Local, _: PlaceContext, _: Location) {
590 *l = self.map[*l].unwrap();
e74abb32 591 }
c30ab7b3 592}