rucc_opt/memssa.rs
1//! Memory SSA: the chain, and the budgeted walk back to the store a load sees.
2//!
3//! Design: `spec/optimizer/09-memory-ssa.md`. The representation is in `rucc-ir` and this is what
4//! builds it and what reads it.
5//!
6//! # One variable
7//!
8//! GCC has had this since 2004 and calls it virtual operands: a statement that reads memory
9//! carries a VUSE, one that writes memory carries a VDEF, and both are versions of one artificial
10//! variable called `.MEM`. LLVM calls the same three things `MemoryUse`, `MemoryDef` and
11//! `MemoryPhi`. The idea in both is to reuse the scalar SSA machinery for memory by pretending
12//! memory is one scalar, and it is the right idea, so this does the same.
13//!
14//! The consequence is that the def-use chain over memory is maximally conservative. Every store
15//! kills every load, structurally. All of the precision comes from walking it, which is what
16//! [`Walk::clobber`] does.
17//!
18//! [`build`] is the construction: place a memory parameter at every join the memory versions
19//! reach, which is the same iterated dominance frontier that SSA construction uses, and thread
20//! the operand through every instruction that touches memory. A memory phi is an ordinary block
21//! parameter, so nothing here is a side table and the CFG updates that keep memory SSA in step
22//! with the blocks are the ones every other value already needed.
23//!
24//! # The walk
25//!
26//! [`Walk::clobber`] is GCC's `walk_non_aliased_vuses` at `gcc/tree-ssa-alias.cc:3915`. Given the
27//! version of memory a load reads, it walks back through the defs, asks the alias analysis at each
28//! one whether that def could have written what the load reads, and stops at the first one that
29//! could. Two parts of GCC's interface are worth copying and both are here.
30//!
31//! **The budget.** `sccvn-max-alias-queries-per-access`, default 1000 at `gcc/params.opt:1020`,
32//! and it is [`MAX_ALIAS_QUERIES_PER_ACCESS`] here under the same name, because a user who knows
33//! to raise GCC's should not have to learn a second one. The walk is worst case quadratic: every
34//! load can walk back through every store and each step is an alias query, so a function with a
35//! thousand of each and no disambiguation is a million queries per pass that uses it, and there
36//! are four such passes. Exceeding the budget gives [`Clobber::Unknown`], which is not an answer
37//! and is not a no.
38//!
39//! **`translate`.** When the walk reaches a def it cannot see past, the caller may adjust the
40//! reference and carry on, which is [`Step::Retry`]. This is what lets value numbering follow a
41//! load through a `memcpy` by rewriting the reference to the copy's source, and section 9.2 says
42//! it is the mechanism behind a surprising fraction of GCC's memory optimization. Without it the
43//! walk is a stopping condition. With it, it is a way to rewrite the question.
44//!
45//! A rewrite is counted, as [`Counts::rewritten`], for the same reason the steps and the budget
46//! exhaustions are: it is the one thing in the walk that starts the walk again, so it is where the
47//! work goes when the work goes somewhere unexpected, and it is what says whether the callback is
48//! reaching anything at all on a build rather than only on the build somebody last looked at.
49//!
50//! # Five answers, not two
51//!
52//! [`Clobber`] has five variants and the shape of it is deliberate. Section 9.6 names two ways
53//! this goes wrong and the type is what rules both out.
54//!
55//! The first is a caller treating a budget exhaustion as a no. There is no `Option` anywhere in
56//! the return and there is no default arm to fall into, so [`Clobber::Unknown`] has to be handled
57//! by name.
58//!
59//! The second is partial overlap. A four byte store followed by a one byte load at offset one:
60//! the load sees the store, but it cannot be replaced by the stored value, because the byte it
61//! wants is somewhere inside that value and getting it out is a shift and a truncate. So a
62//! clobber that wrote exactly the bytes of the reference is [`Clobber::Exact`], one that wrote
63//! some of them is [`Clobber::Partial`], and one that may have written them is
64//! [`Clobber::Maybe`]. Section 9.5 says getting this down to two answers is a class of
65//! miscompilation.
66//!
67//! # What is conservative on purpose
68//!
69//! Every atomic and every fence is a full memory def and a full memory use. Section 9.5 says this
70//! is correct and it is what M4 should do, and that doing better means modelling the memory model
71//! rather than the memory, which is post-1.0. The failure mode it names is treating a relaxed
72//! atomic load as an ordinary load because it orders nothing: it orders nothing and it is still a
73//! load, and hoisting it out of a loop changes an observable. Atomics are never moved.
74//!
75//! `volatile` is checked before anything else and is never walked past. Alias analysis says
76//! nothing about how many times an access happens and `volatile` constrains that too, so it is a
77//! separate bit rather than a strong alias fact.
78//!
79//! # The cache
80//!
81//! There is not one. Section 9.3 is explicit: build the uncached walk, instrument how many alias
82//! queries a `-O2` compilation makes, and add caching only if that number is a measurable
83//! fraction of compile time. GCC has run without it for twenty years and LLVM's caching walker is
84//! a large part of its MemorySSA complexity and a known source of invalidation bugs. The
85//! instrumentation is the M4 deliverable and it is [`Counts`]. The number that decides it is the
86//! fraction of walks that end by exhausting the budget rather than by finding a clobber: above
87//! one percent and the budget is too small or the alias analysis is too weak, and both of those
88//! are better fixed than cached around.
89
90use std::collections::{HashMap, HashSet};
91
92use rucc_ir::{Block, BlockCall, Def, Flags, Func, Inst, InstData, MemOrder, Opcode, Type, Value};
93
94use crate::alias::{Access, Alias, Answer, Options};
95use crate::cfg::Cfg;
96use crate::dom::Dominators;
97use crate::outside::Outside;
98
99/// How many alias queries one walk may make before it gives up.
100///
101/// GCC's `sccvn-max-alias-queries-per-access`, default 1000 at `gcc/params.opt:1020`, under the
102/// same name on purpose. Exceeding it gives [`Clobber::Unknown`] rather than a wrong answer.
103pub const MAX_ALIAS_QUERIES_PER_ACCESS: u32 = 1000;
104
105/// What the walk found.
106///
107/// Five variants, and section 9.6 is why. Three of them are a clobber and they differ in how much
108/// of the reference the clobber covers, because a caller that cannot tell `Exact` from `Partial`
109/// replaces a one byte load with the wrong byte of a four byte store. The other two are the ways
110/// a walk ends without one, and `Unknown` is not a no.
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum Clobber {
113 /// This instruction wrote exactly the bytes the reference covers.
114 ///
115 /// The only answer redundant load elimination may act on by taking the stored value, and
116 /// even then only after checking the two types are the same width.
117 Exact(Inst),
118 /// This instruction wrote some of the reference, or wrote all of it and more.
119 ///
120 /// The load sees it, and what it sees cannot be had without taking part of what was stored
121 /// or combining it with something else, which is document 16's decision rather than this
122 /// one's.
123 Partial(Inst),
124 /// This instruction may have written the reference, and there is no telling how much.
125 Maybe(Inst),
126 /// Nothing in this function wrote it. The walk reached the start of the chain.
127 NoClobber,
128 /// The walk ran out of budget, or the paths into a join disagreed. Nothing is known.
129 Unknown,
130}
131
132impl Clobber {
133 /// The instruction, for the three answers that name one.
134 #[must_use]
135 pub const fn inst(self) -> Option<Inst> {
136 match self {
137 Self::Exact(inst) | Self::Partial(inst) | Self::Maybe(inst) => Some(inst),
138 Self::NoClobber | Self::Unknown => None,
139 }
140 }
141}
142
143/// What a caller does when the walk reaches a def it cannot see past.
144///
145/// GCC's `translate` callback, section 9.2. A caller with no rewrite to offer says [`Step::Stop`]
146/// and gets the clobber. One that can see through the def rewrites the reference and the walk
147/// carries on with the new one.
148#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub enum Step {
150 /// Stop here. This is the answer.
151 Stop,
152 /// Carry on past this def, asking about this reference instead.
153 Retry(Access),
154}
155
156/// What the walks have cost, which section 9.7 asks for as its own counter.
157///
158/// The walk is charged to whichever pass made it, so `-ftime-report` shows it under GVN and PRE
159/// and not under memory SSA. That is misleading, and the fix section 9.7 asks for is to report
160/// the step count separately from the wall time, because it is the thing to look at when a
161/// pathological input turns up.
162#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
163pub struct Counts {
164 walks: u64,
165 steps: u64,
166 exhausted: u64,
167 rewritten: u64,
168}
169
170impl Counts {
171 /// How many walks were made.
172 #[must_use]
173 pub const fn walks(&self) -> u64 {
174 self.walks
175 }
176
177 /// How many defs those walks looked at, which is one alias query each.
178 #[must_use]
179 pub const fn steps(&self) -> u64 {
180 self.steps
181 }
182
183 /// How many walks ended by running out of budget.
184 ///
185 /// This is the number section 9.3 says decides whether the cache gets built. Above one
186 /// percent of walks and the budget is too small or the alias analysis is too weak.
187 #[must_use]
188 pub const fn exhausted(&self) -> u64 {
189 self.exhausted
190 }
191
192 /// How many times a caller rewrote the reference and the walk carried on with the new one.
193 ///
194 /// A rewrite starts a walk of its own, so this is both how much work the `translate` callback
195 /// is asking for and how much it is getting, and it is the counter that says whether the
196 /// callback is doing anything at all on a given build.
197 #[must_use]
198 pub const fn rewritten(&self) -> u64 {
199 self.rewritten
200 }
201}
202
203/// Puts a function on the memory chain, and says whether it did.
204///
205/// Construction is the same iterated dominance frontier SSA construction uses, over one variable:
206/// the blocks that write memory are the definitions, the joins their versions reach get a memory
207/// parameter, and a walk of the dominator tree threads the operand through every instruction that
208/// touches memory. Linear with a dominance frontier factor, per section 9.7.
209///
210/// It gives back `false` and changes nothing for a function that has no memory operations at all,
211/// for a declaration, and for one that is already on the chain. The first of those is the reason
212/// the answer is a `bool` rather than nothing: a function with no memory in it must not get a
213/// `mem_entry`, because a chain that starts and reaches nothing is a chain the verifier turns
214/// down and a reader would have to interpret.
215pub fn build(func: &mut Func) -> bool {
216 let Some(entry) = func.entry() else {
217 return false;
218 };
219 let cfg = Cfg::new(func);
220 let doms = Dominators::new(&cfg);
221
222 // Where the writes are, which is where the versions of memory are defined.
223 let mut defs = vec![entry];
224 let mut any = false;
225 for block in func.blocks() {
226 // A block nothing reaches is one the verifier turns down on its own, and it is not on
227 // the dominator tree either, so threading would leave it off the chain and the chain
228 // would then be neither all of the function nor none of it. Running the cleanup that
229 // deletes it first is the caller's job.
230 if !cfg.reaches(block) {
231 return false;
232 }
233 let mut writes = false;
234 for inst in func.insts(block) {
235 if func.carries_mem(inst) {
236 return false;
237 }
238 let opcode = func[inst].opcode;
239 any |= opcode.touches_memory();
240 writes |= opcode.writes_memory();
241 }
242 if writes && block != entry {
243 defs.push(block);
244 }
245 }
246 // An entry block with nothing in it has no terminator either, so this is not a function the
247 // verifier would have let through and there is nothing sensible to build over it.
248 let Some(first) = func.insts(entry).next() else {
249 return false;
250 };
251 if !any {
252 return false;
253 }
254
255 let joins = iterated_frontier(&cfg, &doms, &defs);
256 let mut params = HashMap::new();
257 for block in func.blocks().collect::<Vec<_>>() {
258 if joins.contains(&block) {
259 params.insert(block, func.append_param(block, Type::MEM));
260 }
261 }
262
263 let start = start_of_chain(func, first);
264 let ends = thread(func, &doms, ¶ms, entry, start);
265 pass_it_on(func, ¶ms, &ends);
266 true
267}
268
269/// Takes the chain back off, and says whether it did.
270///
271/// The inverse of [`build`], and it is here because the back end has never seen memory SSA and is
272/// not going to: `rucc_codegen::capability` says outright that the chain comes off before it runs.
273/// Nothing was taking it off, so until this existed the only way to use the chain was to not use
274/// it. A pass that wants the walk builds the chain, does its work and strips it, which is a linear
275/// walk each way on top of whatever the pass itself costs.
276///
277/// Keeping the chain across passes instead would be cheaper and is a much bigger claim to make,
278/// since every edit to the control flow graph in the optimizer would have to keep the memory
279/// parameters in step with the blocks. That is worth wanting later and is not what this is.
280///
281/// Three things come off, in the order they have to. Every instruction on the chain loses its
282/// incoming version and its outgoing one, which is [`Func::without_mem`], and what it produced
283/// otherwise is forwarded to what the bare one produces. Every memory parameter comes off the
284/// block that has it and the matching argument comes off every branch to that block. The
285/// `mem_entry` at the top goes last, because until the rest is off it is a definition with
286/// readers.
287///
288/// It gives back `false` and changes nothing for a function that is not on the chain.
289pub fn strip(func: &mut Func) -> bool {
290 let mut forward: Vec<(Value, Value)> = Vec::new();
291 let mut gone: Vec<Inst> = Vec::new();
292 let mut entry = None;
293 for block in func.blocks().collect::<Vec<Block>>() {
294 for inst in func.insts(block).collect::<Vec<Inst>>() {
295 if func[inst].opcode == Opcode::MemEntry {
296 entry = Some(inst);
297 continue;
298 }
299 if !func.carries_mem(inst) {
300 continue;
301 }
302 let bare = func.without_mem(inst);
303 func.insert_before(bare, inst);
304 // The results the bare one kept are at the same positions, and the version of memory
305 // the old one produced is past the end of them, so zipping forwards exactly the ones
306 // that have somewhere to go.
307 for (old, new) in func[inst].results().zip(func[bare].results()) {
308 forward.push((old, new));
309 }
310 gone.push(inst);
311 }
312 }
313 if entry.is_none() && gone.is_empty() {
314 return false;
315 }
316 for inst in gone {
317 func.remove_inst(inst);
318 }
319 let forward: HashMap<Value, Value> = forward.into_iter().collect();
320 if !forward.is_empty() {
321 substitute(func, &forward);
322 }
323 drop_params(func);
324 if let Some(inst) = entry {
325 func.remove_inst(inst);
326 }
327 true
328}
329
330/// Takes the memory parameter off every block that has one, and the argument off every branch to
331/// it.
332///
333/// A parameter that goes has to take the argument in the same position out of every branch, and
334/// only the caller knows which branches there are, which is why [`Func::retain_params`] does not
335/// do it. The position is worked out before anything is removed, because renumbering the
336/// parameters and rewriting the arguments cannot both go first.
337fn drop_params(func: &mut Func) {
338 let mut at: HashMap<Block, Vec<usize>> = HashMap::new();
339 let mut going: HashSet<Value> = HashSet::new();
340 for block in func.blocks().collect::<Vec<Block>>() {
341 let mut keep = Vec::new();
342 for (index, ¶m) in func[block].params.iter().enumerate() {
343 if func[param].ty.is_mem() {
344 going.insert(param);
345 } else {
346 keep.push(index);
347 }
348 }
349 if keep.len() != func[block].params.len() {
350 at.insert(block, keep);
351 }
352 }
353 if at.is_empty() {
354 return;
355 }
356 for block in func.blocks().collect::<Vec<Block>>() {
357 let Some(terminator) = func.terminator(block) else {
358 continue;
359 };
360 for target in func.target_list(terminator).iter() {
361 let call = func[target];
362 let Some(keep) = at.get(&call.block) else {
363 continue;
364 };
365 let args: Vec<Value> = keep.iter().map(|&index| func[call.args][index]).collect();
366 let args = func.push_values(&args);
367 func.set_block_call(target, BlockCall { args, ..call });
368 }
369 }
370 for block in at.keys().copied().collect::<Vec<Block>>() {
371 func.retain_params(block, |param| !going.contains(¶m));
372 }
373}
374
375/// The `mem_entry` above that instruction, which is where every chain starts.
376///
377/// It goes at the very top of the entry block, and the verifier insists on that: a start to the
378/// chain anywhere else would have instructions above it that are on the chain and reach a version
379/// of memory defined below them.
380fn start_of_chain(func: &mut Func, first: Inst) -> Value {
381 let span = func.span(first);
382 let inst = func.create_inst(InstData::new(Opcode::MemEntry), &[Type::MEM], span);
383 func.insert_before(inst, first);
384 func[inst].results().next().expect("mem_entry produces one value")
385}
386
387/// Threads the operand through every instruction that touches memory, and says which version of
388/// memory each block ends with.
389///
390/// The walk is over the dominator tree rather than the CFG, because the version reaching the top
391/// of a block is the one its immediate dominator ended with unless the block has a parameter of
392/// its own. That is the ordinary SSA renaming and memory is an ordinary variable here.
393fn thread(
394 func: &mut Func,
395 doms: &Dominators,
396 params: &HashMap<Block, Value>,
397 entry: Block,
398 start: Value,
399) -> HashMap<Block, Value> {
400 // An instruction cannot grow a result, so threading one makes a new instruction beside it and
401 // the old one goes away. What the old one produced is forwarded to what the new one produces,
402 // at the same positions, in one substitution at the end rather than as each is replaced,
403 // because an instruction threaded early can be an operand of one threaded late.
404 let mut forward: Vec<(Value, Value)> = Vec::new();
405 let mut ends = HashMap::new();
406 let mut stack = vec![(entry, start)];
407 while let Some((block, incoming)) = stack.pop() {
408 let mut current = params.get(&block).copied().unwrap_or(incoming);
409 for inst in func.insts(block).collect::<Vec<_>>() {
410 if !func[inst].opcode.touches_memory() {
411 continue;
412 }
413 let fresh = func.with_mem(inst, current);
414 func.insert_before(fresh, inst);
415 for (old, new) in func[inst].results().zip(func[fresh].results()) {
416 forward.push((old, new));
417 }
418 func.remove_inst(inst);
419 if let Some(next) = func.mem_out(fresh) {
420 current = next;
421 }
422 }
423 ends.insert(block, current);
424 stack.extend(doms.children(block).map(|child| (child, current)));
425 }
426
427 let forward: HashMap<Value, Value> = forward.into_iter().collect();
428 if !forward.is_empty() {
429 substitute(func, &forward);
430 }
431 ends
432}
433
434/// Replaces every use of what a threaded instruction produced with what its replacement produces.
435fn substitute(func: &mut Func, forward: &HashMap<Value, Value>) {
436 let with = |value: Value| forward.get(&value).copied().unwrap_or(value);
437 for block in func.blocks().collect::<Vec<_>>() {
438 for inst in func.insts(block).collect::<Vec<_>>() {
439 let args = func[inst].args;
440 func.rewrite(args, with);
441 for call in func.successors(inst).collect::<Vec<_>>() {
442 func.rewrite(call.args, with);
443 }
444 }
445 }
446 // And the names, which go where the readers went, for the same reason `crate::uses::substitute`
447 // moves them. A call is an instruction that carries memory and `int x = f();` names what one
448 // produced, so a value rewritten here can be a value a declaration is spelled by.
449 let mut moving: Vec<Value> = forward.keys().copied().collect();
450 moving.sort_unstable();
451 for from in moving {
452 func.rename_value(from, with(from));
453 }
454}
455
456/// Passes the version of memory each block ends with to the joins it branches to.
457fn pass_it_on(func: &mut Func, params: &HashMap<Block, Value>, ends: &HashMap<Block, Value>) {
458 for block in func.blocks().collect::<Vec<_>>() {
459 let Some(terminator) = func.terminator(block) else {
460 continue;
461 };
462 let Some(&value) = ends.get(&block) else {
463 continue;
464 };
465 for at in func.target_list(terminator).iter() {
466 let call = func[at];
467 if !params.contains_key(&call.block) {
468 continue;
469 }
470 // The memory parameter was appended last, so the argument goes last too, which is
471 // the same rule the operand follows and for the same reason.
472 let args = func.append_arg(call.args, value);
473 func.set_block_call(at, BlockCall { args, ..call });
474 }
475 }
476}
477
478/// The blocks that need a memory parameter, which is the iterated dominance frontier of the
479/// blocks that define a version of memory.
480fn iterated_frontier(cfg: &Cfg, doms: &Dominators, defs: &[Block]) -> HashSet<Block> {
481 let frontier = frontiers(cfg, doms);
482 let mut placed = HashSet::new();
483 let mut seen: HashSet<Block> = defs.iter().copied().collect();
484 let mut work: Vec<Block> = defs.to_vec();
485 while let Some(block) = work.pop() {
486 let Some(targets) = frontier.get(&block) else {
487 continue;
488 };
489 for &target in targets {
490 if placed.insert(target) && seen.insert(target) {
491 work.push(target);
492 }
493 }
494 }
495 placed
496}
497
498/// The dominance frontier of every block, by Cytron's walk from each join up to its immediate
499/// dominator.
500fn frontiers(cfg: &Cfg, doms: &Dominators) -> HashMap<Block, Vec<Block>> {
501 let mut frontier: HashMap<Block, Vec<Block>> = HashMap::new();
502 for block in cfg.reverse_postorder() {
503 let preds = cfg.predecessors(block);
504 if preds.len() < 2 {
505 continue;
506 }
507 let Some(top) = doms.immediate_dominator(block) else {
508 continue;
509 };
510 for &pred in preds {
511 let mut runner = pred;
512 while runner != top {
513 let at = frontier.entry(runner).or_default();
514 if !at.contains(&block) {
515 at.push(block);
516 }
517 let Some(next) = doms.immediate_dominator(runner) else {
518 break;
519 };
520 runner = next;
521 }
522 }
523 }
524 frontier
525}
526
527/// The walk back through the memory chain.
528///
529/// It borrows the function rather than owning anything, and it holds the alias analysis because
530/// every step is a query and the escape analysis inside it is worth building once.
531#[derive(Debug)]
532pub struct Walk<'a> {
533 func: &'a Func,
534 cfg: Cfg,
535 alias: Alias<'a>,
536 limit: u32,
537 counts: Counts,
538}
539
540impl<'a> Walk<'a> {
541 /// A walk over this function, with GCC's budget.
542 #[must_use]
543 pub fn new(func: &'a Func, outside: &'a Outside) -> Self {
544 Self::with(func, outside, Options::default(), MAX_ALIAS_QUERIES_PER_ACCESS)
545 }
546
547 /// The same, with the alias options the command line left and a budget of your own.
548 #[must_use]
549 pub fn with(func: &'a Func, outside: &'a Outside, options: Options, limit: u32) -> Self {
550 Self {
551 func,
552 cfg: Cfg::new(func),
553 alias: Alias::with(func, outside, options),
554 limit,
555 counts: Counts::default(),
556 }
557 }
558
559 /// What the walks have cost so far.
560 #[must_use]
561 pub const fn counts(&self) -> &Counts {
562 &self.counts
563 }
564
565 /// The same walk, with what the module's functions were worked out to do to memory.
566 ///
567 /// Handed straight to the oracle underneath, where [`Alias::knowing`] says what it is for.
568 #[must_use]
569 pub fn knowing(mut self, summaries: &'a crate::modref::Summaries) -> Self {
570 self.alias = self.alias.knowing(summaries);
571 self
572 }
573
574 /// The alias analysis underneath, whose own counters say which layer answered.
575 #[must_use]
576 pub const fn alias(&self) -> &Alias<'a> {
577 &self.alias
578 }
579
580 /// The store this load sees.
581 ///
582 /// [`Clobber::Unknown`] for an instruction that reads nothing, for one that is not on the
583 /// chain, and for a walk that ran out of budget, because all three mean the same thing to a
584 /// caller, which is that nothing was established.
585 pub fn clobber(&mut self, load: Inst) -> Clobber {
586 self.clobber_with(load, &mut |_, _| Step::Stop)
587 }
588
589 /// The same, with the chance to rewrite the reference at every def the walk cannot see past.
590 ///
591 /// Section 9.2's `translate`. The callback is handed the reference as it stands and the def
592 /// in the way, and answers [`Step::Stop`] to take the clobber or [`Step::Retry`] to carry on
593 /// past it asking about something else. Following a load through a `memcpy` by rewriting the
594 /// reference to the copy's source is the case worth having it for, since that is what a
595 /// struct assignment lowers to.
596 ///
597 /// Section 9.6 calls a `translate` that rewrites the reference wrongly the subtlest bug in
598 /// the document and essentially untestable by unit test, so the defence is differential
599 /// execution per document 41 rather than anything here.
600 pub fn clobber_with(
601 &mut self,
602 load: Inst,
603 translate: &mut dyn FnMut(&Access, Inst) -> Step,
604 ) -> Clobber {
605 let (Some(reference), Some(version)) = (self.alias.reads(load), self.func.mem_in(load))
606 else {
607 return Clobber::Unknown;
608 };
609 self.counts.walks += 1;
610 let mut budget = self.limit;
611 let mut seen = HashSet::new();
612 let answer = self.back(reference, version, &mut budget, &mut seen, translate);
613 // Nothing new on any path back is nothing that wrote it, which is the same answer as
614 // reaching the start of the chain and is only reachable through a cycle of parameters.
615 answer.unwrap_or(Clobber::NoClobber)
616 }
617
618 /// One version of memory, and everything that reaches it.
619 ///
620 /// `None` means this version has already been accounted for on another path, which is the
621 /// neutral answer: it is how a loop is cut, since the back edge of a loop whose body writes
622 /// nothing relevant leads back to the parameter the walk started from.
623 fn back(
624 &mut self,
625 reference: Access,
626 version: Value,
627 budget: &mut u32,
628 seen: &mut HashSet<Value>,
629 translate: &mut dyn FnMut(&Access, Inst) -> Step,
630 ) -> Option<Clobber> {
631 if !seen.insert(version) {
632 return None;
633 }
634 match self.func[version].def {
635 // A memory phi. The answer is the same down every path into the block or it is not
636 // an answer, which is conservative and is what keeps a caller from acting on a store
637 // that only one predecessor made.
638 Def::Param { block, index } => {
639 let mut answer = None;
640 for pred in self.cfg.predecessors(block).to_vec() {
641 let Some(terminator) = self.func.terminator(pred) else {
642 continue;
643 };
644 for call in self.func.successors(terminator).collect::<Vec<_>>() {
645 if call.block != block {
646 continue;
647 }
648 let Some(&incoming) = self.func[call.args].get(index as usize) else {
649 continue;
650 };
651 let one = self.back(reference, incoming, budget, seen, translate);
652 answer = combine(answer, one);
653 if answer == Some(Clobber::Unknown) {
654 return answer;
655 }
656 }
657 }
658 answer
659 }
660 Def::Result { inst, .. } => {
661 if self.func[inst].opcode == Opcode::MemEntry {
662 return Some(Clobber::NoClobber);
663 }
664 if *budget == 0 {
665 self.counts.exhausted += 1;
666 return Some(Clobber::Unknown);
667 }
668 *budget -= 1;
669 self.counts.steps += 1;
670 let past = match self.wrote(&reference, inst) {
671 None => reference,
672 Some(answer) => match translate(&reference, inst) {
673 Step::Stop => return Some(answer),
674 // A rewritten question is a walk of its own and gets a visited set of its
675 // own. The set is there to stop a cycle being walked twice, and what makes
676 // the second time round pointless is that the answer at a version is an
677 // answer about one reference: a version this walk has already been to was
678 // visited asking something else, and what it said then says nothing about
679 // what is being asked now. Carrying the set across the rewrite loses an
680 // answer rather than repeating one, because a version declined as already
681 // seen contributes nothing to the join above it, and a join whose two paths
682 // disagree would come back holding whichever of them was walked first
683 // rather than `Unknown`.
684 Step::Retry(next) => {
685 self.counts.rewritten += 1;
686 let before = self.func.mem_in(inst)?;
687 let mut fresh = HashSet::new();
688 return self.back(next, before, budget, &mut fresh, translate);
689 }
690 },
691 };
692 let next = self.func.mem_in(inst)?;
693 self.back(past, next, budget, seen, translate)
694 }
695 }
696 }
697
698 /// Whether this def wrote the reference, and how much of it.
699 ///
700 /// `None` is the answer that lets the walk carry on, and it is only given where the alias
701 /// analysis said the two cannot touch the same byte.
702 fn wrote(&mut self, reference: &Access, inst: Inst) -> Option<Clobber> {
703 // Section 9.5, and it is first. Alias analysis says nothing about how many times an
704 // access happens and `volatile` constrains that too, so this is a separate bit rather
705 // than a strong alias fact, and it is checked before the analysis is asked anything.
706 if reference.volatile || self.func[inst].flags.contains(Flags::VOLATILE) {
707 return Some(Clobber::Maybe(inst));
708 }
709 // Every atomic and every fence is a full def and a full use. Pessimistic for lock-free
710 // code and correct, and section 9.5 says doing better means modelling the memory model
711 // rather than the memory, which is post-1.0.
712 if self.ordered(inst) {
713 return Some(Clobber::Maybe(inst));
714 }
715 if let Some(write) = self.alias.writes(inst) {
716 return match self.alias.query(reference, &write) {
717 Answer::No(_) => None,
718 Answer::May => Some(self.extent(reference, &write, inst)),
719 };
720 }
721 // A call, or anything else that writes memory without an access saying what. What a call
722 // touches is its attributes and the escape analysis, which is section 8.4's, and without
723 // those the honest answer is that it wrote everything.
724 match self.alias.clobbered_by(reference, inst) {
725 Answer::No(_) => None,
726 Answer::May => Some(Clobber::Maybe(inst)),
727 }
728 }
729
730 /// How much of the reference a write that may touch it covered.
731 ///
732 /// Two accesses to the same origin with both offsets and both sizes known are two runs of
733 /// bytes at known places, and comparing them is what tells `Exact` from `Partial`. Anything
734 /// less is `Maybe`, since a `May` from the alias analysis is not a proof that anything was
735 /// written at all.
736 ///
737 /// `Exact` is the same bytes and not merely a superset of them. A four byte store and the
738 /// one byte load at offset one inside it is `Partial`, because the byte the load wants is
739 /// somewhere in the value the store wrote and getting it out is a shift and a truncate that
740 /// document 16 decides on rather than this. Two runs that are the same bytes can still be
741 /// two different types, and checking that is the caller's as well.
742 fn extent(&self, reference: &Access, write: &Access, inst: Inst) -> Clobber {
743 if reference.origin != write.origin {
744 return Clobber::Maybe(inst);
745 }
746 let (Some(want), Some(wrote)) = (reference.range(), write.range()) else {
747 return Clobber::Maybe(inst);
748 };
749 if want == wrote {
750 Clobber::Exact(inst)
751 } else if wrote.0 < want.1 && want.0 < wrote.1 {
752 Clobber::Partial(inst)
753 } else {
754 // No overlap at all, which the alias analysis should have said no to. Saying `Maybe`
755 // rather than walking past is the conservative reading of a disagreement.
756 Clobber::Maybe(inst)
757 }
758 }
759
760 /// Whether the instruction orders memory, which is every atomic and every fence.
761 fn ordered(&self, inst: Inst) -> bool {
762 use rucc_ir::Extra;
763 let order = match self.func[inst].extra {
764 Extra::Mem(at) => self.func[at].order,
765 Extra::Rmw(_, at) => self.func[at].order,
766 Extra::Order(order) => order,
767 _ => return false,
768 };
769 order != MemOrder::NotAtomic
770 }
771}
772
773/// Two answers from two paths into a join.
774///
775/// The same answer on both is the answer. Nothing on one path is whatever the other said, which
776/// is how a cycle contributes nothing. Anything else is a disagreement, and a disagreement is
777/// `Unknown` rather than the weaker of the two, because there is no order on these that a caller
778/// could act on.
779fn combine(a: Option<Clobber>, b: Option<Clobber>) -> Option<Clobber> {
780 match (a, b) {
781 (None, other) | (other, None) => other,
782 (Some(one), Some(other)) if one == other => Some(one),
783 _ => Some(Clobber::Unknown),
784 }
785}
786
787#[cfg(test)]
788mod tests {
789 use rucc_base::Interner;
790 use rucc_ir::{Builder, MemInfo, Module, Restrict, Signature, parse, verify_func};
791
792 use super::*;
793
794 /// A module and a function built from the text, which is how these are written.
795 fn read(text: &str) -> (Module, Interner) {
796 let mut names = Interner::new();
797 let module = parse(text, &mut names).expect("the text parses");
798 (module, names)
799 }
800
801 const HEADER: &str = "\
802; ModuleID = 'mem.c'
803; format 0
804target triple = \"x86_64-unknown-linux-gnu\"
805target datalayout = \"e-p:64:64-i64:64-f80:128-S128\"
806";
807
808 fn wrap(signature: &str, body: &str) -> String {
809 format!("{HEADER}\nfunc @f{signature}, linkage(external) {{\n{body}}}\n")
810 }
811
812 /// Builds memory SSA over the function and insists the result verifies, which is where most
813 /// of the strength of these tests is: the rules in the verifier are the specification of the
814 /// chain and construction has to satisfy all of them.
815 fn built(text: &str) -> (Module, bool) {
816 let (mut module, names) = read(text);
817 let id = module.funcs().next().expect("one function");
818 let changed = build(&mut module[id]);
819 if let Err(errors) = verify_func(&module, &module[id], &names) {
820 panic!("{errors:#?}");
821 }
822 (module, changed)
823 }
824
825 fn one(module: &Module) -> &Func {
826 &module[module.funcs().next().expect("one function")]
827 }
828
829 /// The instruction with that opcode, counting from the top of the function.
830 fn nth(func: &Func, opcode: Opcode, want: usize) -> Inst {
831 func.blocks()
832 .flat_map(|block| func.insts(block).collect::<Vec<_>>())
833 .filter(|&inst| func[inst].opcode == opcode)
834 .nth(want)
835 .expect("that many of them")
836 }
837
838 #[test]
839 fn a_function_with_no_memory_in_it_gets_no_chain() {
840 let text = wrap(
841 "(i32) -> i32",
842 "block0(%0: i32):
843 %1 = add %0, %0
844 return %1
845",
846 );
847 let (module, changed) = built(&text);
848 assert!(!changed);
849 assert_eq!(one(&module).blocks().count(), 1);
850 }
851
852 #[test]
853 fn a_straight_line_is_threaded_in_order() {
854 let text = wrap(
855 "(ptr) -> i32",
856 "block0(%0: ptr):
857 %1 = iconst.i32 7
858 store %1 -> %0, align 4
859 %2 = load.i32 %0, align 4
860 return %2
861",
862 );
863 let (module, changed) = built(&text);
864 assert!(changed);
865 let func = one(&module);
866 let start = nth(func, Opcode::MemEntry, 0);
867 let store = nth(func, Opcode::Store, 0);
868 let load = nth(func, Opcode::Load, 0);
869 assert_eq!(func.mem_in(store), func.mem_out(start));
870 assert_eq!(func.mem_in(load), func.mem_out(store));
871 assert_eq!(func.mem_out(load), None);
872 }
873
874 #[test]
875 fn a_join_gets_a_memory_parameter_and_every_branch_passes_one() {
876 let text = wrap(
877 "(ptr, i1) -> i32",
878 "block0(%0: ptr, %1: i1):
879 br_if %1, block1, block2
880
881block1:
882 %2 = iconst.i32 7
883 store %2 -> %0, align 4
884 jump block3
885
886block2:
887 jump block3
888
889block3:
890 %3 = load.i32 %0, align 4
891 return %3
892",
893 );
894 let (module, _) = built(&text);
895 let func = one(&module);
896 let join = func.blocks().nth(3).expect("four blocks");
897 assert_eq!(func[join].params.len(), 1);
898 let param = func[join].params[0];
899 assert!(func[param].ty.is_mem());
900 assert_eq!(func.mem_in(nth(func, Opcode::Load, 0)), Some(param));
901 }
902
903 #[test]
904 fn a_block_that_only_reads_needs_no_parameter() {
905 let text = wrap(
906 "(ptr, i1) -> i32",
907 "block0(%0: ptr, %1: i1):
908 br_if %1, block1, block2
909
910block1:
911 %2 = load.i32 %0, align 4
912 jump block3
913
914block2:
915 jump block3
916
917block3:
918 %3 = load.i32 %0, align 4
919 return %3
920",
921 );
922 let (module, _) = built(&text);
923 let func = one(&module);
924 // One version of memory reaches the whole function, so no join needs a parameter and
925 // every load reads what `mem_entry` produced.
926 for block in func.blocks() {
927 assert!(func[block].params.iter().all(|¶m| !func[param].ty.is_mem()));
928 }
929 }
930
931 #[test]
932 fn every_arm_of_a_switch_passes_its_own_version_along() {
933 let text = wrap(
934 "(ptr, i32) -> i32",
935 "block0(%0: ptr, %1: i32):
936 switch %1, block1, [0 => block2, 1 => block3]
937
938block1:
939 %2 = iconst.i32 1
940 store %2 -> %0, align 4
941 jump block4
942
943block2:
944 %3 = iconst.i32 2
945 store %3 -> %0, align 4
946 jump block4
947
948block3:
949 jump block4
950
951block4:
952 %4 = load.i32 %0, align 4
953 return %4
954",
955 );
956 let (module, _) = built(&text);
957 let func = one(&module);
958 let join = func.blocks().nth(4).expect("five blocks");
959 let param = *func[join].params.last().expect("a parameter");
960 assert!(func[param].ty.is_mem());
961 // Each arm reaches the join with the version it ended on, and the two that wrote reach
962 // it with the version their own store produced.
963 for (arm, want) in [(1, Some(0)), (2, Some(1)), (3, None)] {
964 let block = func.blocks().nth(arm).expect("that block");
965 let jump = func.terminator(block).expect("a terminator");
966 let call = func.successors(jump).next().expect("one target");
967 let sent = *func[call.args].last().expect("an argument");
968 let expect = match want {
969 Some(store) => func.mem_out(nth(func, Opcode::Store, store)),
970 None => func.mem_out(nth(func, Opcode::MemEntry, 0)),
971 };
972 assert_eq!(Some(sent), expect, "arm {arm} passed the wrong version");
973 }
974 }
975
976 #[test]
977 fn a_function_with_a_block_nothing_reaches_is_left_alone() {
978 let text = wrap(
979 "(ptr) -> i32",
980 "block0(%0: ptr):
981 %1 = iconst.i32 7
982 store %1 -> %0, align 4
983 jump block2
984
985block1:
986 %2 = iconst.i32 9
987 store %2 -> %0, align 4
988 jump block2
989
990block2:
991 %3 = load.i32 %0, align 4
992 return %3
993",
994 );
995 // Block 1 has no predecessor. Half a function on the chain is worse than none of it, so
996 // this declines rather than producing something the verifier would turn down.
997 let (mut module, _) = read(&text);
998 let id = module.funcs().next().expect("one function");
999 assert!(!build(&mut module[id]));
1000 assert_eq!(module[id].blocks().filter(|&b| !module[id][b].params.is_empty()).count(), 1);
1001 }
1002
1003 /// The last load in the function, which is the one every walk here starts from.
1004 fn last_load(func: &Func) -> Inst {
1005 func.blocks()
1006 .flat_map(|block| func.insts(block).collect::<Vec<_>>())
1007 .filter(|&inst| func[inst].opcode == Opcode::Load)
1008 .last()
1009 .expect("a load")
1010 }
1011
1012 /// A load, a store and the walk between them, over a function written as text.
1013 fn walked(text: &str) -> (Clobber, Counts) {
1014 let (module, changed) = built(text);
1015 assert!(changed, "the function has memory in it");
1016 let func = one(&module);
1017 let outside = Outside::of(&module);
1018 let mut walk = Walk::new(func, &outside);
1019 let answer = walk.clobber(last_load(func));
1020 (answer, *walk.counts())
1021 }
1022
1023 #[test]
1024 fn a_load_sees_the_store_before_it() {
1025 let text = wrap(
1026 "(ptr) -> i32",
1027 "block0(%0: ptr):
1028 %1 = iconst.i32 7
1029 store %1 -> %0, align 4
1030 %2 = load.i32 %0, align 4
1031 return %2
1032",
1033 );
1034 let (answer, counts) = walked(&text);
1035 assert!(matches!(answer, Clobber::Exact(_)));
1036 assert_eq!(counts.walks(), 1);
1037 assert_eq!(counts.steps(), 1);
1038 assert_eq!(counts.exhausted(), 0);
1039 }
1040
1041 #[test]
1042 fn a_load_walks_past_a_store_to_another_object() {
1043 let text = wrap(
1044 "() -> i32",
1045 "block0:
1046 %0 = alloca, size 8, align 8
1047 %1 = alloca, size 8, align 8
1048 %2 = iconst.i32 7
1049 store %2 -> %0, align 4
1050 %3 = load.i32 %1, align 4
1051 return %3
1052",
1053 );
1054 let (answer, counts) = walked(&text);
1055 assert_eq!(answer, Clobber::NoClobber);
1056 // It looked at the store, said no, and reached the start of the chain.
1057 assert_eq!(counts.steps(), 1);
1058 }
1059
1060 #[test]
1061 fn a_load_of_one_byte_of_a_wider_store_is_partial() {
1062 let text = wrap(
1063 "() -> i8",
1064 "block0:
1065 %0 = alloca, size 8, align 8
1066 %1 = iconst.i32 7
1067 store %1 -> %0, align 4
1068 %2 = iconst.i64 1
1069 %3 = ptr_add %0, %2
1070 %4 = load.i8 %3, align 1
1071 return %4
1072",
1073 );
1074 let (answer, _) = walked(&text);
1075 assert!(matches!(answer, Clobber::Partial(_)), "{answer:?}");
1076 }
1077
1078 #[test]
1079 fn a_load_after_a_call_that_cannot_reach_it_walks_past_the_call() {
1080 let text = wrap(
1081 "() -> i32",
1082 "block0:
1083 %0 = alloca, size 8, align 8
1084 %1 = iconst.i32 7
1085 store %1 -> %0, align 4
1086 call @g() : ()
1087 %2 = load.i32 %0, align 4
1088 return %2
1089",
1090 );
1091 // The local's address never leaves the function, so the call cannot touch it and the
1092 // walk goes straight past to the store. That is the escape layer paying for itself.
1093 let (answer, _) = walked(&text);
1094 assert!(matches!(answer, Clobber::Exact(_)), "{answer:?}");
1095 }
1096
1097 #[test]
1098 fn a_load_after_a_call_that_could_have_the_address_sees_the_call() {
1099 let text = wrap(
1100 "(ptr) -> i32",
1101 "block0(%0: ptr):
1102 %1 = iconst.i32 7
1103 store %1 -> %0, align 4
1104 call @g() : ()
1105 %2 = load.i32 %0, align 4
1106 return %2
1107",
1108 );
1109 let (answer, _) = walked(&text);
1110 assert!(matches!(answer, Clobber::Maybe(_)), "{answer:?}");
1111 }
1112
1113 #[test]
1114 fn a_load_after_an_atomic_store_sees_it_whatever_it_wrote() {
1115 let text = wrap(
1116 "() -> i32",
1117 "block0:
1118 %0 = alloca, size 8, align 8
1119 %1 = alloca, size 8, align 8
1120 %2 = iconst.i32 7
1121 atomic_store %2 -> %0, align 4, release
1122 %3 = load.i32 %1, align 4
1123 return %3
1124",
1125 );
1126 // Two different objects, and it still stops: an atomic is a full def and a full use, per
1127 // section 9.5, and this is the test that says so rather than a comment.
1128 let (answer, _) = walked(&text);
1129 assert!(matches!(answer, Clobber::Maybe(_)), "{answer:?}");
1130 }
1131
1132 #[test]
1133 fn a_load_after_a_volatile_store_sees_it_whatever_it_wrote() {
1134 let text = wrap(
1135 "() -> i32",
1136 "block0:
1137 %0 = alloca, size 8, align 8
1138 %1 = alloca, size 8, align 8
1139 %2 = iconst.i32 7
1140 store.volatile %2 -> %0, align 4
1141 %3 = load.i32 %1, align 4
1142 return %3
1143",
1144 );
1145 let (answer, _) = walked(&text);
1146 assert!(matches!(answer, Clobber::Maybe(_)), "{answer:?}");
1147 }
1148
1149 #[test]
1150 fn paths_that_disagree_are_unknown_rather_than_the_weaker_of_the_two() {
1151 let text = wrap(
1152 "(i1) -> i32",
1153 "block0(%0: i1):
1154 %1 = alloca, size 8, align 8
1155 br_if %0, block1, block2
1156
1157block1:
1158 %2 = iconst.i32 7
1159 store %2 -> %1, align 4
1160 jump block3
1161
1162block2:
1163 jump block3
1164
1165block3:
1166 %3 = load.i32 %1, align 4
1167 return %3
1168",
1169 );
1170 let (answer, _) = walked(&text);
1171 assert_eq!(answer, Clobber::Unknown);
1172 }
1173
1174 #[test]
1175 fn a_loop_that_writes_nothing_relevant_walks_out_of_it() {
1176 let text = wrap(
1177 "(i32) -> i32",
1178 "block0(%0: i32):
1179 %1 = alloca, size 8, align 8
1180 %2 = alloca, size 8, align 8
1181 %3 = iconst.i32 7
1182 store %3 -> %1, align 4
1183 jump block1(%0)
1184
1185block1(%4: i32):
1186 %5 = iconst.i32 1
1187 %6 = sub %4, %5
1188 store %5 -> %2, align 4
1189 %7 = icmp sgt %6, %5
1190 br_if %7, block1(%6), block2
1191
1192block2:
1193 %8 = load.i32 %1, align 4
1194 return %8
1195",
1196 );
1197 // The store in the loop is to the other object, so the walk goes round the back edge,
1198 // meets the parameter it started from, contributes nothing, and takes the answer from
1199 // the path that leaves the loop.
1200 let (answer, counts) = walked(&text);
1201 assert!(matches!(answer, Clobber::Exact(_)), "{answer:?}");
1202 assert_eq!(counts.exhausted(), 0);
1203 }
1204
1205 #[test]
1206 fn a_budget_of_nothing_gives_unknown_and_says_so() {
1207 let text = wrap(
1208 "(ptr) -> i32",
1209 "block0(%0: ptr):
1210 %1 = iconst.i32 7
1211 store %1 -> %0, align 4
1212 %2 = load.i32 %0, align 4
1213 return %2
1214",
1215 );
1216 let (module, _) = built(&text);
1217 let func = one(&module);
1218 let load = nth(func, Opcode::Load, 0);
1219 let outside = Outside::of(&module);
1220 let mut walk = Walk::with(func, &outside, Options::default(), 0);
1221 assert_eq!(walk.clobber(load), Clobber::Unknown);
1222 assert_eq!(walk.counts().exhausted(), 1);
1223 }
1224
1225 #[test]
1226 fn translate_carries_the_walk_past_a_def_it_would_have_stopped_at() {
1227 let text = wrap(
1228 "(ptr) -> i32",
1229 "block0(%0: ptr):
1230 %1 = iconst.i32 7
1231 store %1 -> %0, align 4
1232 memcpy %0, %0, size 4, align 4
1233 %2 = load.i32 %0, align 4
1234 return %2
1235",
1236 );
1237 let (module, _) = built(&text);
1238 let func = one(&module);
1239 let load = nth(func, Opcode::Load, 0);
1240
1241 // With no rewrite to offer, the copy is where it stops.
1242 let outside = Outside::of(&module);
1243 let mut walk = Walk::new(func, &outside);
1244 let stopped_at = walk.clobber(load).inst().expect("something wrote it");
1245 assert_eq!(func[stopped_at].opcode, Opcode::Memcpy);
1246
1247 // The same walk, with a caller that can see through the copy. It says nothing about the
1248 // reference here, which is enough to show the callback is reached and obeyed.
1249 let mut walk = Walk::new(func, &outside);
1250 let mut seen = Vec::new();
1251 let answer = walk.clobber_with(load, &mut |reference, inst| {
1252 seen.push(func[inst].opcode);
1253 if func[inst].opcode == Opcode::Memcpy { Step::Retry(*reference) } else { Step::Stop }
1254 });
1255 assert_eq!(seen, [Opcode::Memcpy, Opcode::Store]);
1256 assert_eq!(answer.inst().map(|inst| func[inst].opcode), Some(Opcode::Store));
1257
1258 // One rewrite offered and one taken, which is the counter a caller reads to find out
1259 // whether its callback reached anything.
1260 assert_eq!(walk.counts().rewritten(), 1);
1261 }
1262
1263 #[test]
1264 fn building_twice_changes_nothing_the_second_time() {
1265 let text = wrap(
1266 "(ptr) -> i32",
1267 "block0(%0: ptr):
1268 %1 = load.i32 %0, align 4
1269 return %1
1270",
1271 );
1272 let (mut module, _) = read(&text);
1273 let id = module.funcs().next().expect("one function");
1274 let func = &mut module[id];
1275 assert!(build(func));
1276 let before = func.counts().insts;
1277 assert!(!build(func));
1278 assert_eq!(func.counts().insts, before);
1279 }
1280
1281 /// The builder path rather than the parser path, since a pass that adds a store adds it with
1282 /// the builder and the chain has to survive that too.
1283 #[test]
1284 fn a_function_built_by_hand_threads_the_same_way() {
1285 let mut names = Interner::new();
1286 let i32_ = Type::int(32);
1287 let mut func = Func::new(
1288 names.intern("f"),
1289 Signature::new().with_params(&[Type::PTR]).with_returns(&[i32_]),
1290 );
1291 let entry = func.create_block();
1292 let addr = func.append_param(entry, Type::PTR);
1293 let info = MemInfo {
1294 size: 4,
1295 align: 4,
1296 order: MemOrder::NotAtomic,
1297 tbaa: None,
1298 owns: 0,
1299 restrict: Restrict::NONE,
1300 };
1301 let mut b = Builder::new(&mut func, entry);
1302 let seven = b.iconst(i32_, 7);
1303 b.store(seven, addr, info, Flags::NONE);
1304 let read = b.load(i32_, addr, info, Flags::NONE);
1305 b.ret(&[read]);
1306
1307 assert!(build(&mut func));
1308 let store = nth(&func, Opcode::Store, 0);
1309 let load = nth(&func, Opcode::Load, 0);
1310 assert_eq!(func.mem_in(load), func.mem_out(store));
1311 }
1312
1313 /// Builds the chain, takes it back off, and insists the result verifies both times. A half
1314 /// removed chain is exactly the kind of thing that would pass a shape assertion and fail on a
1315 /// real file, so the verifier is the assertion that matters here too.
1316 fn stripped(text: &str) -> (Module, bool) {
1317 let (mut module, names) = read(text);
1318 let id = module.funcs().next().expect("one function");
1319 build(&mut module[id]);
1320 if let Err(errors) = verify_func(&module, &module[id], &names) {
1321 panic!("after building: {errors:#?}");
1322 }
1323 let changed = strip(&mut module[id]);
1324 if let Err(errors) = verify_func(&module, &module[id], &names) {
1325 panic!("after stripping: {errors:#?}");
1326 }
1327 (module, changed)
1328 }
1329
1330 /// Nothing anywhere in the function is on the chain any more.
1331 fn off(func: &Func) {
1332 for block in func.blocks() {
1333 assert!(
1334 func[block].params.iter().all(|¶m| !func[param].ty.is_mem()),
1335 "a block kept a memory parameter"
1336 );
1337 for inst in func.insts(block) {
1338 assert_ne!(
1339 func[inst].opcode,
1340 Opcode::MemEntry,
1341 "the start of the chain is still here"
1342 );
1343 assert!(!func.carries_mem(inst), "an instruction is still on the chain");
1344 }
1345 }
1346 }
1347
1348 #[test]
1349 fn a_straight_line_comes_off_the_chain_the_way_it_went_on() {
1350 let text = wrap(
1351 "(ptr) -> i32",
1352 "block0(%0: ptr):
1353 %1 = iconst.i32 7
1354 store %1 -> %0, align 4
1355 %2 = load.i32 %0, align 4
1356 return %2
1357",
1358 );
1359 let (module, changed) = stripped(&text);
1360 assert!(changed);
1361 let func = one(&module);
1362 off(func);
1363 // The instructions are the same ones doing the same thing, which is the whole claim: the
1364 // address the load reads is still the function's parameter and the value returned is
1365 // still what the load read.
1366 let load = nth(func, Opcode::Load, 0);
1367 let param = func[func.entry().expect("an entry")].params[0];
1368 assert_eq!(func[func[load].args][0], param);
1369 let ret = nth(func, Opcode::Return, 0);
1370 assert_eq!(func[func[ret].args][0], func[load].results().next().expect("a result"));
1371 }
1372
1373 #[test]
1374 fn a_join_gives_its_memory_parameter_back_and_so_does_every_branch_to_it() {
1375 let text = wrap(
1376 "(ptr, i1) -> i32",
1377 "block0(%0: ptr, %1: i1):
1378 br_if %1, block1, block2
1379
1380block1:
1381 %2 = iconst.i32 7
1382 store %2 -> %0, align 4
1383 jump block3
1384
1385block2:
1386 jump block3
1387
1388block3:
1389 %3 = load.i32 %0, align 4
1390 return %3
1391",
1392 );
1393 let (module, changed) = stripped(&text);
1394 assert!(changed);
1395 let func = one(&module);
1396 off(func);
1397 let join = func.blocks().nth(3).expect("four blocks");
1398 assert!(func[join].params.is_empty(), "the join kept a parameter");
1399 for block in func.blocks() {
1400 let Some(terminator) = func.terminator(block) else { continue };
1401 for call in func.successors(terminator) {
1402 assert!(func[call.args].is_empty(), "a branch kept an argument");
1403 }
1404 }
1405 }
1406
1407 #[test]
1408 fn a_parameter_that_was_never_memory_keeps_its_place() {
1409 // The argument a branch passes goes by position, so a block with a memory parameter
1410 // beside an ordinary one is where taking the wrong one out would show.
1411 let text = wrap(
1412 "(ptr, i1) -> i32",
1413 "block0(%0: ptr, %1: i1):
1414 %2 = iconst.i32 7
1415 br_if %1, block1(%2), block2
1416
1417block1(%3: i32):
1418 store %3 -> %0, align 4
1419 jump block3
1420
1421block2:
1422 jump block3
1423
1424block3:
1425 %4 = load.i32 %0, align 4
1426 return %4
1427",
1428 );
1429 let (module, _) = stripped(&text);
1430 let func = one(&module);
1431 off(func);
1432 let arm = func.blocks().nth(1).expect("four blocks");
1433 assert_eq!(func[arm].params.len(), 1);
1434 let param = func[arm].params[0];
1435 assert_eq!(func[param].ty, Type::int(32));
1436 let store = nth(func, Opcode::Store, 0);
1437 assert_eq!(func[func[store].args][0], param, "the store lost the value it writes");
1438 }
1439
1440 #[test]
1441 fn a_function_that_was_never_on_the_chain_is_left_alone() {
1442 let text = wrap(
1443 "(i32) -> i32",
1444 "block0(%0: i32):
1445 %1 = add %0, %0
1446 return %1
1447",
1448 );
1449 let (mut module, names) = read(&text);
1450 let id = module.funcs().next().expect("one function");
1451 assert!(!strip(&mut module[id]));
1452 if let Err(errors) = verify_func(&module, &module[id], &names) {
1453 panic!("{errors:#?}");
1454 }
1455 }
1456
1457 #[test]
1458 fn a_call_that_returns_something_keeps_it() {
1459 // A call is threaded like a store and gives back a value as well, so its results are the
1460 // one place where the version of memory sits behind something that has a reader.
1461 let text = format!(
1462 "{HEADER}\nfunc @f() -> i32, linkage(external) {{\nblock0:\n %0 = call @g() : () -> \
1463 i32\n return %0\n}}\n"
1464 );
1465 let (module, changed) = stripped(&text);
1466 assert!(changed);
1467 let func = one(&module);
1468 off(func);
1469 let call = nth(func, Opcode::Call, 0);
1470 let ret = nth(func, Opcode::Return, 0);
1471 assert_eq!(func[call].results().count(), 1);
1472 assert_eq!(func[func[ret].args][0], func[call].results().next().expect("a result"));
1473 }
1474}