/src/wasmtime/cranelift/codegen/src/alias_analysis.rs
Line | Count | Source |
1 | | //! Alias analysis, consisting of a "last store" pass and a "memory |
2 | | //! values" pass. These two passes operate as one fused pass, and so |
3 | | //! are implemented together here. |
4 | | //! |
5 | | //! We partition memory state into several *disjoint regions* of |
6 | | //! "abstract state". These regions are defined by `ir::AliasRegion` |
7 | | //! and may correspond to distinct linear memories in Wasm, different |
8 | | //! types (or fields) that cannot alias each other (known as |
9 | | //! type-based alias analysis, or TBAA), unique stack slots, |
10 | | //! etc... Any given address in memory belongs to at most one region. |
11 | | //! |
12 | | //! We never track which piece a concrete address belongs to at |
13 | | //! runtime; this is a purely static concept. Instead, all |
14 | | //! memory-accessing instructions (loads and stores) are tagged with |
15 | | //! one of these regions in their `ir::MemFlagsData`. It is forbidden |
16 | | //! for one instruction tagged with region `R` to access a memory |
17 | | //! location `L` and then for another instruction tagged with region |
18 | | //! `S` to access the same memory location `L`. This invariant must be |
19 | | //! provided by the CLIF-producing frontend. |
20 | | //! |
21 | | //! Given that this non-aliasing property is provided by the CLIF |
22 | | //! producer, we can compute a *may-alias* property: one load or store |
23 | | //! may-alias another load or store if both access the same region. |
24 | | //! |
25 | | //! The "last store" pass helps to compute this aliasing: it scans the |
26 | | //! code, finding at each program point the last instruction that |
27 | | //! *might have* written to a given region. |
28 | | //! |
29 | | //! We can't say for sure that the "last store" *did* actually write |
30 | | //! that region, but we know for sure that no instruction *later* than |
31 | | //! it (up to the current instruction) did. However, we can derive a |
32 | | //! *must-alias* property from this: if at a given load or store, we |
33 | | //! look backward to the "last store", *AND* we find that it has |
34 | | //! exactly the same address expression and type, then we know that |
35 | | //! the current instruction's access *must* be to the same memory |
36 | | //! location. |
37 | | //! |
38 | | //! To get this must-alias property, we compute a sparse table of |
39 | | //! "memory values": these are known equivalences between SSA `Value`s |
40 | | //! and particular locations in memory. The memory-values table is a |
41 | | //! mapping from a memory location (address, type, byte order, etc...) |
42 | | //! to a known value. At a store, we can insert into this table |
43 | | //! directly. At a load, we can also insert, if we don't already have a |
44 | | //! value (from the store that produced the load's value). |
45 | | //! |
46 | | //! Then we do a few optimizations at once given this table: |
47 | | //! |
48 | | //! * If a load accesses a location identified by a (last store, |
49 | | //! address, type) key already in the table, we replace it with the |
50 | | //! SSA value for that memory location. This is usually known as |
51 | | //! "redundant load elimination" if the value came from an earlier |
52 | | //! load of the same location, or "store-to-load forwarding" if the |
53 | | //! value came from an earlier store to the same location. |
54 | | //! |
55 | | //! * If a store writes the same value that is already in the table |
56 | | //! for its memory location, then we can elide this store because it |
57 | | //! doesn't actually modify memory. We call this "idempotent-store |
58 | | //! elimination". |
59 | | //! |
60 | | //! * If a store overwrites a key in the table, *and* if this |
61 | | //! overwriting store always executes after the original store |
62 | | //! (i.e. this store post-dominates the original), *and* if no other |
63 | | //! instruction has "observed" the original store, then we can |
64 | | //! eliminate the original store. This is called "dead-store |
65 | | //! elimination". Note that observing a store is not just loading |
66 | | //! from the location it wrote, all potentially-trapping |
67 | | //! instructions must be treated as observing every store because we |
68 | | //! must preserve post-trap memory state. Similarly, loop back edges |
69 | | //! observe every store, because the loop might never terminate and |
70 | | //! reach the overwriting store. |
71 | | //! |
72 | | //! None of these apply to `volatile` accesses (see `MemFlagsData::volatile`), |
73 | | //! which must happen exactly as written: a volatile load is never replaced by |
74 | | //! a known value, a volatile store is never removed as idempotent or dead, and |
75 | | //! neither one provides a known value for a later access. A volatile access |
76 | | //! also never makes another store dead. Beyond that, every volatile access is |
77 | | //! a fence here, so no known value is forwarded across it, and every store |
78 | | //! before it is observed by it. |
79 | | //! |
80 | | //! Which store is the "last store" to a region is flow-sensitive, but |
81 | | //! whether a store is ever observed is *not*: it is observed if there |
82 | | //! is *any* path on which some instruction can observe it. We |
83 | | //! therefore compute the set of observed stores for the whole function |
84 | | //! up front, in `AliasAnalysis::observed_stores`, rather than tracking |
85 | | //! it as part of the per-block `LastStores` state. |
86 | | |
87 | | use crate::{FxHashMap, FxHashSet}; |
88 | | use crate::{ |
89 | | cursor::{Cursor, CursorPosition, FuncCursor}, |
90 | | dominator_tree::DominatorTree, |
91 | | flowgraph::ControlFlowGraph, |
92 | | inst_predicates::{ |
93 | | inst_addr_offset_type, inst_store_data, is_volatile_access, visit_block_succs, |
94 | | }, |
95 | | ir::{ |
96 | | AliasRegion, Block, Endianness, Function, Inst, MemFlagsData, Opcode, Type, Value, |
97 | | immediates::Offset32, |
98 | | }, |
99 | | post_dominator_tree::PostDominatorTree, |
100 | | trace, |
101 | | }; |
102 | | use core::cmp::Ordering; |
103 | | use cranelift_entity::{EntityRef, SecondaryMap}; |
104 | | use smallvec::SmallVec; |
105 | | |
106 | | /// Determine whether this opcode behaves as a memory fence, i.e., |
107 | | /// prohibits any moving of memory accesses across it. |
108 | 763M | fn has_memory_fence_semantics(op: Opcode) -> bool { |
109 | 763M | match op { |
110 | | Opcode::AtomicRmw |
111 | | | Opcode::AtomicCas |
112 | | | Opcode::AtomicLoad |
113 | | | Opcode::AtomicStore |
114 | | | Opcode::Fence |
115 | | | Opcode::Debugtrap |
116 | 274k | | Opcode::SequencePoint => true, |
117 | 45.4M | Opcode::Call | Opcode::CallIndirect | Opcode::TryCall | Opcode::TryCallIndirect => true, |
118 | 717M | _ => false, |
119 | | } |
120 | 763M | } |
121 | | |
122 | | /// A description of which alias region(s) can an instruction observe. |
123 | | enum AliasRegionsObserved { |
124 | | /// All alias regions. |
125 | | All, |
126 | | /// Just the given alias region. |
127 | | Just(AliasRegion), |
128 | | /// Just the "other" / missing alias region. |
129 | | Other, |
130 | | /// No alias regions observed. |
131 | | None, |
132 | | } |
133 | | |
134 | | /// Which alias region(s) can an instruction observe? |
135 | | /// |
136 | | /// `memflags` must be the instruction's memflags, if it has any. |
137 | 620M | fn alias_regions_observed( |
138 | 620M | func: &Function, |
139 | 620M | inst: Inst, |
140 | 620M | opcode: Opcode, |
141 | 620M | memflags: Option<MemFlagsData>, |
142 | 620M | ) -> AliasRegionsObserved { |
143 | 620M | debug_assert_eq!(func.dfg.insts[inst].opcode(), opcode); |
144 | 620M | debug_assert_eq!(func.dfg.insts[inst].memflags_data(&func.dfg), memflags); |
145 | 620M | if opcode.is_return() |
146 | 610M | || opcode.is_call() |
147 | 610M | || opcode == Opcode::InterruptPoll |
148 | 610M | || opcode.can_trap() |
149 | | // NB: the `opcode.can_trap()` check above only covers explicitly |
150 | | // trapping instructions (like `trap` and `trapz`), not loads/stores |
151 | | // that can implicitly trap; we check those via their memflags. |
152 | 610M | || memflags.and_then(|flags| flags.trap_code()).is_some() |
153 | | { |
154 | 24.0M | return AliasRegionsObserved::All; |
155 | 596M | } |
156 | | |
157 | 596M | if opcode.can_load() { |
158 | 139M | if let Some(region) = memflags.and_then(|flags| flags.alias_region()) { |
159 | 130M | AliasRegionsObserved::Just(region) |
160 | | } else { |
161 | 9.42M | AliasRegionsObserved::Other |
162 | | } |
163 | | } else { |
164 | 457M | AliasRegionsObserved::None |
165 | | } |
166 | 620M | } |
167 | | |
168 | | /// Who was the observer of some store instruction? |
169 | | /// |
170 | | /// `Option<Observer>` -- where `None` is logically represented by the absense |
171 | | /// of an entry in `AliasAnalysis::observed_stores` -- forms the following |
172 | | /// lattice: |
173 | | /// |
174 | | /// ```ignore |
175 | | /// None |
176 | | /// / | \ \ \ |
177 | | /// / | \ \ \ |
178 | | /// / | \ \ \ |
179 | | /// / | \ \ \ |
180 | | /// inst0 inst1 instN... |
181 | | /// \ | / / / |
182 | | /// \ | / / / |
183 | | /// \ | / / / |
184 | | /// \ | / / / |
185 | | /// Many |
186 | | /// ``` |
187 | | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
188 | | pub(crate) enum Observer { |
189 | | /// There was exactly one observer: this instruction. |
190 | | One(Inst), |
191 | | /// There were many observers. |
192 | | Many, |
193 | | } |
194 | | |
195 | | impl Observer { |
196 | 48.5M | fn meet(a: Self, b: Self) -> Self { |
197 | 48.5M | match (a, b) { |
198 | 29.6M | (Observer::Many, _) | (_, Observer::Many) => Observer::Many, |
199 | 18.8M | (Observer::One(a), Observer::One(b)) => { |
200 | 18.8M | if a == b { |
201 | 14.2M | Observer::One(a) |
202 | | } else { |
203 | 4.61M | Observer::Many |
204 | | } |
205 | | } |
206 | | } |
207 | 48.5M | } |
208 | | } |
209 | | |
210 | | /// Mark the store, if any, named by the given slot value as observed. |
211 | 324M | fn observe( |
212 | 324M | func: &Function, |
213 | 324M | observed_stores: &mut FxHashMap<Inst, Observer>, |
214 | 324M | slot: LastStore, |
215 | 324M | observer: Inst, |
216 | 324M | ) { |
217 | 324M | let Some(last_store) = slot.inst() else { |
218 | 240M | return; |
219 | | }; |
220 | | |
221 | | // NB: the instruction is not necessarily a store: slots also hold calls, |
222 | | // fences, and atomics. Only actual stores can be DSE candidates, so don't |
223 | | // bother recording anything else as observed. |
224 | 84.1M | if func.dfg.insts[last_store].opcode().can_store() { |
225 | 48.1M | let entry = observed_stores |
226 | 48.1M | .entry(last_store) |
227 | 48.1M | .or_insert(Observer::One(observer)); |
228 | 48.1M | *entry = Observer::meet(*entry, Observer::One(observer)); |
229 | 48.1M | trace!(" observed_stores[{last_store:?}] = {entry:?}"); |
230 | 35.9M | } |
231 | 324M | } |
232 | | |
233 | | /// Which instruction, if any, most recently wrote to a region. |
234 | | /// |
235 | | /// This is a simple meet semi-lattice: |
236 | | /// |
237 | | /// ```ignore |
238 | | /// NoStore Inst(i) |
239 | | /// \ / |
240 | | /// \ / |
241 | | /// Unknown |
242 | | /// ``` |
243 | | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] |
244 | | enum LastStore { |
245 | | /// Nothing has written to this region since the last fence (if any). |
246 | | /// |
247 | | /// This is _not_ the same as `Unknown`! This is *positive* information that |
248 | | /// nothing has been written since the last fence; in contrast, `Unknown` is |
249 | | /// the *absence* of information. It is sound to fall back to the last fence |
250 | | /// from `NoStore`; it is unsound to do that from `Unknown`. |
251 | | #[default] |
252 | | NoStore, |
253 | | |
254 | | /// `Inst` was the last store (or fence-like) instruction to write to this |
255 | | /// region. |
256 | | Inst(Inst), |
257 | | |
258 | | /// We know nothing about the contents of this memory region: the paths |
259 | | /// flowing into this program point disagreed. |
260 | | /// |
261 | | /// This is the semi-lattice's bottom. |
262 | | Unknown, |
263 | | } |
264 | | |
265 | | impl From<Inst> for LastStore { |
266 | | #[inline] |
267 | 71.3M | fn from(inst: Inst) -> Self { |
268 | 71.3M | Self::Inst(inst) |
269 | 71.3M | } |
270 | | } |
271 | | |
272 | | impl LastStore { |
273 | | /// Meet two last-store values. |
274 | 53.7M | fn meet(a: Self, b: Self) -> Self { |
275 | 53.7M | if a == b { a } else { LastStore::Unknown } |
276 | 53.7M | } |
277 | | |
278 | | /// The last instruction to write to this slot's associated region, if |
279 | | /// known. |
280 | 404M | fn inst(self) -> Option<Inst> { |
281 | 404M | match self { |
282 | 109M | LastStore::Inst(i) => Some(i), |
283 | 295M | LastStore::NoStore | LastStore::Unknown => None, |
284 | | } |
285 | 404M | } |
286 | | } |
287 | | |
288 | | /// For a given program point, the last store to each disjoint memory region. |
289 | | /// |
290 | | /// ### Instructions In `LastStores` Might Not Be In The Function's `Layout` |
291 | | /// |
292 | | /// The instructions named here (`regions[r]` and `last_fence`) are *not* |
293 | | /// guaranteed to still be in the layout (unlike `mem_values`, this state does |
294 | | /// not maintain that invariant). A slot can name a store we already removed |
295 | | /// because `block_input` snapshots are computed once up front (in |
296 | | /// `compute_block_input_states`) and can name a dead store that a later-visited |
297 | | /// block eliminates. |
298 | | /// |
299 | | /// Note that this is only a hazard when processing blocks that read their state |
300 | | /// from the initial snapshot. A block with exactly one reachable predecessor |
301 | | /// instead inherits its predecessor's live exit state (see |
302 | | /// `AliasAnalysis::push_scope` and `AliasAnalysis::finish_scope`), which names |
303 | | /// only stores that are still in the layout; joins are the remaining source of |
304 | | /// stale instructions here. |
305 | | /// |
306 | | /// We tolerate this, rather than enforce the invariant, because enforcing it |
307 | | /// would mean repairing a precomputed fixpoint's references across |
308 | | /// not-yet-visited blocks, which would result in more work and more complicated |
309 | | /// code than simply checking whether an instruction is in the layout at a |
310 | | /// couple sites. |
311 | | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
312 | | struct LastStores { |
313 | | /// The last store to each named alias region. |
314 | | regions: SecondaryMap<AliasRegion, LastStore>, |
315 | | |
316 | | /// The store created by the last instruction with fence semantics. |
317 | | /// |
318 | | /// This applies to ALL regions, including ones not yet in the `regions` |
319 | | /// map. |
320 | | /// |
321 | | /// This is also the last store for memory accesses that have no alias |
322 | | /// region: such a store may alias any region, and so is treated as a fence. |
323 | | last_fence: LastStore, |
324 | | } |
325 | | |
326 | | /// What effect does an instruction have on the last-store state? |
327 | | /// |
328 | | /// This factors out the shared logic between `LastStores::update` and |
329 | | /// `LastStores::observe_inst` so they can't drift apart from each other. |
330 | | enum InstEffect { |
331 | | /// A memory fence: it observes every region and then clobbers all of them. |
332 | | Fence, |
333 | | |
334 | | /// An explicitly-trapping instruction: it observes every region, but |
335 | | /// clobbers none of them. |
336 | | Trap, |
337 | | |
338 | | /// A store to a particular alias region. |
339 | | Store { |
340 | | /// The alias region this store writes. |
341 | | region: AliasRegion, |
342 | | /// Whether this store can trap. |
343 | | can_trap: bool, |
344 | | }, |
345 | | |
346 | | /// An instruction that clobbers nothing and observes the given regions. |
347 | | Observes(AliasRegionsObserved), |
348 | | } |
349 | | |
350 | | /// Determine what effect the given instruction has on the last-store state. |
351 | 757M | fn classify(func: &Function, inst: Inst) -> InstEffect { |
352 | 757M | let opcode = func.dfg.insts[inst].opcode(); |
353 | | |
354 | 757M | if has_memory_fence_semantics(opcode) { |
355 | 43.2M | return InstEffect::Fence; |
356 | 713M | } |
357 | | |
358 | | // Explicitly trapping instructions (`trap`, `trapz`, `udiv`, |
359 | | // `uadd_overflow_trap`, etc... but not loads/stores that can implicitly |
360 | | // trap): allow store-to-load forwarding across these instructions, but do |
361 | | // not eliminate dead stores across them, as that would change the state of |
362 | | // memory on trap. We do this by marking every last-store as observed, but |
363 | | // not clearing our last-store information. |
364 | 713M | if opcode.can_trap() { |
365 | 23.1M | return InstEffect::Trap; |
366 | 690M | } |
367 | | |
368 | | // A volatile access must stay as written, in order with the accesses |
369 | | // around it: treat it as a fence, which observes every earlier store (so |
370 | | // that none of them is removed as dead across it) and forgets everything |
371 | | // known about memory (so that nothing is forwarded across it). Only loads |
372 | | // and stores can be volatile, so rather than looking up every |
373 | | // instruction's memflags up here, we check for it below, where we already |
374 | | // look them up. |
375 | | |
376 | | // Store instructions: update the last-store information for this |
377 | | // instruction's alias region, or, if it has no alias region, treat it as a |
378 | | // fence. |
379 | 690M | if opcode.can_store() { |
380 | | // A store with no memflags, and therefore no alias region, may alias |
381 | | // any region, so treat it like a fence. Ditto for a store whose |
382 | | // memflags name no alias region, and for a volatile store. |
383 | 69.9M | let Some(memflags) = func.dfg.insts[inst].memflags() else { |
384 | 260 | return InstEffect::Fence; |
385 | | }; |
386 | 69.9M | let memflags = func.dfg.mem_flags[memflags]; |
387 | 69.9M | if memflags.volatile() { |
388 | 0 | return InstEffect::Fence; |
389 | 69.9M | } |
390 | 69.9M | let Some(region) = memflags.alias_region() else { |
391 | 1.51M | return InstEffect::Fence; |
392 | | }; |
393 | | |
394 | 68.4M | return InstEffect::Store { |
395 | 68.4M | region, |
396 | 68.4M | can_trap: memflags.trap_code().is_some(), |
397 | 68.4M | }; |
398 | 620M | } |
399 | | |
400 | | // Everything else, loads included. Look up the memflags once: a volatile |
401 | | // load is a fence too, and otherwise they tell us which, if any, alias |
402 | | // regions this instruction observes. |
403 | 620M | let memflags = func.dfg.insts[inst].memflags_data(&func.dfg); |
404 | 620M | if memflags.is_some_and(|flags| flags.volatile()) { |
405 | 0 | return InstEffect::Fence; |
406 | 620M | } |
407 | 620M | InstEffect::Observes(alias_regions_observed(func, inst, opcode, memflags)) |
408 | 757M | } |
409 | | |
410 | | impl LastStores { |
411 | | /// Advance this state across the given instruction. |
412 | 425M | fn update(&mut self, func: &Function, inst: Inst) { |
413 | 425M | match classify(func, inst) { |
414 | 28.9M | InstEffect::Fence => { |
415 | 28.9M | self.regions.clear(); |
416 | 28.9M | |
417 | 28.9M | // NB: unlike every region slot, `self.last_fence` is *not* |
418 | 28.9M | // observed by a fence; see `observe_inst`. |
419 | 28.9M | self.last_fence = inst.into(); |
420 | 28.9M | } |
421 | | |
422 | | // Trapping instructions and pure observers leave every slot alone. |
423 | 354M | InstEffect::Trap | InstEffect::Observes(_) => {} |
424 | | |
425 | | InstEffect::Store { |
426 | 41.9M | region, |
427 | | can_trap: _, |
428 | 41.9M | } => { |
429 | 41.9M | self.regions[region] = inst.into(); |
430 | 41.9M | } |
431 | | } |
432 | 425M | } |
433 | | |
434 | | /// Record every store that the given instruction can observe into |
435 | | /// `observed`. |
436 | | /// |
437 | | /// This reads the state as of just before the instruction, so it must be |
438 | | /// called before `update` for the given instruction. |
439 | 181M | fn observe_inst(&self, func: &Function, inst: Inst, observed: &mut FxHashMap<Inst, Observer>) { |
440 | 181M | match classify(func, inst) { |
441 | | InstEffect::Fence => { |
442 | | // A fence can observe every region, so every store we are |
443 | | // currently tracking for a region becomes observed. |
444 | 43.8M | for (_region, slot) in self.regions.iter() { |
445 | 43.8M | observe(func, observed, *slot, inst); |
446 | 43.8M | } |
447 | | |
448 | | // NB: `self.last_fence` is *not* observed here. Marking it |
449 | | // observed would, for example, prevent eliminating the first of |
450 | | // two adjacent stores that have no alias region. |
451 | | } |
452 | | |
453 | 5.15M | InstEffect::Trap => self.observe_others(func, observed, None, inst), |
454 | | |
455 | 14.0M | InstEffect::Store { region, can_trap } => { |
456 | 14.0M | observe(func, observed, self.regions[region], inst); |
457 | | |
458 | | // If this store can trap, then we need to observe all other |
459 | | // alias regions, to ensure that their state is preserved in the |
460 | | // case that this store traps (similar to the `InstEffect::Trap` |
461 | | // handling above). |
462 | | // |
463 | | // This prevents removing the first store in the following |
464 | | // snippet, for example: |
465 | | // |
466 | | // store notrap region0 v0, v3+8 |
467 | | // store user42 region1 v1, v4+16 |
468 | | // store notrap region0 v2, v3+8 |
469 | | // |
470 | | // ==/==> |
471 | | // |
472 | | // store user42 region1 v1, v4+16 |
473 | | // store notrap region0 v2, v3+8 |
474 | | // |
475 | | // Removing it would be invalid because it drops a memory store |
476 | | // to `v3+8` that would otherwise have been performed when |
477 | | // writing to `v4+16` traps. |
478 | | // |
479 | | // On the other hand, if it cannot trap, then we need to observe |
480 | | // all the regions whose last-store *can* trap so that we don't |
481 | | // allow a non-trapping store to effectively be moved ahead of a |
482 | | // trapping store: |
483 | | // |
484 | | // store user42 region0 v0, v3+8 |
485 | | // store notrap region1 v1, v4+16 |
486 | | // store user42 region0 v2, v3+8 |
487 | | // |
488 | | // ==/==> |
489 | | // |
490 | | // store notrap region1 v1, v4+16 |
491 | | // store user42 region0 v2, v3+8 |
492 | | // |
493 | | // In this case, removing the first store would mean that when |
494 | | // writing to `v3+8` traps, we would incorrectly store to |
495 | | // `v4+16`, when we otherwise wouldn't have. |
496 | 14.0M | if can_trap { |
497 | 2.31M | self.observe_others(func, observed, Some(region), inst); |
498 | 11.7M | } else { |
499 | 11.7M | self.observe_trapping_others(func, observed, region, inst); |
500 | 11.7M | } |
501 | | } |
502 | | |
503 | | InstEffect::Observes(AliasRegionsObserved::All) => { |
504 | 5.25M | self.observe_others(func, observed, None, inst) |
505 | | } |
506 | 31.0M | InstEffect::Observes(AliasRegionsObserved::Just(region)) => { |
507 | 31.0M | observe(func, observed, self.last_store_for_region(region), inst); |
508 | 31.0M | // NB: Because stores without regions may alias any other |
509 | 31.0M | // region, we have also observed the last such store, which |
510 | 31.0M | // `self.last_fence` tracks. |
511 | 31.0M | observe(func, observed, self.last_fence, inst); |
512 | 31.0M | } |
513 | | InstEffect::Observes(AliasRegionsObserved::Other) => { |
514 | 2.52M | observe(func, observed, self.last_fence, inst) |
515 | | } |
516 | 113M | InstEffect::Observes(AliasRegionsObserved::None) => {} |
517 | | } |
518 | 181M | } |
519 | | |
520 | | /// Mark the last store to every region except for `excluding` (if given), as |
521 | | /// well as the last fence, as observed. |
522 | 13.3M | fn observe_others( |
523 | 13.3M | &self, |
524 | 13.3M | func: &Function, |
525 | 13.3M | observed_stores: &mut FxHashMap<Inst, Observer>, |
526 | 13.3M | excluding: Option<AliasRegion>, |
527 | 13.3M | observer: Inst, |
528 | 13.3M | ) { |
529 | 142M | for (region, slot) in self.regions.iter() { |
530 | 142M | if excluding.is_none_or(|r| r != region) { |
531 | 141M | observe(func, observed_stores, *slot, observer); |
532 | 141M | } |
533 | | } |
534 | 13.3M | observe(func, observed_stores, self.last_fence, observer); |
535 | 13.3M | } |
536 | | |
537 | | /// Mark the last store to every region whose last store can trap, except for |
538 | | /// `excluding`, as observed. |
539 | 11.7M | fn observe_trapping_others( |
540 | 11.7M | &self, |
541 | 11.7M | func: &Function, |
542 | 11.7M | observed_stores: &mut FxHashMap<Inst, Observer>, |
543 | 11.7M | excluding: AliasRegion, |
544 | 11.7M | observer: Inst, |
545 | 11.7M | ) { |
546 | 79.8M | let can_trap = |slot: LastStore| { |
547 | 79.8M | slot.inst() |
548 | 79.8M | .is_some_and(|s| func.dfg.insts[s].memflags_trap_code(&func.dfg).is_some()) |
549 | 79.8M | }; |
550 | | |
551 | 74.1M | for (region, slot) in self.regions.iter() { |
552 | 74.1M | if region != excluding && can_trap(*slot) { |
553 | 2.59M | observe(func, observed_stores, *slot, observer); |
554 | 71.5M | } |
555 | | } |
556 | | |
557 | 11.7M | if can_trap(self.last_fence) { |
558 | 992 | observe(func, observed_stores, self.last_fence, observer); |
559 | 11.7M | } |
560 | 11.7M | } |
561 | | |
562 | | /// Get the last store to the given alias region. |
563 | 112M | fn last_store_for_region(&self, region: AliasRegion) -> LastStore { |
564 | 112M | match self.regions[region] { |
565 | | // Nothing has written this region since the last fence, so the |
566 | | // fence is what last (may have) written it. |
567 | 84.0M | LastStore::NoStore => self.last_fence, |
568 | 28.4M | slot => slot, |
569 | | } |
570 | 112M | } |
571 | | |
572 | | /// Get the contents of `inst`'s own alias region's slot, without falling |
573 | | /// back to the last fence. |
574 | | /// |
575 | | /// Returns `None` when `inst` has no alias region. |
576 | 14.0M | fn raw_region_slot(&self, func: &Function, inst: Inst) -> Option<LastStore> { |
577 | 14.0M | let region = func.dfg.insts[inst].alias_region(&func.dfg)?; |
578 | 13.6M | Some(self.regions[region]) |
579 | 14.0M | } |
580 | | |
581 | | /// Roll this state back to the last-store information from just before |
582 | | /// `dead`, which is a store being removed from the function by dead-store |
583 | | /// elimination. |
584 | | /// |
585 | | /// `prev_region_slot` must be what `dead`'s own alias-region slot held |
586 | | /// immediately before `dead` overwrote it, as recorded by |
587 | | /// `raw_region_slot` when `dead` itself was processed (that is, it must not |
588 | | /// be the last-fence fallback). |
589 | | /// |
590 | | /// Only `dead`'s own alias-region slot is restored. A store with no alias |
591 | | /// region is treated as a fence by `update`, which clears *every* region |
592 | | /// slot, and we do not undo that; in that case, we leave this state |
593 | | /// alone. Similarly, stores marked observed while processing `dead` stay |
594 | | /// observed. |
595 | 366k | fn undo_store(&mut self, func: &Function, dead: Inst, prev_region_slot: LastStore) { |
596 | 366k | debug_assert!(func.dfg.insts[dead].opcode().can_store()); |
597 | | |
598 | 366k | let Some(region) = func.dfg.insts[dead].alias_region(&func.dfg) else { |
599 | 0 | return; |
600 | | }; |
601 | | |
602 | | // Only roll back if `dead` really is the current last store to its |
603 | | // region. |
604 | 366k | if self.regions[region] == dead.into() { |
605 | 366k | self.regions[region] = prev_region_slot; |
606 | 366k | } |
607 | 366k | } |
608 | | |
609 | | /// Get the last store to the given `inst`'s alias region. |
610 | 68.1M | fn get_last_store(&self, func: &Function, inst: Inst) -> LastStore { |
611 | 68.1M | if let Some(memflags) = func.dfg.insts[inst].memflags() { |
612 | 68.1M | return match func.dfg.mem_flags[memflags].alias_region() { |
613 | 5.80M | None => self.last_fence, |
614 | 62.3M | Some(region) => self.last_store_for_region(region), |
615 | | }; |
616 | 0 | } |
617 | | |
618 | 0 | let opcode = func.dfg.insts[inst].opcode(); |
619 | 0 | if opcode.can_load() || opcode.can_store() { |
620 | 0 | inst.into() |
621 | | } else { |
622 | 0 | LastStore::NoStore |
623 | | } |
624 | 68.1M | } |
625 | | |
626 | | /// Meet `self` with `rhs`, placing the result in `self`. |
627 | | /// |
628 | | /// Returns `true` if `self` changed, `false` otherwise. |
629 | 9.42M | fn meet_from(&mut self, rhs: &LastStores) -> bool { |
630 | | // NB: Destructure to make sure we don't accidentally forget a |
631 | | // field. |
632 | | let LastStores { |
633 | 9.42M | regions, |
634 | 9.42M | last_fence, |
635 | 9.42M | } = self; |
636 | | |
637 | 9.42M | let mut changed = false; |
638 | | |
639 | 53.7M | let mut meet = |a: &mut LastStore, b: LastStore| { |
640 | 53.7M | let new = LastStore::meet(*a, b); |
641 | 53.7M | changed |= new != *a; |
642 | 53.7M | *a = new; |
643 | 53.7M | }; |
644 | | |
645 | 9.42M | let max_len = core::cmp::max(regions.keys().len(), rhs.regions.keys().len()); |
646 | 44.3M | for i in 0..max_len { |
647 | 44.3M | let region = AliasRegion::new(i); |
648 | 44.3M | meet(&mut regions[region], rhs.regions[region]); |
649 | 44.3M | } |
650 | | |
651 | 9.42M | meet(last_fence, rhs.last_fence); |
652 | | |
653 | 9.42M | changed |
654 | 9.42M | } |
655 | | } |
656 | | |
657 | | /// The alias-analysis state as a walk over a single block advances it. |
658 | | #[derive(Clone, Debug)] |
659 | | pub struct MemoryState { |
660 | | /// The last store to each slot, as of the current program point. |
661 | | stores: LastStores, |
662 | | |
663 | | /// The token identifying this program point's extent. |
664 | | /// |
665 | | /// See `MemoryLoc::extent` for details. |
666 | | extent: u32, |
667 | | |
668 | | /// The current block we are walking. |
669 | | #[cfg(debug_assertions)] |
670 | | current_block: Block, |
671 | | } |
672 | | |
673 | | const NULL_EXTENT: u32 = 0; |
674 | | |
675 | | /// A key identifying a unique memory location. |
676 | | /// |
677 | | /// For the result of a load to be equivalent to the result of another load, or |
678 | | /// the store data from a store, we need all of these fields to match. |
679 | | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
680 | | struct MemoryLoc { |
681 | | /// The last store to this location's alias region. |
682 | | last_store: LastStore, |
683 | | |
684 | | /// A token identifying the extent of our `LastStore`, since |
685 | | /// `LastStore::Unknown` is only valid relative to its last control-flow |
686 | | /// join point. |
687 | | /// |
688 | | /// For `LastStore::Unknown`, the token distinguishes unknown memory versions |
689 | | /// at different control-flow joins. Named regions can retain their token |
690 | | /// across a join when no path from the immediate dominator's exit writes |
691 | | /// the region and its effective last-store state agrees with the join's |
692 | | /// initial fixpoint snapshot. Otherwise, the region gets a fresh token. |
693 | | /// Different tokens do not imply different bytes, only that equivalence |
694 | | /// has not been established. Reusing a value still requires the full key |
695 | | /// to match and the known value's definition to dominate its use. |
696 | | /// |
697 | | /// This is necessary because on one hand, we need `LastStore::Unknown` to |
698 | | /// be a single bottom value so that `LastStore` and `LastStores` are proper |
699 | | /// lattices, but on the other hand we need identity to differentiate |
700 | | /// between instances of `LastStore::Unknown` to prevent, e.g., unsoundly |
701 | | /// store-to-load forwarding from a store in one control-flow join point to |
702 | | /// a load at a different control-flow join point. |
703 | | /// |
704 | | /// Extent is computed incrementally in `AliasAnalysis::push_scope`. |
705 | | extent: u32, |
706 | | |
707 | | /// The dynamic part of this memory location's address. |
708 | | address: Value, |
709 | | |
710 | | /// The static part of this memory location's address. |
711 | | offset: Offset32, |
712 | | |
713 | | /// The type being accessed at this memory location. |
714 | | ty: Type, |
715 | | |
716 | | /// We keep the *opcode* of the instruction that produced the |
717 | | /// value we record at this key if the opcode is anything other |
718 | | /// than an ordinary load or store. This is needed when we |
719 | | /// consider loads that extend the value: e.g., an 8-to-32 |
720 | | /// sign-extending load will produce a 32-bit value from an 8-bit |
721 | | /// value in memory, so we can only reuse that (as part of RLE) |
722 | | /// for another load with the same extending opcode. |
723 | | /// |
724 | | /// We could improve the transform to insert explicit extend ops |
725 | | /// in place of extending loads when we know the memory value, but |
726 | | /// we haven't yet done this. |
727 | | extending_opcode: Option<Opcode>, |
728 | | |
729 | | /// The byte order of this access, as explicitly specified in its memory |
730 | | /// flags, or `None` when the access uses the target's native byte order. |
731 | | /// |
732 | | /// Without this, two accesses to the same address that disagree about byte |
733 | | /// order would share a key, and we would happily forward a value from one |
734 | | /// to the other, dropping the byte swap that the mismatch implies. |
735 | | /// |
736 | | /// We only record the *explicit* byte order here, rather than resolving |
737 | | /// `None` to the target's native byte order. This keeps the pass |
738 | | /// independent of the target, but does mean we never share a key between an |
739 | | /// access that spells out the native byte order and one that leaves it |
740 | | /// implicit. That scenario leads to missed optimizations, never |
741 | | /// miscompiles, and is exceedingly rare, so we deem the trade off worth it |
742 | | /// for simplicity. |
743 | | endianness: Option<Endianness>, |
744 | | } |
745 | | |
746 | | /// What is known to be in memory at an associated `MemoryLoc`. |
747 | | #[derive(Clone, Copy, Debug)] |
748 | | struct KnownValue { |
749 | | /// The value held at the associated `MemoryLoc`. |
750 | | value: Value, |
751 | | |
752 | | /// The instruction that produced `value`: either the load that read it out |
753 | | /// of memory or the store that wrote it there. |
754 | | /// |
755 | | /// Kept around for quick dominance checks. |
756 | | def_inst: Inst, |
757 | | |
758 | | /// When this entry was created by a store to a particular alias region, |
759 | | /// whatever that region's last-store slot held just *before* `def_inst` |
760 | | /// overwrote it, as given by `LastStores::raw_region_slot`. |
761 | | /// |
762 | | /// `None` means either the entry was created by a load or by a store with |
763 | | /// no alias region. Neither will ever undo `LastStores` state. |
764 | | /// |
765 | | /// `Some(slot)` contains the alias region slot's previous value, so that it |
766 | | /// can be restored if `def_inst` is a dead store that gets eliminated. |
767 | | prev_region_slot: Option<LastStore>, |
768 | | } |
769 | | |
770 | | /// The result of processing an instruction through alias analysis. |
771 | | pub enum OptResult { |
772 | | /// No optimization applied. |
773 | | None, |
774 | | /// A redundant load; alias its result to this value. |
775 | | AliasedLoad(Value), |
776 | | /// An idempotent store; remove it. |
777 | | IdempotentStore, |
778 | | /// We determined that an instruction is a dead store and its memory write |
779 | | /// cannot be observed. |
780 | | DeadStore { |
781 | | /// The store instruction that is dead. |
782 | | dead: Inst, |
783 | | /// The other store instruction that makes the previous instruction |
784 | | /// dead. |
785 | | overwriter: Inst, |
786 | | }, |
787 | | } |
788 | | |
789 | | /// An alias-analysis pass. |
790 | | pub struct AliasAnalysis<'a> { |
791 | | /// The domtree for the function. |
792 | | domtree: &'a DominatorTree, |
793 | | |
794 | | /// The post-dominator tree for the function. |
795 | | /// |
796 | | /// This is computed lazily, on the first cross-block dead-store candidate, |
797 | | /// because it is only ever consulted by dead-store elimination and only for |
798 | | /// candidates whose two stores live in different blocks (because we can |
799 | | /// easily test post-domination without building a post-dominator tree when |
800 | | /// the two instructions are in the same block). The majority of functions |
801 | | /// have no such dead-store candidates, so building it eagerly for every |
802 | | /// function is a waste. |
803 | | post_dom_tree: Option<PostDominatorTree>, |
804 | | |
805 | | /// The set of store instructions that some other instruction can observe, |
806 | | /// and which therefore cannot be eliminated as dead stores. |
807 | | /// |
808 | | /// Unlike the last-store state in `block_input`, this is *not* flow |
809 | | /// sensitive: a store is either observable somewhere in the function or it |
810 | | /// is not. |
811 | | observed_stores: FxHashMap<Inst, Observer>, |
812 | | |
813 | | /// Input state to a basic block. |
814 | | block_input: FxHashMap<Block, LastStores>, |
815 | | |
816 | | /// Known memory-value equivalences. |
817 | | /// |
818 | | /// This is the result of the analysis: a mapping from a memory location to |
819 | | /// its known value. |
820 | | mem_values: FxHashMap<MemoryLoc, KnownValue>, |
821 | | |
822 | | /// The scopes currently on the dominator-tree path we are walking. |
823 | | scopes: SmallVec<[Scope; 8]>, |
824 | | |
825 | | /// Counter for minting fresh extent tokens. |
826 | | next_extent: u32, |
827 | | |
828 | | /// Regions written by each block before optimization, so eliminated stores |
829 | | /// remain conservatively accounted for. `None` means a fence can clobber |
830 | | /// every region. |
831 | | block_clobbers: SecondaryMap<Block, Option<FxHashSet<AliasRegion>>>, |
832 | | |
833 | | /// Reusable set of regions written along the paths being searched. |
834 | | clobbers_scratch: FxHashSet<AliasRegion>, |
835 | | pending_scratch: SmallVec<[Block; 8]>, |
836 | | visited_scratch: FxHashSet<Block>, |
837 | | } |
838 | | |
839 | | /// One block's scope on the dominator-tree path currently being walked. |
840 | | struct Scope { |
841 | | /// The block whose scope this is. |
842 | | block: Block, |
843 | | |
844 | | /// The extent token for this scope. |
845 | | /// |
846 | | /// See `MemoryLoc::extent` for details. |
847 | | extent: u32, |
848 | | |
849 | | /// Per-region tokens inherited by children; see `MemoryLoc::extent`. |
850 | | region_extents: SecondaryMap<AliasRegion, u32>, |
851 | | |
852 | | /// This block's last-store state on exit, once we have finished walking its |
853 | | /// instructions. |
854 | | /// |
855 | | /// This is `None` between `push_scope` and `finish_scope`, and `Some` from |
856 | | /// `finish_scope` until this scope is popped. Therefore it is always `Some` |
857 | | /// for every scope strictly below the top of the stack, since we always |
858 | | /// finish a block before descending into any of its dominator-tree |
859 | | /// children. |
860 | | exit_state: Option<LastStores>, |
861 | | } |
862 | | |
863 | | impl<'a> AliasAnalysis<'a> { |
864 | | /// Perform an alias analysis pass. |
865 | 1.99M | pub fn new(func: &Function, domtree: &'a DominatorTree) -> AliasAnalysis<'a> { |
866 | 1.99M | trace!("alias analysis input is:\n{func:?}"); |
867 | 1.99M | assert!(domtree.is_valid()); |
868 | | |
869 | 1.99M | let block_clobbers = func |
870 | 1.99M | .layout |
871 | 1.99M | .blocks() |
872 | 21.1M | .map(|block| { |
873 | 21.1M | let mut regions = FxHashSet::default(); |
874 | 149M | for inst in func.layout.block_insts(block) { |
875 | 149M | match classify(func, inst) { |
876 | 6.15M | InstEffect::Fence => return (block, None), |
877 | 12.4M | InstEffect::Store { region, .. } => { |
878 | 12.4M | regions.insert(region); |
879 | 12.4M | } |
880 | 131M | _ => {} |
881 | | } |
882 | | } |
883 | 15.0M | (block, Some(regions)) |
884 | 21.1M | }) |
885 | 1.99M | .collect(); |
886 | | |
887 | 1.99M | let mut analysis = AliasAnalysis { |
888 | 1.99M | domtree, |
889 | 1.99M | post_dom_tree: None, |
890 | 1.99M | observed_stores: FxHashMap::default(), |
891 | 1.99M | block_input: FxHashMap::default(), |
892 | 1.99M | mem_values: FxHashMap::default(), |
893 | 1.99M | scopes: SmallVec::new(), |
894 | 1.99M | next_extent: 0, |
895 | 1.99M | block_clobbers, |
896 | 1.99M | clobbers_scratch: FxHashSet::default(), |
897 | 1.99M | pending_scratch: SmallVec::new(), |
898 | 1.99M | visited_scratch: FxHashSet::default(), |
899 | 1.99M | }; |
900 | | |
901 | 1.99M | analysis.compute_block_input_states(func); |
902 | 1.99M | analysis.verify_fixpoint(func); |
903 | 1.99M | analysis.compute_observed_stores(func); |
904 | | |
905 | 1.99M | analysis |
906 | 1.99M | } |
907 | | |
908 | | /// Does `overwriter` post-dominate `maybe_dead`? |
909 | | /// |
910 | | /// That is, does every path from `maybe_dead` out of the function pass |
911 | | /// through `overwriter`? Used as part of deciding whether `maybe_dead` is |
912 | | /// truly a dead store. |
913 | 371k | fn post_dominates_maybe_dead_store( |
914 | 371k | &mut self, |
915 | 371k | func: &Function, |
916 | 371k | cfg: &ControlFlowGraph, |
917 | 371k | overwriter: Inst, |
918 | 371k | maybe_dead: Inst, |
919 | 371k | ) -> bool { |
920 | 368k | let (Some(overwriter_block), Some(maybe_dead_block)) = ( |
921 | 371k | func.layout.inst_block(overwriter), |
922 | 371k | func.layout.inst_block(maybe_dead), |
923 | | ) else { |
924 | 2.32k | return false; |
925 | | }; |
926 | | |
927 | | // When our instructions are in the same block, we do not need to |
928 | | // force computation of the whole post-dominator tree: `overwriter` |
929 | | // post-dominates `maybe_dead` iff `overwriter` is at or after |
930 | | // `maybe_dead`. |
931 | 368k | if overwriter_block == maybe_dead_block { |
932 | 365k | return func.layout.pp_cmp(overwriter, maybe_dead) != Ordering::Less; |
933 | 2.88k | } |
934 | | |
935 | 2.88k | self.post_dom_tree |
936 | 2.88k | .get_or_insert_with(|| PostDominatorTree::with_cfg(cfg)) |
937 | 2.88k | .post_dominates(overwriter, maybe_dead, &func.layout) |
938 | 371k | } |
939 | | |
940 | 1.99M | fn compute_block_input_states(&mut self, func: &Function) { |
941 | 1.99M | let entry = func.layout.entry_block().unwrap(); |
942 | 1.99M | self.block_input.insert(entry, LastStores::default()); |
943 | | |
944 | | // Seed the worklist in reverse post-order (well, post order, but |
945 | | // visited in reverse due to popping). This visits a block's |
946 | | // predecessors before the block itself, which minimizes the number of |
947 | | // times we need to reprocess a block to reach the fixed point (ignoring |
948 | | // backedges). |
949 | 1.99M | let mut queue = self.domtree.cfg_postorder().to_vec(); |
950 | 1.99M | let mut queue_set: FxHashSet<Block> = queue.iter().copied().collect(); |
951 | | |
952 | 23.6M | while let Some(block) = queue.pop() { |
953 | 21.6M | queue_set.remove(&block); |
954 | | |
955 | 21.6M | let Some(mut state) = self.block_input.get(&block).cloned() else { |
956 | | // Nothing has propagated into this block yet, so there is |
957 | | // nothing to propagate out of it. If/when some predecessor gets |
958 | | // state to propagate to this block, it will be re-enqueued. |
959 | 0 | continue; |
960 | | }; |
961 | | |
962 | 21.6M | trace!("analyzing {block:?}"); |
963 | 21.6M | trace!(" initial block state = {state:?}"); |
964 | | |
965 | 185M | for inst in func.layout.block_insts(block) { |
966 | 185M | trace!(" analyzing {inst:?}: {}", func.dfg.display_inst(inst)); |
967 | 185M | state.update(func, inst); |
968 | 185M | trace!(" updated state = {state:?}"); |
969 | | } |
970 | | |
971 | 28.6M | visit_block_succs(func, block, |_inst, succ, _from_table| { |
972 | 28.6M | let updated = match self.block_input.get_mut(&succ) { |
973 | 9.42M | Some(succ_state) => succ_state.meet_from(&state), |
974 | | None => { |
975 | 19.1M | self.block_input.insert(succ, state.clone()); |
976 | 19.1M | true |
977 | | } |
978 | | }; |
979 | | |
980 | 28.6M | if updated && queue_set.insert(succ) { |
981 | 448k | queue.push(succ); |
982 | 28.1M | } |
983 | 28.6M | }); |
984 | | } |
985 | 1.99M | } |
986 | | |
987 | | /// Assert that `self.block_input` really is a fixed point. |
988 | | /// |
989 | | /// This should help catch regressions that don't result in miscompiles, |
990 | | /// only worse codegen and/or order-dependent results, both of which are |
991 | | /// otherwise hard to test against in filetests. |
992 | 1.99M | fn verify_fixpoint(&self, func: &Function) { |
993 | 1.99M | if !cfg!(debug_assertions) { |
994 | 1.99M | return; |
995 | 0 | } |
996 | | |
997 | 0 | let entry = func.layout.entry_block().unwrap(); |
998 | | |
999 | 0 | let mut expected = FxHashMap::default(); |
1000 | 0 | expected.insert(entry, LastStores::default()); |
1001 | | |
1002 | | // Note that iterating through this hash map gives us ~nondeterministic |
1003 | | // block ordering -- but that shouldn't matter if we _actually_ computed |
1004 | | // an order-independent result! This is a convenient little foil to our |
1005 | | // worklist's deterministic ordering. |
1006 | 0 | for (&block, input) in &self.block_input { |
1007 | | // Compute the output state for this block. |
1008 | 0 | let mut state = input.clone(); |
1009 | 0 | for inst in func.layout.block_insts(block) { |
1010 | 0 | state.update(func, inst); |
1011 | 0 | } |
1012 | | |
1013 | | // Meet that output state with the input state of each of this |
1014 | | // block's successors. |
1015 | 0 | visit_block_succs(func, block, |_inst, succ, _from_table| { |
1016 | 0 | match expected.get_mut(&succ) { |
1017 | 0 | Some(succ_state) => { |
1018 | 0 | succ_state.meet_from(&state); |
1019 | 0 | } |
1020 | 0 | None => { |
1021 | 0 | expected.insert(succ, state.clone()); |
1022 | 0 | } |
1023 | | } |
1024 | 0 | }); |
1025 | | } |
1026 | | |
1027 | | // Our expected results should match our actual results. |
1028 | 0 | for (&block, input) in &self.block_input { |
1029 | 0 | assert_eq!( |
1030 | 0 | expected.get(&block), |
1031 | 0 | Some(input), |
1032 | | "last-store analysis did not reach a fixpoint at {block}", |
1033 | | ); |
1034 | | } |
1035 | 0 | assert_eq!( |
1036 | 0 | expected.len(), |
1037 | 0 | self.block_input.len(), |
1038 | | "last-store analysis and its verifier disagree on which blocks are reachable", |
1039 | | ); |
1040 | 1.99M | } |
1041 | | |
1042 | | /// The single reachable predecessor of `block`, if it has exactly one. |
1043 | | /// |
1044 | | /// Returns `None` both when `block` has two or more distinct reachable |
1045 | | /// predecessors and when it has none at all. |
1046 | 21.1M | fn single_reachable_pred(&self, cfg: &ControlFlowGraph, block: Block) -> Option<Block> { |
1047 | 21.1M | let mut preds = cfg |
1048 | 21.1M | .pred_iter(block) |
1049 | 21.1M | .map(|pred| pred.block) |
1050 | | // Skip unreachable predecessors. Our fixpoint never propagates |
1051 | | // state out of them. |
1052 | 23.0M | .filter(|pred| self.block_input.contains_key(pred)); |
1053 | 21.1M | let first = preds.next()?; |
1054 | 19.1M | preds.all(|pred| pred == first).then_some(first) |
1055 | 21.1M | } |
1056 | | |
1057 | | /// Compute the set of stores that some instruction in this function can |
1058 | | /// observe. |
1059 | | /// |
1060 | | /// This is deliberately not folded into the last-store fixpoint. While that |
1061 | | /// fixpoint iterates, a slot can transiently name a store that the final |
1062 | | /// solution does not, and observing it would make the resulting |
1063 | | /// observed-stores set depend on the order in which the worklist visited |
1064 | | /// blocks. Instead we walk the function once, in layout order, over the |
1065 | | /// solved fixpoint. |
1066 | 1.99M | fn compute_observed_stores(&mut self, func: &Function) { |
1067 | 1.99M | let mut observed_stores = FxHashMap::default(); |
1068 | | |
1069 | 21.1M | for block in func.layout.blocks() { |
1070 | | // Ignore unreachable blocks. |
1071 | 21.1M | if !self.block_input.contains_key(&block) { |
1072 | 0 | continue; |
1073 | 21.1M | } |
1074 | | |
1075 | | // Compute this block's final state. |
1076 | 21.1M | let mut state = self.block_input_stores(block); |
1077 | 181M | for inst in func.layout.block_insts(block) { |
1078 | 181M | state.observe_inst(func, inst, &mut observed_stores); |
1079 | 181M | state.update(func, inst); |
1080 | 181M | } |
1081 | | |
1082 | 27.5M | visit_block_succs(func, block, |branch, succ, _from_table| { |
1083 | | // A loop between a maybe-dead store and its overwriter might |
1084 | | // never terminate, but if the maybe-dead store traps, then we |
1085 | | // need to preserve that rather than rewrite the program to |
1086 | | // infinite loop. Therefore, we observe every store in |
1087 | | // `LastStores` on retreating edges. |
1088 | 27.5M | if self.domtree.is_retreating_edge(block, succ) { |
1089 | 581k | state.observe_others(func, &mut observed_stores, None, branch); |
1090 | 581k | return; |
1091 | 26.9M | } |
1092 | | |
1093 | | // When a predecessor and successor disagree on the last store |
1094 | | // to a region, we need to mark the predecessor's last store as |
1095 | | // observed, so that dead-store elimination cannot remove it. |
1096 | 26.9M | let succ_input = self |
1097 | 26.9M | .block_input |
1098 | 26.9M | .get(&succ) |
1099 | 26.9M | .expect("successors of a reachable block are reachable"); |
1100 | | |
1101 | 26.9M | let observer = func.layout.block_insts(succ).next().unwrap(); |
1102 | | |
1103 | 26.9M | let max_len = |
1104 | 26.9M | core::cmp::max(state.regions.keys().len(), succ_input.regions.keys().len()); |
1105 | 141M | for i in 0..max_len { |
1106 | 141M | let region = AliasRegion::new(i); |
1107 | 141M | if succ_input.regions[region] == LastStore::Unknown { |
1108 | 29.5M | observe(func, &mut observed_stores, state.regions[region], observer); |
1109 | 111M | } |
1110 | | } |
1111 | | |
1112 | 26.9M | if succ_input.last_fence == LastStore::Unknown { |
1113 | 15.7M | observe(func, &mut observed_stores, state.last_fence, observer); |
1114 | 15.7M | } |
1115 | 27.5M | }); |
1116 | | } |
1117 | | |
1118 | 1.99M | trace!("final observed_stores = {observed_stores:#?}"); |
1119 | 1.99M | self.observed_stores = observed_stores; |
1120 | 1.99M | } |
1121 | | |
1122 | | /// Get the extent token to key a `MemoryLoc` on for a memory-access instruction. |
1123 | 33.8M | fn extent_for(&self, state: &MemoryState, func: &Function, inst: Inst) -> u32 { |
1124 | 33.8M | match state.stores.get_last_store(func, inst) { |
1125 | | // Each of these already names a version of memory all on its own, |
1126 | | // function wide, and so doesn't need an additional extent token. |
1127 | 24.3M | LastStore::NoStore | LastStore::Inst(_) => NULL_EXTENT, |
1128 | | |
1129 | | // This one, on the other hand, only names a version of memory |
1130 | | // relative to the control-flow join that lost track of it. |
1131 | | LastStore::Unknown => { |
1132 | 9.56M | debug_assert_ne!(state.extent, NULL_EXTENT); |
1133 | 9.56M | let scope = self.scopes.last().expect("active alias-analysis scope"); |
1134 | 9.56M | func.dfg.insts[inst] |
1135 | 9.56M | .alias_region(&func.dfg) |
1136 | 9.56M | .map_or(state.extent, |region| scope.region_extents[region]) |
1137 | | } |
1138 | | } |
1139 | 33.8M | } |
1140 | | |
1141 | | /// Get the solved last-store state on entry to the given block. |
1142 | 27.0M | fn block_input_stores(&self, block: Block) -> LastStores { |
1143 | 27.0M | match self.block_input.get(&block) { |
1144 | 27.0M | Some(input) => input.clone(), |
1145 | 0 | None => LastStores::default(), |
1146 | | } |
1147 | 27.0M | } |
1148 | | |
1149 | | /// Regions written on paths from `dominator`'s exit to `block`'s entry. |
1150 | | /// Return `false` if a fence or missing effects prevent proving which regions |
1151 | | /// are untouched. Also give up after 64 blocks to bound the analysis cost. |
1152 | 2.41M | fn clobbers_since( |
1153 | 2.41M | &self, |
1154 | 2.41M | cfg: &ControlFlowGraph, |
1155 | 2.41M | block: Block, |
1156 | 2.41M | dominator: Block, |
1157 | 2.41M | clobbers: &mut FxHashSet<AliasRegion>, |
1158 | 2.41M | pending: &mut SmallVec<[Block; 8]>, |
1159 | 2.41M | visited: &mut FxHashSet<Block>, |
1160 | 2.41M | ) -> bool { |
1161 | 2.41M | debug_assert!(clobbers.is_empty()); |
1162 | 2.41M | debug_assert!(pending.is_empty()); |
1163 | 2.41M | debug_assert!(visited.is_empty()); |
1164 | 2.41M | pending.extend(cfg.pred_iter(block).map(|p| p.block)); |
1165 | 11.6M | while let Some(pred) = pending.pop() { |
1166 | 10.5M | if pred == dominator || !self.block_input.contains_key(&pred) || !visited.insert(pred) { |
1167 | 4.72M | continue; |
1168 | 5.80M | } |
1169 | 5.80M | if visited.len() > 64 { |
1170 | 12.9k | return false; |
1171 | 5.78M | } |
1172 | 5.78M | let Some(Some(regions)) = self.block_clobbers.get(pred) else { |
1173 | 1.29M | return false; |
1174 | | }; |
1175 | 4.49M | clobbers.extend(regions.iter().copied()); |
1176 | 4.49M | pending.extend(cfg.pred_iter(pred).map(|p| p.block)); |
1177 | | } |
1178 | 1.10M | true |
1179 | 2.41M | } |
1180 | | |
1181 | | /// Compute region tokens for a new extent, inheriting unchanged regions when safe. |
1182 | 5.90M | fn compute_region_extents( |
1183 | 5.90M | &mut self, |
1184 | 5.90M | cfg: &ControlFlowGraph, |
1185 | 5.90M | block: Block, |
1186 | 5.90M | stores: &LastStores, |
1187 | 5.90M | extent: u32, |
1188 | 5.90M | ) -> SecondaryMap<AliasRegion, u32> { |
1189 | 5.90M | let mut region_extents = SecondaryMap::with_default(extent); |
1190 | 5.90M | let mut clobbers = core::mem::take(&mut self.clobbers_scratch); |
1191 | 5.90M | let mut pending = core::mem::take(&mut self.pending_scratch); |
1192 | 5.90M | let mut visited = core::mem::take(&mut self.visited_scratch); |
1193 | 5.90M | clobbers.clear(); |
1194 | 5.90M | pending.clear(); |
1195 | 5.90M | visited.clear(); |
1196 | 5.90M | if let Some(parent) = self.scopes.last() { |
1197 | 3.91M | let parent_stores = parent.exit_state.as_ref().expect("finished parent scope"); |
1198 | | // The parent's and join's fence states must match. |
1199 | | // The parent must have an Unknown version. |
1200 | | // The path search must identify the regions that may be written. |
1201 | 3.91M | if parent_stores.last_fence == stores.last_fence |
1202 | 2.73M | && (parent_stores.last_fence == LastStore::Unknown |
1203 | 543k | || parent_stores |
1204 | 543k | .regions |
1205 | 543k | .iter() |
1206 | 3.55M | .any(|(_, slot)| *slot == LastStore::Unknown)) |
1207 | 2.41M | && self.clobbers_since( |
1208 | 2.41M | cfg, |
1209 | 2.41M | block, |
1210 | 2.41M | parent.block, |
1211 | 2.41M | &mut clobbers, |
1212 | 2.41M | &mut pending, |
1213 | 2.41M | &mut visited, |
1214 | | ) |
1215 | | { |
1216 | 1.10M | region_extents = parent.region_extents.clone(); |
1217 | 1.10M | for ®ion in &clobbers { |
1218 | 312k | region_extents[region] = extent; |
1219 | 312k | } |
1220 | 1.10M | let len = parent_stores |
1221 | 1.10M | .regions |
1222 | 1.10M | .keys() |
1223 | 1.10M | .len() |
1224 | 1.10M | .max(stores.regions.keys().len()); |
1225 | 9.59M | for i in 0..len { |
1226 | 9.59M | let region = AliasRegion::new(i); |
1227 | 9.59M | if parent_stores.last_store_for_region(region) |
1228 | 9.59M | != stores.last_store_for_region(region) |
1229 | 21.3k | { |
1230 | 21.3k | region_extents[region] = extent; |
1231 | 9.57M | } |
1232 | | } |
1233 | 2.80M | } |
1234 | 1.99M | } |
1235 | 5.90M | self.clobbers_scratch = clobbers; |
1236 | 5.90M | self.pending_scratch = pending; |
1237 | 5.90M | self.visited_scratch = visited; |
1238 | 5.90M | region_extents |
1239 | 5.90M | } |
1240 | | |
1241 | | /// Enter the given block's scope, getting its initial memory state. |
1242 | | /// |
1243 | | /// Callers must walk the dominator tree in pre-order, entering each block's |
1244 | | /// scope on the way down and calling `pop_scope` before moving on to any |
1245 | | /// block that this one does not dominate. |
1246 | 21.1M | pub fn push_scope(&mut self, cfg: &ControlFlowGraph, block: Block) -> MemoryState { |
1247 | 21.1M | debug_assert!(cfg.is_valid()); |
1248 | 21.1M | debug_assert_eq!( |
1249 | 0 | self.domtree.idom(block), |
1250 | 0 | self.scopes.last().map(|s| s.block), |
1251 | | "`push_scope` must be called in dominator-tree pre-order", |
1252 | | ); |
1253 | | |
1254 | | // A block with exactly one reachable predecessor sees exactly the |
1255 | | // memory that its predecessor left behind. |
1256 | 21.1M | let only_pred = self.single_reachable_pred(cfg, block); |
1257 | | |
1258 | 21.1M | let (stores, extent, region_extents) = match (only_pred, self.scopes.last()) { |
1259 | | // With exactly one reachable predecessor, this block's entry state |
1260 | | // is exactly that predecessor's exit state, which we just finished |
1261 | | // computing and is strictly more precise than the `block_input` |
1262 | | // snapshot: that snapshot describes the pre-optimization function, |
1263 | | // and so it can still name dead stores we have since eliminated. |
1264 | | // |
1265 | | // And, because it sees exactly the predecessor's memory state, it |
1266 | | // also continues that predecessor's extent. |
1267 | 15.2M | (Some(only_pred), Some(parent)) if parent.block == only_pred => { |
1268 | | // A sole predecessor must be this block's immediate dominator. |
1269 | | // Since the scope stack is all of our ordered dominators, and |
1270 | | // because no other dominator sits between a block and its |
1271 | | // immediate dominator, the top of the scope stack is both this |
1272 | | // block's sole predecessor and immediate dominator. |
1273 | 15.2M | debug_assert_eq!(self.domtree.idom(block), Some(parent.block)); |
1274 | | |
1275 | 15.2M | let stores = parent |
1276 | 15.2M | .exit_state |
1277 | 15.2M | .as_ref() |
1278 | 15.2M | .expect("`finish_scope` is always called before descending into a child scope") |
1279 | 15.2M | .clone(); |
1280 | 15.2M | (stores, parent.extent, parent.region_extents.clone()) |
1281 | | } |
1282 | | |
1283 | | // Anything else (e.g. a control-flow join, the entry block) falls |
1284 | | // back to the initial fixpoint's snapshot, and begins a new extent. |
1285 | | _ => { |
1286 | 5.90M | self.next_extent += 1; |
1287 | 5.90M | let extent = self.next_extent; |
1288 | 5.90M | let stores = self.block_input_stores(block); |
1289 | 5.90M | let region_extents = self.compute_region_extents(cfg, block, &stores, extent); |
1290 | 5.90M | (stores, extent, region_extents) |
1291 | | } |
1292 | | }; |
1293 | | |
1294 | 21.1M | self.scopes.push(Scope { |
1295 | 21.1M | block, |
1296 | 21.1M | extent, |
1297 | 21.1M | region_extents, |
1298 | 21.1M | exit_state: None, |
1299 | 21.1M | }); |
1300 | | |
1301 | 21.1M | MemoryState { |
1302 | 21.1M | stores, |
1303 | 21.1M | extent, |
1304 | 21.1M | #[cfg(debug_assertions)] |
1305 | 21.1M | current_block: block, |
1306 | 21.1M | } |
1307 | 21.1M | } |
1308 | | |
1309 | | /// Record the given block's exit state, so that a successor for which it is |
1310 | | /// the sole predecessor can inherit that state. |
1311 | | /// |
1312 | | /// Callers must call this exactly once per `push_scope`, after walking the |
1313 | | /// block's instructions and before visiting any of its dominator-tree |
1314 | | /// children. |
1315 | 21.1M | pub fn finish_scope(&mut self, block: Block, state: MemoryState) { |
1316 | 21.1M | let scope = self |
1317 | 21.1M | .scopes |
1318 | 21.1M | .last_mut() |
1319 | 21.1M | .expect("`finish_scope` without a matching `push_scope`"); |
1320 | | |
1321 | 21.1M | debug_assert_eq!( |
1322 | | scope.block, block, |
1323 | | "`finish_scope` must be called on the block most recently passed to `push_scope`", |
1324 | | ); |
1325 | | |
1326 | | #[cfg(debug_assertions)] |
1327 | | debug_assert_eq!(state.current_block, block); |
1328 | | |
1329 | 21.1M | debug_assert!( |
1330 | 0 | scope.exit_state.is_none(), |
1331 | | "`finish_scope` must be called at most once per `push_scope`", |
1332 | | ); |
1333 | | |
1334 | 21.1M | scope.exit_state = Some(state.stores); |
1335 | 21.1M | } |
1336 | | |
1337 | | /// Leave the scope of the block most recently passed to `push_scope`. |
1338 | 13.9M | pub fn pop_scope(&mut self) { |
1339 | 13.9M | self.scopes |
1340 | 13.9M | .pop() |
1341 | 13.9M | .expect("`pop_scope` without a matching `push_scope`"); |
1342 | 13.9M | } |
1343 | | |
1344 | | /// Process one instruction. |
1345 | | /// |
1346 | | /// Must be invoked in program order within a block. |
1347 | 66.2M | pub fn process_inst( |
1348 | 66.2M | &mut self, |
1349 | 66.2M | func: &mut Function, |
1350 | 66.2M | cfg: &ControlFlowGraph, |
1351 | 66.2M | state: &mut MemoryState, |
1352 | 66.2M | inst: Inst, |
1353 | 66.2M | ) -> OptResult { |
1354 | 66.2M | trace!( |
1355 | | "process_inst: {inst}: {}\n\twith last stores: {state:?}", |
1356 | 0 | func.dfg.display_inst(inst), |
1357 | | ); |
1358 | | |
1359 | | #[cfg(debug_assertions)] |
1360 | | debug_assert_eq!(func.layout.inst_block(inst), Some(state.current_block)); |
1361 | | |
1362 | 66.2M | let result = if is_volatile_access(func, inst) { |
1363 | | // A volatile access is never removed, never replaced by a known |
1364 | | // value, and never the source of one: skip straight to updating the |
1365 | | // last-store state, where it acts as a fence. |
1366 | 0 | trace!(" --> volatile access: leaving it alone"); |
1367 | 0 | OptResult::None |
1368 | 66.2M | } else if let Some((address, offset, ty)) = inst_addr_offset_type(func, inst) { |
1369 | 34.2M | let address = func.dfg.resolve_aliases(address); |
1370 | 34.2M | let opcode = func.dfg.insts[inst].opcode(); |
1371 | | |
1372 | 34.2M | if opcode.can_store() { |
1373 | 14.7M | let store_data = inst_store_data(func, inst).unwrap(); |
1374 | 14.7M | let store_data = func.dfg.resolve_aliases(store_data); |
1375 | | |
1376 | 14.7M | let last_store = state.stores.get_last_store(func, inst); |
1377 | | |
1378 | | // Check whether this store makes the last store dead. |
1379 | 14.7M | if let LastStore::Inst(last_store) = last_store { |
1380 | | // A store can only be dead when unobserved or only observed |
1381 | | // by its overwriter. |
1382 | 8.14M | if self.observed_stores.get(&last_store).is_none_or(|o| *o == Observer::One(inst)) |
1383 | | // This instruction doesn't make the last |
1384 | | // store dead if it itself is the last store. |
1385 | 5.77M | && inst != last_store |
1386 | | // The last store isn't dead if this |
1387 | | // instruction is a fetch-add or something |
1388 | | // like that, as these instructions first load |
1389 | | // from (and therefore observe) memory before |
1390 | | // storing to it. |
1391 | 5.77M | && !func.dfg.insts[inst].opcode().can_load() |
1392 | | // A store with memory fence semantics (such as an |
1393 | | // atomic store) is observable by other threads, so it |
1394 | | // can never be eliminated. |
1395 | 5.77M | && !has_memory_fence_semantics(func.dfg.insts[last_store].opcode()) |
1396 | | // Nor can a volatile store, which must happen exactly as |
1397 | | // written. |
1398 | 3.26M | && !is_volatile_access(func, last_store) |
1399 | | // `last_store` must really be a store that |
1400 | | // writes exactly the bytes this store |
1401 | | // overwrites (same region, address, offset, |
1402 | | // type, and width). |
1403 | 3.26M | && fully_overwrites(func, last_store, inst, address, offset, ty) |
1404 | | // The last store is only dead if all paths out of the |
1405 | | // function from it go through this instruction. |
1406 | 371k | && self.post_dominates_maybe_dead_store(func, cfg, inst, last_store) |
1407 | | { |
1408 | 368k | trace!( |
1409 | | " --> discovered dead store at {last_store}: {}", |
1410 | 0 | func.dfg.display_inst(last_store) |
1411 | | ); |
1412 | | // The dead store is about to be removed from the |
1413 | | // layout, so drop its entry from `mem_values`. This |
1414 | | // maintains the invariant that `mem_values` only ever |
1415 | | // references instructions that are still in the layout. |
1416 | | // |
1417 | | // NB: the entry we are looking for was keyed on the |
1418 | | // *dead* store's byte order, which `fully_overwrites` |
1419 | | // does not require to match this store's byte order. |
1420 | | // Everything else in the key does have to match, so we |
1421 | | // can take it from this store. |
1422 | 368k | let dead_slot = LastStore::Inst(last_store); |
1423 | 368k | let dead_loc = MemoryLoc { |
1424 | 368k | last_store: dead_slot, |
1425 | 368k | extent: NULL_EXTENT, |
1426 | 368k | address, |
1427 | 368k | offset, |
1428 | 368k | ty, |
1429 | 368k | extending_opcode: get_ext_opcode(opcode), |
1430 | 368k | endianness: get_endianness(func, last_store), |
1431 | 368k | }; |
1432 | 368k | let dead_entry = self.mem_values.remove(&dead_loc); |
1433 | | |
1434 | | // Roll our last-store state back to just before the |
1435 | | // dead store, so that `state` describes memory as if |
1436 | | // the dead store had never happened. |
1437 | | // |
1438 | | // Our callers remove the dead store from the layout and |
1439 | | // then reprocess this overwriting store. Without the |
1440 | | // rollback, that reprocessing keys its `mem_values` |
1441 | | // lookup on the instruction we just removed, finds |
1442 | | // nothing, and so fails to notice that the overwriter |
1443 | | // has now become an idempotent store. Chains like |
1444 | | // |
1445 | | // v1 = load.i32 region0 v0 |
1446 | | // store region0 v2, v0 ;; dead |
1447 | | // store region0 v1, v0 ;; idempotent, once the |
1448 | | // ;; dead store is gone |
1449 | | // |
1450 | | // would then need a whole additional pass over the |
1451 | | // function to collapse each link. |
1452 | | // |
1453 | | // A missing entry means we have no previous version to |
1454 | | // roll back to, and simply don't: either we never |
1455 | | // processed the dead store as a store in this pass (it |
1456 | | // can come from a precomputed `block_input` snapshot, |
1457 | | // for a predecessor block we have not walked yet) or it |
1458 | | // has no alias region and therefore no slot of its own. |
1459 | 368k | if let Some(prev) = dead_entry |
1460 | 368k | .filter(|e| self.domtree.dominates(e.def_inst, inst, &func.layout)) |
1461 | 368k | .and_then(|e| e.prev_region_slot) |
1462 | 366k | { |
1463 | 366k | state.stores.undo_store(func, last_store, prev); |
1464 | 366k | } |
1465 | | |
1466 | 368k | return OptResult::DeadStore { |
1467 | 368k | dead: last_store, |
1468 | 368k | overwriter: inst, |
1469 | 368k | }; |
1470 | 7.77M | } |
1471 | 6.65M | } |
1472 | | |
1473 | 14.4M | let check_loc = MemoryLoc { |
1474 | 14.4M | last_store, |
1475 | 14.4M | extent: self.extent_for(state, func, inst), |
1476 | 14.4M | address, |
1477 | 14.4M | offset, |
1478 | 14.4M | ty, |
1479 | 14.4M | extending_opcode: get_ext_opcode(opcode), |
1480 | 14.4M | endianness: get_endianness(func, inst), |
1481 | 14.4M | }; |
1482 | | if let Some(KnownValue { |
1483 | 3.88M | def_inst, |
1484 | 3.88M | value: known_value, |
1485 | | .. |
1486 | 14.4M | }) = self.mem_values.get(&check_loc).cloned() |
1487 | | { |
1488 | | // Check for idempotent stores, where we are |
1489 | | // storing the exact same value back to a location |
1490 | | // that already has that value. |
1491 | 3.88M | if known_value == store_data |
1492 | | // We cannot remove this store unless all control-flow |
1493 | | // paths leading to it go through the original store |
1494 | | // instruction. |
1495 | 389k | && self.domtree.dominates(def_inst, inst, &func.layout) |
1496 | | // An atomic store still publishes its value to other |
1497 | | // threads and orders the accesses around it, even when |
1498 | | // the bytes do not change. |
1499 | 389k | && !has_memory_fence_semantics(opcode) |
1500 | | { |
1501 | 388k | trace!(" --> idempotent store of {store_data} to loc {check_loc:?}"); |
1502 | | |
1503 | 388k | if let LastStore::Inst(last_store) = last_store { |
1504 | | // We are removing this idempotent store in favor of |
1505 | | // the original, so if this idempotent store was |
1506 | | // observed, then the original must now be observed |
1507 | | // as well. |
1508 | 336k | if let Some(observer) = self.observed_stores.get(&inst).copied() { |
1509 | 334k | let entry = |
1510 | 334k | self.observed_stores.entry(last_store).or_insert(observer); |
1511 | 334k | *entry = Observer::meet(*entry, observer); |
1512 | 334k | trace!(" observed_stores[{last_store:?}] = {entry:?}"); |
1513 | 2.18k | } |
1514 | | |
1515 | | // And if the `last_store` has a trap code but this |
1516 | | // one doesn't, then we need to additionally mark it |
1517 | | // as observed by many because a later non-trapping |
1518 | | // store can observe whether or not it trapped. |
1519 | 336k | let trap_code = |
1520 | 668k | |i: Inst| func.dfg.insts[i].memflags_trap_code(&func.dfg); |
1521 | 336k | if trap_code(inst).is_none() |
1522 | 332k | && trap_code(last_store).is_some() |
1523 | 737 | && func.dfg.insts[last_store].opcode().can_store() |
1524 | | { |
1525 | 683 | self.observed_stores.insert(last_store, Observer::Many); |
1526 | 683 | trace!(" observed_stores[{last_store:?}] = Many"); |
1527 | 335k | } |
1528 | 51.9k | } |
1529 | | |
1530 | 388k | return OptResult::IdempotentStore; |
1531 | 3.49M | } |
1532 | 10.5M | } |
1533 | | |
1534 | | // Otherwise, update our state to reflect this store. |
1535 | 14.0M | let this_store = LastStore::Inst(inst); |
1536 | 14.0M | let mem_loc = MemoryLoc { |
1537 | 14.0M | last_store: this_store, |
1538 | 14.0M | extent: NULL_EXTENT, |
1539 | 14.0M | address, |
1540 | 14.0M | offset, |
1541 | 14.0M | ty, |
1542 | 14.0M | extending_opcode: get_ext_opcode(opcode), |
1543 | 14.0M | endianness: get_endianness(func, inst), |
1544 | 14.0M | }; |
1545 | 14.0M | trace!(" --> updating known values in memory: {mem_loc:?} = {store_data}"); |
1546 | 14.0M | self.mem_values.insert( |
1547 | 14.0M | mem_loc, |
1548 | 14.0M | KnownValue { |
1549 | 14.0M | def_inst: inst, |
1550 | 14.0M | value: store_data, |
1551 | 14.0M | // NB: we use the raw region slot, without the |
1552 | 14.0M | // last-fence fallback, because we don't want to move an |
1553 | 14.0M | // instruction without a region into a region slot on |
1554 | 14.0M | // DSE rollback. |
1555 | 14.0M | prev_region_slot: state.stores.raw_region_slot(func, inst), |
1556 | 14.0M | }, |
1557 | | ); |
1558 | | |
1559 | 14.0M | OptResult::None |
1560 | 19.4M | } else if opcode.can_load() { |
1561 | 19.4M | let last_store = state.stores.get_last_store(func, inst); |
1562 | 19.4M | let load_result = func.dfg.inst_results(inst)[0]; |
1563 | 19.4M | let mem_loc = MemoryLoc { |
1564 | 19.4M | last_store, |
1565 | 19.4M | extent: self.extent_for(state, func, inst), |
1566 | 19.4M | address, |
1567 | 19.4M | offset, |
1568 | 19.4M | ty, |
1569 | 19.4M | extending_opcode: get_ext_opcode(opcode), |
1570 | 19.4M | endianness: get_endianness(func, inst), |
1571 | 19.4M | }; |
1572 | 19.4M | trace!(" load with last_store at loc {mem_loc:?}"); |
1573 | | |
1574 | | // Is there a Value already known to be stored |
1575 | | // at this specific memory location? If so, |
1576 | | // we can alias the load result to this |
1577 | | // already-known Value. |
1578 | | // |
1579 | | // Check if the definition dominates this |
1580 | | // location; it might not, if it comes from a |
1581 | | // load (stores will always dominate though if |
1582 | | // their `last_store` survives through |
1583 | | // meet-points to this use-site). |
1584 | 19.4M | let aliased = if let Some(KnownValue { |
1585 | 6.90M | def_inst, value, .. |
1586 | 19.4M | }) = self.mem_values.get(&mem_loc).cloned() |
1587 | | { |
1588 | 6.90M | trace!(" see known value {value} from {def_inst}"); |
1589 | 6.90M | if self.domtree.dominates(def_inst, inst, &func.layout) { |
1590 | 6.63M | trace!( |
1591 | | " --> dominates; inserting value equivalence from {load_result} to {value}", |
1592 | | ); |
1593 | 6.63M | Some(value) |
1594 | | } else { |
1595 | 277k | None |
1596 | | } |
1597 | | } else { |
1598 | 12.5M | None |
1599 | | }; |
1600 | | |
1601 | | // Otherwise, we can keep *this* load around |
1602 | | // as a new equivalent value. |
1603 | 19.4M | if aliased.is_none() { |
1604 | 12.8M | trace!(" --> inserting load result {load_result} at loc {mem_loc:?}"); |
1605 | 12.8M | self.mem_values.insert( |
1606 | 12.8M | mem_loc, |
1607 | 12.8M | KnownValue { |
1608 | 12.8M | def_inst: inst, |
1609 | 12.8M | value: load_result, |
1610 | 12.8M | // A load does not advance the memory version, so |
1611 | 12.8M | // there is no previous slot value to roll back to. |
1612 | 12.8M | prev_region_slot: None, |
1613 | 12.8M | }, |
1614 | | ); |
1615 | 6.63M | } |
1616 | | |
1617 | 19.4M | match aliased { |
1618 | 6.63M | Some(value) => { |
1619 | | // NB: Early return to skip the `state.update` below -- |
1620 | | // store-to-load forwarding does not observe the store |
1621 | | // and its region and should not prevent the store from |
1622 | | // being dead-store eliminated. |
1623 | 6.63M | return OptResult::AliasedLoad(value); |
1624 | | } |
1625 | 12.8M | None => OptResult::None, |
1626 | | } |
1627 | | } else { |
1628 | 0 | OptResult::None |
1629 | | } |
1630 | | } else { |
1631 | 31.9M | OptResult::None |
1632 | | }; |
1633 | | |
1634 | | // `compute_observed_stores` walks the whole function up front, so |
1635 | | // processing an instruction here must never turn up a store that it did |
1636 | | // not already find. |
1637 | | #[cfg(debug_assertions)] |
1638 | | { |
1639 | | let mut new_observations = FxHashMap::default(); |
1640 | | state.stores.observe_inst(func, inst, &mut new_observations); |
1641 | | for observed in new_observations.keys() { |
1642 | | debug_assert!( |
1643 | | self.observed_stores.contains_key(observed), |
1644 | | "`compute_observed_stores` should have already found all observed \ |
1645 | | stores, but processing {inst} found that {observed} is observed", |
1646 | | ); |
1647 | | } |
1648 | | } |
1649 | | |
1650 | 58.8M | state.stores.update(func, inst); |
1651 | | |
1652 | 58.8M | result |
1653 | 66.2M | } |
1654 | | |
1655 | | /// Make a pass and update known-redundant loads to aliased |
1656 | | /// values. We interleave the updates with the memory-location |
1657 | | /// tracking because resolving some aliases may expose others |
1658 | | /// (e.g. in cases of double-indirection with two separate chains |
1659 | | /// of loads). |
1660 | 0 | pub fn compute_and_update_aliases(&mut self, func: &mut Function, cfg: &ControlFlowGraph) { |
1661 | 0 | let domtree = self.domtree; |
1662 | 0 | let mut pos = FuncCursor::new(func); |
1663 | | |
1664 | 0 | let Some(entry) = pos.func.layout.entry_block() else { |
1665 | 0 | return; |
1666 | | }; |
1667 | | |
1668 | | // Marks a block we have not walked yet, or the point at which we are |
1669 | | // done with everything a block dominates and must leave its scope. |
1670 | | enum BlockStackEntry { |
1671 | | Visit(Block), |
1672 | | Pop, |
1673 | | } |
1674 | | |
1675 | | // Walk the dominator tree in pre-order. Unreachable blocks are not in |
1676 | | // the dominator tree, and are simply skipped. |
1677 | 0 | let mut stack = vec![BlockStackEntry::Visit(entry)]; |
1678 | 0 | while let Some(top) = stack.pop() { |
1679 | 0 | let block = match top { |
1680 | | BlockStackEntry::Pop => { |
1681 | 0 | self.pop_scope(); |
1682 | 0 | continue; |
1683 | | } |
1684 | 0 | BlockStackEntry::Visit(block) => block, |
1685 | | }; |
1686 | | |
1687 | 0 | stack.push(BlockStackEntry::Pop); |
1688 | 0 | let mut state = self.push_scope(cfg, block); |
1689 | | |
1690 | 0 | pos.goto_top(block); |
1691 | 0 | while let Some(inst) = pos.next_inst() { |
1692 | 0 | match self.process_inst(pos.func, cfg, &mut state, inst) { |
1693 | 0 | OptResult::None => {} |
1694 | 0 | OptResult::AliasedLoad(replaced_result) => { |
1695 | 0 | let result = pos.func.dfg.inst_results(inst)[0]; |
1696 | 0 | pos.func.dfg.clear_results(inst); |
1697 | 0 | pos.func.dfg.change_to_alias(result, replaced_result); |
1698 | 0 | pos.remove_inst_and_step_back(); |
1699 | 0 | } |
1700 | 0 | OptResult::IdempotentStore => { |
1701 | 0 | pos.remove_inst_and_step_back(); |
1702 | 0 | } |
1703 | | OptResult::DeadStore { |
1704 | 0 | dead, |
1705 | | overwriter: _, |
1706 | | } => { |
1707 | 0 | assert!( |
1708 | 0 | !matches!(pos.position(), CursorPosition::At(other) if dead == other) |
1709 | | ); |
1710 | 0 | pos.func.layout.remove_inst(dead); |
1711 | | // Step back so that we reprocess the overwriter. This |
1712 | | // lets us unwind chains of dead stores, one link at a |
1713 | | // time. |
1714 | 0 | pos.prev_inst(); |
1715 | | } |
1716 | | } |
1717 | | } |
1718 | | |
1719 | 0 | self.finish_scope(block, state); |
1720 | | |
1721 | 0 | let children = SmallVec::<[Block; 8]>::from_iter(domtree.children(block)); |
1722 | 0 | stack.extend(children.into_iter().rev().map(BlockStackEntry::Visit)); |
1723 | | } |
1724 | 0 | } |
1725 | | } |
1726 | | |
1727 | | /// Get the explicitly-specified byte order of the given memory access, |
1728 | | /// if any. |
1729 | 48.2M | fn get_endianness(func: &Function, inst: Inst) -> Option<Endianness> { |
1730 | 48.2M | func.dfg.insts[inst] |
1731 | 48.2M | .memflags_data(&func.dfg) |
1732 | 48.2M | .and_then(|flags| flags.explicit_endianness()) |
1733 | 48.2M | } |
1734 | | |
1735 | 54.8M | fn get_ext_opcode(op: Opcode) -> Option<Opcode> { |
1736 | 54.8M | debug_assert!(op.can_load() || op.can_store()); |
1737 | 54.8M | match op { |
1738 | 53.0M | Opcode::Load | Opcode::Store => None, |
1739 | 1.78M | _ => Some(op), |
1740 | | } |
1741 | 54.8M | } |
1742 | | |
1743 | | /// Can `overwriter` make `maybe_dead` a dead store? |
1744 | | /// |
1745 | | /// Only if `maybe_dead` is itself a store that writes exactly the |
1746 | | /// bytes `overwriter` overwrites: the same alias region, address, |
1747 | | /// offset, type, and store width (i.e. extending/truncating |
1748 | | /// opcode). Otherwise some (or all) of `maybe_dead`'s bytes may |
1749 | | /// remain observable after `overwriter` runs, and removing |
1750 | | /// `maybe_dead` would change the program's behavior. |
1751 | | /// |
1752 | | /// `overwriter_addr` must already have had its value-aliases resolved |
1753 | | /// (as the caller does for the overwriter's address). |
1754 | 3.26M | fn fully_overwrites( |
1755 | 3.26M | func: &Function, |
1756 | 3.26M | maybe_dead: Inst, |
1757 | 3.26M | overwriter: Inst, |
1758 | 3.26M | overwriter_addr: Value, |
1759 | 3.26M | overwriter_offset: Offset32, |
1760 | 3.26M | overwriter_ty: Type, |
1761 | 3.26M | ) -> bool { |
1762 | 3.26M | debug_assert!(!func.dfg.value_is_alias(overwriter_addr)); |
1763 | | |
1764 | 3.26M | let maybe_dead_opcode = func.dfg.insts[maybe_dead].opcode(); |
1765 | | |
1766 | | // `maybe_dead` must really be a store (this rejects the `last_fence` and merge |
1767 | | // fallbacks that point at calls/fences/atomics or unrelated instructions). |
1768 | 3.26M | if !maybe_dead_opcode.can_store() { |
1769 | 0 | return false; |
1770 | 3.26M | } |
1771 | | |
1772 | | // A volatile store is never dead, and a volatile store never makes another |
1773 | | // store dead. |
1774 | 3.26M | if is_volatile_access(func, maybe_dead) || is_volatile_access(func, overwriter) { |
1775 | 0 | return false; |
1776 | 3.26M | } |
1777 | | |
1778 | | // Both must write the same number of bytes: e.g. `istore8` and `store` |
1779 | | // write different widths even when their value types are equal. |
1780 | 3.26M | let overwriter_opcode = func.dfg.insts[overwriter].opcode(); |
1781 | 3.26M | if get_ext_opcode(maybe_dead_opcode) != get_ext_opcode(overwriter_opcode) { |
1782 | 3.18k | return false; |
1783 | 3.26M | } |
1784 | | |
1785 | | // Both must target the same alias region; a store to one region cannot make |
1786 | | // a store to a disjoint region dead. |
1787 | 3.26M | if func.dfg.insts[maybe_dead].alias_region(&func.dfg) |
1788 | 3.26M | != func.dfg.insts[overwriter].alias_region(&func.dfg) |
1789 | | { |
1790 | 5.31k | return false; |
1791 | 3.25M | } |
1792 | | |
1793 | | // Both must have the same trap code, if any. Otherwise, removing |
1794 | | // `maybe_dead` could change which code an execution traps with. |
1795 | 3.25M | if func.dfg.insts[maybe_dead] |
1796 | 3.25M | .memflags() |
1797 | 3.25M | .and_then(|f| func.dfg.mem_flags[f].trap_code()) |
1798 | 3.25M | != func.dfg.insts[overwriter] |
1799 | 3.25M | .memflags() |
1800 | 3.25M | .and_then(|f| func.dfg.mem_flags[f].trap_code()) |
1801 | | { |
1802 | 1.11k | return false; |
1803 | 3.25M | } |
1804 | | |
1805 | | // NB: unlike store-to-load forwarding and redundant-load |
1806 | | // elimination, our two stores' byte orders do *not* have to match |
1807 | | // Both write the same range of bytes, just in a different order |
1808 | | // within that range, and the overwriting store's bytes are the |
1809 | | // ones that survive either way. |
1810 | | |
1811 | | // Both must write the same address, offset, and type. |
1812 | 3.25M | match inst_addr_offset_type(func, maybe_dead) { |
1813 | 3.25M | Some((addr, offset, ty)) => { |
1814 | 3.25M | func.dfg.resolve_aliases(addr) == overwriter_addr |
1815 | 2.82M | && offset == overwriter_offset |
1816 | 371k | && ty == overwriter_ty |
1817 | | } |
1818 | 0 | None => false, |
1819 | | } |
1820 | 3.26M | } |