rucc_codegen/fold.rs
1//! Folding an address computation into the memory operand of whatever reads it.
2//!
3//! Design: `spec/10-backend.md` section 10.9, and `spec/optimizer/37-machine-level-optimization.md`
4//! section 37.4.
5//!
6//! The selector matches one instruction at a time and offers it its operands' operands, which is
7//! two levels of term and is exactly what an address needs to become a `lea`: `a + i * 4` is an
8//! add at the root with a multiply under it. Put that same address under a load and everything
9//! moves down a level, the multiply is at level two, and no plan the selector has reaches it. So
10//! an array read comes out of selection as two instructions, the `lea` that works the address out
11//! and the `mov` that reads through it, and the second one's addressing mode holds nothing but a
12//! base.
13//!
14//! Which is a pair a peephole can see. When an instruction reads the register a `lea` wrote as the
15//! base of its memory operand, the two addresses compose: the reader's displacement is a constant
16//! added to an address the `lea` already worked out, so adding the two displacements together gives
17//! the address the reader wanted in the mode the `lea` was using.
18//!
19//! The question is asked of the readers together rather than one at a time, which is what section
20//! 37.4 says the pass is really for. One address read at several offsets is what a structure
21//! written field by field comes out as, and what a loop the unroller took apart comes out as, and
22//! in neither of those does any one reader own the address. If every reader can take it then
23//! nothing reads the `lea` any more and it goes, and the arithmetic moved into addressing modes
24//! that were doing an addition anyway. If one reader cannot, folding into the rest buys nothing:
25//! the `lea` stays where it is for the one that refused, the address is worked out twice rather
26//! than once, and the registers it reads are now live across every reader as well. So it is all of
27//! them or none of them, and that is a property of the set rather than of a pair.
28//!
29//! # What it will not do
30//!
31//! A set with a reader in it that cannot take the address. Each of the refusals below is one
32//! reader's, and any one of them turns down the whole set it belongs to.
33//!
34//! An address relative to a symbol, with more than one reader. A reader that reads through a
35//! register has room in it for a register and a displacement, and an address made of registers and
36//! a displacement goes into that room whoever takes it. A symbol does not: the reader has to name
37//! the symbol, which is a whole address word rather than a register number, so each reader that
38//! takes one grows by the difference and several readers pay it several times while the `lea` is
39//! saved once. Taking those as well loses 2643 bytes over the corpus at -O2 and gains 386, and the
40//! loss is almost all soft float and bit counting expansions, which read one global thirty or
41//! forty times each. One reader keeps the old answer, since there the address word is written once
42//! either way and what goes is the whole `lea`.
43//!
44//! Two indexes. The reader having an index of its own means the composed address wants two scaled
45//! registers and this machine, like every machine, has one. Nothing looks for a way to put them
46//! together because there is not one.
47//!
48//! A displacement that does not fit. The two are added as `i64` and the answer has to be an `i32`,
49//! which is what the field holds. It is not a case that comes up in a program anybody wrote, and
50//! the check is there because the alternative to checking is wrapping.
51//!
52//! A reader in another block. Folding moves the work from where the `lea` is to where the reader
53//! is, and across a block boundary that can mean moving it into a loop. The same rule and the same
54//! reason as `crate::lower::Lowering::foldable`, which is the selector's version of this question.
55//!
56//! A register that something writes between the address and the last of its readers. Machine IR is
57//! in SSA form until the allocator has run, so a virtual register cannot be, but a physical one
58//! can: the frame pointer and the stack pointer are already physical here, and a call in between
59//! writes every register it is allowed to. Rather than ask which registers are the exceptions, the
60//! walk below drops a candidate the moment anything writes a register its address reads. The last
61//! reader rather than the first is what makes this the set's question too, since a write after the
62//! first reader and before the second is a write the one at a time version would never have seen.
63//!
64//! # The addresses into the frame
65//!
66//! A local's place in the frame and an argument's place in the caller's area is a distance from the
67//! stack pointer, and there is no frame until the allocator has finished, so [`crate::lower`]
68//! leaves those instructions with a zero in the displacement and [`crate::finish`] writes the
69//! number in later against a list of which instruction is which.
70//!
71//! This used to refuse them for that reason, and refusing was expensive: it is the shape of every
72//! access to a local that has to go through its address, and of every argument that arrives in the
73//! caller's area. What it takes to fold one is that the entry moves. The instruction the list names
74//! goes away and the ones that took the
75//! address arrive, so [`Pending`] rewrites the list as the fold is applied, and `finish` adds the
76//! frame's offset to the displacement rather than assigning it, because the reader brought a
77//! displacement of its own and the field it is reading is some way past where the object starts.
78//! tamnd/rucc#784.
79//!
80//! What they do not get is the whole of the set rule above. An address into the frame is off the
81//! stack pointer and a memory operand based on the stack pointer needs an index byte on this
82//! machine whether or not anything is indexed, so a reader that takes one grows by more than a
83//! reader that takes an address in an ordinary register does. Past three of them the bytes the
84//! readers put on are more than the whole `lea` was, which is the same arithmetic as the symbol
85//! above and comes out at a different number. `FRAME_READERS` below has the measurement.
86//!
87//! # Where it runs
88//!
89//! After selection and before the allocator, which is the one window where both instructions
90//! exist and the registers are still virtual. Running it after allocation would work on the
91//! arithmetic and would be reading a register file where the reader's base may have been reused
92//! for something else in between.
93
94use std::collections::HashMap;
95
96use rucc_base::Interner;
97use rucc_mir as mir;
98use rucc_target::{FrameInsts, MachineInsts, Role};
99
100use crate::changes::{Changes, Plan, Reads};
101
102/// The addresses [`crate::finish`] has still to write a displacement into.
103///
104/// Three lists, because the frame holds three kinds of place this pass runs before the layout of:
105/// a local's address is an offset into this function's own objects, a stack argument's is an offset
106/// into the caller's area, and a variable length array's is an offset above wherever the stack
107/// pointer ended up. What they have in common is the shape, a `lea` off the stack pointer with the
108/// displacement left at zero, and what this type is for is that folding one of those away has to
109/// move the entry rather than lose it.
110///
111/// This used to be a set of instructions the pass refused to touch, and refusing was expensive.
112/// Every access to a local through its address was a `lea` and then a memory instruction reading
113/// through the register it wrote, which is one instruction more than it needs, on the shape any
114/// function whose locals have their address taken is full of. tamnd/rucc#784.
115#[derive(Debug)]
116pub struct Pending<'a> {
117 /// Which instruction carries the address of which of this function's stack objects.
118 pub addresses: &'a mut Vec<(mir::Inst, usize)>,
119 /// Which instruction reads which of the arguments the caller passed on the stack.
120 pub arguments: &'a mut Vec<(mir::Inst, u32)>,
121 /// Which instructions carry the address of a local whose size the program worked out.
122 ///
123 /// There is no number beside one of these, because where a variable length array starts is not
124 /// a place the frame layout hands back: the bytes are already off the stack pointer by the time
125 /// the address is taken, so what gets written in is how much of the bottom of the frame the
126 /// arguments of a call keep, which is the same for all of them.
127 pub dynamic: &'a mut Vec<mir::Inst>,
128}
129
130impl Pending<'_> {
131 /// Moves an entry from an address that has gone to the instructions that took it.
132 ///
133 /// One entry becomes as many as there were readers, because an address every reader has room
134 /// for is handed to all of them, and each of those now carries a displacement of its own that
135 /// the frame layout has still to be added to.
136 ///
137 /// An address on any of the lists reads the stack pointer and nothing else, so it never reads a
138 /// register another one of them wrote, which is what makes it impossible for a reader to end up
139 /// on a list twice and be given two offsets.
140 pub(crate) fn moved(&mut self, from: mir::Inst, into: &[mir::Inst]) {
141 move_entries(self.addresses, from, into);
142 move_entries(self.arguments, from, into);
143 if let Some(at) = self.dynamic.iter().position(|&inst| inst == from) {
144 self.dynamic.splice(at..=at, into.iter().copied());
145 }
146 }
147
148 /// Whether this instruction is on one of the lists, which is how many readers it may go to.
149 fn holds(&self, inst: mir::Inst) -> bool {
150 let named = self.addresses.iter().map(|&(at, _)| at);
151 let listed = named.chain(self.arguments.iter().map(|&(at, _)| at));
152 listed.chain(self.dynamic.iter().copied()).any(|at| at == inst)
153 }
154}
155
156/// How many readers an address into the frame may be handed to.
157///
158/// There is a limit at all for the same reason a symbol has one, in the list above. An address into
159/// the frame is off the stack pointer, and a memory operand whose base is the stack pointer needs
160/// an index byte on this machine whether or not anything is indexed, so every reader that takes one
161/// grows by that byte and by the displacement while the `lea` is saved once. Reading through a
162/// register the `lea` wrote is three or four bytes and reading the same place off the stack pointer
163/// is five or eight, against the five or eight the `lea` itself costs, so the readers are ahead of
164/// it while there are few of them and behind it once there are enough.
165///
166/// Three is where they turn, measured. Over the 1838 corpus programs that come out of both
167/// compilers at `-O2`, one reader is 757 bytes better than folding none of them, two is 806, three
168/// is 868, four is 848 and five is 520. Handing them to every reader with room, which is what every
169/// other address gets, is 528 bytes worse than folding none: 97 programs larger by 1117 bytes
170/// against 100 smaller by 589. Up to three, only two programs anywhere in the corpus are larger at
171/// all, by two bytes each.
172///
173/// 690 of the 868 are the ten `long-double` programs, which is the shape this is about at its
174/// plainest. A `long double` argument arrives in the caller's area and the `fld` that reads it is
175/// its only reader, so the address goes and the read costs nothing more than it did.
176const FRAME_READERS: usize = 3;
177
178/// The half of [`Pending::moved`] that does not care what the entry says.
179fn move_entries<T: Copy>(list: &mut Vec<(mir::Inst, T)>, from: mir::Inst, into: &[mir::Inst]) {
180 let Some(at) = list.iter().position(|&(inst, _)| inst == from) else { return };
181 let (_, what) = list[at];
182 list.splice(at..=at, into.iter().map(|&inst| (inst, what)));
183}
184
185/// Folds every address computation that one memory operand reads, and gives back how many.
186///
187/// `pending` is the addresses [`crate::finish`] has still to write a displacement into, and folding
188/// one moves its entry to the instruction that took it. The displacement composed in by the fold
189/// stays where it is and the frame's offset is added to it later, which is why that write is an
190/// addition rather than an assignment.
191///
192/// Run after lowering and before allocation. Running it twice can find more than running it once.
193/// Folding a `lea` into a second `lea` leaves that second one foldable in turn, and the walk below
194/// takes those in the one pass since it goes forwards. What it does not take in the one pass is the
195/// other order, where the second `lea` has a reader of its own and goes before the first one's set
196/// is complete, and that is a set the next run finds whole.
197pub fn addresses(
198 func: &mut mir::Func,
199 insts: &FrameInsts,
200 machine: &MachineInsts,
201 names: &mut Interner,
202 pending: &mut Pending<'_>,
203) -> usize {
204 let lea = mir::Opcode::new(names.intern(&format!("{}{}", insts.prefix, insts.lea)));
205 let mut reads = Reads::of(func);
206 let mut folded = 0;
207 for block in func.blocks().collect::<Vec<_>>() {
208 // One `lea` per register it wrote, along with the folds its readers so far have agreed to.
209 // A register leaves the table the moment the set can no longer be all of them: anything
210 // writes what the address reads, or a reader turns up that cannot take it.
211 let mut open: HashMap<mir::Reg, Open> = HashMap::new();
212 for inst in func.insts(block).collect::<Vec<_>>() {
213 if let Some(ready) = offer(func, &mut open, inst) {
214 // The set is the whole of what this fold is: every reader takes the address and
215 // the address computation goes, and a set that is missing either half is one that
216 // works the address out twice. So it is proposed together and the target is asked
217 // about all of it at once.
218 let mut set = Changes::new();
219 for folding in &ready.folds {
220 let plan = Plan {
221 operands: folding.operands.clone(),
222 amode: Some(folding.amode),
223 ..Plan::of(func, folding.into)
224 };
225 set.rewrite(folding.into, plan);
226 }
227 set.remove(ready.from);
228 if set.commit(func, &mut reads, names, machine).is_ok() {
229 folded += ready.folds.len();
230 let took: Vec<mir::Inst> = ready.folds.iter().map(|fold| fold.into).collect();
231 pending.moved(ready.from, &took);
232 // Anything still open that was going to fold into the instruction just removed
233 // is holding a plan for an instruction that is not there any more. That is a
234 // chain whose middle went first, and the outer address waits for the next run
235 // of the pass rather than being written into a gap.
236 open.retain(|_, held| held.folds.iter().all(|fold| fold.into != ready.from));
237 }
238 }
239 for written in written(func, inst) {
240 open.retain(|reg, held| *reg != written && !touches(func, held.from, written));
241 }
242 if func[inst].opcode == lea {
243 let room = if pending.holds(inst) { FRAME_READERS } else { usize::MAX };
244 match folding_def(func, &reads, inst) {
245 Some((reg, wanted))
246 if wanted <= room && (wanted == 1 || fits_every_reader(func, inst)) =>
247 {
248 open.insert(reg, Open { from: inst, wanted, folds: Vec::new() });
249 }
250 _ => {}
251 }
252 }
253 }
254 }
255 folded
256}
257
258/// An address computation whose readers are still being counted.
259struct Open {
260 /// The address instruction, which goes once every one of its readers has taken it.
261 from: mir::Inst,
262 /// How many reads of the register it wrote there are in the whole function.
263 wanted: usize,
264 /// The folds agreed to so far, which are applied together or not at all.
265 folds: Vec<Folding>,
266}
267
268/// Offers an instruction the addresses that are open, and gives back the set that is now complete.
269///
270/// Every open register this instruction reads either takes the address into its own memory operand
271/// or ends the chance for the whole set. Reading it any other way is what makes it a reader nothing
272/// can fold into, and one of those is enough, so the register is dropped rather than the read being
273/// passed over. Reading it twice in the one instruction counts as that too, since only one of the
274/// two reads is the memory operand and the other would be left naming a register nothing writes.
275fn offer(func: &mir::Func, open: &mut HashMap<mir::Reg, Open>, inst: mir::Inst) -> Option<Open> {
276 let folding = candidate(func, open, inst);
277 let takes = |reg: mir::Reg| folding.as_ref().is_some_and(|fold| fold.base == reg);
278 let refused: Vec<mir::Reg> = open
279 .keys()
280 .copied()
281 .filter(|®| {
282 let times = times_read(func, inst, reg);
283 times > 0 && !(times == 1 && takes(reg))
284 })
285 .collect();
286 for reg in refused {
287 open.remove(®);
288 }
289 let folding = folding?;
290 let base = folding.base;
291 let held = open.get_mut(&base)?;
292 held.folds.push(folding);
293 if held.folds.len() < held.wanted {
294 return None;
295 }
296 open.remove(&base)
297}
298
299/// Whether an address is one every reader can carry in the room it already has, which is what
300/// makes handing it to more than one of them free.
301///
302/// A reader that reads an address through a register has room in it for a register and for a
303/// displacement, and an address made of registers and a displacement fits in exactly that room
304/// however many readers take it. An address relative to a symbol does not. The reader was naming a
305/// register and now has to name the symbol, which is a whole address word rather than a register
306/// number, so each reader that takes it grows by the difference and several readers pay it several
307/// times over while the `lea` is only saved once.
308///
309/// The measurement is what settled the size of that: folding symbol relative addresses into every
310/// reader as well loses 2643 bytes over the corpus at -O2 against 386 gained, and the 2643 is
311/// almost all soft float and bit counting expansions, which read one global thirty or forty times
312/// each and are the longest runs of straight line code in the corpus.
313///
314/// One reader is a different question and keeps the old answer, since there the address word is
315/// written once either way and what goes is the whole `lea`.
316fn fits_every_reader(func: &mir::Func, inst: mir::Inst) -> bool {
317 func[inst].mem.is_some_and(|mem| func[mem].symbol.is_none())
318}
319
320/// How many of an instruction's operands read that register.
321fn times_read(func: &mir::Func, inst: mir::Inst, reg: mir::Reg) -> usize {
322 func[func[inst].operands]
323 .iter()
324 .filter(|operand| operand.role == Role::Use && operand.reg == reg)
325 .count()
326}
327
328/// The one virtual register an instruction writes, and how many reads of it there are, when it
329/// writes exactly one and something reads it.
330///
331/// A `lea` is only worth folding when the instructions folding it are the whole of what reads the
332/// register, since folding does not delete the `lea` for anybody else and doing the address twice
333/// is not a saving. The count is what says when the set is complete, and it is taken over the whole
334/// function rather than over the block, so a read anywhere else is a set that never completes and
335/// an address that stays where it is.
336///
337/// A register nothing reads is left alone rather than folded into nothing, since an address whose
338/// answer is never wanted is dead code and belongs to the pass that removes dead code.
339fn folding_def(func: &mir::Func, reads: &Reads, inst: mir::Inst) -> Option<(mir::Reg, usize)> {
340 let operands = &func[func[inst].operands];
341 let mut defs = operands.iter().filter(|operand| operand.role != Role::Use);
342 let def = defs.next()?;
343 if defs.next().is_some() || !def.reg.is_virtual() {
344 return None;
345 }
346 let wanted = reads.count(def.reg);
347 (wanted > 0).then_some((def.reg, wanted))
348}
349
350/// The registers an instruction writes.
351fn written(func: &mir::Func, inst: mir::Inst) -> Vec<mir::Reg> {
352 func[func[inst].operands]
353 .iter()
354 .filter(|operand| operand.role != Role::Use)
355 .map(|operand| operand.reg)
356 .collect()
357}
358
359/// Whether an address computation reads that register, which is what makes writing it the end of
360/// the chance to fold it.
361fn touches(func: &mir::Func, inst: mir::Inst, reg: mir::Reg) -> bool {
362 let Some(mem) = func[inst].mem else { return false };
363 let amode = func[mem];
364 let operands = &func[func[inst].operands];
365 [amode.base, amode.index]
366 .into_iter()
367 .flatten()
368 .filter_map(|at| operands.get(usize::from(at)))
369 .any(|operand| operand.reg == reg)
370}
371
372/// The register an instruction's memory operand reads as its base, when that is the whole of what
373/// its memory operand is.
374///
375/// A symbol or an index means the two addresses do not compose, and this is where both are turned
376/// down, because the reader is the half of the pair with no room left in it.
377fn base_reg(func: &mir::Func, inst: mir::Inst) -> Option<mir::Reg> {
378 let amode = func[func[inst].mem?];
379 if amode.index.is_some() || amode.symbol.is_some() || amode.reach != mir::Reach::Itself {
380 return None;
381 }
382 Some(func[func[inst].operands].get(usize::from(amode.base?))?.reg)
383}
384
385/// A fold that has been checked and not yet done.
386///
387/// Everything the rewrite needs is worked out here rather than after the decision, so that the
388/// decision is the last thing that can go either way and the rewrite itself is three assignments
389/// that cannot fail.
390struct Folding {
391 /// The reader this rewrites, which is not always the instruction being looked at, since the
392 /// set is applied when its last reader arrives rather than as each one agrees.
393 into: mir::Inst,
394 /// The register the address instruction wrote, which is what ties this to its set.
395 base: mir::Reg,
396 /// What the reader's operands become.
397 operands: Vec<mir::Operand>,
398 /// What the reader's addressing mode becomes.
399 amode: mir::Amode,
400}
401
402/// The `lea` whose address this instruction should read directly, and what reading it directly
403/// makes of the instruction.
404///
405/// The operand vector is rebuilt rather than edited because the registers a memory operand names
406/// come last in it, which is the invariant [`mir::InstBuilder::mem`] keeps and the printer and the
407/// allocator both read. Dropping the base the reader had and putting the `lea`'s base and index on
408/// the end keeps it, and the indices in the new addressing mode are worked out from the length
409/// rather than carried over.
410fn candidate(func: &mir::Func, open: &HashMap<mir::Reg, Open>, inst: mir::Inst) -> Option<Folding> {
411 let base = base_reg(func, inst)?;
412 let from = open.get(&base)?.from;
413 let address = func[func[from].mem?];
414 // The reader holds the base in its last operand, and [`offer`] is what checks that nothing else
415 // in the same instruction names it. So the composed address is the `lea`'s with the reader's
416 // displacement added, and the only thing that can go wrong is the width of the field it goes
417 // in.
418 let disp = i64::from(address.disp) + i64::from(func[func[inst].mem?].disp);
419 let mut amode = mir::Amode { disp: i32::try_from(disp).ok()?, ..address };
420
421 let taken = &func[func[from].operands];
422 let reader = &func[func[inst].operands];
423 let mut operands = reader.get(..reader.len().checked_sub(1)?)?.to_vec();
424 for (at, into) in [(address.base, &mut amode.base), (address.index, &mut amode.index)] {
425 let Some(at) = at else { continue };
426 operands.push(*taken.get(usize::from(at))?);
427 *into = Some(u8::try_from(operands.len() - 1).ok()?);
428 }
429 Some(Folding { into: inst, base, operands, amode })
430}
431
432#[cfg(test)]
433mod tests {
434 use rucc_target::x86_64::{FRAME, GPR, MACHINE, RDI};
435
436 use super::*;
437
438 /// A function with one block, and the names it was built with.
439 fn empty() -> (Interner, mir::Func, mir::Block) {
440 let mut names = Interner::new();
441 let mut func = mir::Func::new(names.intern("f"));
442 let block = func.create_block();
443 (names, func, block)
444 }
445
446 /// The pass, run over a function with nothing owed a frame offset, which is most of these.
447 ///
448 /// The lists are still there because the pass rewrites them, and a test that is about what it
449 /// wrote in them builds its own rather than calling this.
450 fn folds(func: &mut mir::Func, names: &mut Interner) -> usize {
451 let (mut locals, mut arguments, mut growable) = (Vec::new(), Vec::new(), Vec::new());
452 addresses(
453 func,
454 &FRAME,
455 &MACHINE,
456 names,
457 &mut Pending {
458 addresses: &mut locals,
459 arguments: &mut arguments,
460 dynamic: &mut growable,
461 },
462 )
463 }
464
465 /// The opcode of that name on this target.
466 fn op(names: &mut Interner, name: &str) -> mir::Opcode {
467 mir::Opcode::new(names.intern(&format!("{}{name}", FRAME.prefix)))
468 }
469
470 /// What every instruction in a block came to, as opcodes and addressing modes.
471 fn shape(func: &mir::Func, names: &Interner, block: mir::Block) -> Vec<(String, mir::Amode)> {
472 func.insts(block)
473 .map(|inst| {
474 let amode = func[inst].mem.map_or(mir::Amode::NOTHING, |mem| func[mem]);
475 (names.resolve(func[inst].opcode.name()).to_owned(), amode)
476 })
477 .collect()
478 }
479
480 /// The registers a memory operand names, in the order the addressing mode names them.
481 fn address_regs(func: &mir::Func, inst: mir::Inst) -> Vec<mir::Reg> {
482 let amode = func[func[inst].mem.expect("a memory operand")];
483 let operands = &func[func[inst].operands];
484 [amode.base, amode.index]
485 .into_iter()
486 .flatten()
487 .map(|at| operands[usize::from(at)].reg)
488 .collect()
489 }
490
491 /// An array read as selection leaves it: a `lea` that scales the index and adds the base, and
492 /// a `mov` that reads through the register it wrote.
493 #[test]
494 fn an_address_a_load_reads_once_becomes_the_load_s_own_addressing_mode() {
495 let (mut names, mut func, block) = empty();
496 let array = func.new_vreg(GPR);
497 let index = func.new_vreg(GPR);
498 let address = func.new_vreg(GPR);
499 let value = func.new_vreg(GPR);
500 let lea = op(&mut names, FRAME.lea);
501 let load = op(&mut names, "mov_rm_32");
502 func.build(block, lea)
503 .def(address, GPR)
504 .mem(
505 mir::Mem::at(mir::Operand::read(array, GPR))
506 .indexed(mir::Operand::read(index, GPR), 4),
507 )
508 .finish();
509 func.build(block, load)
510 .def(value, GPR)
511 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
512 .finish();
513
514 assert_eq!(folds(&mut func, &mut names), 1);
515
516 let left = shape(&func, &names, block);
517 assert_eq!(left.len(), 1, "the address is worked out twice: {left:?}");
518 assert_eq!(left[0].0, format!("{}mov_rm_32", FRAME.prefix));
519 assert_eq!(left[0].1.scale, 4);
520 assert_eq!(left[0].1.disp, 0);
521 let inst = func.insts(block).next().expect("the load is still there");
522 assert_eq!(address_regs(&func, inst), vec![array, index], "the load reads the wrong pair");
523 }
524
525 /// The two displacements are added, which is the whole of what composing them takes when one
526 /// of the two addresses has room for an index and the other has none.
527 #[test]
528 fn the_displacements_of_the_two_addresses_are_added() {
529 let (mut names, mut func, block) = empty();
530 let array = func.new_vreg(GPR);
531 let address = func.new_vreg(GPR);
532 let value = func.new_vreg(GPR);
533 let lea = op(&mut names, FRAME.lea);
534 let load = op(&mut names, "mov_rm_32");
535 func.build(block, lea)
536 .def(address, GPR)
537 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
538 .finish();
539 func.build(block, load)
540 .def(value, GPR)
541 .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(8))
542 .finish();
543
544 assert_eq!(folds(&mut func, &mut names), 1);
545
546 let left = shape(&func, &names, block);
547 assert_eq!(left.len(), 1);
548 assert_eq!(left[0].1.disp, 24, "the field is at the sum of the two offsets or nowhere");
549 }
550
551 /// A store keeps the value it writes, which is the operand the address does not name, and the
552 /// rebuilt operand vector has to hold on to it.
553 #[test]
554 fn a_store_keeps_the_value_it_is_storing() {
555 let (mut names, mut func, block) = empty();
556 let array = func.new_vreg(GPR);
557 let index = func.new_vreg(GPR);
558 let address = func.new_vreg(GPR);
559 let value = func.new_vreg(GPR);
560 let lea = op(&mut names, FRAME.lea);
561 let store = op(&mut names, "mov_mr_32");
562 func.build(block, lea)
563 .def(address, GPR)
564 .mem(
565 mir::Mem::at(mir::Operand::read(array, GPR))
566 .indexed(mir::Operand::read(index, GPR), 8),
567 )
568 .finish();
569 func.build(block, store)
570 .uses(value, GPR)
571 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
572 .finish();
573
574 assert_eq!(folds(&mut func, &mut names), 1);
575
576 let inst = func.insts(block).next().expect("the store is still there");
577 let regs: Vec<mir::Reg> = func[func[inst].operands].iter().map(|op| op.reg).collect();
578 assert_eq!(regs, vec![value, array, index], "the value the store writes went missing");
579 assert_eq!(func[func[inst].mem.expect("a memory operand")].scale, 8);
580 }
581
582 /// One address at three offsets, which is what a structure written field by field comes out
583 /// as. Every reader can carry the whole of it in its own mode, so all three take it and the
584 /// `lea` has nothing left reading it. This is the case section 37.4 says the pass is for.
585 #[test]
586 fn an_address_every_reader_can_take_is_folded_into_all_of_them() {
587 let (mut names, mut func, block) = empty();
588 let array = func.new_vreg(GPR);
589 let address = func.new_vreg(GPR);
590 let value = func.new_vreg(GPR);
591 let lea = op(&mut names, FRAME.lea);
592 let store = op(&mut names, "mov_mr_32");
593 func.build(block, lea)
594 .def(address, GPR)
595 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
596 .finish();
597 for offset in [0, 12, 28] {
598 func.build(block, store)
599 .uses(value, GPR)
600 .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(offset))
601 .finish();
602 }
603
604 assert_eq!(folds(&mut func, &mut names), 3);
605
606 let left = shape(&func, &names, block);
607 assert_eq!(left.len(), 3, "the address is still worked out on its own: {left:?}");
608 let disps: Vec<i32> = left.iter().map(|(_, amode)| amode.disp).collect();
609 assert_eq!(disps, vec![16, 28, 44], "each store is at its own offset from the address");
610 for inst in func.insts(block).collect::<Vec<_>>() {
611 assert_eq!(address_regs(&func, inst), vec![array]);
612 }
613 }
614
615 /// Three readers and the middle one has an index of its own. Folding into the other two would
616 /// leave the `lea` where it is for the third, so the address would be worked out twice rather
617 /// than once and the two folds would have bought nothing but a longer live range for what it
618 /// reads. All or nothing over the set means none of them.
619 #[test]
620 fn an_address_one_reader_cannot_take_is_folded_into_none_of_them() {
621 let (mut names, mut func, block) = empty();
622 let array = func.new_vreg(GPR);
623 let index = func.new_vreg(GPR);
624 let address = func.new_vreg(GPR);
625 let lea = op(&mut names, FRAME.lea);
626 let load = op(&mut names, "mov_rm_32");
627 func.build(block, lea)
628 .def(address, GPR)
629 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
630 .finish();
631 for at in 0..3 {
632 let value = func.new_vreg(GPR);
633 let mem = mir::Mem::at(mir::Operand::read(address, GPR));
634 let mem = if at == 1 { mem.indexed(mir::Operand::read(index, GPR), 4) } else { mem };
635 func.build(block, load).def(value, GPR).mem(mem).finish();
636 }
637
638 assert_eq!(folds(&mut func, &mut names), 0);
639 assert_eq!(shape(&func, &names, block).len(), 4);
640 }
641
642 /// An indexed address with two readers, which both of them can take. The index goes into the
643 /// room the reader already has for one, the same as the base does, so this is the ordinary
644 /// case rather than a special one.
645 #[test]
646 fn an_indexed_address_every_reader_can_take_is_folded_into_all_of_them() {
647 let (mut names, mut func, block) = empty();
648 let array = func.new_vreg(GPR);
649 let index = func.new_vreg(GPR);
650 let address = func.new_vreg(GPR);
651 let lea = op(&mut names, FRAME.lea);
652 let load = op(&mut names, "mov_rm_32");
653 func.build(block, lea)
654 .def(address, GPR)
655 .mem(
656 mir::Mem::at(mir::Operand::read(array, GPR))
657 .indexed(mir::Operand::read(index, GPR), 4),
658 )
659 .finish();
660 for offset in [0, 8] {
661 let value = func.new_vreg(GPR);
662 func.build(block, load)
663 .def(value, GPR)
664 .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(offset))
665 .finish();
666 }
667
668 assert_eq!(folds(&mut func, &mut names), 2);
669
670 let left = shape(&func, &names, block);
671 assert_eq!(left.len(), 2, "the address is gone and both loads carry it: {left:?}");
672 let disps: Vec<i32> = left.iter().map(|(_, amode)| amode.disp).collect();
673 assert_eq!(disps, vec![0, 8], "each load is at its own offset from the address");
674 for inst in func.insts(block).collect::<Vec<_>>() {
675 assert_eq!(address_regs(&func, inst), vec![array, index]);
676 }
677 }
678
679 /// A symbol relative address with two readers, which both of them could take and which is left
680 /// alone anyway. Each reader would have to name the symbol where it names a register now, and
681 /// a symbol is a whole address word, so two readers write that word twice to save one `lea`
682 /// that wrote it once. The corpus says that is a loss well before the reader count gets large.
683 #[test]
684 fn a_symbol_address_with_more_than_one_reader_is_left_where_it_is() {
685 let (mut names, mut func, block) = empty();
686 let address = func.new_vreg(GPR);
687 let lea = op(&mut names, FRAME.lea);
688 let load = op(&mut names, "mov_rm_32");
689 let cell = names.intern("cell");
690 func.build(block, lea).def(address, GPR).mem(mir::Mem::of(cell)).finish();
691 for offset in [0, 8] {
692 let value = func.new_vreg(GPR);
693 func.build(block, load)
694 .def(value, GPR)
695 .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(offset))
696 .finish();
697 }
698
699 assert_eq!(folds(&mut func, &mut names), 0);
700 assert_eq!(shape(&func, &names, block).len(), 3);
701 }
702
703 /// Two readers and one of them is in another block, which is the same refusal as the single
704 /// reader case and is caught by a different half of the pass. The count of reads is taken over
705 /// the whole function, so a set that leaves one out never becomes complete.
706 #[test]
707 fn an_address_read_outside_the_block_as_well_is_left_where_it_is() {
708 let (mut names, mut func, block) = empty();
709 let next = func.create_block();
710 let array = func.new_vreg(GPR);
711 let address = func.new_vreg(GPR);
712 let lea = op(&mut names, FRAME.lea);
713 let load = op(&mut names, "mov_rm_32");
714 func.build(block, lea)
715 .def(address, GPR)
716 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
717 .finish();
718 for at in [block, next] {
719 let value = func.new_vreg(GPR);
720 func.build(at, load)
721 .def(value, GPR)
722 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
723 .finish();
724 }
725 *func.succs_mut(block) = vec![mir::BlockCall::to(next)];
726
727 assert_eq!(folds(&mut func, &mut names), 0);
728 assert_eq!(shape(&func, &names, block).len(), 2);
729 }
730
731 /// A register the address reads, written between the first reader and the second. This is the
732 /// one refusal the set adds that the pair version had no way to need, since a write after the
733 /// only reader is a write nobody was ever going to fold across.
734 #[test]
735 fn a_write_between_one_reader_and_the_next_ends_the_chance_for_the_set() {
736 let (mut names, mut func, block) = empty();
737 let array = mir::Reg::physical(RDI);
738 let address = func.new_vreg(GPR);
739 let first = func.new_vreg(GPR);
740 let second = func.new_vreg(GPR);
741 let lea = op(&mut names, FRAME.lea);
742 let load = op(&mut names, "mov_rm_32");
743 let put = op(&mut names, "mov_ri_64");
744 func.build(block, lea)
745 .def(address, GPR)
746 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
747 .finish();
748 func.build(block, load)
749 .def(first, GPR)
750 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
751 .finish();
752 func.build(block, put).def(array, GPR).imm(7).finish();
753 func.build(block, load)
754 .def(second, GPR)
755 .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(4))
756 .finish();
757
758 assert_eq!(folds(&mut func, &mut names), 0);
759 assert_eq!(shape(&func, &names, block).len(), 4);
760 }
761
762 /// A reader that is not reading it as an address at all. There is nowhere in an ordinary
763 /// operand to put a base and an index and a displacement, so that read is one no fold can take
764 /// and it turns down the set the way any other refusal does.
765 #[test]
766 fn an_address_something_reads_as_a_plain_operand_is_left_where_it_is() {
767 let (mut names, mut func, block) = empty();
768 let array = func.new_vreg(GPR);
769 let address = func.new_vreg(GPR);
770 let value = func.new_vreg(GPR);
771 let sum = func.new_vreg(GPR);
772 let lea = op(&mut names, FRAME.lea);
773 let load = op(&mut names, "mov_rm_32");
774 let add = op(&mut names, "add_rr_64");
775 func.build(block, lea)
776 .def(address, GPR)
777 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
778 .finish();
779 func.build(block, load)
780 .def(value, GPR)
781 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
782 .finish();
783 func.build(block, add).def(sum, GPR).uses(address, GPR).finish();
784
785 assert_eq!(folds(&mut func, &mut names), 0);
786 assert_eq!(shape(&func, &names, block).len(), 3);
787 }
788
789 /// The one instruction reading the address twice, once as the value it stores and once as the
790 /// place it stores to. Only one of those two reads is the memory operand, so folding would
791 /// leave the other one naming a register nothing writes any more.
792 #[test]
793 fn an_address_the_one_instruction_reads_twice_is_left_where_it_is() {
794 let (mut names, mut func, block) = empty();
795 let array = func.new_vreg(GPR);
796 let address = func.new_vreg(GPR);
797 let lea = op(&mut names, FRAME.lea);
798 let store = op(&mut names, "mov_mr_64");
799 func.build(block, lea)
800 .def(address, GPR)
801 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
802 .finish();
803 func.build(block, store)
804 .uses(address, GPR)
805 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
806 .finish();
807
808 assert_eq!(folds(&mut func, &mut names), 0);
809 assert_eq!(shape(&func, &names, block).len(), 2);
810 }
811
812 /// A chain whose middle has a reader of its own, so the inner address is complete while the
813 /// outer one is still waiting for its second reader. Folding the inner one away takes with it
814 /// the instruction the outer one's plan was written for, and the outer one waits rather than
815 /// being written into a gap. The second run is where it lands, which is the whole of what
816 /// waiting costs.
817 #[test]
818 fn a_chain_whose_middle_goes_first_leaves_the_outer_address_for_the_next_run() {
819 let (mut names, mut func, block) = empty();
820 let array = func.new_vreg(GPR);
821 let outer = func.new_vreg(GPR);
822 let inner = func.new_vreg(GPR);
823 let first = func.new_vreg(GPR);
824 let second = func.new_vreg(GPR);
825 let lea = op(&mut names, FRAME.lea);
826 let load = op(&mut names, "mov_rm_32");
827 func.build(block, lea)
828 .def(outer, GPR)
829 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
830 .finish();
831 func.build(block, lea)
832 .def(inner, GPR)
833 .mem(mir::Mem::at(mir::Operand::read(outer, GPR)).plus(4))
834 .finish();
835 func.build(block, load)
836 .def(first, GPR)
837 .mem(mir::Mem::at(mir::Operand::read(inner, GPR)))
838 .finish();
839 func.build(block, load)
840 .def(second, GPR)
841 .mem(mir::Mem::at(mir::Operand::read(outer, GPR)).plus(8))
842 .finish();
843
844 assert_eq!(folds(&mut func, &mut names), 1);
845 assert_eq!(shape(&func, &names, block).len(), 3, "the inner address is still there");
846
847 assert_eq!(folds(&mut func, &mut names), 2);
848 let left = shape(&func, &names, block);
849 assert_eq!(left.len(), 2, "the outer address is still there: {left:?}");
850 let disps: Vec<i32> = left.iter().map(|(_, amode)| amode.disp).collect();
851 assert_eq!(disps, vec![20, 24], "the two loads are at the two composed offsets");
852 }
853
854 /// The reader having an index of its own is the one shape that does not compose, since the
855 /// answer would want two scaled registers.
856 #[test]
857 fn a_reader_that_already_has_an_index_is_left_alone() {
858 let (mut names, mut func, block) = empty();
859 let array = func.new_vreg(GPR);
860 let index = func.new_vreg(GPR);
861 let address = func.new_vreg(GPR);
862 let value = func.new_vreg(GPR);
863 let lea = op(&mut names, FRAME.lea);
864 let load = op(&mut names, "mov_rm_32");
865 func.build(block, lea)
866 .def(address, GPR)
867 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
868 .finish();
869 func.build(block, load)
870 .def(value, GPR)
871 .mem(
872 mir::Mem::at(mir::Operand::read(address, GPR))
873 .indexed(mir::Operand::read(index, GPR), 4),
874 )
875 .finish();
876
877 assert_eq!(folds(&mut func, &mut names), 0);
878 assert_eq!(shape(&func, &names, block).len(), 2);
879 }
880
881 /// The two displacements add up to more than the field holds, so the pair stays a pair. The
882 /// program that does this is one nobody wrote, and the point of the test is that the answer is
883 /// a refusal rather than a wrap.
884 #[test]
885 fn two_displacements_that_do_not_fit_together_are_not_put_together() {
886 let (mut names, mut func, block) = empty();
887 let array = func.new_vreg(GPR);
888 let address = func.new_vreg(GPR);
889 let value = func.new_vreg(GPR);
890 let lea = op(&mut names, FRAME.lea);
891 let load = op(&mut names, "mov_rm_32");
892 func.build(block, lea)
893 .def(address, GPR)
894 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(i32::MAX))
895 .finish();
896 func.build(block, load)
897 .def(value, GPR)
898 .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(1))
899 .finish();
900
901 assert_eq!(folds(&mut func, &mut names), 0);
902 assert_eq!(shape(&func, &names, block).len(), 2);
903 }
904
905 /// A physical register the address reads, written between the two. Machine IR is in SSA form
906 /// here so a virtual register cannot be, and this is why the walk asks anyway.
907 #[test]
908 fn a_register_the_address_reads_being_written_in_between_ends_the_chance() {
909 let (mut names, mut func, block) = empty();
910 let array = mir::Reg::physical(RDI);
911 let address = func.new_vreg(GPR);
912 let value = func.new_vreg(GPR);
913 let lea = op(&mut names, FRAME.lea);
914 let load = op(&mut names, "mov_rm_32");
915 let put = op(&mut names, "mov_ri_64");
916 func.build(block, lea)
917 .def(address, GPR)
918 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
919 .finish();
920 func.build(block, put).def(array, GPR).imm(7).finish();
921 func.build(block, load)
922 .def(value, GPR)
923 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
924 .finish();
925
926 assert_eq!(folds(&mut func, &mut names), 0);
927 assert_eq!(shape(&func, &names, block).len(), 3);
928 }
929
930 /// A reader in another block. Folding would move the address to wherever that block is, and
931 /// this pass has no way to know whether that is somewhere it runs more often.
932 #[test]
933 fn a_reader_in_another_block_is_not_one_this_folds_into() {
934 let (mut names, mut func, block) = empty();
935 let next = func.create_block();
936 let array = func.new_vreg(GPR);
937 let address = func.new_vreg(GPR);
938 let value = func.new_vreg(GPR);
939 let lea = op(&mut names, FRAME.lea);
940 let load = op(&mut names, "mov_rm_32");
941 func.build(block, lea)
942 .def(address, GPR)
943 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
944 .finish();
945 *func.succs_mut(block) = vec![mir::BlockCall::to(next)];
946 func.build(next, load)
947 .def(value, GPR)
948 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
949 .finish();
950
951 assert_eq!(folds(&mut func, &mut names), 0);
952 }
953
954 /// A chain of two, which is what an address of a field of an element of an array comes out as.
955 /// The walk goes forwards, so the second `lea` is folded into the load and then the first is
956 /// folded into what is left of the second, both in the one pass.
957 #[test]
958 fn a_chain_of_two_addresses_is_folded_the_whole_way_in_one_pass() {
959 let (mut names, mut func, block) = empty();
960 let array = func.new_vreg(GPR);
961 let index = func.new_vreg(GPR);
962 let element = func.new_vreg(GPR);
963 let field = func.new_vreg(GPR);
964 let value = func.new_vreg(GPR);
965 let lea = op(&mut names, FRAME.lea);
966 let load = op(&mut names, "mov_rm_32");
967 func.build(block, lea)
968 .def(element, GPR)
969 .mem(
970 mir::Mem::at(mir::Operand::read(array, GPR))
971 .indexed(mir::Operand::read(index, GPR), 8),
972 )
973 .finish();
974 func.build(block, lea)
975 .def(field, GPR)
976 .mem(mir::Mem::at(mir::Operand::read(element, GPR)).plus(4))
977 .finish();
978 func.build(block, load)
979 .def(value, GPR)
980 .mem(mir::Mem::at(mir::Operand::read(field, GPR)))
981 .finish();
982
983 assert_eq!(folds(&mut func, &mut names), 2);
984
985 let left = shape(&func, &names, block);
986 assert_eq!(left.len(), 1, "one of the two addresses is still its own instruction");
987 assert_eq!(left[0].1.scale, 8);
988 assert_eq!(left[0].1.disp, 4);
989 let inst = func.insts(block).next().expect("the load is still there");
990 assert_eq!(address_regs(&func, inst), vec![array, index]);
991 }
992
993 /// An address of a global, which the `lea` holds as a symbol rather than as a register. It
994 /// composes the same way and the reader ends up naming the symbol itself, which is one
995 /// instruction rather than two for every read of a global with a constant subscript.
996 #[test]
997 fn an_address_of_a_global_folds_into_the_reader_symbol_and_all() {
998 let (mut names, mut func, block) = empty();
999 let global = names.intern("counters");
1000 let address = func.new_vreg(GPR);
1001 let value = func.new_vreg(GPR);
1002 let lea = op(&mut names, FRAME.lea);
1003 let load = op(&mut names, "mov_rm_32");
1004 func.build(block, lea).def(address, GPR).mem(mir::Mem::of(global)).finish();
1005 func.build(block, load)
1006 .def(value, GPR)
1007 .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(12))
1008 .finish();
1009
1010 assert_eq!(folds(&mut func, &mut names), 1);
1011
1012 let left = shape(&func, &names, block);
1013 assert_eq!(left.len(), 1);
1014 assert_eq!(left[0].1.symbol, Some(global));
1015 assert_eq!(left[0].1.disp, 12);
1016 }
1017
1018 /// An address into the frame, which reads as an address of nothing until `finish` writes the
1019 /// distance in. It folds like any other and the entry moves to the instruction that took it, so
1020 /// the distance is still written into something that runs, and into the reader's own
1021 /// displacement rather than over it.
1022 #[test]
1023 fn an_address_whose_displacement_is_still_to_be_written_folds_and_takes_its_entry_with_it() {
1024 let (mut names, mut func, block) = empty();
1025 let sp = mir::Reg::physical(RDI);
1026 let address = func.new_vreg(GPR);
1027 let value = func.new_vreg(GPR);
1028 let lea = op(&mut names, FRAME.lea);
1029 let load = op(&mut names, "mov_rm_32");
1030 let local = func
1031 .build(block, lea)
1032 .def(address, GPR)
1033 .mem(mir::Mem::at(mir::Operand::read(sp, GPR)))
1034 .finish();
1035 func.build(block, load)
1036 .def(value, GPR)
1037 .mem(mir::Mem::at(mir::Operand::read(address, GPR)).plus(8))
1038 .finish();
1039
1040 let (mut locals, mut arguments, mut growable) = (vec![(local, 3)], Vec::new(), Vec::new());
1041 let mut pending =
1042 Pending { addresses: &mut locals, arguments: &mut arguments, dynamic: &mut growable };
1043 assert_eq!(addresses(&mut func, &FRAME, &MACHINE, &mut names, &mut pending), 1);
1044
1045 let left = shape(&func, &names, block);
1046 assert_eq!(left.len(), 1, "the address is worked out twice: {left:?}");
1047 assert_eq!(left[0].1.disp, 8, "the field's offset is what finish adds the frame's to");
1048 let reader = func.insts(block).next().expect("the load is still there");
1049 assert_eq!(locals, vec![(reader, 3)], "the offset is owed to whoever took the address");
1050 }
1051
1052 /// One address into the frame read at that many offsets, which is a structure written field by
1053 /// field. Gives back how many folded, which instructions are in the block afterwards, and what
1054 /// the caller is still owed an offset into.
1055 fn a_frame_address(readers: u32) -> (usize, Vec<mir::Inst>, Vec<(mir::Inst, u32)>) {
1056 let (mut names, mut func, block) = empty();
1057 let sp = mir::Reg::physical(RDI);
1058 let address = func.new_vreg(GPR);
1059 let lea = op(&mut names, FRAME.lea);
1060 let load = op(&mut names, "mov_rm_32");
1061 let local = func
1062 .build(block, lea)
1063 .def(address, GPR)
1064 .mem(mir::Mem::at(mir::Operand::read(sp, GPR)))
1065 .finish();
1066 for at in 0..readers {
1067 let value = func.new_vreg(GPR);
1068 func.build(block, load)
1069 .def(value, GPR)
1070 .mem(
1071 mir::Mem::at(mir::Operand::read(address, GPR))
1072 .plus(i32::try_from(at).unwrap_or(0) * 4),
1073 )
1074 .finish();
1075 }
1076
1077 let (mut locals, mut arguments, mut growable) = (Vec::new(), vec![(local, 7)], Vec::new());
1078 let mut pending =
1079 Pending { addresses: &mut locals, arguments: &mut arguments, dynamic: &mut growable };
1080 let folded = addresses(&mut func, &FRAME, &MACHINE, &mut names, &mut pending);
1081 assert!(locals.is_empty(), "an argument is owed off the other list");
1082 (folded, func.insts(block).collect(), arguments)
1083 }
1084
1085 /// One entry on the list becomes one per reader, since each of them now carries a displacement
1086 /// the frame's offset has to be added to and there is no instruction left to add it to instead.
1087 #[test]
1088 fn an_address_into_the_frame_that_three_readers_take_is_owed_to_all_of_them() {
1089 let (folded, left, owed) = a_frame_address(3);
1090 assert_eq!(folded, 3);
1091 assert_eq!(left.len(), 3, "the address is not its own instruction any more");
1092 assert_eq!(owed, vec![(left[0], 7), (left[1], 7), (left[2], 7)]);
1093 }
1094
1095 /// And the reader after that is one too many, so none of them takes it. What each of them would
1096 /// put on is more than what the whole address instruction costs, which is [`FRAME_READERS`].
1097 #[test]
1098 fn an_address_into_the_frame_a_fourth_reader_wants_is_left_where_it_is() {
1099 let (folded, left, owed) = a_frame_address(4);
1100 assert_eq!(folded, 0);
1101 assert_eq!(left.len(), 5, "the address and its four readers");
1102 assert_eq!(owed, vec![(left[0], 7)], "the offset is still owed to the address itself");
1103 }
1104
1105 /// An instruction that is not the target's address instruction, writing a register a load
1106 /// reads. A load through the result of a load is two loads and folding one into the other
1107 /// would read the wrong memory, so the opcode is checked rather than the shape.
1108 #[test]
1109 fn only_the_target_s_address_instruction_is_one_this_folds() {
1110 let (mut names, mut func, block) = empty();
1111 let array = func.new_vreg(GPR);
1112 let address = func.new_vreg(GPR);
1113 let value = func.new_vreg(GPR);
1114 let load = op(&mut names, "mov_rm_64");
1115 let read = op(&mut names, "mov_rm_32");
1116 func.build(block, load)
1117 .def(address, GPR)
1118 .mem(mir::Mem::at(mir::Operand::read(array, GPR)).plus(16))
1119 .finish();
1120 func.build(block, read)
1121 .def(value, GPR)
1122 .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
1123 .finish();
1124
1125 assert_eq!(folds(&mut func, &mut names), 0);
1126 assert_eq!(shape(&func, &names, block).len(), 2);
1127 }
1128}