Skip to main content

rucc_codegen/
shorten.rs

1//! Writing the same answer in fewer bytes, once the registers are the real ones.
2//!
3//! Design: `spec/optimizer/37-machine-level-optimization.md` section 37.4, which calls these the
4//! size directed peepholes and puts them after register allocation. tamnd/rucc#741 is the issue
5//! about the back end never learning what it is compiling for, and names three of these as free
6//! before any of that is settled and one as waiting for it.
7//!
8//! Five rewrites. A move of zero into a register becomes an exclusive or of the register with
9//! itself: `movl $0, %eax` spells the zero out in four bytes of zero bits and is five bytes, `xorl
10//! %eax, %eax` says it without spelling it and is two. The processor knows the idiom, so the
11//! shorter one is no slower, and this is not a trade of speed for size and does not wait for a size
12//! goal to arrive.
13//!
14//! And a move of a number into a sixty-four bit register becomes the thirty-two bit move where the
15//! number is one that fits, because the narrow instruction clears the half of the register it does
16//! not write rather than leaving it alone. `movq $7, %rax` is seven bytes and `movl $7, %eax` is
17//! five, and for a number above two to the thirty-first it is ten against five, since the wide move
18//! cannot reach one by sign extending and writes all eight bytes of it out.
19//!
20//! The two meet on a zero, and the order they are asked in is the order they are worth: a zero
21//! whose condition state is free becomes the exclusive or, and a zero whose state is not becomes
22//! the narrow move, which is two bytes off rather than five but costs nothing to say.
23//!
24//! And a comparison of a register against zero becomes a test of the register against itself.
25//! `cmpl $0, %eax` is three bytes and `testl %eax, %eax` is two, the byte being the zero the first
26//! one writes out. That one is asked of every instruction whatever the walk has seen, because the
27//! test writes the condition state exactly as the comparison does: both leave the sign, the zero
28//! and the parity of what is in the register and both clear the carry and the overflow, so every
29//! condition this machine jumps on reads the same answer behind either of them.
30//!
31//! And an addition of one to a register becomes the instruction that adds one and says so in its
32//! opcode. `addl $1, %eax` is three bytes, one for the opcode, one saying which register and one
33//! for the number, and `incl %eax` is two. A subtraction of one becomes the instruction that takes
34//! one away, and each of the two is also what the other one written against minus one becomes.
35//!
36//! And an address computation whose address is a register becomes a move of that register. `leaq
37//! (%rsp), %rax` works out an address that is a base and nothing else, which is what is already in
38//! the base, and `movq %rsp, %rax` puts the same number in the same place in three bytes rather than
39//! four. The byte is the one an address counted from the stack pointer has to spend saying it has no
40//! index, and the stack pointer is the register this turns up on, because what makes it is taking
41//! the address of whichever local sits at the bottom of the frame.
42//!
43//! That fifth one is the only one here worth taking for something other than bytes. A move between
44//! registers is a thing the machine can do by renaming, so it is off the critical path, and an
45//! address computation is an addition however small the numbers in it are. gcc writes no address
46//! computation of that shape anywhere in the SQLite amalgamation and rucc wrote 444 of them.
47//!
48//! That fourth one is the only one here that is not free, and it is the only one that reads the
49//! goal. An addition writes the carry and an increment leaves the carry as it found it, so the
50//! machine has to merge what was left with what the next instruction writes, which costs a little
51//! where the code is hot and is worth a byte where the goal is size. gcc writes the addition at
52//! `-O2` and the increment at `-Os`, and so does this. The goal arriving here at all is the first
53//! half of tamnd/rucc#741: before it, `-Os` was a shorter list of middle end passes and the back
54//! end compiled what came out of it exactly as `-O2` would have.
55//!
56//! The numbers over the corpus at `-Os` before this pass existed: rucc wrote a move of zero into a
57//! register 21,304 times and GCC 16 wrote it 9 times, and GCC wrote the exclusive or 23,729 times
58//! against rucc's 965. So this is not a case the selector catches most of and misses at the edges.
59//! It is one it does not do. Afterwards rucc writes the move 1,232 times and the exclusive or
60//! 21,037, and the two moved by the same number, which is what says every one that went became one
61//! of these and none of them came from anywhere else.
62//!
63//! # Why it is not something the encoder does
64//!
65//! Because the two are not the same instruction. The exclusive or writes the condition state and
66//! the move does not, so an encoder that quietly swapped one for the other would change what the
67//! instruction behind it reads. Whether anything reads it is a question about the instructions that
68//! follow rather than about this one, which is what makes this a pass. [`rucc_target::FlagInsts`]
69//! is where the answer comes from, the same description [`crate::compare`] asks, and it answers
70//! that a name it does not know writes the state, so an opcode added to a rule set and not to that
71//! table makes this find less rather than making it wrong.
72//!
73//! The narrower move and the test are a different answer to the same question. Those two an encoder
74//! could do without asking anything, since the narrower move leaves the same number in the same
75//! register and the test leaves the same condition state the comparison left. They are not done
76//! there because an encoder handed a sixty-four bit move and writing the bytes of a thirty-two bit
77//! one would be writing bytes the listing beside them does not say, and the listing and the bytes
78//! agreeing is worth more than the two bytes. Choosing the instruction is this pass and spelling
79//! the one it chose is the encoder.
80//!
81//! # Why it runs last
82//!
83//! After [`crate::compare`], because that pass takes comparisons out and a comparison that is gone
84//! is one whose write of the condition state is gone with it. Running before it would see a state
85//! written where the output has none and would refuse rewrites that are allowed. After the layout
86//! for the reason `compare` is: the layout writes the jump that reads a comparison into the same
87//! block as the comparison, and this is the other pass that has to see that pair whole.
88//!
89//! Nothing here moves an instruction, removes one or changes a block, so running after the freeze
90//! costs nothing. The rewrite is one instruction becoming one instruction in the same place.
91//!
92//! # What a block boundary is
93//!
94//! The end of everything this knows, which is the same sentence [`crate::compare`] uses and the
95//! same reason: the condition state is not a register, nothing in this back end carries one from a
96//! block to its successors, and the only place a comparison is read is the block it was made in.
97//!
98//! That is an invariant of the passes in front rather than of this one, so it is checked instead of
99//! believed. `carried` walks every block and asks whether any of them reads the condition state
100//! before writing it, which is what a block reading a predecessor's state would look like from
101//! here, and one that does turns the whole function down. What it buys is that if some later pass
102//! starts writing that shape, this pass stops rather than starts being wrong.
103//!
104//! Reads it rather than mentions it. A comparison that keeps a byte makes the comparison and reads
105//! the answer in the one instruction, so a block opening with one is not a block reading anything a
106//! predecessor left, and the description is asked which of the two kinds of read it is rather than
107//! being taken at the word. tamnd/rucc#1432 is what that cost before it was asked: 456 functions in
108//! the SQLite amalgamation were turned down and every one of them was turned down by this, which is
109//! most of the functions in it that have anything for this pass to do.
110//!
111//! Down for the exclusive or and the increment. The narrower move reads no condition state and
112//! writes none, the test writes the same state the comparison it replaces wrote, and neither an
113//! address computation nor a move touches any state at all, so where a state is alive is not a
114//! question those three have to ask, and a function this turns down still gets all of them.
115//!
116//! What the walk carries for the increment is a second answer beside the first, which is whether
117//! anything behind reads the carry rather than whether anything behind reads the state. The two are
118//! not the same question and neither implies the other: a jump on whether a value was zero reads the
119//! state and not the carry, and an increment already in the code writes the state and not the carry
120//! and so ends the life of neither. That last case is the reason the walk and the check above both
121//! ask the target which instructions leave the carry alone rather than stopping at the flag saying
122//! the state was written.
123//!
124//! # A template a program wrote
125//!
126//! An `asm` statement is not opaque to this. `rucc_target::x86_64::read` turns the text of a
127//! template into the opcodes this back end already has, so by the time this runs a template is
128//! ordinary instructions carrying ordinary names, and the ones in it that read the condition state
129//! are seen the same way any other instruction's read is. A move of zero in front of a template is
130//! rewritten when nothing in that template reads a state it did not write itself, which is the same
131//! rule as everywhere else and not a rule about templates.
132//!
133//! Nothing weaker is being assumed there than what a program could already rely on. On this machine
134//! GCC has every `asm` clobber the condition state whether the statement said so or not, so a
135//! template reading one set before it was never something to hold on to.
136//!
137//! # What it will not do
138//!
139//! Turn a move into the exclusive or when anything reads its condition state before anything
140//! writes. That is the rule and what it costs is now a small number: the zero going into a register
141//! right before a comparison of something else stays a move, and the most the other rewrite can do
142//! for it is make it a narrower one. Of the 215 moves of zero left over the corpus at `-Os`, 146
143//! are this and the other 69 are the eight bit rule below. Not one of them is sixty-four bits wide.
144//!
145//! It was 1,232 until the whole function check stopped counting a comparison that keeps a byte as a
146//! state read from in front of it, which is tamnd/rucc#1432 and was most of what this pass was
147//! leaving alone rather than anything about the instructions it was looking at.
148//!
149//! Eight bits. `movb $0, %al` and `xorb %al, %al` are both two bytes, so the exchange buys nothing
150//! and would spend the condition state on it. The target's table is where that is written down.
151//!
152//! Write an increment at a level that asked for fast code. That is the goal doing its job rather
153//! than a limit, and it is why the same corpus compiled at `-O2` and at `-Os` now differs by
154//! something other than which middle end passes ran.
155//!
156//! Add or take away anything but one. The machine has an opcode for one and for nothing else, so a
157//! constant of two is already as short as it is going to be written.
158//!
159//! Turn an address computation into a move when the address is anything more than a register. An
160//! index is a multiplication, a constant is an addition and a symbol is an address the assembler
161//! fills in, and a move does none of those. That is what most address computations are for, so this
162//! last rewrite is about the ones that were not computing anything rather than about address
163//! computation in general.
164
165use rucc_base::Interner;
166use rucc_cost::Goal;
167use rucc_mir::{self as mir, Role};
168use rucc_target::{FlagInsts, MachineInsts, Reads, ShortInsts};
169
170use crate::changes::{self, Changes, Plan};
171
172/// Rewrites every instruction that has a shorter spelling nothing would notice.
173///
174/// Gives back how many were rewritten, which the tests read and nothing else does.
175pub fn shorter(
176    func: &mut mir::Func,
177    short: &ShortInsts,
178    flags: &FlagInsts,
179    machine: &MachineInsts,
180    names: &mut Interner,
181    goal: Goal,
182) -> usize {
183    // Every name a rewrite could want, before the walk rather than inside it, because the walk
184    // holds a name it read out of the interner while it edits the function and interning a new one
185    // there would be the same interner borrowed twice. The same reason [`crate::compare`] has.
186    let wanted = short.zeroing.iter().map(|entry| entry.into);
187    let wanted = wanted.chain(short.narrowing.iter().map(|entry| entry.into));
188    let wanted = wanted.chain(short.testing.iter().map(|entry| entry.into));
189    let wanted = wanted.chain(short.stepping.iter().map(|entry| entry.into));
190    let wanted = wanted.chain(short.copying.iter().map(|entry| entry.into));
191    let opcodes: Vec<(&'static str, mir::Opcode)> = wanted
192        .map(|into| (into, mir::Opcode::new(names.intern(&format!("{}{into}", short.prefix)))))
193        .collect();
194    let names = &*names;
195    let mut counts = changes::Reads::of(func);
196    let mut took = 0;
197    // Whether the rewrite that spends the condition state may be asked for at all. The narrower
198    // instruction neither reads the state nor writes it, so it is not asked this and a function
199    // this turns down still gets that one.
200    let free = !carried(func, short, flags, names);
201    // Whether the rewrite that trades the carry for a byte may be asked for. It is the one thing
202    // here that is not free, so it waits for a level that said it wanted small code.
203    let small = free && goal == Goal::Size;
204    for block in func.blocks().collect::<Vec<_>>() {
205        // Backwards, because the question each instruction asks is about the ones behind it. The
206        // state is dead at the end of a block, which is the invariant [`carried`] has just held the
207        // function to.
208        let mut live = false;
209        // The same question about the carry alone, which is the part of the state the shorter
210        // addition does not write. It starts false for the reason `live` does and moves separately,
211        // because an instruction that writes the whole state ends the life of both and one that
212        // writes everything but the carry ends the life of neither.
213        let mut carry = false;
214        for inst in func.insts(block).collect::<Vec<_>>().into_iter().rev() {
215            if free && !live {
216                let into = shorter_form(func, short, names, &opcodes, inst);
217                if into.is_some_and(|op| zeroed(func, &mut counts, machine, names, inst, op)) {
218                    took += 1;
219                    // What stands there now writes the state, and the state was already dead, so
220                    // nothing about what the instructions in front of it may do has changed.
221                    continue;
222                }
223            }
224            // The zero that could not become an exclusive or can still be written in fewer bytes,
225            // which is why this is asked after that one and not instead of it.
226            let into = narrower_form(func, short, names, &opcodes, inst);
227            if into.is_some_and(|op| narrowed(func, &mut counts, machine, names, inst, op)) {
228                took += 1;
229                // What stands there now is the same instruction at half the width, which is a
230                // move either way, so what it does to the state is what it did before: nothing.
231            }
232            // A comparison against zero asked of the register alone. Nothing about where the state
233            // is live comes into it, because the shorter instruction writes the same five bits of
234            // state the comparison wrote, so this is asked of every instruction whatever the walk
235            // has seen behind it.
236            let into = tested_form(func, short, names, &opcodes, inst);
237            if into.is_some_and(|op| tested(func, &mut counts, machine, names, inst, op)) {
238                took += 1;
239            }
240            // An address that is a register, written as the move it is. Nothing about the condition
241            // state comes into it either, since neither instruction writes any, so this is asked of
242            // every instruction the same way the narrower move is.
243            let into = copied_form(func, short, names, &opcodes, inst);
244            if into.is_some_and(|op| copied(func, &mut counts, machine, names, inst, op)) {
245                took += 1;
246            }
247            // Adding one with the one in the opcode, which is the only rewrite here that is a
248            // trade. It needs the carry to be dead rather than the whole state, since that is the
249            // only part of the state the shorter instruction leaves behind, and it needs the level
250            // to have asked for small code.
251            if small && !carry {
252                let into = stepped_form(func, short, names, &opcodes, inst);
253                if into.is_some_and(|op| stepped(func, &mut counts, machine, names, inst, op)) {
254                    took += 1;
255                    // What stands there now writes everything but the carry, and the carry was
256                    // already dead, so both answers below are the ones they already are and the
257                    // walk past it is the walk it would have taken anyway.
258                }
259            }
260            let Some(name) = opcode(func, flags, names, inst) else {
261                // A name the description does not cover may have read the state and may have
262                // written it, and the answer that finds fewer rewrites is that it read it.
263                live = true;
264                carry = true;
265                continue;
266            };
267            // What it reads before whether it writes, because an instruction can do both and the
268            // read it does is a read of what is there now. An add with carry is the one that does,
269            // and asking the other way round would call it the end of the state's life and let a
270            // rewrite in front of it take the carry away.
271            //
272            // Unless what it reads is what it wrote itself. A comparison that keeps a byte makes
273            // the comparison and reads the answer in the one instruction, so the state it was
274            // handed is state it wrote over before anything looked at it, and it ends a life rather
275            // than extending one. Asking the description which kind it is rather than stopping at
276            // the word read is most of what this pass gets to do in real code, since a C function
277            // of any size has one of these in it.
278            if flags.asks_what_it_reads(name) {
279                live = false;
280                carry = false;
281            } else if let Some(reads) = flags.reads(name) {
282                live = true;
283                // Which part of the state the condition on it is about. A condition that asks where
284                // a value sits as an unsigned number reads the carry, and so does an instruction
285                // that is adding a carry on rather than asking a question about one.
286                if matches!(reads, Reads::Unsigned | Reads::Carry) {
287                    carry = true;
288                }
289            } else if (flags.writes)(name) && !short.steps(name) {
290                // An instruction that writes the state ends the life of everything in it. One that
291                // writes all of it but the carry ends the life of none of it, which is the second
292                // half of the sentence and is why this asks the description rather than stopping at
293                // the flag. That answer is about `live` as much as about `carry`: a rewrite in front
294                // that spends the state would be spending a carry this instruction was going to
295                // leave for something behind it.
296                live = false;
297                carry = false;
298            }
299        }
300    }
301    took
302}
303
304/// Whether any block reads the condition state before writing it, which is what a state carried in
305/// from a predecessor would look like from inside this pass.
306///
307/// The passes in front are the ones that promise this does not happen and the promise is theirs to
308/// keep, so what this does is hold them to it rather than restate it. A function where it is broken
309/// gets no rewrites at all, which is the answer that is wrong about nothing.
310///
311/// An instruction that leaves the carry alone does not count as having written the state here, for
312/// the same reason it does not count as having written it in the walk. A block opening with one and
313/// reading a carry afterwards is reading a carry a predecessor left, which is exactly the shape this
314/// is looking for, and stopping at it would be calling that block clean.
315///
316/// An instruction that reads what it wrote itself does not count as having read the state, for the
317/// same reason it does not in the walk. A block opening with a comparison that keeps a byte opens
318/// with a comparison, and what the comparison found is not what anything in front of it left.
319/// Counting it as a read is the difference between this turning down a few functions and turning
320/// down most of them, because a comparison that keeps a byte is what every `!` and every `==` in a
321/// value position comes out as.
322fn carried(func: &mir::Func, short: &ShortInsts, flags: &FlagInsts, names: &Interner) -> bool {
323    func.blocks().any(|block| {
324        for inst in func.insts(block) {
325            let Some(name) = opcode(func, flags, names, inst) else { return true };
326            if flags.reads(name).is_some() && !flags.asks_what_it_reads(name) {
327                return true;
328            }
329            if (flags.writes)(name) && !short.steps(name) {
330                return false;
331            }
332        }
333        false
334    })
335}
336
337/// The shorter instruction this one has, when it has one and the constant it carries is the one
338/// that instruction writes.
339///
340/// The name says which instruction it is and the description says which names have a shorter
341/// spelling, and neither of them says what number this one holds. That is the half that decides
342/// whether the shorter spelling says the same thing, since the short way of writing zero is only
343/// the short way of writing zero.
344fn shorter_form(
345    func: &mir::Func,
346    short: &ShortInsts,
347    names: &Interner,
348    opcodes: &[(&'static str, mir::Opcode)],
349    inst: mir::Inst,
350) -> Option<mir::Opcode> {
351    let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
352    let into = short.zeroed(name)?;
353    if func[inst].imm.map(|at| func[at].0) != Some(0) {
354        return None;
355    }
356    opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
357}
358
359/// The narrower instruction this one has, when it has one and the number it carries is one that
360/// instruction holds.
361///
362/// A number the narrower instruction cannot hold is every negative one and everything above what
363/// fits in the bits it writes, since what it does to the rest of the register is clear it. So the
364/// question is not whether the number fits in that many bits the way the program meant it, which is
365/// a question about a type, but whether the bits the wide instruction would leave in the register
366/// are the bits the narrow one leaves there, which is a question about the number.
367fn narrower_form(
368    func: &mir::Func,
369    short: &ShortInsts,
370    names: &Interner,
371    opcodes: &[(&'static str, mir::Opcode)],
372    inst: mir::Inst,
373) -> Option<mir::Opcode> {
374    let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
375    let narrow = short.narrowed(name)?;
376    let held = u64::try_from(func[func[inst].imm?].0).ok()?;
377    if narrow.writes >= u64::BITS || held >= 1u64 << narrow.writes {
378        return None;
379    }
380    opcodes.iter().find(|&&(at, _)| at == narrow.into).map(|&(_, opcode)| opcode)
381}
382
383/// Rewrites the move into the narrower move, which is the same instruction with a different name.
384///
385/// So the operands are the ones it had, where the exclusive or below needs its own built: the two
386/// moves take a register they write and a number, and the number is the one that was already there.
387/// A description where that is not so is one [`Changes`] turns down, and a rewrite it turns down is
388/// one this reports as not taken rather than one that goes in anyway.
389fn narrowed(
390    func: &mut mir::Func,
391    counts: &mut changes::Reads,
392    machine: &MachineInsts,
393    names: &Interner,
394    inst: mir::Inst,
395    opcode: mir::Opcode,
396) -> bool {
397    let mut set = Changes::new();
398    set.rewrite(inst, Plan { opcode, ..Plan::of(func, inst) });
399    set.commit(func, counts, names, machine).is_ok()
400}
401
402/// The shorter comparison this one has, when it has one and the constant it carries is zero.
403///
404/// Zero is the whole of it. A comparison of a register against itself asks whether the register is
405/// zero and nothing else, so the description's entry says what to write instead of a comparison
406/// against zero and says nothing about a comparison against anything, and an instruction carrying
407/// any other number is one this walks past.
408fn tested_form(
409    func: &mir::Func,
410    short: &ShortInsts,
411    names: &Interner,
412    opcodes: &[(&'static str, mir::Opcode)],
413    inst: mir::Inst,
414) -> Option<mir::Opcode> {
415    let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
416    let into = short.tested(name)?;
417    if func[inst].imm.map(|at| func[at].0) != Some(0) {
418        return None;
419    }
420    opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
421}
422
423/// Rewrites the comparison into the test, which reads the register the comparison read and drops
424/// the constant.
425///
426/// The operands are the ones it had, for the reason [`narrowed`] keeps them: both instructions name
427/// one register and read it, and what changes is the number, which the shorter one does not carry.
428/// So the constant goes and nothing else does. A description where the two are not that shape is one
429/// [`Changes`] turns down, and this reports a rewrite it turned down as not taken.
430fn tested(
431    func: &mut mir::Func,
432    counts: &mut changes::Reads,
433    machine: &MachineInsts,
434    names: &Interner,
435    inst: mir::Inst,
436    opcode: mir::Opcode,
437) -> bool {
438    let mut set = Changes::new();
439    set.rewrite(inst, Plan { opcode, imm: None, ..Plan::of(func, inst) });
440    set.commit(func, counts, names, machine).is_ok()
441}
442
443/// The move this address computation is, when the address it works out is a register.
444///
445/// Which is an addressing mode naming a base and nothing else. An index is a multiplication and an
446/// addition, a constant is an addition, and a symbol or a label is an address the assembler fills in
447/// later, so any of those is work the move does not do. What is left is a mode that says to take
448/// what is in one register, and taking what is in one register is the move.
449///
450/// The width is not asked about, unlike the narrower move above. An address on this machine is
451/// sixty four bits wide whatever is at it, so an address computation that keeps its answer keeps all
452/// of it, and the move the description names beside it is the move of that width.
453fn copied_form(
454    func: &mir::Func,
455    short: &ShortInsts,
456    names: &Interner,
457    opcodes: &[(&'static str, mir::Opcode)],
458    inst: mir::Inst,
459) -> Option<mir::Opcode> {
460    let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
461    let into = short.copied(name)?;
462    let amode = func[inst].mem.map(|at| func[at])?;
463    if amode.base.is_none() || amode.index.is_some() || amode.disp != 0 {
464        return None;
465    }
466    if amode.symbol.is_some() || amode.block.is_some() || amode.segment.is_some() {
467        return None;
468    }
469    opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
470}
471
472/// Rewrites the address computation into the move, which keeps the operands and drops the mode.
473///
474/// The operands are already the move's. An instruction with an addressing mode carries the registers
475/// that mode names in its operand vector, behind the ones it writes, so an address computation whose
476/// mode is one base is an instruction that writes one register and reads one register, in that
477/// order, which is the move's shape. What goes is the mode itself, since the move has none.
478///
479/// A description where those two are not the same shape is one [`Changes`] turns down, and this
480/// reports a rewrite it turned down as not taken, which is how an address computation with more in
481/// its operand vector than the mode accounted for is left alone rather than guessed at.
482fn copied(
483    func: &mut mir::Func,
484    counts: &mut changes::Reads,
485    machine: &MachineInsts,
486    names: &Interner,
487    inst: mir::Inst,
488    opcode: mir::Opcode,
489) -> bool {
490    let mut set = Changes::new();
491    set.rewrite(inst, Plan { opcode, amode: None, ..Plan::of(func, inst) });
492    set.commit(func, counts, names, machine).is_ok()
493}
494
495/// Rewrites the move into the exclusive or, which names the one register the move wrote in every
496/// operand it has.
497///
498/// The shapes come from the description rather than from the move, since the shorter instruction is
499/// not the shape the longer one was: the exclusive or writes a register it also reads, which on this
500/// machine is an operand constrained to the same place as one of the reads, and a plan whose
501/// operands do not say so is one [`Changes`] turns down. So each operand is built to what the
502/// description asks for and the register in it is the one the move wrote, which after allocation is
503/// a physical register and so is a register every operand can name without anything being arranged.
504/// The constant goes with the move, the shorter instruction being the one that carries none.
505///
506/// A description whose operands are not all of the register's class, or which writes more than the
507/// one register or none, is a description this does not fit, and the answer there is to leave the
508/// instruction alone rather than to guess.
509fn zeroed(
510    func: &mut mir::Func,
511    counts: &mut changes::Reads,
512    machine: &MachineInsts,
513    names: &Interner,
514    inst: mir::Inst,
515    opcode: mir::Opcode,
516) -> bool {
517    let written: Vec<mir::Operand> = func[func[inst].operands]
518        .iter()
519        .filter(|operand| operand.role != Role::Use)
520        .copied()
521        .collect();
522    let [def] = written[..] else { return false };
523    let bare = machine.bare(names.resolve(opcode.name()));
524    let Some(desc) = (machine.operands)(bare) else { return false };
525    if desc.iter().any(|want| want.class != def.class) {
526        return false;
527    }
528    if desc.iter().filter(|want| want.role != Role::Use).count() != 1 {
529        return false;
530    }
531    let operands = desc
532        .iter()
533        .map(|want| mir::Operand {
534            reg: def.reg,
535            class: want.class,
536            role: want.role,
537            constraint: want.constraint,
538        })
539        .collect();
540    let mut set = Changes::new();
541    set.rewrite(inst, Plan { opcode, operands, imm: None, ..Plan::of(func, inst) });
542    set.commit(func, counts, names, machine).is_ok()
543}
544
545/// The shorter addition this one has, when it has one and the number it carries is the number that
546/// shorter instruction is about.
547///
548/// Both halves again, and the second one is doing more work here than anywhere else in this pass.
549/// One addition has two shorter instructions, one for each of the two numbers a machine has an
550/// opcode for, and a subtraction has the same two the other way round, so the number is what says
551/// which of the two is meant rather than only whether either is.
552fn stepped_form(
553    func: &mir::Func,
554    short: &ShortInsts,
555    names: &Interner,
556    opcodes: &[(&'static str, mir::Opcode)],
557    inst: mir::Inst,
558) -> Option<mir::Opcode> {
559    let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
560    let into = short.stepped(name, func[func[inst].imm?].0)?;
561    opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
562}
563
564/// Rewrites the addition into the one that carries its number in its opcode.
565///
566/// The operands are the ones it had, for the reason [`tested`] keeps them: both instructions write
567/// one register and read that same register, and what changes is the number, which the shorter one
568/// does not carry. So the constant goes and nothing else does.
569fn stepped(
570    func: &mut mir::Func,
571    counts: &mut changes::Reads,
572    machine: &MachineInsts,
573    names: &Interner,
574    inst: mir::Inst,
575    opcode: mir::Opcode,
576) -> bool {
577    let mut set = Changes::new();
578    set.rewrite(inst, Plan { opcode, imm: None, ..Plan::of(func, inst) });
579    set.commit(func, counts, names, machine).is_ok()
580}
581
582/// The name this target knows an instruction by, for an instruction that is one of this target's.
583///
584/// The opcode in machine IR carries the target's prefix, because a function in the middle of being
585/// compiled holds instructions of one machine and the prefix is what says which. Anything without
586/// it is not something this description covers, and the walk treats that as knowing nothing rather
587/// than as knowing it is safe.
588fn opcode<'a>(
589    func: &mir::Func,
590    flags: &FlagInsts,
591    names: &'a Interner,
592    inst: mir::Inst,
593) -> Option<&'a str> {
594    names.resolve(func[inst].opcode.name()).strip_prefix(flags.prefix)
595}
596
597#[cfg(test)]
598mod tests {
599    use rucc_target::x86_64::{FLAGS, GPR, MACHINE, SHORT};
600
601    use super::*;
602
603    /// A function with one block, and the names it was built with.
604    fn empty() -> (Interner, mir::Func, mir::Block) {
605        let mut names = Interner::new();
606        let mut func = mir::Func::new(names.intern("f"));
607        let block = func.create_block();
608        (names, func, block)
609    }
610
611    /// The opcode of that name on this target.
612    fn op(names: &mut Interner, name: &str) -> mir::Opcode {
613        mir::Opcode::new(names.intern(&format!("{}{name}", SHORT.prefix)))
614    }
615
616    /// The pass, over the machine this crate has a backend for, at a level that wanted fast code.
617    fn takes(func: &mut mir::Func, names: &mut Interner) -> usize {
618        shorter(func, &SHORT, &FLAGS, &MACHINE, names, Goal::Speed)
619    }
620
621    /// The same pass at a level that wanted small code, which is the only one that steps.
622    fn small(func: &mut mir::Func, names: &mut Interner) -> usize {
623        shorter(func, &SHORT, &FLAGS, &MACHINE, names, Goal::Size)
624    }
625
626    /// What every instruction in a block came to, as opcodes with the target's prefix taken off.
627    fn shape(func: &mir::Func, names: &Interner, block: mir::Block) -> Vec<String> {
628        func.insts(block)
629            .map(|inst| {
630                names
631                    .resolve(func[inst].opcode.name())
632                    .strip_prefix(SHORT.prefix)
633                    .unwrap_or("")
634                    .to_owned()
635            })
636            .collect()
637    }
638
639    /// The destination of a two-address instruction, which the description constrains to the same
640    /// register as the first source. The builder's own `def` leaves the constraint off, and the
641    /// change framework holds a rewrite to the shape the target asks for, so a test that built one
642    /// without it would be a test of a function the allocator could not have produced.
643    fn reuse(reg: mir::Reg) -> mir::Operand {
644        mir::Operand {
645            reg,
646            class: GPR,
647            role: Role::Def,
648            constraint: rucc_mir::Constraint::Reuse(1),
649        }
650    }
651
652    /// The registers an instruction names, in the order its operands do.
653    fn regs(func: &mir::Func, inst: mir::Inst) -> Vec<mir::Reg> {
654        func[func[inst].operands].iter().map(|operand| operand.reg).collect()
655    }
656
657    /// The number an instruction carries, for an instruction that carries one.
658    fn imm(func: &mir::Func, inst: mir::Inst) -> Option<i64> {
659        func[inst].imm.map(|at| func[at].0)
660    }
661
662    /// The shape the pass is for: a move of zero with nothing reading the condition state after it
663    /// becomes the exclusive or, which names the register it writes in all three of its operands and
664    /// carries no constant.
665    #[test]
666    fn a_move_of_zero_becomes_an_exclusive_or() {
667        let (mut names, mut func, block) = empty();
668        let into = func.new_vreg(GPR);
669        let zero = op(&mut names, "mov_ri_32");
670        let inst = func.build(block, zero).def(into, GPR).imm(0).finish();
671
672        assert_eq!(takes(&mut func, &mut names), 1);
673        assert_eq!(shape(&func, &names, block), ["xor_rr_32"]);
674        assert_eq!(regs(&func, inst), [into, into, into]);
675        assert!(func[inst].imm.is_none());
676    }
677
678    /// Sixty-four bits is the same rewrite and the biggest one, since the long way of writing a zero
679    /// there is seven bytes. The instruction it becomes is the thirty-two bit one, which clears the
680    /// half of the register it does not write and so leaves the same sixty-four bit zero in one
681    /// byte less.
682    #[test]
683    fn sixty_four_bits_is_the_same_rewrite_at_half_the_width() {
684        let (mut names, mut func, block) = empty();
685        let into = func.new_vreg(GPR);
686        let zero = op(&mut names, "mov_ri_64");
687        func.build(block, zero).def(into, GPR).imm(0).finish();
688
689        assert_eq!(takes(&mut func, &mut names), 1);
690        assert_eq!(shape(&func, &names, block), ["xor_rr_32"]);
691    }
692
693    /// The other rewrite. A number that is not zero has nothing shorter than a move, and the move
694    /// that writes half the register is shorter than the one that writes all of it.
695    #[test]
696    fn a_number_a_narrower_move_holds_is_written_by_the_narrower_move() {
697        for value in [1, 7, 0x7fff_ffff, 0x8000_0000, 0xffff_ffff] {
698            let (mut names, mut func, block) = empty();
699            let into = func.new_vreg(GPR);
700            let wide = op(&mut names, "mov_ri_64");
701            let inst = func.build(block, wide).def(into, GPR).imm(value).finish();
702
703            assert_eq!(takes(&mut func, &mut names), 1, "{value}");
704            assert_eq!(shape(&func, &names, block), ["mov_ri_32"], "{value}");
705            assert_eq!(imm(&func, inst), Some(value), "{value}");
706            assert_eq!(regs(&func, inst), [into], "{value}");
707        }
708    }
709
710    /// A number the narrower move does not hold, which is everything above what fits in the bits it
711    /// writes and every negative number, since what it does to the rest of the register is clear it
712    /// rather than fill it with the sign.
713    #[test]
714    fn a_number_the_narrower_move_does_not_hold_stays_wide() {
715        for value in [-1, -7, 0x1_0000_0000, i64::MIN, i64::MAX] {
716            let (mut names, mut func, block) = empty();
717            let into = func.new_vreg(GPR);
718            let wide = op(&mut names, "mov_ri_64");
719            func.build(block, wide).def(into, GPR).imm(value).finish();
720
721            assert_eq!(takes(&mut func, &mut names), 0, "{value}");
722            assert_eq!(shape(&func, &names, block), ["mov_ri_64"], "{value}");
723        }
724    }
725
726    /// A zero the condition state is not free for, which the first rewrite has to leave alone. The
727    /// second one has nothing to do with the state and takes it, so the instruction that stays is
728    /// five bytes rather than seven.
729    #[test]
730    fn a_zero_the_state_is_not_free_for_is_narrowed_instead() {
731        let (mut names, mut func, block) = empty();
732        let left = func.new_vreg(GPR);
733        let right = func.new_vreg(GPR);
734        let into = func.new_vreg(GPR);
735        let byte = func.new_vreg(GPR);
736        let cmp = op(&mut names, "cmp_rr_32");
737        let zero = op(&mut names, "mov_ri_64");
738        let set = op(&mut names, "set_e");
739        func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
740        let inst = func.build(block, zero).def(into, GPR).imm(0).finish();
741        func.build(block, set).def(byte, GPR).finish();
742
743        assert_eq!(takes(&mut func, &mut names), 1);
744        assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_ri_32", "set_e"]);
745        assert_eq!(imm(&func, inst), Some(0));
746    }
747
748    /// A function the state carried across an edge turns down, which is the first rewrite's rule
749    /// and not the second one's. The narrower move writes no state and reads none, so a function
750    /// that rule turns down still gets it.
751    #[test]
752    fn a_function_the_carried_state_turns_down_is_still_narrowed() {
753        let (mut names, mut func, first) = empty();
754        let second = func.create_block();
755        let into = func.new_vreg(GPR);
756        let byte = func.new_vreg(GPR);
757        let wide = op(&mut names, "mov_ri_64");
758        let set = op(&mut names, "set_e");
759        func.build(first, wide).def(into, GPR).imm(7).finish();
760        func.build(second, set).def(byte, GPR).finish();
761
762        assert_eq!(takes(&mut func, &mut names), 1);
763        assert_eq!(shape(&func, &names, first), ["mov_ri_32"]);
764    }
765
766    /// A move of anything else. The shorter instruction writes zero, so it says the same thing only
767    /// where the longer one said zero.
768    #[test]
769    fn a_move_of_a_number_that_is_not_zero_stays() {
770        let (mut names, mut func, block) = empty();
771        let into = func.new_vreg(GPR);
772        let one = op(&mut names, "mov_ri_32");
773        func.build(block, one).def(into, GPR).imm(1).finish();
774
775        assert_eq!(takes(&mut func, &mut names), 0);
776        assert_eq!(shape(&func, &names, block), ["mov_ri_32"]);
777    }
778
779    /// Eight bits, where both spellings are two bytes. The target's table leaves it out and the pass
780    /// has nothing to look up, so the move stays and the condition state stays with it.
781    #[test]
782    fn eight_bits_buys_nothing_and_is_left_alone() {
783        let (mut names, mut func, block) = empty();
784        let into = func.new_vreg(GPR);
785        let zero = op(&mut names, "mov_ri_8");
786        func.build(block, zero).def(into, GPR).imm(0).finish();
787
788        assert_eq!(takes(&mut func, &mut names), 0);
789        assert_eq!(shape(&func, &names, block), ["mov_ri_8"]);
790    }
791
792    /// The cost of the rewrite, which is the zero going into a register in front of something that
793    /// reads a comparison of something else. The exclusive or would write over the answer the byte
794    /// is about, so the move stays.
795    #[test]
796    fn a_move_a_condition_reads_the_state_after_stays() {
797        let (mut names, mut func, block) = empty();
798        let left = func.new_vreg(GPR);
799        let right = func.new_vreg(GPR);
800        let into = func.new_vreg(GPR);
801        let byte = func.new_vreg(GPR);
802        let cmp = op(&mut names, "cmp_rr_32");
803        let zero = op(&mut names, "mov_ri_32");
804        let set = op(&mut names, "set_e");
805        func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
806        func.build(block, zero).def(into, GPR).imm(0).finish();
807        func.build(block, set).def(byte, GPR).finish();
808
809        assert_eq!(takes(&mut func, &mut names), 0);
810        assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_ri_32", "set_e"]);
811    }
812
813    /// The same three instructions with something writing the condition state in between. What the
814    /// byte reads is what the addition left, so the state the move would write is one nothing was
815    /// going to read and the rewrite is back on.
816    #[test]
817    fn a_state_something_else_writes_first_lets_the_rewrite_back_in() {
818        let (mut names, mut func, block) = empty();
819        let left = func.new_vreg(GPR);
820        let right = func.new_vreg(GPR);
821        let sum = func.new_vreg(GPR);
822        let into = func.new_vreg(GPR);
823        let byte = func.new_vreg(GPR);
824        let zero = op(&mut names, "mov_ri_32");
825        let add = op(&mut names, "add_rr_32");
826        let set = op(&mut names, "set_e");
827        func.build(block, zero).def(into, GPR).imm(0).finish();
828        func.build(block, add).def(sum, GPR).uses(left, GPR).uses(right, GPR).finish();
829        func.build(block, set).def(byte, GPR).finish();
830
831        assert_eq!(takes(&mut func, &mut names), 1);
832        assert_eq!(shape(&func, &names, block), ["xor_rr_32", "add_rr_32", "set_e"]);
833    }
834
835    /// A function where a block reads the condition state before it writes one, which is what a
836    /// state carried across an edge looks like from here. The passes in front say that does not
837    /// happen and this is where that is held to rather than believed, so the whole function is
838    /// turned down and the move in the other block stays as well.
839    #[test]
840    fn a_state_carried_into_a_block_turns_the_whole_function_down() {
841        let (mut names, mut func, first) = empty();
842        let second = func.create_block();
843        let into = func.new_vreg(GPR);
844        let byte = func.new_vreg(GPR);
845        let zero = op(&mut names, "mov_ri_32");
846        let set = op(&mut names, "set_e");
847        func.build(first, zero).def(into, GPR).imm(0).finish();
848        func.build(second, set).def(byte, GPR).finish();
849
850        assert_eq!(takes(&mut func, &mut names), 0);
851        assert_eq!(shape(&func, &names, first), ["mov_ri_32"]);
852    }
853
854    /// The third rewrite. A comparison of a register against zero asks whether the register is
855    /// zero, and so does a test of the register against itself, which says it without a number on
856    /// the instruction.
857    #[test]
858    fn a_comparison_against_zero_becomes_a_test_of_the_register_against_itself() {
859        for (wide, narrow) in [
860            ("cmp_ri_8", "test_rr_8"),
861            ("cmp_ri_16", "test_rr_16"),
862            ("cmp_ri_32", "test_rr_32"),
863            ("cmp_ri_64", "test_rr_64"),
864        ] {
865            let (mut names, mut func, block) = empty();
866            let value = func.new_vreg(GPR);
867            let byte = func.new_vreg(GPR);
868            let cmp = op(&mut names, wide);
869            let set = op(&mut names, "set_e");
870            let inst = func.build(block, cmp).uses(value, GPR).imm(0).finish();
871            func.build(block, set).def(byte, GPR).finish();
872
873            assert_eq!(takes(&mut func, &mut names), 1, "{wide}");
874            assert_eq!(shape(&func, &names, block), [narrow, "set_e"], "{wide}");
875            assert_eq!(regs(&func, inst), [value], "{wide}");
876            assert_eq!(imm(&func, inst), None, "{wide}");
877        }
878    }
879
880    /// A comparison against anything else, which the test cannot ask. What a test leaves is the
881    /// bits of the register it was given, so it answers one question and the question is zero.
882    #[test]
883    fn a_comparison_against_a_number_that_is_not_zero_is_left_alone() {
884        for value in [1, -1, 7, 255, i64::from(i32::MIN)] {
885            let (mut names, mut func, block) = empty();
886            let held = func.new_vreg(GPR);
887            let byte = func.new_vreg(GPR);
888            let cmp = op(&mut names, "cmp_ri_32");
889            let set = op(&mut names, "set_e");
890            let inst = func.build(block, cmp).uses(held, GPR).imm(value).finish();
891            func.build(block, set).def(byte, GPR).finish();
892
893            assert_eq!(takes(&mut func, &mut names), 0, "{value}");
894            assert_eq!(shape(&func, &names, block), ["cmp_ri_32", "set_e"], "{value}");
895            assert_eq!(imm(&func, inst), Some(value), "{value}");
896        }
897    }
898
899    /// The condition state is not a question this rewrite asks. The comparison writes the state and
900    /// the test writes the same state, so a comparison whose answer something reads right behind it
901    /// is rewritten exactly as one whose answer nothing wants is, and a function the carried state
902    /// rule turns down gets it too.
903    #[test]
904    fn a_comparison_is_tested_whatever_the_condition_state_is_doing() {
905        let (mut names, mut func, first) = empty();
906        let second = func.create_block();
907        let value = func.new_vreg(GPR);
908        let byte = func.new_vreg(GPR);
909        let cmp = op(&mut names, "cmp_ri_32");
910        let set = op(&mut names, "set_e");
911        func.build(first, cmp).uses(value, GPR).imm(0).finish();
912        // A block that reads the state before writing it, which is what `carried` turns a function
913        // down for and what the first rewrite is the only one to need.
914        func.build(second, set).def(byte, GPR).finish();
915
916        assert_eq!(takes(&mut func, &mut names), 1);
917        assert_eq!(shape(&func, &names, first), ["test_rr_32"]);
918        assert_eq!(shape(&func, &names, second), ["set_e"]);
919    }
920
921    /// The fourth rewrite, at every width and in both directions. An addition of one and a
922    /// subtraction of minus one are the instruction that adds one, and the other two are the one
923    /// that takes one away. The register is the one it had and the number is gone, the shorter
924    /// instruction being the one that carries the number in its opcode.
925    #[test]
926    fn adding_or_taking_away_one_becomes_the_instruction_that_says_so_in_its_opcode() {
927        for (name, by, into) in [
928            ("add_ri_8", 1, "inc_r_8"),
929            ("add_ri_16", 1, "inc_r_16"),
930            ("add_ri_32", 1, "inc_r_32"),
931            ("add_ri_64", 1, "inc_r_64"),
932            ("add_ri_8", -1, "dec_r_8"),
933            ("add_ri_16", -1, "dec_r_16"),
934            ("add_ri_32", -1, "dec_r_32"),
935            ("add_ri_64", -1, "dec_r_64"),
936            ("sub_ri_8", 1, "dec_r_8"),
937            ("sub_ri_16", 1, "dec_r_16"),
938            ("sub_ri_32", 1, "dec_r_32"),
939            ("sub_ri_64", 1, "dec_r_64"),
940            ("sub_ri_8", -1, "inc_r_8"),
941            ("sub_ri_16", -1, "inc_r_16"),
942            ("sub_ri_32", -1, "inc_r_32"),
943            ("sub_ri_64", -1, "inc_r_64"),
944        ] {
945            let (mut names, mut func, block) = empty();
946            let value = func.new_vreg(GPR);
947            let add = op(&mut names, name);
948            let inst =
949                func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(by).finish();
950
951            assert_eq!(small(&mut func, &mut names), 1, "{name} {by}");
952            assert_eq!(shape(&func, &names, block), [into], "{name} {by}");
953            assert_eq!(regs(&func, inst), [value, value], "{name} {by}");
954            assert_eq!(imm(&func, inst), None, "{name} {by}");
955        }
956    }
957
958    /// The same function at a level that asked for fast code, which is the goal doing its job. This
959    /// is the only rewrite in the pass that asks it, and it is the only one that is a trade.
960    #[test]
961    fn a_level_that_wanted_fast_code_keeps_the_addition() {
962        let (mut names, mut func, block) = empty();
963        let value = func.new_vreg(GPR);
964        let add = op(&mut names, "add_ri_32");
965        let inst = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
966
967        assert_eq!(takes(&mut func, &mut names), 0);
968        assert_eq!(shape(&func, &names, block), ["add_ri_32"]);
969        assert_eq!(imm(&func, inst), Some(1));
970    }
971
972    /// Any other number. The machine has an opcode that means one and none that means anything
973    /// else, so the constant is written out either way and the addition is already as short as it
974    /// gets.
975    #[test]
976    fn adding_anything_but_one_stays_an_addition() {
977        for by in [0, 2, -2, 7, 255, i64::from(i32::MIN)] {
978            let (mut names, mut func, block) = empty();
979            let value = func.new_vreg(GPR);
980            let add = op(&mut names, "add_ri_32");
981            func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(by).finish();
982
983            assert_eq!(small(&mut func, &mut names), 0, "{by}");
984            assert_eq!(shape(&func, &names, block), ["add_ri_32"], "{by}");
985        }
986    }
987
988    /// What the rewrite is really conditional on. Something behind it reading where the value sits
989    /// as an unsigned number is something reading the carry, and the carry is the one part of the
990    /// condition state the shorter instruction does not write.
991    #[test]
992    fn an_addition_whose_carry_something_reads_stays_an_addition() {
993        for reader in ["set_b", "set_be", "set_a", "set_ae", "adc_ri_32"] {
994            let (mut names, mut func, block) = empty();
995            let value = func.new_vreg(GPR);
996            let byte = func.new_vreg(GPR);
997            let add = op(&mut names, "add_ri_32");
998            let reads = op(&mut names, reader);
999            func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1000            func.build(block, reads).def(byte, GPR).finish();
1001
1002            assert_eq!(small(&mut func, &mut names), 0, "{reader}");
1003            assert_eq!(shape(&func, &names, block), ["add_ri_32", reader], "{reader}");
1004        }
1005    }
1006
1007    /// A reader of any other part of the state, which the shorter instruction writes exactly as the
1008    /// addition did. So the rewrite is not about whether the state is read, it is about which part.
1009    #[test]
1010    fn an_addition_whose_zero_or_sign_something_reads_still_steps() {
1011        for reader in ["set_e", "set_ne", "set_l", "set_le", "set_g", "set_ge"] {
1012            let (mut names, mut func, block) = empty();
1013            let value = func.new_vreg(GPR);
1014            let byte = func.new_vreg(GPR);
1015            let add = op(&mut names, "add_ri_32");
1016            let reads = op(&mut names, reader);
1017            func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1018            func.build(block, reads).def(byte, GPR).finish();
1019
1020            assert_eq!(small(&mut func, &mut names), 1, "{reader}");
1021            assert_eq!(shape(&func, &names, block), ["inc_r_32", reader], "{reader}");
1022        }
1023    }
1024
1025    /// The carry read behind an instruction that writes the rest of the state, which is what the
1026    /// walk asking the description rather than the flag is for. The addition in front of the
1027    /// comparison stays, because the comparison writes the carry the reader wants and the addition
1028    /// would not have to, and the addition behind it goes, because nothing reads a carry after it.
1029    #[test]
1030    fn a_write_of_the_state_ends_the_life_of_the_carry_and_a_step_does_not() {
1031        let (mut names, mut func, block) = empty();
1032        let value = func.new_vreg(GPR);
1033        let byte = func.new_vreg(GPR);
1034        let add = op(&mut names, "add_ri_32");
1035        let cmp = op(&mut names, "cmp_rr_32");
1036        let below = op(&mut names, "set_b");
1037        let first = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1038        func.build(block, cmp).uses(value, GPR).uses(value, GPR).finish();
1039        func.build(block, below).def(byte, GPR).finish();
1040
1041        assert_eq!(small(&mut func, &mut names), 1);
1042        assert_eq!(shape(&func, &names, block), ["inc_r_32", "cmp_rr_32", "set_b"]);
1043        assert_eq!(imm(&func, first), None);
1044    }
1045
1046    /// An instruction that leaves the carry alone is not a write of the condition state as far as
1047    /// the walk is concerned, which is what stops one of them from hiding a carry read behind it.
1048    /// The increment here is one a program wrote in a template rather than one this put there, and
1049    /// the addition in front of it is the only thing that sets the carry the reader wants, so the
1050    /// addition stays.
1051    #[test]
1052    fn a_step_does_not_hide_the_carry_read_behind_it() {
1053        let (mut names, mut func, block) = empty();
1054        let value = func.new_vreg(GPR);
1055        let byte = func.new_vreg(GPR);
1056        let add = op(&mut names, "add_ri_32");
1057        let step = op(&mut names, "inc_r_32");
1058        let below = op(&mut names, "set_b");
1059        let first = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1060        func.build(block, step).operand(reuse(value)).uses(value, GPR).finish();
1061        func.build(block, below).def(byte, GPR).finish();
1062
1063        assert_eq!(small(&mut func, &mut names), 0);
1064        assert_eq!(shape(&func, &names, block), ["add_ri_32", "inc_r_32", "set_b"]);
1065        assert_eq!(imm(&func, first), Some(1));
1066    }
1067
1068    /// Two additions in a row with a carry read behind them. The second one sets the carry the
1069    /// reader wants and stays, and the first one goes, because whatever the first leaves the second
1070    /// writes over. That is the same walk as the test above arriving at the other answer, and it is
1071    /// what says the rule is about the carry rather than about the addition.
1072    #[test]
1073    fn an_addition_the_next_addition_writes_over_still_steps() {
1074        let (mut names, mut func, block) = empty();
1075        let value = func.new_vreg(GPR);
1076        let byte = func.new_vreg(GPR);
1077        let add = op(&mut names, "add_ri_32");
1078        let below = op(&mut names, "set_b");
1079        func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1080        let second = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1081        func.build(block, below).def(byte, GPR).finish();
1082
1083        assert_eq!(small(&mut func, &mut names), 1);
1084        assert_eq!(shape(&func, &names, block), ["inc_r_32", "add_ri_32", "set_b"]);
1085        assert_eq!(imm(&func, second), Some(1));
1086    }
1087
1088    /// The instruction the whole function check used to stop at. A comparison that keeps a byte
1089    /// reads the condition state and the state it reads is the one it wrote itself a moment
1090    /// earlier, so a block opening with one is not a block reading what a predecessor left, and the
1091    /// move in the other block is rewritten.
1092    #[test]
1093    fn a_block_opening_with_a_comparison_that_keeps_a_byte_is_not_a_carried_state() {
1094        let (mut names, mut func, first) = empty();
1095        let second = func.create_block();
1096        let into = func.new_vreg(GPR);
1097        let byte = func.new_vreg(GPR);
1098        let value = func.new_vreg(GPR);
1099        let zero = op(&mut names, "mov_ri_32");
1100        let fused = op(&mut names, "cmp_set_e_32");
1101        func.build(first, zero).def(into, GPR).imm(0).finish();
1102        func.build(second, fused).def(byte, GPR).uses(value, GPR).uses(value, GPR).finish();
1103
1104        assert_eq!(takes(&mut func, &mut names), 1);
1105        assert_eq!(shape(&func, &names, first), ["xor_rr_32"]);
1106    }
1107
1108    /// The same sentence inside a block. What the comparison reads is what it wrote, so what it was
1109    /// handed is written over before anything looks at it, and the move in front of it may spend a
1110    /// state nothing wants.
1111    #[test]
1112    fn a_comparison_that_keeps_a_byte_ends_the_life_of_the_state() {
1113        let (mut names, mut func, block) = empty();
1114        let into = func.new_vreg(GPR);
1115        let byte = func.new_vreg(GPR);
1116        let value = func.new_vreg(GPR);
1117        let zero = op(&mut names, "mov_ri_32");
1118        let fused = op(&mut names, "cmp_set_e_32");
1119        func.build(block, zero).def(into, GPR).imm(0).finish();
1120        func.build(block, fused).def(byte, GPR).uses(value, GPR).uses(value, GPR).finish();
1121
1122        assert_eq!(takes(&mut func, &mut names), 1);
1123        assert_eq!(shape(&func, &names, block), ["xor_rr_32", "cmp_set_e_32"]);
1124    }
1125
1126    /// And the carry with it. A comparison that keeps a byte and asks where a value sits as an
1127    /// unsigned number reads the carry, and it is the carry it set itself, so the addition in front
1128    /// of it is free to become the instruction that leaves the carry alone.
1129    #[test]
1130    fn a_comparison_that_keeps_a_byte_does_not_keep_the_carry_alive() {
1131        let (mut names, mut func, block) = empty();
1132        let value = func.new_vreg(GPR);
1133        let byte = func.new_vreg(GPR);
1134        let add = op(&mut names, "add_ri_32");
1135        let fused = op(&mut names, "cmp_set_b_32");
1136        func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1137        func.build(block, fused).def(byte, GPR).uses(value, GPR).uses(value, GPR).finish();
1138
1139        assert_eq!(small(&mut func, &mut names), 1);
1140        assert_eq!(shape(&func, &names, block), ["inc_r_32", "cmp_set_b_32"]);
1141    }
1142
1143    /// The other kind of read, which is the one this must go on stopping at. An add with carry is
1144    /// reading the bit the instruction in front of it left rather than one it wrote itself, and it
1145    /// makes no comparison, which is how the description tells the two apart.
1146    #[test]
1147    fn an_add_with_carry_opening_a_block_is_still_a_carried_state() {
1148        let (mut names, mut func, first) = empty();
1149        let second = func.create_block();
1150        let into = func.new_vreg(GPR);
1151        let value = func.new_vreg(GPR);
1152        let zero = op(&mut names, "mov_ri_32");
1153        let adc = op(&mut names, "adc_ri_32");
1154        func.build(first, zero).def(into, GPR).imm(0).finish();
1155        func.build(second, adc).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1156
1157        assert_eq!(takes(&mut func, &mut names), 0);
1158        assert_eq!(shape(&func, &names, first), ["mov_ri_32"]);
1159    }
1160
1161    /// A name the description does not cover, which is anything without this target's prefix. It
1162    /// may read the condition state and it may write one, and the answer that is wrong about
1163    /// nothing is that it read it, so the move in front of it stays.
1164    #[test]
1165    fn a_name_this_target_does_not_know_stops_the_walk() {
1166        let (mut names, mut func, block) = empty();
1167        let left = func.new_vreg(GPR);
1168        let right = func.new_vreg(GPR);
1169        let into = func.new_vreg(GPR);
1170        let cmp = op(&mut names, "cmp_rr_32");
1171        let zero = op(&mut names, "mov_ri_32");
1172        let strange = mir::Opcode::new(names.intern("nowhere.thing"));
1173        func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
1174        func.build(block, zero).def(into, GPR).imm(0).finish();
1175        func.build(block, strange).finish();
1176
1177        assert_eq!(takes(&mut func, &mut names), 0);
1178        assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_ri_32", ""]);
1179    }
1180
1181    /// The fifth rewrite. An address that is a base register and nothing else is that register, so
1182    /// the instruction that works it out and keeps it is the move, which keeps both registers in the
1183    /// order it had them and drops the addressing mode it no longer has a place for.
1184    #[test]
1185    fn an_address_that_is_a_register_becomes_a_move() {
1186        let (mut names, mut func, block) = empty();
1187        let base = func.new_vreg(GPR);
1188        let into = func.new_vreg(GPR);
1189        let lea = op(&mut names, "lea_64");
1190        let mem = mir::Mem::at(mir::Operand::read(base, GPR));
1191        let inst = func.build(block, lea).def(into, GPR).mem(mem).finish();
1192
1193        assert_eq!(takes(&mut func, &mut names), 1);
1194        assert_eq!(shape(&func, &names, block), ["mov_rr_64"]);
1195        assert_eq!(regs(&func, inst), [into, base]);
1196        assert!(func[inst].mem.is_none());
1197    }
1198
1199    /// A constant added to the address, which is the shape most address computations have. The move
1200    /// adds nothing, so there is nothing here for it to say.
1201    #[test]
1202    fn an_address_with_a_constant_added_stays() {
1203        let (mut names, mut func, block) = empty();
1204        let base = func.new_vreg(GPR);
1205        let into = func.new_vreg(GPR);
1206        let lea = op(&mut names, "lea_64");
1207        let mem = mir::Mem { disp: 8, ..mir::Mem::at(mir::Operand::read(base, GPR)) };
1208        func.build(block, lea).def(into, GPR).mem(mem).finish();
1209
1210        assert_eq!(takes(&mut func, &mut names), 0);
1211        assert_eq!(shape(&func, &names, block), ["lea_64"]);
1212    }
1213
1214    /// An index, which is the other half of what an address computation is for. It is a
1215    /// multiplication and an addition and the move is neither.
1216    #[test]
1217    fn an_address_with_an_index_stays() {
1218        let (mut names, mut func, block) = empty();
1219        let base = func.new_vreg(GPR);
1220        let index = func.new_vreg(GPR);
1221        let into = func.new_vreg(GPR);
1222        let lea = op(&mut names, "lea_64");
1223        let mem = mir::Mem {
1224            index: Some(mir::Operand::read(index, GPR)),
1225            scale: 4,
1226            ..mir::Mem::at(mir::Operand::read(base, GPR))
1227        };
1228        func.build(block, lea).def(into, GPR).mem(mem).finish();
1229
1230        assert_eq!(takes(&mut func, &mut names), 0);
1231        assert_eq!(shape(&func, &names, block), ["lea_64"]);
1232    }
1233
1234    /// The address of a global, which names no register at all. What it works out is a number the
1235    /// assembler fills in rather than a number that is already somewhere, so there is nothing for a
1236    /// move to move.
1237    #[test]
1238    fn an_address_of_a_symbol_stays() {
1239        let (mut names, mut func, block) = empty();
1240        let into = func.new_vreg(GPR);
1241        let lea = op(&mut names, "lea_64");
1242        let mem = mir::Mem::of(names.intern("table"));
1243        func.build(block, lea).def(into, GPR).mem(mem).finish();
1244
1245        assert_eq!(takes(&mut func, &mut names), 0);
1246        assert_eq!(shape(&func, &names, block), ["lea_64"]);
1247    }
1248
1249    /// And it does not wait on the condition state. Neither the address computation nor the move
1250    /// writes any, so a byte reading a comparison from in front of it reads the same comparison
1251    /// afterwards, and the rewrite is taken in the one function the first rewrite has to turn down.
1252    #[test]
1253    fn an_address_is_copied_whatever_the_state_behind_it_is() {
1254        let (mut names, mut func, block) = empty();
1255        let left = func.new_vreg(GPR);
1256        let right = func.new_vreg(GPR);
1257        let base = func.new_vreg(GPR);
1258        let into = func.new_vreg(GPR);
1259        let byte = func.new_vreg(GPR);
1260        let cmp = op(&mut names, "cmp_rr_32");
1261        let lea = op(&mut names, "lea_64");
1262        let set = op(&mut names, "set_e");
1263        let mem = mir::Mem::at(mir::Operand::read(base, GPR));
1264        func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
1265        func.build(block, lea).def(into, GPR).mem(mem).finish();
1266        func.build(block, set).def(byte, GPR).finish();
1267
1268        assert_eq!(takes(&mut func, &mut names), 1);
1269        assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_rr_64", "set_e"]);
1270    }
1271}