]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/dest_prop.rs
3e45319431cec0e9de6816ed78310c892d09d461
[rust.git] / compiler / rustc_mir_transform / src / dest_prop.rs
1 //! Propagates assignment destinations backwards in the CFG to eliminate redundant assignments.
2 //!
3 //! # Motivation
4 //!
5 //! MIR building can insert a lot of redundant copies, and Rust code in general often tends to move
6 //! values around a lot. The result is a lot of assignments of the form `dest = {move} src;` in MIR.
7 //! MIR building for constants in particular tends to create additional locals that are only used
8 //! inside a single block to shuffle a value around unnecessarily.
9 //!
10 //! LLVM by itself is not good enough at eliminating these redundant copies (eg. see
11 //! <https://github.com/rust-lang/rust/issues/32966>), so this leaves some performance on the table
12 //! that we can regain by implementing an optimization for removing these assign statements in rustc
13 //! itself. When this optimization runs fast enough, it can also speed up the constant evaluation
14 //! and code generation phases of rustc due to the reduced number of statements and locals.
15 //!
16 //! # The Optimization
17 //!
18 //! Conceptually, this optimization is "destination propagation". It is similar to the Named Return
19 //! Value Optimization, or NRVO, known from the C++ world, except that it isn't limited to return
20 //! values or the return place `_0`. On a very high level, independent of the actual implementation
21 //! details, it does the following:
22 //!
23 //! 1) Identify `dest = src;` statements with values for `dest` and `src` whose storage can soundly
24 //!    be merged.
25 //! 2) Replace all mentions of `src` with `dest` ("unifying" them and propagating the destination
26 //!    backwards).
27 //! 3) Delete the `dest = src;` statement (by making it a `nop`).
28 //!
29 //! Step 1) is by far the hardest, so it is explained in more detail below.
30 //!
31 //! ## Soundness
32 //!
33 //! We have a pair of places `p` and `q`, whose memory we would like to merge. In order for this to
34 //! be sound, we need to check a number of conditions:
35 //!
36 //! * `p` and `q` must both be *constant* - it does not make much sense to talk about merging them
37 //!   if they do not consistently refer to the same place in memory. This is satisfied if they do
38 //!   not contain any indirection through a pointer or any indexing projections.
39 //!
40 //! * We need to make sure that the goal of "merging the memory" is actually structurally possible
41 //!   in MIR. For example, even if all the other conditions are satisfied, there is no way to
42 //!   "merge" `_5.foo` and `_6.bar`. For now, we ensure this by requiring that both `p` and `q` are
43 //!   locals with no further projections. Future iterations of this pass should improve on this.
44 //!
45 //! * Finally, we want `p` and `q` to use the same memory - however, we still need to make sure that
46 //!   each of them has enough "ownership" of that memory to continue "doing its job." More
47 //!   precisely, what we will check is that whenever the program performs a write to `p`, then it
48 //!   does not currently care about what the value in `q` is (and vice versa). We formalize the
49 //!   notion of "does not care what the value in `q` is" by checking the *liveness* of `q`.
50 //!
51 //!   Because of the difficulty of computing liveness of places that have their address taken, we do
52 //!   not even attempt to do it. Any places that are in a local that has its address taken is
53 //!   excluded from the optimization.
54 //!
55 //! The first two conditions are simple structural requirements on the `Assign` statements that can
56 //! be trivially checked. The third requirement however is more difficult and costly to check.
57 //!
58 //! ## Future Improvements
59 //!
60 //! There are a number of ways in which this pass could be improved in the future:
61 //!
62 //! * Merging storage liveness ranges instead of removing storage statements completely. This may
63 //!   improve stack usage.
64 //!
65 //! * Allow merging locals into places with projections, eg `_5` into `_6.foo`.
66 //!
67 //! * Liveness analysis with more precision than whole locals at a time. The smaller benefit of this
68 //!   is that it would allow us to dest prop at "sub-local" levels in some cases. The bigger benefit
69 //!   of this is that such liveness analysis can report more accurate results about whole locals at
70 //!   a time. For example, consider:
71 //!
72 //!   ```ignore (syntax-highliting-only)
73 //!   _1 = u;
74 //!   // unrelated code
75 //!   _1.f1 = v;
76 //!   _2 = _1.f1;
77 //!   ```
78 //!
79 //!   Because the current analysis only thinks in terms of locals, it does not have enough
80 //!   information to report that `_1` is dead in the "unrelated code" section.
81 //!
82 //! * Liveness analysis enabled by alias analysis. This would allow us to not just bail on locals
83 //!   that ever have their address taken. Of course that requires actually having alias analysis
84 //!   (and a model to build it on), so this might be a bit of a ways off.
85 //!
86 //! * Various perf improvents. There are a bunch of comments in here marked `PERF` with ideas for
87 //!   how to do things more efficiently. However, the complexity of the pass as a whole should be
88 //!   kept in mind.
89 //!
90 //! ## Previous Work
91 //!
92 //! A [previous attempt][attempt 1] at implementing an optimization like this turned out to be a
93 //! significant regression in compiler performance. Fixing the regressions introduced a lot of
94 //! undesirable complexity to the implementation.
95 //!
96 //! A [subsequent approach][attempt 2] tried to avoid the costly computation by limiting itself to
97 //! acyclic CFGs, but still turned out to be far too costly to run due to suboptimal performance
98 //! within individual basic blocks, requiring a walk across the entire block for every assignment
99 //! found within the block. For the `tuple-stress` benchmark, which has 458745 statements in a
100 //! single block, this proved to be far too costly.
101 //!
102 //! [Another approach after that][attempt 3] was much closer to correct, but had some soundness
103 //! issues - it was failing to consider stores outside live ranges, and failed to uphold some of the
104 //! requirements that MIR has for non-overlapping places within statements. However, it also had
105 //! performance issues caused by `O(l² * s)` runtime, where `l` is the number of locals and `s` is
106 //! the number of statements and terminators.
107 //!
108 //! Since the first attempt at this, the compiler has improved dramatically, and new analysis
109 //! frameworks have been added that should make this approach viable without requiring a limited
110 //! approach that only works for some classes of CFGs:
111 //! - rustc now has a powerful dataflow analysis framework that can handle forwards and backwards
112 //!   analyses efficiently.
113 //! - Layout optimizations for generators have been added to improve code generation for
114 //!   async/await, which are very similar in spirit to what this optimization does.
115 //!
116 //! Also, rustc now has a simple NRVO pass (see `nrvo.rs`), which handles a subset of the cases that
117 //! this destination propagation pass handles, proving that similar optimizations can be performed
118 //! on MIR.
119 //!
120 //! ## Pre/Post Optimization
121 //!
122 //! It is recommended to run `SimplifyCfg` and then `SimplifyLocals` some time after this pass, as
123 //! it replaces the eliminated assign statements with `nop`s and leaves unused locals behind.
124 //!
125 //! [liveness]: https://en.wikipedia.org/wiki/Live_variable_analysis
126 //! [attempt 1]: https://github.com/rust-lang/rust/pull/47954
127 //! [attempt 2]: https://github.com/rust-lang/rust/pull/71003
128 //! [attempt 3]: https://github.com/rust-lang/rust/pull/72632
129
130 use std::collections::hash_map::{Entry, OccupiedEntry};
131
132 use crate::MirPass;
133 use rustc_data_structures::fx::FxHashMap;
134 use rustc_index::bit_set::BitSet;
135 use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
136 use rustc_middle::mir::{dump_mir, PassWhere};
137 use rustc_middle::mir::{
138     traversal, BasicBlock, Body, InlineAsmOperand, Local, LocalKind, Location, Operand, Place,
139     Rvalue, Statement, StatementKind, TerminatorKind,
140 };
141 use rustc_middle::ty::TyCtxt;
142 use rustc_mir_dataflow::impls::MaybeLiveLocals;
143 use rustc_mir_dataflow::{Analysis, ResultsCursor};
144
145 pub struct DestinationPropagation;
146
147 impl<'tcx> MirPass<'tcx> for DestinationPropagation {
148     fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
149         // For now, only run at MIR opt level 3. Two things need to be changed before this can be
150         // turned on by default:
151         //  1. Because of the overeager removal of storage statements, this can cause stack space
152         //     regressions. This opt is not the place to fix this though, it's a more general
153         //     problem in MIR.
154         //  2. Despite being an overall perf improvement, this still causes a 30% regression in
155         //     keccak. We can temporarily fix this by bounding function size, but in the long term
156         //     we should fix this by being smarter about invalidating analysis results.
157         sess.mir_opt_level() >= 3
158     }
159
160     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
161         let def_id = body.source.def_id();
162         let mut allocations = Allocations::default();
163         trace!(func = ?tcx.def_path_str(def_id));
164
165         let borrowed = rustc_mir_dataflow::impls::borrowed_locals(body);
166
167         // In order to avoid having to collect data for every single pair of locals in the body, we
168         // do not allow doing more than one merge for places that are derived from the same local at
169         // once. To avoid missed opportunities, we instead iterate to a fixed point - we'll refer to
170         // each of these iterations as a "round."
171         //
172         // Reaching a fixed point could in theory take up to `min(l, s)` rounds - however, we do not
173         // expect to see MIR like that. To verify this, a test was run against `[rust-lang/regex]` -
174         // the average MIR body saw 1.32 full iterations of this loop. The most that was hit were 30
175         // for a single function. Only 80/2801 (2.9%) of functions saw at least 5.
176         //
177         // [rust-lang/regex]:
178         //     https://github.com/rust-lang/regex/tree/b5372864e2df6a2f5e543a556a62197f50ca3650
179         let mut round_count = 0;
180         loop {
181             // PERF: Can we do something smarter than recalculating the candidates and liveness
182             // results?
183             let mut candidates = find_candidates(
184                 body,
185                 &borrowed,
186                 &mut allocations.candidates,
187                 &mut allocations.candidates_reverse,
188             );
189             trace!(?candidates);
190             let mut live = MaybeLiveLocals
191                 .into_engine(tcx, body)
192                 .iterate_to_fixpoint()
193                 .into_results_cursor(body);
194             dest_prop_mir_dump(tcx, body, &mut live, round_count);
195
196             FilterInformation::filter_liveness(
197                 &mut candidates,
198                 &mut live,
199                 &mut allocations.write_info,
200                 body,
201             );
202
203             // Because we do not update liveness information, it is unsound to use a local for more
204             // than one merge operation within a single round of optimizations. We store here which
205             // ones we have already used.
206             let mut merged_locals: BitSet<Local> = BitSet::new_empty(body.local_decls.len());
207
208             // This is the set of merges we will apply this round. It is a subset of the candidates.
209             let mut merges = FxHashMap::default();
210
211             for (src, candidates) in candidates.c.iter() {
212                 if merged_locals.contains(*src) {
213                     continue;
214                 }
215                 let Some(dest) =
216                     candidates.iter().find(|dest| !merged_locals.contains(**dest)) else {
217                         continue;
218                 };
219                 if !tcx.consider_optimizing(|| {
220                     format!("{} round {}", tcx.def_path_str(def_id), round_count)
221                 }) {
222                     break;
223                 }
224                 merges.insert(*src, *dest);
225                 merged_locals.insert(*src);
226                 merged_locals.insert(*dest);
227             }
228             trace!(merging = ?merges);
229
230             if merges.is_empty() {
231                 break;
232             }
233             round_count += 1;
234
235             apply_merges(body, tcx, &merges, &merged_locals);
236         }
237
238         trace!(round_count);
239     }
240 }
241
242 /// Container for the various allocations that we need.
243 ///
244 /// We store these here and hand out `&mut` access to them, instead of dropping and recreating them
245 /// frequently. Everything with a `&'alloc` lifetime points into here.
246 #[derive(Default)]
247 struct Allocations {
248     candidates: FxHashMap<Local, Vec<Local>>,
249     candidates_reverse: FxHashMap<Local, Vec<Local>>,
250     write_info: WriteInfo,
251     // PERF: Do this for `MaybeLiveLocals` allocations too.
252 }
253
254 #[derive(Debug)]
255 struct Candidates<'alloc> {
256     /// The set of candidates we are considering in this optimization.
257     ///
258     /// We will always merge the key into at most one of its values.
259     ///
260     /// Whether a place ends up in the key or the value does not correspond to whether it appears as
261     /// the lhs or rhs of any assignment. As a matter of fact, the places in here might never appear
262     /// in an assignment at all. This happens because if we see an assignment like this:
263     ///
264     /// ```ignore (syntax-highlighting-only)
265     /// _1.0 = _2.0
266     /// ```
267     ///
268     /// We will still report that we would like to merge `_1` and `_2` in an attempt to allow us to
269     /// remove that assignment.
270     c: &'alloc mut FxHashMap<Local, Vec<Local>>,
271     /// A reverse index of the `c` set; if the `c` set contains `a => Place { local: b, proj }`,
272     /// then this contains `b => a`.
273     // PERF: Possibly these should be `SmallVec`s?
274     reverse: &'alloc mut FxHashMap<Local, Vec<Local>>,
275 }
276
277 //////////////////////////////////////////////////////////
278 // Merging
279 //
280 // Applies the actual optimization
281
282 fn apply_merges<'tcx>(
283     body: &mut Body<'tcx>,
284     tcx: TyCtxt<'tcx>,
285     merges: &FxHashMap<Local, Local>,
286     merged_locals: &BitSet<Local>,
287 ) {
288     let mut merger = Merger { tcx, merges, merged_locals };
289     merger.visit_body_preserves_cfg(body);
290 }
291
292 struct Merger<'a, 'tcx> {
293     tcx: TyCtxt<'tcx>,
294     merges: &'a FxHashMap<Local, Local>,
295     merged_locals: &'a BitSet<Local>,
296 }
297
298 impl<'a, 'tcx> MutVisitor<'tcx> for Merger<'a, 'tcx> {
299     fn tcx(&self) -> TyCtxt<'tcx> {
300         self.tcx
301     }
302
303     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _location: Location) {
304         if let Some(dest) = self.merges.get(local) {
305             *local = *dest;
306         }
307     }
308
309     fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
310         match &statement.kind {
311             // FIXME: Don't delete storage statements, but "merge" the storage ranges instead.
312             StatementKind::StorageDead(local) | StatementKind::StorageLive(local)
313                 if self.merged_locals.contains(*local) =>
314             {
315                 statement.make_nop();
316                 return;
317             }
318             _ => (),
319         };
320         self.super_statement(statement, location);
321         match &statement.kind {
322             StatementKind::Assign(box (dest, rvalue)) => {
323                 match rvalue {
324                     Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) => {
325                         // These might've been turned into self-assignments by the replacement
326                         // (this includes the original statement we wanted to eliminate).
327                         if dest == place {
328                             debug!("{:?} turned into self-assignment, deleting", location);
329                             statement.make_nop();
330                         }
331                     }
332                     _ => {}
333                 }
334             }
335
336             _ => {}
337         }
338     }
339 }
340
341 //////////////////////////////////////////////////////////
342 // Liveness filtering
343 //
344 // This section enforces bullet point 2
345
346 struct FilterInformation<'a, 'body, 'alloc, 'tcx> {
347     body: &'body Body<'tcx>,
348     live: &'a mut ResultsCursor<'body, 'tcx, MaybeLiveLocals>,
349     candidates: &'a mut Candidates<'alloc>,
350     write_info: &'alloc mut WriteInfo,
351     at: Location,
352 }
353
354 // We first implement some utility functions which we will expose removing candidates according to
355 // different needs. Throughout the livenss filtering, the `candidates` are only ever accessed
356 // through these methods, and not directly.
357 impl<'alloc> Candidates<'alloc> {
358     /// Just `Vec::retain`, but the condition is inverted and we add debugging output
359     fn vec_filter_candidates(
360         src: Local,
361         v: &mut Vec<Local>,
362         mut f: impl FnMut(Local) -> CandidateFilter,
363         at: Location,
364     ) {
365         v.retain(|dest| {
366             let remove = f(*dest);
367             if remove == CandidateFilter::Remove {
368                 trace!("eliminating {:?} => {:?} due to conflict at {:?}", src, dest, at);
369             }
370             remove == CandidateFilter::Keep
371         });
372     }
373
374     /// `vec_filter_candidates` but for an `Entry`
375     fn entry_filter_candidates(
376         mut entry: OccupiedEntry<'_, Local, Vec<Local>>,
377         p: Local,
378         f: impl FnMut(Local) -> CandidateFilter,
379         at: Location,
380     ) {
381         let candidates = entry.get_mut();
382         Self::vec_filter_candidates(p, candidates, f, at);
383         if candidates.len() == 0 {
384             entry.remove();
385         }
386     }
387
388     /// For all candidates `(p, q)` or `(q, p)` removes the candidate if `f(q)` says to do so
389     fn filter_candidates_by(
390         &mut self,
391         p: Local,
392         mut f: impl FnMut(Local) -> CandidateFilter,
393         at: Location,
394     ) {
395         // Cover the cases where `p` appears as a `src`
396         if let Entry::Occupied(entry) = self.c.entry(p) {
397             Self::entry_filter_candidates(entry, p, &mut f, at);
398         }
399         // And the cases where `p` appears as a `dest`
400         let Some(srcs) = self.reverse.get_mut(&p) else {
401             return;
402         };
403         // We use `retain` here to remove the elements from the reverse set if we've removed the
404         // matching candidate in the forward set.
405         srcs.retain(|src| {
406             if f(*src) == CandidateFilter::Keep {
407                 return true;
408             }
409             let Entry::Occupied(entry) = self.c.entry(*src) else {
410                 return false;
411             };
412             Self::entry_filter_candidates(
413                 entry,
414                 *src,
415                 |dest| {
416                     if dest == p { CandidateFilter::Remove } else { CandidateFilter::Keep }
417                 },
418                 at,
419             );
420             false
421         });
422     }
423 }
424
425 #[derive(Copy, Clone, PartialEq, Eq)]
426 enum CandidateFilter {
427     Keep,
428     Remove,
429 }
430
431 impl<'a, 'body, 'alloc, 'tcx> FilterInformation<'a, 'body, 'alloc, 'tcx> {
432     /// Filters the set of candidates to remove those that conflict.
433     ///
434     /// The steps we take are exactly those that are outlined at the top of the file. For each
435     /// statement/terminator, we collect the set of locals that are written to in that
436     /// statement/terminator, and then we remove all pairs of candidates that contain one such local
437     /// and another one that is live.
438     ///
439     /// We need to be careful about the ordering of operations within each statement/terminator
440     /// here. Many statements might write and read from more than one place, and we need to consider
441     /// them all. The strategy for doing this is as follows: We first gather all the places that are
442     /// written to within the statement/terminator via `WriteInfo`. Then, we use the liveness
443     /// analysis from *before* the statement/terminator (in the control flow sense) to eliminate
444     /// candidates - this is because we want to conservatively treat a pair of locals that is both
445     /// read and written in the statement/terminator to be conflicting, and the liveness analysis
446     /// before the statement/terminator will correctly report locals that are read in the
447     /// statement/terminator to be live. We are additionally conservative by treating all written to
448     /// locals as also being read from.
449     fn filter_liveness<'b>(
450         candidates: &mut Candidates<'alloc>,
451         live: &mut ResultsCursor<'b, 'tcx, MaybeLiveLocals>,
452         write_info_alloc: &'alloc mut WriteInfo,
453         body: &'b Body<'tcx>,
454     ) {
455         let mut this = FilterInformation {
456             body,
457             live,
458             candidates,
459             // We don't actually store anything at this scope, we just keep things here to be able
460             // to reuse the allocation.
461             write_info: write_info_alloc,
462             // Doesn't matter what we put here, will be overwritten before being used
463             at: Location { block: BasicBlock::from_u32(0), statement_index: 0 },
464         };
465         this.internal_filter_liveness();
466     }
467
468     fn internal_filter_liveness(&mut self) {
469         for (block, data) in traversal::preorder(self.body) {
470             self.at = Location { block, statement_index: data.statements.len() };
471             self.live.seek_after_primary_effect(self.at);
472             self.write_info.for_terminator(&data.terminator().kind);
473             self.apply_conflicts();
474
475             for (i, statement) in data.statements.iter().enumerate().rev() {
476                 self.at = Location { block, statement_index: i };
477                 self.live.seek_after_primary_effect(self.at);
478                 self.write_info.for_statement(&statement.kind, self.body);
479                 self.apply_conflicts();
480             }
481         }
482     }
483
484     fn apply_conflicts(&mut self) {
485         let writes = &self.write_info.writes;
486         for p in writes {
487             let other_skip = self.write_info.skip_pair.and_then(|(a, b)| {
488                 if a == *p {
489                     Some(b)
490                 } else if b == *p {
491                     Some(a)
492                 } else {
493                     None
494                 }
495             });
496             self.candidates.filter_candidates_by(
497                 *p,
498                 |q| {
499                     if Some(q) == other_skip {
500                         return CandidateFilter::Keep;
501                     }
502                     // It is possible that a local may be live for less than the
503                     // duration of a statement This happens in the case of function
504                     // calls or inline asm. Because of this, we also mark locals as
505                     // conflicting when both of them are written to in the same
506                     // statement.
507                     if self.live.contains(q) || writes.contains(&q) {
508                         CandidateFilter::Remove
509                     } else {
510                         CandidateFilter::Keep
511                     }
512                 },
513                 self.at,
514             );
515         }
516     }
517 }
518
519 /// Describes where a statement/terminator writes to
520 #[derive(Default, Debug)]
521 struct WriteInfo {
522     writes: Vec<Local>,
523     /// If this pair of locals is a candidate pair, completely skip processing it during this
524     /// statement. All other candidates are unaffected.
525     skip_pair: Option<(Local, Local)>,
526 }
527
528 impl WriteInfo {
529     fn for_statement<'tcx>(&mut self, statement: &StatementKind<'tcx>, body: &Body<'tcx>) {
530         self.reset();
531         match statement {
532             StatementKind::Assign(box (lhs, rhs)) => {
533                 self.add_place(*lhs);
534                 match rhs {
535                     Rvalue::Use(op) => {
536                         self.add_operand(op);
537                         self.consider_skipping_for_assign_use(*lhs, op, body);
538                     }
539                     Rvalue::Repeat(op, _) => {
540                         self.add_operand(op);
541                     }
542                     Rvalue::Cast(_, op, _)
543                     | Rvalue::UnaryOp(_, op)
544                     | Rvalue::ShallowInitBox(op, _) => {
545                         self.add_operand(op);
546                     }
547                     Rvalue::BinaryOp(_, ops) | Rvalue::CheckedBinaryOp(_, ops) => {
548                         for op in [&ops.0, &ops.1] {
549                             self.add_operand(op);
550                         }
551                     }
552                     Rvalue::Aggregate(_, ops) => {
553                         for op in ops {
554                             self.add_operand(op);
555                         }
556                     }
557                     Rvalue::ThreadLocalRef(_)
558                     | Rvalue::NullaryOp(_, _)
559                     | Rvalue::Ref(_, _, _)
560                     | Rvalue::AddressOf(_, _)
561                     | Rvalue::Len(_)
562                     | Rvalue::Discriminant(_)
563                     | Rvalue::CopyForDeref(_) => (),
564                 }
565             }
566             // Retags are technically also reads, but reporting them as a write suffices
567             StatementKind::SetDiscriminant { place, .. }
568             | StatementKind::Deinit(place)
569             | StatementKind::Retag(_, place) => {
570                 self.add_place(**place);
571             }
572             StatementKind::Intrinsic(_)
573             | StatementKind::Nop
574             | StatementKind::Coverage(_)
575             | StatementKind::StorageLive(_)
576             | StatementKind::StorageDead(_) => (),
577             StatementKind::FakeRead(_) | StatementKind::AscribeUserType(_, _) => {
578                 bug!("{:?} not found in this MIR phase", statement)
579             }
580         }
581     }
582
583     fn consider_skipping_for_assign_use<'tcx>(
584         &mut self,
585         lhs: Place<'tcx>,
586         rhs: &Operand<'tcx>,
587         body: &Body<'tcx>,
588     ) {
589         let Some(rhs) = rhs.place() else {
590             return
591         };
592         if let Some(pair) = places_to_candidate_pair(lhs, rhs, body) {
593             self.skip_pair = Some(pair);
594         }
595     }
596
597     fn for_terminator<'tcx>(&mut self, terminator: &TerminatorKind<'tcx>) {
598         self.reset();
599         match terminator {
600             TerminatorKind::SwitchInt { discr: op, .. }
601             | TerminatorKind::Assert { cond: op, .. } => {
602                 self.add_operand(op);
603             }
604             TerminatorKind::Call { destination, func, args, .. } => {
605                 self.add_place(*destination);
606                 self.add_operand(func);
607                 for arg in args {
608                     self.add_operand(arg);
609                 }
610             }
611             TerminatorKind::InlineAsm { operands, .. } => {
612                 for asm_operand in operands {
613                     match asm_operand {
614                         InlineAsmOperand::In { value, .. } => {
615                             self.add_operand(value);
616                         }
617                         InlineAsmOperand::Out { place, .. } => {
618                             if let Some(place) = place {
619                                 self.add_place(*place);
620                             }
621                         }
622                         // Note that the `late` field in `InOut` is about whether the registers used
623                         // for these things overlap, and is of absolutely no interest to us.
624                         InlineAsmOperand::InOut { in_value, out_place, .. } => {
625                             if let Some(place) = out_place {
626                                 self.add_place(*place);
627                             }
628                             self.add_operand(in_value);
629                         }
630                         InlineAsmOperand::Const { .. }
631                         | InlineAsmOperand::SymFn { .. }
632                         | InlineAsmOperand::SymStatic { .. } => (),
633                     }
634                 }
635             }
636             TerminatorKind::Goto { .. }
637             | TerminatorKind::Resume { .. }
638             | TerminatorKind::Abort { .. }
639             | TerminatorKind::Return
640             | TerminatorKind::Unreachable { .. } => (),
641             TerminatorKind::Drop { .. } => {
642                 // `Drop`s create a `&mut` and so are not considered
643             }
644             TerminatorKind::DropAndReplace { .. }
645             | TerminatorKind::Yield { .. }
646             | TerminatorKind::GeneratorDrop
647             | TerminatorKind::FalseEdge { .. }
648             | TerminatorKind::FalseUnwind { .. } => {
649                 bug!("{:?} not found in this MIR phase", terminator)
650             }
651         }
652     }
653
654     fn add_place<'tcx>(&mut self, place: Place<'tcx>) {
655         self.writes.push(place.local);
656     }
657
658     fn add_operand<'tcx>(&mut self, op: &Operand<'tcx>) {
659         match op {
660             // FIXME(JakobDegen): In a previous version, the `Move` case was incorrectly treated as
661             // being a read only. This was unsound, however we cannot add a regression test because
662             // it is not possible to set this off with current MIR. Once we have that ability, a
663             // regression test should be added.
664             Operand::Move(p) => self.add_place(*p),
665             Operand::Copy(_) | Operand::Constant(_) => (),
666         }
667     }
668
669     fn reset(&mut self) {
670         self.writes.clear();
671         self.skip_pair = None;
672     }
673 }
674
675 /////////////////////////////////////////////////////
676 // Candidate accumulation
677
678 /// If the pair of places is being considered for merging, returns the candidate which would be
679 /// merged in order to accomplish this.
680 ///
681 /// The contract here is in one direction - there is a guarantee that merging the locals that are
682 /// outputted by this function would result in an assignment between the inputs becoming a
683 /// self-assignment. However, there is no guarantee that the returned pair is actually suitable for
684 /// merging - candidate collection must still check this independently.
685 ///
686 /// This output is unique for each unordered pair of input places.
687 fn places_to_candidate_pair<'tcx>(
688     a: Place<'tcx>,
689     b: Place<'tcx>,
690     body: &Body<'tcx>,
691 ) -> Option<(Local, Local)> {
692     let (mut a, mut b) = if a.projection.len() == 0 && b.projection.len() == 0 {
693         (a.local, b.local)
694     } else {
695         return None;
696     };
697
698     // By sorting, we make sure we're input order independent
699     if a > b {
700         std::mem::swap(&mut a, &mut b);
701     }
702
703     // We could now return `(a, b)`, but then we miss some candidates in the case where `a` can't be
704     // used as a `src`.
705     if is_local_required(a, body) {
706         std::mem::swap(&mut a, &mut b);
707     }
708     // We could check `is_local_required` again here, but there's no need - after all, we make no
709     // promise that the candidate pair is actually valid
710     Some((a, b))
711 }
712
713 /// Collects the candidates for merging
714 ///
715 /// This is responsible for enforcing the first and third bullet point.
716 fn find_candidates<'alloc, 'tcx>(
717     body: &Body<'tcx>,
718     borrowed: &BitSet<Local>,
719     candidates: &'alloc mut FxHashMap<Local, Vec<Local>>,
720     candidates_reverse: &'alloc mut FxHashMap<Local, Vec<Local>>,
721 ) -> Candidates<'alloc> {
722     candidates.clear();
723     candidates_reverse.clear();
724     let mut visitor = FindAssignments { body, candidates, borrowed };
725     visitor.visit_body(body);
726     // Deduplicate candidates
727     for (_, cands) in candidates.iter_mut() {
728         cands.sort();
729         cands.dedup();
730     }
731     // Generate the reverse map
732     for (src, cands) in candidates.iter() {
733         for dest in cands.iter().copied() {
734             candidates_reverse.entry(dest).or_default().push(*src);
735         }
736     }
737     Candidates { c: candidates, reverse: candidates_reverse }
738 }
739
740 struct FindAssignments<'a, 'alloc, 'tcx> {
741     body: &'a Body<'tcx>,
742     candidates: &'alloc mut FxHashMap<Local, Vec<Local>>,
743     borrowed: &'a BitSet<Local>,
744 }
745
746 impl<'tcx> Visitor<'tcx> for FindAssignments<'_, '_, 'tcx> {
747     fn visit_statement(&mut self, statement: &Statement<'tcx>, _: Location) {
748         if let StatementKind::Assign(box (
749             lhs,
750             Rvalue::Use(Operand::Copy(rhs) | Operand::Move(rhs)),
751         )) = &statement.kind
752         {
753             let Some((src, dest)) = places_to_candidate_pair(*lhs, *rhs, self.body) else {
754                 return;
755             };
756
757             // As described at the top of the file, we do not go near things that have their address
758             // taken.
759             if self.borrowed.contains(src) || self.borrowed.contains(dest) {
760                 return;
761             }
762
763             // Also, we need to make sure that MIR actually allows the `src` to be removed
764             if is_local_required(src, self.body) {
765                 return;
766             }
767
768             // We may insert duplicates here, but that's fine
769             self.candidates.entry(src).or_default().push(dest);
770         }
771     }
772 }
773
774 /// Some locals are part of the function's interface and can not be removed.
775 ///
776 /// Note that these locals *can* still be merged with non-required locals by removing that other
777 /// local.
778 fn is_local_required(local: Local, body: &Body<'_>) -> bool {
779     match body.local_kind(local) {
780         LocalKind::Arg | LocalKind::ReturnPointer => true,
781         LocalKind::Var | LocalKind::Temp => false,
782     }
783 }
784
785 /////////////////////////////////////////////////////////
786 // MIR Dump
787
788 fn dest_prop_mir_dump<'body, 'tcx>(
789     tcx: TyCtxt<'tcx>,
790     body: &'body Body<'tcx>,
791     live: &mut ResultsCursor<'body, 'tcx, MaybeLiveLocals>,
792     round: usize,
793 ) {
794     let mut reachable = None;
795     dump_mir(tcx, false, "DestinationPropagation-dataflow", &round, body, |pass_where, w| {
796         let reachable = reachable.get_or_insert_with(|| traversal::reachable_as_bitset(body));
797
798         match pass_where {
799             PassWhere::BeforeLocation(loc) if reachable.contains(loc.block) => {
800                 live.seek_after_primary_effect(loc);
801                 writeln!(w, "        // live: {:?}", live.get())?;
802             }
803             PassWhere::AfterTerminator(bb) if reachable.contains(bb) => {
804                 let loc = body.terminator_loc(bb);
805                 live.seek_before_primary_effect(loc);
806                 writeln!(w, "        // live: {:?}", live.get())?;
807             }
808
809             PassWhere::BeforeBlock(bb) if reachable.contains(bb) => {
810                 live.seek_to_block_start(bb);
811                 writeln!(w, "    // live: {:?}", live.get())?;
812             }
813
814             PassWhere::BeforeCFG | PassWhere::AfterCFG | PassWhere::AfterLocation(_) => {}
815
816             PassWhere::BeforeLocation(_) | PassWhere::AfterTerminator(_) => {
817                 writeln!(w, "        // live: <unreachable>")?;
818             }
819
820             PassWhere::BeforeBlock(_) => {
821                 writeln!(w, "    // live: <unreachable>")?;
822             }
823         }
824
825         Ok(())
826     });
827 }