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_base::hash::Map;
167use rucc_cost::Goal;
168use rucc_mir::{self as mir, Role};
169use rucc_target::{FlagInsts, MachineInsts, Reads, ShortInsts};
170
171use crate::changes::{self, Changes, Plan};
172
173/// Rewrites every instruction that has a shorter spelling nothing would notice.
174///
175/// Gives back how many were rewritten, which the tests read and nothing else does.
176pub fn shorter(
177 func: &mut mir::Func,
178 short: &ShortInsts,
179 flags: &FlagInsts,
180 machine: &MachineInsts,
181 names: &mut Interner,
182 goal: Goal,
183) -> usize {
184 // Every name a rewrite could want, before the walk rather than inside it, because the walk
185 // holds a name it read out of the interner while it edits the function and interning a new one
186 // there would be the same interner borrowed twice. The same reason [`crate::compare`] has.
187 let wanted = short.zeroing.iter().map(|entry| entry.into);
188 let wanted = wanted.chain(short.narrowing.iter().map(|entry| entry.into));
189 let wanted = wanted.chain(short.testing.iter().map(|entry| entry.into));
190 let wanted = wanted.chain(short.stepping.iter().map(|entry| entry.into));
191 let wanted = wanted.chain(short.copying.iter().map(|entry| entry.into));
192 let opcodes: Vec<(&'static str, mir::Opcode)> = wanted
193 .map(|into| (into, mir::Opcode::new(names.intern(&format!("{}{into}", short.prefix)))))
194 .collect();
195 let names = &*names;
196 let mut counts = changes::Reads::of(func);
197 let mut took = 0;
198 let mut seen = Map::default();
199 // Whether the rewrite that spends the condition state may be asked for at all. The narrower
200 // instruction neither reads the state nor writes it, so it is not asked this and a function
201 // this turns down still gets that one.
202 let free = !carried(func, short, flags, names, &mut seen);
203 // Whether the rewrite that trades the carry for a byte may be asked for. It is the one thing
204 // here that is not free, so it waits for a level that said it wanted small code.
205 let small = free && goal == Goal::Size;
206 for block in func.blocks().collect::<Vec<_>>() {
207 // Backwards, because the question each instruction asks is about the ones behind it. The
208 // state is dead at the end of a block, which is the invariant [`carried`] has just held the
209 // function to.
210 let mut live = false;
211 // The same question about the carry alone, which is the part of the state the shorter
212 // addition does not write. It starts false for the reason `live` does and moves separately,
213 // because an instruction that writes the whole state ends the life of both and one that
214 // writes everything but the carry ends the life of neither.
215 let mut carry = false;
216 for inst in func.insts(block).collect::<Vec<_>>().into_iter().rev() {
217 // Asked again after each rewrite that is taken, since what stands there then is another
218 // instruction and the questions below are about that one.
219 let mut known = Known::of(&mut seen, func, short, flags, names, inst);
220 if free && !live && known.zeroing {
221 let into = shorter_form(func, short, names, &opcodes, inst);
222 if into.is_some_and(|op| zeroed(func, &mut counts, machine, names, inst, op)) {
223 took += 1;
224 // What stands there now writes the state, and the state was already dead, so
225 // nothing about what the instructions in front of it may do has changed.
226 continue;
227 }
228 }
229 // The zero that could not become an exclusive or can still be written in fewer bytes,
230 // which is why this is asked after that one and not instead of it.
231 let into = if known.narrowing {
232 narrower_form(func, short, names, &opcodes, inst)
233 } else {
234 None
235 };
236 if into.is_some_and(|op| narrowed(func, &mut counts, machine, names, inst, op)) {
237 took += 1;
238 known = Known::of(&mut seen, func, short, flags, names, inst);
239 // What stands there now is the same instruction at half the width, which is a
240 // move either way, so what it does to the state is what it did before: nothing.
241 }
242 // A comparison against zero asked of the register alone. Nothing about where the state
243 // is live comes into it, because the shorter instruction writes the same five bits of
244 // state the comparison wrote, so this is asked of every instruction whatever the walk
245 // has seen behind it.
246 let into =
247 if known.testing { tested_form(func, short, names, &opcodes, inst) } else { None };
248 if into.is_some_and(|op| tested(func, &mut counts, machine, names, inst, op)) {
249 took += 1;
250 known = Known::of(&mut seen, func, short, flags, names, inst);
251 }
252 // An address that is a register, written as the move it is. Nothing about the condition
253 // state comes into it either, since neither instruction writes any, so this is asked of
254 // every instruction the same way the narrower move is.
255 let into =
256 if known.copying { copied_form(func, short, names, &opcodes, inst) } else { None };
257 if into.is_some_and(|op| copied(func, &mut counts, machine, names, inst, op)) {
258 took += 1;
259 known = Known::of(&mut seen, func, short, flags, names, inst);
260 }
261 // Adding one with the one in the opcode, which is the only rewrite here that is a
262 // trade. It needs the carry to be dead rather than the whole state, since that is the
263 // only part of the state the shorter instruction leaves behind, and it needs the level
264 // to have asked for small code.
265 if small && !carry && known.stepping {
266 let into = stepped_form(func, short, names, &opcodes, inst);
267 if into.is_some_and(|op| stepped(func, &mut counts, machine, names, inst, op)) {
268 took += 1;
269 known = Known::of(&mut seen, func, short, flags, names, inst);
270 // What stands there now writes everything but the carry, and the carry was
271 // already dead, so both answers below are the ones they already are and the
272 // walk past it is the walk it would have taken anyway.
273 }
274 }
275 if !known.covered {
276 // A name the description does not cover may have read the state and may have
277 // written it, and the answer that finds fewer rewrites is that it read it.
278 live = true;
279 carry = true;
280 continue;
281 }
282 // What it reads before whether it writes, because an instruction can do both and the
283 // read it does is a read of what is there now. An add with carry is the one that does,
284 // and asking the other way round would call it the end of the state's life and let a
285 // rewrite in front of it take the carry away.
286 //
287 // Unless what it reads is what it wrote itself. A comparison that keeps a byte makes
288 // the comparison and reads the answer in the one instruction, so the state it was
289 // handed is state it wrote over before anything looked at it, and it ends a life rather
290 // than extending one. Asking the description which kind it is rather than stopping at
291 // the word read is most of what this pass gets to do in real code, since a C function
292 // of any size has one of these in it.
293 if known.own {
294 live = false;
295 carry = false;
296 } else if let Some(reads) = known.reads {
297 live = true;
298 // Which part of the state the condition on it is about. A condition that asks where
299 // a value sits as an unsigned number reads the carry, and so does an instruction
300 // that is adding a carry on rather than asking a question about one.
301 if matches!(reads, Reads::Unsigned | Reads::Carry) {
302 carry = true;
303 }
304 } else if known.ends {
305 // An instruction that writes the state ends the life of everything in it. One that
306 // writes all of it but the carry ends the life of none of it, which is the second
307 // half of the sentence and is why this asks the description rather than stopping at
308 // the flag. That answer is about `live` as much as about `carry`: a rewrite in front
309 // that spends the state would be spending a carry this instruction was going to
310 // leave for something behind it.
311 live = false;
312 carry = false;
313 }
314 }
315 }
316 took
317}
318
319/// Whether any block reads the condition state before writing it, which is what a state carried in
320/// from a predecessor would look like from inside this pass.
321///
322/// The passes in front are the ones that promise this does not happen and the promise is theirs to
323/// keep, so what this does is hold them to it rather than restate it. A function where it is broken
324/// gets no rewrites at all, which is the answer that is wrong about nothing.
325///
326/// An instruction that leaves the carry alone does not count as having written the state here, for
327/// the same reason it does not count as having written it in the walk. A block opening with one and
328/// reading a carry afterwards is reading a carry a predecessor left, which is exactly the shape this
329/// is looking for, and stopping at it would be calling that block clean.
330///
331/// An instruction that reads what it wrote itself does not count as having read the state, for the
332/// same reason it does not in the walk. A block opening with a comparison that keeps a byte opens
333/// with a comparison, and what the comparison found is not what anything in front of it left.
334/// Counting it as a read is the difference between this turning down a few functions and turning
335/// down most of them, because a comparison that keeps a byte is what every `!` and every `==` in a
336/// value position comes out as.
337fn carried(
338 func: &mir::Func,
339 short: &ShortInsts,
340 flags: &FlagInsts,
341 names: &Interner,
342 seen: &mut Map<mir::Opcode, Known>,
343) -> bool {
344 func.blocks().any(|block| {
345 for inst in func.insts(block) {
346 let known = Known::of(seen, func, short, flags, names, inst);
347 if !known.covered {
348 return true;
349 }
350 if known.reads.is_some() && !known.own {
351 return true;
352 }
353 if known.ends {
354 return false;
355 }
356 }
357 false
358 })
359}
360
361/// What the description says about one opcode, asked once for each opcode a function has rather
362/// than once for each instruction.
363///
364/// Every answer here is a walk down one of the target's tables comparing names, and the walk above
365/// asks most of them of every instruction while nearly every answer is no. A function has a few
366/// hundred opcodes at most, so each one is asked about the first time it turns up and read back
367/// after that. On jtckdint's `test.c` at `-O2` the comparing of names in this pass was about two and
368/// a half percent of the build.
369///
370/// The forms are only whether the table has an entry for the name. Whether the instruction carries
371/// the number or the address the shorter one needs is the instruction's own business and is still
372/// asked of it.
373#[derive(Debug, Clone, Copy)]
374struct Known {
375 /// Whether it has a shorter way of writing zero.
376 zeroing: bool,
377 /// Whether it has a narrower instruction.
378 narrowing: bool,
379 /// Whether it has a shorter way of comparing against zero.
380 testing: bool,
381 /// Whether it has a move that says the same thing.
382 copying: bool,
383 /// Whether it has a shorter addition for some number.
384 stepping: bool,
385 /// Whether the description covers the name at all. See [`opcode`].
386 covered: bool,
387 /// Whether it reads what it wrote itself. See [`FlagInsts::asks_what_it_reads`].
388 own: bool,
389 /// Which part of the condition state it reads.
390 reads: Option<Reads>,
391 /// Whether it writes the whole of the condition state, the carry included.
392 ends: bool,
393}
394
395impl Known {
396 fn of(
397 seen: &mut Map<mir::Opcode, Self>,
398 func: &mir::Func,
399 short: &ShortInsts,
400 flags: &FlagInsts,
401 names: &Interner,
402 inst: mir::Inst,
403 ) -> Self {
404 *seen.entry(func[inst].opcode).or_insert_with(|| {
405 let bare = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix);
406 let has =
407 |name: fn(&ShortInsts, &str) -> bool| bare.is_some_and(|bare| name(short, bare));
408 let name = opcode(func, flags, names, inst);
409 Self {
410 zeroing: has(|short, bare| short.zeroed(bare).is_some()),
411 narrowing: has(|short, bare| short.narrowed(bare).is_some()),
412 testing: has(|short, bare| short.tested(bare).is_some()),
413 copying: has(|short, bare| short.copied(bare).is_some()),
414 stepping: has(|short, bare| short.stepping.iter().any(|entry| entry.name == bare)),
415 covered: name.is_some(),
416 own: name.is_some_and(|name| flags.asks_what_it_reads(name)),
417 reads: name.and_then(|name| flags.reads(name)),
418 ends: name.is_some_and(|name| (flags.writes)(name) && !short.steps(name)),
419 }
420 })
421 }
422}
423
424/// The shorter instruction this one has, when it has one and the constant it carries is the one
425/// that instruction writes.
426///
427/// The name says which instruction it is and the description says which names have a shorter
428/// spelling, and neither of them says what number this one holds. That is the half that decides
429/// whether the shorter spelling says the same thing, since the short way of writing zero is only
430/// the short way of writing zero.
431fn shorter_form(
432 func: &mir::Func,
433 short: &ShortInsts,
434 names: &Interner,
435 opcodes: &[(&'static str, mir::Opcode)],
436 inst: mir::Inst,
437) -> Option<mir::Opcode> {
438 let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
439 let into = short.zeroed(name)?;
440 if func[inst].imm.map(|at| func[at].0) != Some(0) {
441 return None;
442 }
443 opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
444}
445
446/// The narrower instruction this one has, when it has one and the number it carries is one that
447/// instruction holds.
448///
449/// A number the narrower instruction cannot hold is every negative one and everything above what
450/// fits in the bits it writes, since what it does to the rest of the register is clear it. So the
451/// question is not whether the number fits in that many bits the way the program meant it, which is
452/// a question about a type, but whether the bits the wide instruction would leave in the register
453/// are the bits the narrow one leaves there, which is a question about the number.
454fn narrower_form(
455 func: &mir::Func,
456 short: &ShortInsts,
457 names: &Interner,
458 opcodes: &[(&'static str, mir::Opcode)],
459 inst: mir::Inst,
460) -> Option<mir::Opcode> {
461 let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
462 let narrow = short.narrowed(name)?;
463 let held = u64::try_from(func[func[inst].imm?].0).ok()?;
464 if narrow.writes >= u64::BITS || held >= 1u64 << narrow.writes {
465 return None;
466 }
467 opcodes.iter().find(|&&(at, _)| at == narrow.into).map(|&(_, opcode)| opcode)
468}
469
470/// Rewrites the move into the narrower move, which is the same instruction with a different name.
471///
472/// So the operands are the ones it had, where the exclusive or below needs its own built: the two
473/// moves take a register they write and a number, and the number is the one that was already there.
474/// A description where that is not so is one [`Changes`] turns down, and a rewrite it turns down is
475/// one this reports as not taken rather than one that goes in anyway.
476fn narrowed(
477 func: &mut mir::Func,
478 counts: &mut changes::Reads,
479 machine: &MachineInsts,
480 names: &Interner,
481 inst: mir::Inst,
482 opcode: mir::Opcode,
483) -> bool {
484 let mut set = Changes::new();
485 set.rewrite(inst, Plan { opcode, ..Plan::of(func, inst) });
486 set.commit(func, counts, names, machine).is_ok()
487}
488
489/// The shorter comparison this one has, when it has one and the constant it carries is zero.
490///
491/// Zero is the whole of it. A comparison of a register against itself asks whether the register is
492/// zero and nothing else, so the description's entry says what to write instead of a comparison
493/// against zero and says nothing about a comparison against anything, and an instruction carrying
494/// any other number is one this walks past.
495fn tested_form(
496 func: &mir::Func,
497 short: &ShortInsts,
498 names: &Interner,
499 opcodes: &[(&'static str, mir::Opcode)],
500 inst: mir::Inst,
501) -> Option<mir::Opcode> {
502 let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
503 let into = short.tested(name)?;
504 if func[inst].imm.map(|at| func[at].0) != Some(0) {
505 return None;
506 }
507 opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
508}
509
510/// Rewrites the comparison into the test, which reads the register the comparison read and drops
511/// the constant.
512///
513/// The operands are the ones it had, for the reason [`narrowed`] keeps them: both instructions name
514/// one register and read it, and what changes is the number, which the shorter one does not carry.
515/// So the constant goes and nothing else does. A description where the two are not that shape is one
516/// [`Changes`] turns down, and this reports a rewrite it turned down as not taken.
517fn tested(
518 func: &mut mir::Func,
519 counts: &mut changes::Reads,
520 machine: &MachineInsts,
521 names: &Interner,
522 inst: mir::Inst,
523 opcode: mir::Opcode,
524) -> bool {
525 let mut set = Changes::new();
526 set.rewrite(inst, Plan { opcode, imm: None, ..Plan::of(func, inst) });
527 set.commit(func, counts, names, machine).is_ok()
528}
529
530/// The move this address computation is, when the address it works out is a register.
531///
532/// Which is an addressing mode naming a base and nothing else. An index is a multiplication and an
533/// addition, a constant is an addition, and a symbol or a label is an address the assembler fills in
534/// later, so any of those is work the move does not do. What is left is a mode that says to take
535/// what is in one register, and taking what is in one register is the move.
536///
537/// The width is not asked about, unlike the narrower move above. An address on this machine is
538/// sixty four bits wide whatever is at it, so an address computation that keeps its answer keeps all
539/// of it, and the move the description names beside it is the move of that width.
540fn copied_form(
541 func: &mir::Func,
542 short: &ShortInsts,
543 names: &Interner,
544 opcodes: &[(&'static str, mir::Opcode)],
545 inst: mir::Inst,
546) -> Option<mir::Opcode> {
547 let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
548 let into = short.copied(name)?;
549 let amode = func[inst].mem.map(|at| func[at])?;
550 if amode.base.is_none() || amode.index.is_some() || amode.disp != 0 {
551 return None;
552 }
553 if amode.symbol.is_some() || amode.block.is_some() || amode.table.is_some() {
554 return None;
555 }
556 if amode.segment.is_some() {
557 return None;
558 }
559 opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
560}
561
562/// Rewrites the address computation into the move, which keeps the operands and drops the mode.
563///
564/// The operands are already the move's. An instruction with an addressing mode carries the registers
565/// that mode names in its operand vector, behind the ones it writes, so an address computation whose
566/// mode is one base is an instruction that writes one register and reads one register, in that
567/// order, which is the move's shape. What goes is the mode itself, since the move has none.
568///
569/// A description where those two are not the same shape is one [`Changes`] turns down, and this
570/// reports a rewrite it turned down as not taken, which is how an address computation with more in
571/// its operand vector than the mode accounted for is left alone rather than guessed at.
572fn copied(
573 func: &mut mir::Func,
574 counts: &mut changes::Reads,
575 machine: &MachineInsts,
576 names: &Interner,
577 inst: mir::Inst,
578 opcode: mir::Opcode,
579) -> bool {
580 let mut set = Changes::new();
581 set.rewrite(inst, Plan { opcode, amode: None, ..Plan::of(func, inst) });
582 set.commit(func, counts, names, machine).is_ok()
583}
584
585/// Rewrites the move into the exclusive or, which names the one register the move wrote in every
586/// operand it has.
587///
588/// The shapes come from the description rather than from the move, since the shorter instruction is
589/// not the shape the longer one was: the exclusive or writes a register it also reads, which on this
590/// machine is an operand constrained to the same place as one of the reads, and a plan whose
591/// operands do not say so is one [`Changes`] turns down. So each operand is built to what the
592/// description asks for and the register in it is the one the move wrote, which after allocation is
593/// a physical register and so is a register every operand can name without anything being arranged.
594/// The constant goes with the move, the shorter instruction being the one that carries none.
595///
596/// A description whose operands are not all of the register's class, or which writes more than the
597/// one register or none, is a description this does not fit, and the answer there is to leave the
598/// instruction alone rather than to guess.
599fn zeroed(
600 func: &mut mir::Func,
601 counts: &mut changes::Reads,
602 machine: &MachineInsts,
603 names: &Interner,
604 inst: mir::Inst,
605 opcode: mir::Opcode,
606) -> bool {
607 let written: Vec<mir::Operand> = func[func[inst].operands]
608 .iter()
609 .filter(|operand| operand.role != Role::Use)
610 .copied()
611 .collect();
612 let [def] = written[..] else { return false };
613 let bare = machine.bare(names.resolve(opcode.name()));
614 let Some(desc) = (machine.operands)(bare) else { return false };
615 if desc.iter().any(|want| want.class != def.class) {
616 return false;
617 }
618 if desc.iter().filter(|want| want.role != Role::Use).count() != 1 {
619 return false;
620 }
621 let operands = desc
622 .iter()
623 .map(|want| mir::Operand {
624 reg: def.reg,
625 class: want.class,
626 role: want.role,
627 constraint: want.constraint,
628 })
629 .collect();
630 let mut set = Changes::new();
631 set.rewrite(inst, Plan { opcode, operands, imm: None, ..Plan::of(func, inst) });
632 set.commit(func, counts, names, machine).is_ok()
633}
634
635/// The shorter addition this one has, when it has one and the number it carries is the number that
636/// shorter instruction is about.
637///
638/// Both halves again, and the second one is doing more work here than anywhere else in this pass.
639/// One addition has two shorter instructions, one for each of the two numbers a machine has an
640/// opcode for, and a subtraction has the same two the other way round, so the number is what says
641/// which of the two is meant rather than only whether either is.
642fn stepped_form(
643 func: &mir::Func,
644 short: &ShortInsts,
645 names: &Interner,
646 opcodes: &[(&'static str, mir::Opcode)],
647 inst: mir::Inst,
648) -> Option<mir::Opcode> {
649 let name = names.resolve(func[inst].opcode.name()).strip_prefix(short.prefix)?;
650 let into = short.stepped(name, func[func[inst].imm?].0)?;
651 opcodes.iter().find(|&&(at, _)| at == into).map(|&(_, opcode)| opcode)
652}
653
654/// Rewrites the addition into the one that carries its number in its opcode.
655///
656/// The operands are the ones it had, for the reason [`tested`] keeps them: both instructions write
657/// one register and read that same register, and what changes is the number, which the shorter one
658/// does not carry. So the constant goes and nothing else does.
659fn stepped(
660 func: &mut mir::Func,
661 counts: &mut changes::Reads,
662 machine: &MachineInsts,
663 names: &Interner,
664 inst: mir::Inst,
665 opcode: mir::Opcode,
666) -> bool {
667 let mut set = Changes::new();
668 set.rewrite(inst, Plan { opcode, imm: None, ..Plan::of(func, inst) });
669 set.commit(func, counts, names, machine).is_ok()
670}
671
672/// The name this target knows an instruction by, for an instruction that is one of this target's.
673///
674/// The opcode in machine IR carries the target's prefix, because a function in the middle of being
675/// compiled holds instructions of one machine and the prefix is what says which. Anything without
676/// it is not something this description covers, and the walk treats that as knowing nothing rather
677/// than as knowing it is safe.
678fn opcode<'a>(
679 func: &mir::Func,
680 flags: &FlagInsts,
681 names: &'a Interner,
682 inst: mir::Inst,
683) -> Option<&'a str> {
684 names.resolve(func[inst].opcode.name()).strip_prefix(flags.prefix)
685}
686
687#[cfg(test)]
688mod tests {
689 use rucc_target::x86_64::{FLAGS, GPR, MACHINE, SHORT};
690
691 use super::*;
692
693 /// A function with one block, and the names it was built with.
694 fn empty() -> (Interner, mir::Func, mir::Block) {
695 let mut names = Interner::new();
696 let mut func = mir::Func::new(names.intern("f"));
697 let block = func.create_block();
698 (names, func, block)
699 }
700
701 /// The opcode of that name on this target.
702 fn op(names: &mut Interner, name: &str) -> mir::Opcode {
703 mir::Opcode::new(names.intern(&format!("{}{name}", SHORT.prefix)))
704 }
705
706 /// The pass, over the machine this crate has a backend for, at a level that wanted fast code.
707 fn takes(func: &mut mir::Func, names: &mut Interner) -> usize {
708 shorter(func, &SHORT, &FLAGS, &MACHINE, names, Goal::Speed)
709 }
710
711 /// The same pass at a level that wanted small code, which is the only one that steps.
712 fn small(func: &mut mir::Func, names: &mut Interner) -> usize {
713 shorter(func, &SHORT, &FLAGS, &MACHINE, names, Goal::Size)
714 }
715
716 /// What every instruction in a block came to, as opcodes with the target's prefix taken off.
717 fn shape(func: &mir::Func, names: &Interner, block: mir::Block) -> Vec<String> {
718 func.insts(block)
719 .map(|inst| {
720 names
721 .resolve(func[inst].opcode.name())
722 .strip_prefix(SHORT.prefix)
723 .unwrap_or("")
724 .to_owned()
725 })
726 .collect()
727 }
728
729 /// The destination of a two-address instruction, which the description constrains to the same
730 /// register as the first source. The builder's own `def` leaves the constraint off, and the
731 /// change framework holds a rewrite to the shape the target asks for, so a test that built one
732 /// without it would be a test of a function the allocator could not have produced.
733 fn reuse(reg: mir::Reg) -> mir::Operand {
734 mir::Operand {
735 reg,
736 class: GPR,
737 role: Role::Def,
738 constraint: rucc_mir::Constraint::Reuse(1),
739 }
740 }
741
742 /// The registers an instruction names, in the order its operands do.
743 fn regs(func: &mir::Func, inst: mir::Inst) -> Vec<mir::Reg> {
744 func[func[inst].operands].iter().map(|operand| operand.reg).collect()
745 }
746
747 /// The number an instruction carries, for an instruction that carries one.
748 fn imm(func: &mir::Func, inst: mir::Inst) -> Option<i64> {
749 func[inst].imm.map(|at| func[at].0)
750 }
751
752 /// The shape the pass is for: a move of zero with nothing reading the condition state after it
753 /// becomes the exclusive or, which names the register it writes in all three of its operands and
754 /// carries no constant.
755 #[test]
756 fn a_move_of_zero_becomes_an_exclusive_or() {
757 let (mut names, mut func, block) = empty();
758 let into = func.new_vreg(GPR);
759 let zero = op(&mut names, "mov_ri_32");
760 let inst = func.build(block, zero).def(into, GPR).imm(0).finish();
761
762 assert_eq!(takes(&mut func, &mut names), 1);
763 assert_eq!(shape(&func, &names, block), ["xor_rr_32"]);
764 assert_eq!(regs(&func, inst), [into, into, into]);
765 assert!(func[inst].imm.is_none());
766 }
767
768 /// Sixty-four bits is the same rewrite and the biggest one, since the long way of writing a zero
769 /// there is seven bytes. The instruction it becomes is the thirty-two bit one, which clears the
770 /// half of the register it does not write and so leaves the same sixty-four bit zero in one
771 /// byte less.
772 #[test]
773 fn sixty_four_bits_is_the_same_rewrite_at_half_the_width() {
774 let (mut names, mut func, block) = empty();
775 let into = func.new_vreg(GPR);
776 let zero = op(&mut names, "mov_ri_64");
777 func.build(block, zero).def(into, GPR).imm(0).finish();
778
779 assert_eq!(takes(&mut func, &mut names), 1);
780 assert_eq!(shape(&func, &names, block), ["xor_rr_32"]);
781 }
782
783 /// The other rewrite. A number that is not zero has nothing shorter than a move, and the move
784 /// that writes half the register is shorter than the one that writes all of it.
785 #[test]
786 fn a_number_a_narrower_move_holds_is_written_by_the_narrower_move() {
787 for value in [1, 7, 0x7fff_ffff, 0x8000_0000, 0xffff_ffff] {
788 let (mut names, mut func, block) = empty();
789 let into = func.new_vreg(GPR);
790 let wide = op(&mut names, "mov_ri_64");
791 let inst = func.build(block, wide).def(into, GPR).imm(value).finish();
792
793 assert_eq!(takes(&mut func, &mut names), 1, "{value}");
794 assert_eq!(shape(&func, &names, block), ["mov_ri_32"], "{value}");
795 assert_eq!(imm(&func, inst), Some(value), "{value}");
796 assert_eq!(regs(&func, inst), [into], "{value}");
797 }
798 }
799
800 /// A number the narrower move does not hold, which is everything above what fits in the bits it
801 /// writes and every negative number, since what it does to the rest of the register is clear it
802 /// rather than fill it with the sign.
803 #[test]
804 fn a_number_the_narrower_move_does_not_hold_stays_wide() {
805 for value in [-1, -7, 0x1_0000_0000, i64::MIN, i64::MAX] {
806 let (mut names, mut func, block) = empty();
807 let into = func.new_vreg(GPR);
808 let wide = op(&mut names, "mov_ri_64");
809 func.build(block, wide).def(into, GPR).imm(value).finish();
810
811 assert_eq!(takes(&mut func, &mut names), 0, "{value}");
812 assert_eq!(shape(&func, &names, block), ["mov_ri_64"], "{value}");
813 }
814 }
815
816 /// A zero the condition state is not free for, which the first rewrite has to leave alone. The
817 /// second one has nothing to do with the state and takes it, so the instruction that stays is
818 /// five bytes rather than seven.
819 #[test]
820 fn a_zero_the_state_is_not_free_for_is_narrowed_instead() {
821 let (mut names, mut func, block) = empty();
822 let left = func.new_vreg(GPR);
823 let right = func.new_vreg(GPR);
824 let into = func.new_vreg(GPR);
825 let byte = func.new_vreg(GPR);
826 let cmp = op(&mut names, "cmp_rr_32");
827 let zero = op(&mut names, "mov_ri_64");
828 let set = op(&mut names, "set_e");
829 func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
830 let inst = func.build(block, zero).def(into, GPR).imm(0).finish();
831 func.build(block, set).def(byte, GPR).finish();
832
833 assert_eq!(takes(&mut func, &mut names), 1);
834 assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_ri_32", "set_e"]);
835 assert_eq!(imm(&func, inst), Some(0));
836 }
837
838 /// A function the state carried across an edge turns down, which is the first rewrite's rule
839 /// and not the second one's. The narrower move writes no state and reads none, so a function
840 /// that rule turns down still gets it.
841 #[test]
842 fn a_function_the_carried_state_turns_down_is_still_narrowed() {
843 let (mut names, mut func, first) = empty();
844 let second = func.create_block();
845 let into = func.new_vreg(GPR);
846 let byte = func.new_vreg(GPR);
847 let wide = op(&mut names, "mov_ri_64");
848 let set = op(&mut names, "set_e");
849 func.build(first, wide).def(into, GPR).imm(7).finish();
850 func.build(second, set).def(byte, GPR).finish();
851
852 assert_eq!(takes(&mut func, &mut names), 1);
853 assert_eq!(shape(&func, &names, first), ["mov_ri_32"]);
854 }
855
856 /// A move of anything else. The shorter instruction writes zero, so it says the same thing only
857 /// where the longer one said zero.
858 #[test]
859 fn a_move_of_a_number_that_is_not_zero_stays() {
860 let (mut names, mut func, block) = empty();
861 let into = func.new_vreg(GPR);
862 let one = op(&mut names, "mov_ri_32");
863 func.build(block, one).def(into, GPR).imm(1).finish();
864
865 assert_eq!(takes(&mut func, &mut names), 0);
866 assert_eq!(shape(&func, &names, block), ["mov_ri_32"]);
867 }
868
869 /// Eight bits, where both spellings are two bytes. The target's table leaves it out and the pass
870 /// has nothing to look up, so the move stays and the condition state stays with it.
871 #[test]
872 fn eight_bits_buys_nothing_and_is_left_alone() {
873 let (mut names, mut func, block) = empty();
874 let into = func.new_vreg(GPR);
875 let zero = op(&mut names, "mov_ri_8");
876 func.build(block, zero).def(into, GPR).imm(0).finish();
877
878 assert_eq!(takes(&mut func, &mut names), 0);
879 assert_eq!(shape(&func, &names, block), ["mov_ri_8"]);
880 }
881
882 /// The cost of the rewrite, which is the zero going into a register in front of something that
883 /// reads a comparison of something else. The exclusive or would write over the answer the byte
884 /// is about, so the move stays.
885 #[test]
886 fn a_move_a_condition_reads_the_state_after_stays() {
887 let (mut names, mut func, block) = empty();
888 let left = func.new_vreg(GPR);
889 let right = func.new_vreg(GPR);
890 let into = func.new_vreg(GPR);
891 let byte = func.new_vreg(GPR);
892 let cmp = op(&mut names, "cmp_rr_32");
893 let zero = op(&mut names, "mov_ri_32");
894 let set = op(&mut names, "set_e");
895 func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
896 func.build(block, zero).def(into, GPR).imm(0).finish();
897 func.build(block, set).def(byte, GPR).finish();
898
899 assert_eq!(takes(&mut func, &mut names), 0);
900 assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_ri_32", "set_e"]);
901 }
902
903 /// The same three instructions with something writing the condition state in between. What the
904 /// byte reads is what the addition left, so the state the move would write is one nothing was
905 /// going to read and the rewrite is back on.
906 #[test]
907 fn a_state_something_else_writes_first_lets_the_rewrite_back_in() {
908 let (mut names, mut func, block) = empty();
909 let left = func.new_vreg(GPR);
910 let right = func.new_vreg(GPR);
911 let sum = func.new_vreg(GPR);
912 let into = func.new_vreg(GPR);
913 let byte = func.new_vreg(GPR);
914 let zero = op(&mut names, "mov_ri_32");
915 let add = op(&mut names, "add_rr_32");
916 let set = op(&mut names, "set_e");
917 func.build(block, zero).def(into, GPR).imm(0).finish();
918 func.build(block, add).def(sum, GPR).uses(left, GPR).uses(right, GPR).finish();
919 func.build(block, set).def(byte, GPR).finish();
920
921 assert_eq!(takes(&mut func, &mut names), 1);
922 assert_eq!(shape(&func, &names, block), ["xor_rr_32", "add_rr_32", "set_e"]);
923 }
924
925 /// A function where a block reads the condition state before it writes one, which is what a
926 /// state carried across an edge looks like from here. The passes in front say that does not
927 /// happen and this is where that is held to rather than believed, so the whole function is
928 /// turned down and the move in the other block stays as well.
929 #[test]
930 fn a_state_carried_into_a_block_turns_the_whole_function_down() {
931 let (mut names, mut func, first) = empty();
932 let second = func.create_block();
933 let into = func.new_vreg(GPR);
934 let byte = func.new_vreg(GPR);
935 let zero = op(&mut names, "mov_ri_32");
936 let set = op(&mut names, "set_e");
937 func.build(first, zero).def(into, GPR).imm(0).finish();
938 func.build(second, set).def(byte, GPR).finish();
939
940 assert_eq!(takes(&mut func, &mut names), 0);
941 assert_eq!(shape(&func, &names, first), ["mov_ri_32"]);
942 }
943
944 /// The third rewrite. A comparison of a register against zero asks whether the register is
945 /// zero, and so does a test of the register against itself, which says it without a number on
946 /// the instruction.
947 #[test]
948 fn a_comparison_against_zero_becomes_a_test_of_the_register_against_itself() {
949 for (wide, narrow) in [
950 ("cmp_ri_8", "test_rr_8"),
951 ("cmp_ri_16", "test_rr_16"),
952 ("cmp_ri_32", "test_rr_32"),
953 ("cmp_ri_64", "test_rr_64"),
954 ] {
955 let (mut names, mut func, block) = empty();
956 let value = func.new_vreg(GPR);
957 let byte = func.new_vreg(GPR);
958 let cmp = op(&mut names, wide);
959 let set = op(&mut names, "set_e");
960 let inst = func.build(block, cmp).uses(value, GPR).imm(0).finish();
961 func.build(block, set).def(byte, GPR).finish();
962
963 assert_eq!(takes(&mut func, &mut names), 1, "{wide}");
964 assert_eq!(shape(&func, &names, block), [narrow, "set_e"], "{wide}");
965 assert_eq!(regs(&func, inst), [value], "{wide}");
966 assert_eq!(imm(&func, inst), None, "{wide}");
967 }
968 }
969
970 /// A comparison against anything else, which the test cannot ask. What a test leaves is the
971 /// bits of the register it was given, so it answers one question and the question is zero.
972 #[test]
973 fn a_comparison_against_a_number_that_is_not_zero_is_left_alone() {
974 for value in [1, -1, 7, 255, i64::from(i32::MIN)] {
975 let (mut names, mut func, block) = empty();
976 let held = func.new_vreg(GPR);
977 let byte = func.new_vreg(GPR);
978 let cmp = op(&mut names, "cmp_ri_32");
979 let set = op(&mut names, "set_e");
980 let inst = func.build(block, cmp).uses(held, GPR).imm(value).finish();
981 func.build(block, set).def(byte, GPR).finish();
982
983 assert_eq!(takes(&mut func, &mut names), 0, "{value}");
984 assert_eq!(shape(&func, &names, block), ["cmp_ri_32", "set_e"], "{value}");
985 assert_eq!(imm(&func, inst), Some(value), "{value}");
986 }
987 }
988
989 /// The condition state is not a question this rewrite asks. The comparison writes the state and
990 /// the test writes the same state, so a comparison whose answer something reads right behind it
991 /// is rewritten exactly as one whose answer nothing wants is, and a function the carried state
992 /// rule turns down gets it too.
993 #[test]
994 fn a_comparison_is_tested_whatever_the_condition_state_is_doing() {
995 let (mut names, mut func, first) = empty();
996 let second = func.create_block();
997 let value = func.new_vreg(GPR);
998 let byte = func.new_vreg(GPR);
999 let cmp = op(&mut names, "cmp_ri_32");
1000 let set = op(&mut names, "set_e");
1001 func.build(first, cmp).uses(value, GPR).imm(0).finish();
1002 // A block that reads the state before writing it, which is what `carried` turns a function
1003 // down for and what the first rewrite is the only one to need.
1004 func.build(second, set).def(byte, GPR).finish();
1005
1006 assert_eq!(takes(&mut func, &mut names), 1);
1007 assert_eq!(shape(&func, &names, first), ["test_rr_32"]);
1008 assert_eq!(shape(&func, &names, second), ["set_e"]);
1009 }
1010
1011 /// The fourth rewrite, at every width and in both directions. An addition of one and a
1012 /// subtraction of minus one are the instruction that adds one, and the other two are the one
1013 /// that takes one away. The register is the one it had and the number is gone, the shorter
1014 /// instruction being the one that carries the number in its opcode.
1015 #[test]
1016 fn adding_or_taking_away_one_becomes_the_instruction_that_says_so_in_its_opcode() {
1017 for (name, by, into) in [
1018 ("add_ri_8", 1, "inc_r_8"),
1019 ("add_ri_16", 1, "inc_r_16"),
1020 ("add_ri_32", 1, "inc_r_32"),
1021 ("add_ri_64", 1, "inc_r_64"),
1022 ("add_ri_8", -1, "dec_r_8"),
1023 ("add_ri_16", -1, "dec_r_16"),
1024 ("add_ri_32", -1, "dec_r_32"),
1025 ("add_ri_64", -1, "dec_r_64"),
1026 ("sub_ri_8", 1, "dec_r_8"),
1027 ("sub_ri_16", 1, "dec_r_16"),
1028 ("sub_ri_32", 1, "dec_r_32"),
1029 ("sub_ri_64", 1, "dec_r_64"),
1030 ("sub_ri_8", -1, "inc_r_8"),
1031 ("sub_ri_16", -1, "inc_r_16"),
1032 ("sub_ri_32", -1, "inc_r_32"),
1033 ("sub_ri_64", -1, "inc_r_64"),
1034 ] {
1035 let (mut names, mut func, block) = empty();
1036 let value = func.new_vreg(GPR);
1037 let add = op(&mut names, name);
1038 let inst =
1039 func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(by).finish();
1040
1041 assert_eq!(small(&mut func, &mut names), 1, "{name} {by}");
1042 assert_eq!(shape(&func, &names, block), [into], "{name} {by}");
1043 assert_eq!(regs(&func, inst), [value, value], "{name} {by}");
1044 assert_eq!(imm(&func, inst), None, "{name} {by}");
1045 }
1046 }
1047
1048 /// The same function at a level that asked for fast code, which is the goal doing its job. This
1049 /// is the only rewrite in the pass that asks it, and it is the only one that is a trade.
1050 #[test]
1051 fn a_level_that_wanted_fast_code_keeps_the_addition() {
1052 let (mut names, mut func, block) = empty();
1053 let value = func.new_vreg(GPR);
1054 let add = op(&mut names, "add_ri_32");
1055 let inst = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1056
1057 assert_eq!(takes(&mut func, &mut names), 0);
1058 assert_eq!(shape(&func, &names, block), ["add_ri_32"]);
1059 assert_eq!(imm(&func, inst), Some(1));
1060 }
1061
1062 /// Any other number. The machine has an opcode that means one and none that means anything
1063 /// else, so the constant is written out either way and the addition is already as short as it
1064 /// gets.
1065 #[test]
1066 fn adding_anything_but_one_stays_an_addition() {
1067 for by in [0, 2, -2, 7, 255, i64::from(i32::MIN)] {
1068 let (mut names, mut func, block) = empty();
1069 let value = func.new_vreg(GPR);
1070 let add = op(&mut names, "add_ri_32");
1071 func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(by).finish();
1072
1073 assert_eq!(small(&mut func, &mut names), 0, "{by}");
1074 assert_eq!(shape(&func, &names, block), ["add_ri_32"], "{by}");
1075 }
1076 }
1077
1078 /// What the rewrite is really conditional on. Something behind it reading where the value sits
1079 /// as an unsigned number is something reading the carry, and the carry is the one part of the
1080 /// condition state the shorter instruction does not write.
1081 #[test]
1082 fn an_addition_whose_carry_something_reads_stays_an_addition() {
1083 for reader in ["set_b", "set_be", "set_a", "set_ae", "adc_ri_32"] {
1084 let (mut names, mut func, block) = empty();
1085 let value = func.new_vreg(GPR);
1086 let byte = func.new_vreg(GPR);
1087 let add = op(&mut names, "add_ri_32");
1088 let reads = op(&mut names, reader);
1089 func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1090 func.build(block, reads).def(byte, GPR).finish();
1091
1092 assert_eq!(small(&mut func, &mut names), 0, "{reader}");
1093 assert_eq!(shape(&func, &names, block), ["add_ri_32", reader], "{reader}");
1094 }
1095 }
1096
1097 /// A reader of any other part of the state, which the shorter instruction writes exactly as the
1098 /// addition did. So the rewrite is not about whether the state is read, it is about which part.
1099 #[test]
1100 fn an_addition_whose_zero_or_sign_something_reads_still_steps() {
1101 for reader in ["set_e", "set_ne", "set_l", "set_le", "set_g", "set_ge"] {
1102 let (mut names, mut func, block) = empty();
1103 let value = func.new_vreg(GPR);
1104 let byte = func.new_vreg(GPR);
1105 let add = op(&mut names, "add_ri_32");
1106 let reads = op(&mut names, reader);
1107 func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1108 func.build(block, reads).def(byte, GPR).finish();
1109
1110 assert_eq!(small(&mut func, &mut names), 1, "{reader}");
1111 assert_eq!(shape(&func, &names, block), ["inc_r_32", reader], "{reader}");
1112 }
1113 }
1114
1115 /// The carry read behind an instruction that writes the rest of the state, which is what the
1116 /// walk asking the description rather than the flag is for. The addition in front of the
1117 /// comparison stays, because the comparison writes the carry the reader wants and the addition
1118 /// would not have to, and the addition behind it goes, because nothing reads a carry after it.
1119 #[test]
1120 fn a_write_of_the_state_ends_the_life_of_the_carry_and_a_step_does_not() {
1121 let (mut names, mut func, block) = empty();
1122 let value = func.new_vreg(GPR);
1123 let byte = func.new_vreg(GPR);
1124 let add = op(&mut names, "add_ri_32");
1125 let cmp = op(&mut names, "cmp_rr_32");
1126 let below = op(&mut names, "set_b");
1127 let first = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1128 func.build(block, cmp).uses(value, GPR).uses(value, GPR).finish();
1129 func.build(block, below).def(byte, GPR).finish();
1130
1131 assert_eq!(small(&mut func, &mut names), 1);
1132 assert_eq!(shape(&func, &names, block), ["inc_r_32", "cmp_rr_32", "set_b"]);
1133 assert_eq!(imm(&func, first), None);
1134 }
1135
1136 /// An instruction that leaves the carry alone is not a write of the condition state as far as
1137 /// the walk is concerned, which is what stops one of them from hiding a carry read behind it.
1138 /// The increment here is one a program wrote in a template rather than one this put there, and
1139 /// the addition in front of it is the only thing that sets the carry the reader wants, so the
1140 /// addition stays.
1141 #[test]
1142 fn a_step_does_not_hide_the_carry_read_behind_it() {
1143 let (mut names, mut func, block) = empty();
1144 let value = func.new_vreg(GPR);
1145 let byte = func.new_vreg(GPR);
1146 let add = op(&mut names, "add_ri_32");
1147 let step = op(&mut names, "inc_r_32");
1148 let below = op(&mut names, "set_b");
1149 let first = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1150 func.build(block, step).operand(reuse(value)).uses(value, GPR).finish();
1151 func.build(block, below).def(byte, GPR).finish();
1152
1153 assert_eq!(small(&mut func, &mut names), 0);
1154 assert_eq!(shape(&func, &names, block), ["add_ri_32", "inc_r_32", "set_b"]);
1155 assert_eq!(imm(&func, first), Some(1));
1156 }
1157
1158 /// Two additions in a row with a carry read behind them. The second one sets the carry the
1159 /// reader wants and stays, and the first one goes, because whatever the first leaves the second
1160 /// writes over. That is the same walk as the test above arriving at the other answer, and it is
1161 /// what says the rule is about the carry rather than about the addition.
1162 #[test]
1163 fn an_addition_the_next_addition_writes_over_still_steps() {
1164 let (mut names, mut func, block) = empty();
1165 let value = func.new_vreg(GPR);
1166 let byte = func.new_vreg(GPR);
1167 let add = op(&mut names, "add_ri_32");
1168 let below = op(&mut names, "set_b");
1169 func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1170 let second = func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1171 func.build(block, below).def(byte, GPR).finish();
1172
1173 assert_eq!(small(&mut func, &mut names), 1);
1174 assert_eq!(shape(&func, &names, block), ["inc_r_32", "add_ri_32", "set_b"]);
1175 assert_eq!(imm(&func, second), Some(1));
1176 }
1177
1178 /// The instruction the whole function check used to stop at. A comparison that keeps a byte
1179 /// reads the condition state and the state it reads is the one it wrote itself a moment
1180 /// earlier, so a block opening with one is not a block reading what a predecessor left, and the
1181 /// move in the other block is rewritten.
1182 #[test]
1183 fn a_block_opening_with_a_comparison_that_keeps_a_byte_is_not_a_carried_state() {
1184 let (mut names, mut func, first) = empty();
1185 let second = func.create_block();
1186 let into = func.new_vreg(GPR);
1187 let byte = func.new_vreg(GPR);
1188 let value = func.new_vreg(GPR);
1189 let zero = op(&mut names, "mov_ri_32");
1190 let fused = op(&mut names, "cmp_set_e_32");
1191 func.build(first, zero).def(into, GPR).imm(0).finish();
1192 func.build(second, fused).def(byte, GPR).uses(value, GPR).uses(value, GPR).finish();
1193
1194 assert_eq!(takes(&mut func, &mut names), 1);
1195 assert_eq!(shape(&func, &names, first), ["xor_rr_32"]);
1196 }
1197
1198 /// The same with the comparison's operand in memory, which is the shape a loop reading an array
1199 /// and counting with tier six's `setcc` and `movzbl` comes out as. The comparison table leaves
1200 /// these out, and before the description named them apart this turned the function down.
1201 #[test]
1202 fn a_block_opening_with_a_comparison_against_memory_is_not_a_carried_state() {
1203 let (mut names, mut func, first) = empty();
1204 let second = func.create_block();
1205 let into = func.new_vreg(GPR);
1206 let byte = func.new_vreg(GPR);
1207 let value = func.new_vreg(GPR);
1208 let base = func.new_vreg(GPR);
1209 let zero = op(&mut names, "mov_ri_32");
1210 let fused = op(&mut names, "cmp_set_g_rm_32");
1211 func.build(first, zero).def(into, GPR).imm(0).finish();
1212 func.build(second, fused).def(byte, GPR).uses(value, GPR).uses(base, GPR).finish();
1213
1214 assert_eq!(takes(&mut func, &mut names), 1);
1215 assert_eq!(shape(&func, &names, first), ["xor_rr_32"]);
1216 }
1217
1218 /// The same sentence inside a block. What the comparison reads is what it wrote, so what it was
1219 /// handed is written over before anything looks at it, and the move in front of it may spend a
1220 /// state nothing wants.
1221 #[test]
1222 fn a_comparison_that_keeps_a_byte_ends_the_life_of_the_state() {
1223 let (mut names, mut func, block) = empty();
1224 let into = func.new_vreg(GPR);
1225 let byte = func.new_vreg(GPR);
1226 let value = func.new_vreg(GPR);
1227 let zero = op(&mut names, "mov_ri_32");
1228 let fused = op(&mut names, "cmp_set_e_32");
1229 func.build(block, zero).def(into, GPR).imm(0).finish();
1230 func.build(block, fused).def(byte, GPR).uses(value, GPR).uses(value, GPR).finish();
1231
1232 assert_eq!(takes(&mut func, &mut names), 1);
1233 assert_eq!(shape(&func, &names, block), ["xor_rr_32", "cmp_set_e_32"]);
1234 }
1235
1236 /// And the carry with it. A comparison that keeps a byte and asks where a value sits as an
1237 /// unsigned number reads the carry, and it is the carry it set itself, so the addition in front
1238 /// of it is free to become the instruction that leaves the carry alone.
1239 #[test]
1240 fn a_comparison_that_keeps_a_byte_does_not_keep_the_carry_alive() {
1241 let (mut names, mut func, block) = empty();
1242 let value = func.new_vreg(GPR);
1243 let byte = func.new_vreg(GPR);
1244 let add = op(&mut names, "add_ri_32");
1245 let fused = op(&mut names, "cmp_set_b_32");
1246 func.build(block, add).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1247 func.build(block, fused).def(byte, GPR).uses(value, GPR).uses(value, GPR).finish();
1248
1249 assert_eq!(small(&mut func, &mut names), 1);
1250 assert_eq!(shape(&func, &names, block), ["inc_r_32", "cmp_set_b_32"]);
1251 }
1252
1253 /// The other kind of read, which is the one this must go on stopping at. An add with carry is
1254 /// reading the bit the instruction in front of it left rather than one it wrote itself, and it
1255 /// makes no comparison, which is how the description tells the two apart.
1256 #[test]
1257 fn an_add_with_carry_opening_a_block_is_still_a_carried_state() {
1258 let (mut names, mut func, first) = empty();
1259 let second = func.create_block();
1260 let into = func.new_vreg(GPR);
1261 let value = func.new_vreg(GPR);
1262 let zero = op(&mut names, "mov_ri_32");
1263 let adc = op(&mut names, "adc_ri_32");
1264 func.build(first, zero).def(into, GPR).imm(0).finish();
1265 func.build(second, adc).operand(reuse(value)).uses(value, GPR).imm(1).finish();
1266
1267 assert_eq!(takes(&mut func, &mut names), 0);
1268 assert_eq!(shape(&func, &names, first), ["mov_ri_32"]);
1269 }
1270
1271 /// A name the description does not cover, which is anything without this target's prefix. It
1272 /// may read the condition state and it may write one, and the answer that is wrong about
1273 /// nothing is that it read it, so the move in front of it stays.
1274 #[test]
1275 fn a_name_this_target_does_not_know_stops_the_walk() {
1276 let (mut names, mut func, block) = empty();
1277 let left = func.new_vreg(GPR);
1278 let right = func.new_vreg(GPR);
1279 let into = func.new_vreg(GPR);
1280 let cmp = op(&mut names, "cmp_rr_32");
1281 let zero = op(&mut names, "mov_ri_32");
1282 let strange = mir::Opcode::new(names.intern("nowhere.thing"));
1283 func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
1284 func.build(block, zero).def(into, GPR).imm(0).finish();
1285 func.build(block, strange).finish();
1286
1287 assert_eq!(takes(&mut func, &mut names), 0);
1288 assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_ri_32", ""]);
1289 }
1290
1291 /// The fifth rewrite. An address that is a base register and nothing else is that register, so
1292 /// the instruction that works it out and keeps it is the move, which keeps both registers in the
1293 /// order it had them and drops the addressing mode it no longer has a place for.
1294 #[test]
1295 fn an_address_that_is_a_register_becomes_a_move() {
1296 let (mut names, mut func, block) = empty();
1297 let base = func.new_vreg(GPR);
1298 let into = func.new_vreg(GPR);
1299 let lea = op(&mut names, "lea_64");
1300 let mem = mir::Mem::at(mir::Operand::read(base, GPR));
1301 let inst = func.build(block, lea).def(into, GPR).mem(mem).finish();
1302
1303 assert_eq!(takes(&mut func, &mut names), 1);
1304 assert_eq!(shape(&func, &names, block), ["mov_rr_64"]);
1305 assert_eq!(regs(&func, inst), [into, base]);
1306 assert!(func[inst].mem.is_none());
1307 }
1308
1309 /// A constant added to the address, which is the shape most address computations have. The move
1310 /// adds nothing, so there is nothing here for it to say.
1311 #[test]
1312 fn an_address_with_a_constant_added_stays() {
1313 let (mut names, mut func, block) = empty();
1314 let base = func.new_vreg(GPR);
1315 let into = func.new_vreg(GPR);
1316 let lea = op(&mut names, "lea_64");
1317 let mem = mir::Mem { disp: 8, ..mir::Mem::at(mir::Operand::read(base, GPR)) };
1318 func.build(block, lea).def(into, GPR).mem(mem).finish();
1319
1320 assert_eq!(takes(&mut func, &mut names), 0);
1321 assert_eq!(shape(&func, &names, block), ["lea_64"]);
1322 }
1323
1324 /// An index, which is the other half of what an address computation is for. It is a
1325 /// multiplication and an addition and the move is neither.
1326 #[test]
1327 fn an_address_with_an_index_stays() {
1328 let (mut names, mut func, block) = empty();
1329 let base = func.new_vreg(GPR);
1330 let index = func.new_vreg(GPR);
1331 let into = func.new_vreg(GPR);
1332 let lea = op(&mut names, "lea_64");
1333 let mem = mir::Mem {
1334 index: Some(mir::Operand::read(index, GPR)),
1335 scale: 4,
1336 ..mir::Mem::at(mir::Operand::read(base, GPR))
1337 };
1338 func.build(block, lea).def(into, GPR).mem(mem).finish();
1339
1340 assert_eq!(takes(&mut func, &mut names), 0);
1341 assert_eq!(shape(&func, &names, block), ["lea_64"]);
1342 }
1343
1344 /// The address of a global, which names no register at all. What it works out is a number the
1345 /// assembler fills in rather than a number that is already somewhere, so there is nothing for a
1346 /// move to move.
1347 #[test]
1348 fn an_address_of_a_symbol_stays() {
1349 let (mut names, mut func, block) = empty();
1350 let into = func.new_vreg(GPR);
1351 let lea = op(&mut names, "lea_64");
1352 let mem = mir::Mem::of(names.intern("table"));
1353 func.build(block, lea).def(into, GPR).mem(mem).finish();
1354
1355 assert_eq!(takes(&mut func, &mut names), 0);
1356 assert_eq!(shape(&func, &names, block), ["lea_64"]);
1357 }
1358
1359 /// And it does not wait on the condition state. Neither the address computation nor the move
1360 /// writes any, so a byte reading a comparison from in front of it reads the same comparison
1361 /// afterwards, and the rewrite is taken in the one function the first rewrite has to turn down.
1362 #[test]
1363 fn an_address_is_copied_whatever_the_state_behind_it_is() {
1364 let (mut names, mut func, block) = empty();
1365 let left = func.new_vreg(GPR);
1366 let right = func.new_vreg(GPR);
1367 let base = func.new_vreg(GPR);
1368 let into = func.new_vreg(GPR);
1369 let byte = func.new_vreg(GPR);
1370 let cmp = op(&mut names, "cmp_rr_32");
1371 let lea = op(&mut names, "lea_64");
1372 let set = op(&mut names, "set_e");
1373 let mem = mir::Mem::at(mir::Operand::read(base, GPR));
1374 func.build(block, cmp).uses(left, GPR).uses(right, GPR).finish();
1375 func.build(block, lea).def(into, GPR).mem(mem).finish();
1376 func.build(block, set).def(byte, GPR).finish();
1377
1378 assert_eq!(takes(&mut func, &mut names), 1);
1379 assert_eq!(shape(&func, &names, block), ["cmp_rr_32", "mov_rr_64", "set_e"]);
1380 }
1381}