Skip to main content

rucc_codegen/
bits.rs

1//! Taking out a conversion whose bits nothing reads.
2//!
3//! Design: `spec/optimizer/37-machine-level-optimization.md` section 37.4.
4//!
5//! A register is one register at every width, and what says how much of it is in play is the
6//! instruction naming it. `movzbl %sil, %edi` writes thirty two bits of `rdi` and reads eight of
7//! `rsi`, and if the only thing that ever reads `rdi` is a `movb`, then the twenty four bits the
8//! widening worked out are bits nobody ever looks at. What is left of the widening once those bits
9//! are taken away is a copy of eight bits into a register, which is what the instruction after it
10//! was going to read anyway, so the widening goes and its readers read its source instead.
11//!
12//! That is the bit group liveness of `gcc/ext-dce.cc` at the width this compiler needs it at.
13//! Liveness answers whether a register is read at all, this answers how much of it is read, and
14//! the second question is the first one asked per group of bits rather than per register. Section
15//! 37.4 says to build this one of the two passes it offers, because it is more general than
16//! compare elimination and because the analysis is the liveness the allocator already computes
17//! with a number on it.
18//!
19//! # Where the conversions come from
20//!
21//! Not from code anybody wrote. C promotes nearly every operand of nearly every expression to
22//! `int` before doing anything with it, so a program that adds two `char`s widens both of them,
23//! adds at thirty two bits and stores eight, and the front end writes every one of those
24//! conversions out because each of them is in the language's own description of what the program
25//! means. `crate::widths` and tier four of the rewrite rules take the ones that are two
26//! instructions next to each other in the same block. What is left for this pass is the ones that
27//! are not: a conversion in one block whose readers are in another, and a conversion the selector
28//! itself wrote because the machine instruction it picked wanted its operand at a width the value
29//! did not arrive at.
30//!
31//! # What it finds, measured
32//!
33//! Both directions of conversion are in scope and only one of them turns up, which was not what
34//! was expected and is worth writing down rather than rounding off. Over the 1916 programs of
35//! tamnd/rucc-corpus at `-O2` this takes out 970 instructions and puts back 45, and not one of
36//! the 7040 widenings in that assembly is among them: the count of `movz` and `movs` is the same
37//! before and after. What goes is 469 `movl`, 259 `movw` and 242 `movb` between registers, which
38//! are the narrowings, and the 45 that come back are `movq`, which is the allocator wanting a
39//! plain copy where a narrowing had been doing that job as well as its own.
40//!
41//! That is tier four of the rewrite rules having already been through the corpus. A widening the
42//! rules could not reach is one whose upper bits some reader really does read, and there is
43//! nothing here for a bit counter to find in it. A narrowing is the other way round: the machine
44//! writes one where a value is put in a register at a width, and whether the bits above it matter
45//! is a question about every reader of the result rather than about the pair, which is the
46//! question only this pass asks.
47//!
48//! 2091 bytes of `.text` over the corpus, 76 programs smaller and two larger by a byte each, and
49//! 2048 bytes off SQLite's amalgamation at `-O2`. The two that grow are an eight bit division,
50//! where every narrowing that goes was also the move that got the answer out of the register the
51//! division fixes, so the allocator writes a full width copy of the same pair in its place. Nine
52//! of the ten are the same length either way and the tenth is `movb %dl, %bl` becoming
53//! `movq %rdx, %rbx`, which is the one byte: the byte names of those two registers need no prefix
54//! and the sixty four bit move needs the one that says so.
55//!
56//! # The analysis
57//!
58//! One number per register, which is how many of its low bits anything reads. It starts at none
59//! and grows, so a register nothing has been seen to read yet is one whose answer is still being
60//! worked out rather than one nothing reads.
61//!
62//! Three things raise it. An instruction reading a register raises it to the width that
63//! instruction names the operand at, which is [`rucc_target::BitInsts::width`] and is the target's
64//! answer rather than this pass's. An edge carrying a register into a block raises it to whatever
65//! the parameter it arrives as needs, which is what carries the answer across a block boundary and
66//! is the whole reason this finds anything the rules do not. And an instruction that copies the
67//! low bits of its source raises its source only as far as its own result is read, since the bits
68//! of the source above that are bits it puts nowhere anything reads.
69//!
70//! The last of those is what makes the answer a fixpoint rather than a walk: a chain of
71//! conversions passes the number back along itself, and how far it passes depends on a number the
72//! same pass is still working out. It only ever grows and it is bounded by the widest operand on
73//! the machine, so it settles.
74//!
75//! # What it will not do
76//!
77//! An operand the target's description does not name at a width. An address register, an operand
78//! of an opcode written as no instruction at all, and an opcode from somewhere other than this
79//! target all answer that they read everything, which is section 37.7's warning honoured by
80//! construction: a store reads every bit of the value it stores because the description says the
81//! operand is as wide as the store is, and anything the description is silent about is treated as
82//! reading the lot rather than as reading nothing.
83//!
84//! A physical register on either side. Machine IR is in SSA form until the allocator has run, so a
85//! virtual register is written once and the register a reader would be sent to instead still holds
86//! what it held. A physical one is not: the frame pointer and the stack pointer are already
87//! physical here and a call writes every register it is allowed to, so sending a reader to one of
88//! those would be sending it to whatever happened to be there.
89//!
90//! A conversion whose result is read as wide as it is written. That is a widening whose upper bits
91//! somebody does read, which is the whole instruction doing its job.
92//!
93//! A conversion whose result nothing reads at all. That is an instruction that computes something
94//! nobody wants, which is dead code rather than dead bits, and taking it out here would be this
95//! pass answering a question it was not asked and reporting a number that says it found widenings
96//! it had not. What this is about is a register something reads less of than was put in it.
97//!
98//! # How the rewrite is made
99//!
100//! One conversion at a time, as a set of changes [`crate::changes`] either takes or turns down.
101//! The set is the readers sent to the source and the conversion taken out, and those two are worth
102//! nothing apart: a reader left behind reads a register nothing writes any more. So the set is
103//! where the question is asked, and a reader this pass failed to find is a set that is refused
104//! rather than a function with a hole in it.
105//!
106//! The readers an edge holds are in the set the same way. A conversion in one block whose reader is
107//! in another is the case this pass is here for, and the argument the edge carries is how the value
108//! gets there, so sending it somewhere else is half of what taking the conversion out means.
109//!
110//! # Where it runs
111//!
112//! After selection and before allocation, which is the window where the machine instructions exist
113//! and the registers are still virtual. Section 37.6 puts it third in the group that runs there,
114//! after combining and if-conversion and before compare elimination and addressing-mode folding,
115//! and that is where `crate::pipeline` calls it.
116
117use std::collections::HashMap;
118
119use rucc_base::Interner;
120use rucc_mir as mir;
121use rucc_target::{BitInsts, Constraint, MachineInsts, Role};
122
123use crate::changes::{Changes, Reads};
124
125/// How much of a register a read that could be of any of it wants.
126///
127/// Every operand the target does not describe gets this, and no rewrite fires over a register that
128/// has it, since no instruction on any machine writes more bits than this many.
129const EVERYTHING: u32 = u32::MAX;
130
131/// Takes out every conversion whose result nothing reads above the width of its source, and gives
132/// back how many.
133///
134/// Each one that goes takes its readers with it: they are pointed at the source instead, which
135/// holds the same bits as the result did for as far as anything was looking.
136///
137/// One conversion is one set of changes, which is [`crate::changes`] asked the question this pass
138/// would otherwise be trusted about. Sending the readers of a register somewhere else and taking
139/// the instruction that wrote it out are worth nothing apart, and a reader this missed is a set
140/// the framework turns down rather than an instruction taken out from under something still
141/// reading it.
142///
143/// Run after lowering and before allocation. Running it once is enough, because the analysis is
144/// over the whole function at once and a chain of conversions is settled by the fixpoint rather
145/// than by a second run.
146pub fn dead(
147    func: &mut mir::Func,
148    insts: &BitInsts,
149    machine: &MachineInsts,
150    names: &Interner,
151) -> usize {
152    let wanted = demand(func, insts, names);
153    let mut sent: HashMap<mir::Reg, mir::Reg> = HashMap::new();
154    let mut gone: Vec<mir::Inst> = Vec::new();
155    for block in func.blocks() {
156        for inst in func.insts(block) {
157            let Some(name) = opcode(func, insts, names, inst) else { continue };
158            if !(insts.copies_low)(name) {
159                continue;
160            }
161            let Some((def, source)) = conversion(func, inst) else { continue };
162            let kept = (insts.width)(name, SOURCE).unwrap_or(EVERYTHING);
163            let read = wanted.get(def);
164            if read == 0 || read > kept {
165                continue;
166            }
167            sent.insert(def, source);
168            gone.push(inst);
169        }
170    }
171    if gone.is_empty() {
172        return 0;
173    }
174    let sent = chased(&sent);
175    let readers = Readers::of(func, &sent);
176    let mut reads = Reads::of(func);
177    let mut taken = 0;
178    for inst in gone {
179        let Some((def, _)) = conversion(func, inst) else { continue };
180        let Some(&into) = sent.get(&def) else { continue };
181        let mut set = Changes::new();
182        for &reader in readers.insts.get(&def).into_iter().flatten() {
183            // A reader that has gone is one an earlier conversion in a chain took with it, and the
184            // read it was doing went with it.
185            if func.block_of(reader).is_some() {
186                set.rename(reader, def, into);
187            }
188        }
189        for &(from, at) in readers.edges.get(&def).into_iter().flatten() {
190            let args = func[from].succs[at]
191                .args
192                .iter()
193                .map(|&arg| if arg == def { into } else { arg })
194                .collect();
195            set.carry(from, at, args);
196        }
197        set.remove(inst);
198        if set.commit(func, &mut reads, names, machine).is_ok() {
199            taken += 1;
200        }
201    }
202    taken
203}
204
205/// Everything that reads each of the registers a conversion wrote.
206///
207/// Worked out in one walk rather than per conversion, because a function with a thousand of these
208/// in it would otherwise be walked a thousand times. It is the readers as they were when the walk
209/// ran, which is enough: a rename adds a read of the register it sends a reader to, and by the time
210/// that register's own conversion is the one being taken out the reader is found from the function
211/// rather than from here.
212#[derive(Debug, Default)]
213struct Readers {
214    /// The instructions that read it, each named once however many of its operands do.
215    insts: HashMap<mir::Reg, Vec<mir::Inst>>,
216    /// The edges that carry it, as the block each leaves and its position in that block's list.
217    edges: HashMap<mir::Reg, Vec<(mir::Block, usize)>>,
218}
219
220impl Readers {
221    /// Every read of every register in the map, which is the registers the conversions wrote.
222    fn of(func: &mir::Func, sent: &HashMap<mir::Reg, mir::Reg>) -> Self {
223        let mut found = Self::default();
224        for block in func.blocks() {
225            for inst in func.insts(block) {
226                for operand in &func[func[inst].operands] {
227                    if operand.role != Role::Use || !sent.contains_key(&operand.reg) {
228                        continue;
229                    }
230                    let readers = found.insts.entry(operand.reg).or_default();
231                    if !readers.contains(&inst) {
232                        readers.push(inst);
233                    }
234                }
235            }
236            for (at, call) in func[block].succs.iter().enumerate() {
237                for arg in &call.args {
238                    if !sent.contains_key(arg) {
239                        continue;
240                    }
241                    let edges = found.edges.entry(*arg).or_default();
242                    if !edges.contains(&(block, at)) {
243                        edges.push((block, at));
244                    }
245                }
246            }
247        }
248        found
249    }
250}
251
252/// Where a conversion holds the register it reads.
253///
254/// A conversion is one definition and one use in that order, which is what [`conversion`] checks
255/// rather than assumes, so the source is at one.
256const SOURCE: u8 = 1;
257
258/// How many low bits of each register something reads.
259///
260/// Absent means none, which is a register nothing has been seen to read. That is the right
261/// starting point rather than a wrong one to be corrected later: the answer only grows, so a
262/// register still absent when the walk settles is one nothing reads at all.
263fn demand(func: &mir::Func, insts: &BitInsts, names: &Interner) -> Wanted {
264    let mut wanted = Wanted { virtuals: vec![0; func.vregs()], physical: HashMap::new() };
265    loop {
266        let mut moved = false;
267        for block in func.blocks() {
268            for inst in func.insts(block) {
269                let name = opcode(func, insts, names, inst);
270                // A conversion puts the low bits of its source in its result and nothing else, so
271                // the bits of the source above however much of the result is read are bits it
272                // takes nowhere. Anything else reads its operand at the width it names it at.
273                let copies = name.is_some_and(|name| (insts.copies_low)(name));
274                let through = conversion(func, inst)
275                    .filter(|_| copies)
276                    .map_or(EVERYTHING, |(def, _)| wanted.get(def));
277                let operands = &func[func[inst].operands];
278                for (at, operand) in operands.iter().enumerate() {
279                    if operand.role != Role::Use {
280                        continue;
281                    }
282                    let Ok(at) = u8::try_from(at) else { continue };
283                    let asked = read(name, insts, operands, at).min(through);
284                    moved |= wanted.raise(operand.reg, asked);
285                }
286            }
287            for call in &func[block].succs {
288                for (arg, param) in call.args.iter().zip(&func[call.block].params) {
289                    let asked = wanted.get(param.reg);
290                    moved |= wanted.raise(*arg, asked);
291                }
292            }
293        }
294        if !moved {
295            return wanted;
296        }
297    }
298}
299
300/// How many low bits of each register something reads, as [`demand`] works it out.
301///
302/// A virtual register's answer is in a list by its number rather than in a map, since the numbers
303/// run from nought with no gaps and the walk asks about every operand of the function on every
304/// round until nothing moves. The few physical registers go in the map.
305#[derive(Debug)]
306struct Wanted {
307    virtuals: Vec<u32>,
308    physical: HashMap<mir::Reg, u32>,
309}
310
311impl Wanted {
312    /// How many bits of it are read, which is none for a register nothing has been seen to read.
313    fn get(&self, reg: mir::Reg) -> u32 {
314        match reg.number() {
315            Some(number) => self.virtuals.get(number as usize).copied().unwrap_or(0),
316            None => self.physical.get(&reg).copied().unwrap_or(0),
317        }
318    }
319
320    /// Raises how much of a register is read, and says whether that changed anything.
321    fn raise(&mut self, reg: mir::Reg, bits: u32) -> bool {
322        let had = match reg.number() {
323            Some(number) => {
324                let number = number as usize;
325                if number >= self.virtuals.len() {
326                    self.virtuals.resize(number + 1, 0);
327                }
328                &mut self.virtuals[number]
329            }
330            None => self.physical.entry(reg).or_insert(0),
331        };
332        if *had >= bits {
333            return false;
334        }
335        *had = bits;
336        true
337    }
338}
339
340/// How many bits of the operand at that index the instruction reads.
341///
342/// The target's description is asked first and is the answer whenever it has one. Where it has
343/// none the operand may still be a tied one, which is the operand an instruction of this shape
344/// reads and writes in the one place: the machine writes it once and the assembly names it once,
345/// so the description names the definition and says nothing about the use beside it. Those two
346/// are the same register at the same width by the time the allocator has finished, so the width
347/// of the definition is the width of the use.
348///
349/// Anything left over reads everything, which is what keeps an address register, an opcode written
350/// as no instruction and an opcode from another target from being believed to read nothing.
351fn read(name: Option<&str>, insts: &BitInsts, operands: &[mir::Operand], at: u8) -> u32 {
352    let Some(name) = name else { return EVERYTHING };
353    if let Some(bits) = (insts.width)(name, at) {
354        return bits;
355    }
356    for (index, operand) in operands.iter().enumerate() {
357        if operand.role == Role::Use || operand.constraint != Constraint::Reuse(at) {
358            continue;
359        }
360        let Ok(index) = u8::try_from(index) else { continue };
361        return (insts.width)(name, index).unwrap_or(EVERYTHING);
362    }
363    EVERYTHING
364}
365
366/// The name this target knows an instruction by, for an instruction that is one of this target's.
367///
368/// The opcode in machine IR carries the target's prefix, because a function in the middle of being
369/// compiled holds instructions of one machine and the prefix is what says which. Anything without
370/// it is not something this description covers, and the rest of the pass treats that as knowing
371/// nothing rather than as knowing it is safe.
372fn opcode<'a>(
373    func: &mir::Func,
374    insts: &BitInsts,
375    names: &'a Interner,
376    inst: mir::Inst,
377) -> Option<&'a str> {
378    names.resolve(func[inst].opcode.name()).strip_prefix(insts.prefix)
379}
380
381/// The register a conversion writes and the register it reads, when it is one this may take out.
382///
383/// One definition and one use, both of them virtual, and no memory operand. The shape is checked
384/// rather than taken on trust from the opcode, since what the rewrite does is send every reader of
385/// the first register to the second and that is only the same program when there is exactly one of
386/// each.
387fn conversion(func: &mir::Func, inst: mir::Inst) -> Option<(mir::Reg, mir::Reg)> {
388    if func[inst].mem.is_some() {
389        return None;
390    }
391    let operands = &func[func[inst].operands];
392    let [def, source] = operands else { return None };
393    if def.role == Role::Use || source.role != Role::Use {
394        return None;
395    }
396    if !def.reg.is_virtual() || !source.reg.is_virtual() {
397        return None;
398    }
399    Some((def.reg, source.reg))
400}
401
402/// The same map with every chain in it followed to its end.
403///
404/// A chain is two conversions where the outer one reads what the inner one wrote, and both of them
405/// going means a reader of the outer one belongs to the inner one's source rather than to the
406/// inner one. The walk ends because machine IR is in SSA form here and every step goes to a
407/// register written earlier in the function, and the bound is there so that a map built any other
408/// way stops as well.
409fn chased(sent: &HashMap<mir::Reg, mir::Reg>) -> HashMap<mir::Reg, mir::Reg> {
410    sent.iter()
411        .map(|(&from, &first)| {
412            let mut into = first;
413            for _ in 0..sent.len() {
414                match sent.get(&into) {
415                    Some(&next) => into = next,
416                    None => break,
417                }
418            }
419            (from, into)
420        })
421        .collect()
422}
423
424#[cfg(test)]
425mod tests {
426    use rucc_target::x86_64::{BITS, GPR, MACHINE, RDI};
427
428    use super::*;
429
430    /// A function with one block, and the names it was built with.
431    fn empty() -> (Interner, mir::Func, mir::Block) {
432        let mut names = Interner::new();
433        let mut func = mir::Func::new(names.intern("f"));
434        let block = func.create_block();
435        (names, func, block)
436    }
437
438    /// The opcode of that name on this target.
439    fn op(names: &mut Interner, name: &str) -> mir::Opcode {
440        mir::Opcode::new(names.intern(&format!("{}{name}", BITS.prefix)))
441    }
442
443    /// The pass, over the machine this crate has a backend for.
444    fn takes(func: &mut mir::Func, names: &Interner) -> usize {
445        dead(func, &BITS, &MACHINE, names)
446    }
447
448    /// What every instruction in a block came to, as opcodes.
449    fn shape(func: &mir::Func, names: &Interner, block: mir::Block) -> Vec<String> {
450        func.insts(block).map(|inst| names.resolve(func[inst].opcode.name()).to_owned()).collect()
451    }
452
453    /// The registers one instruction reads, in the order its operands hold them.
454    fn reads(func: &mir::Func, inst: mir::Inst) -> Vec<mir::Reg> {
455        func[func[inst].operands]
456            .iter()
457            .filter(|operand| operand.role == Role::Use)
458            .map(|operand| operand.reg)
459            .collect()
460    }
461
462    /// The shape the whole pass is about, and the one the corpus is full of: a byte widened to a
463    /// word because C says to, and then the word written back out as a byte. The twenty four bits
464    /// in between are worked out and read by nobody.
465    #[test]
466    fn a_widening_whose_only_reader_is_as_narrow_as_its_source_goes() {
467        let (mut names, mut func, block) = empty();
468        let byte = func.new_vreg(GPR);
469        let wide = func.new_vreg(GPR);
470        let address = func.new_vreg(GPR);
471        let widen = op(&mut names, "movzx_8_32");
472        let store = op(&mut names, "mov_mr_8");
473        func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
474        func.build(block, store)
475            .uses(wide, GPR)
476            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
477            .finish();
478
479        assert_eq!(takes(&mut func, &names), 1);
480
481        let left = shape(&func, &names, block);
482        assert_eq!(left.len(), 1, "the widening is still there: {left:?}");
483        let inst = func.insts(block).next().expect("the store is still there");
484        assert_eq!(reads(&func, inst)[0], byte, "the store was not sent to the source");
485    }
486
487    /// The same widening with a reader that reads the whole of what it wrote. Those upper bits are
488    /// read, so the instruction that worked them out is one doing its job.
489    #[test]
490    fn a_widening_something_reads_the_whole_of_stays() {
491        let (mut names, mut func, block) = empty();
492        let byte = func.new_vreg(GPR);
493        let wide = func.new_vreg(GPR);
494        let out = func.new_vreg(GPR);
495        let widen = op(&mut names, "movzx_8_32");
496        let copy = op(&mut names, "mov_rr_64");
497        func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
498        func.build(block, copy).def(out, GPR).uses(wide, GPR).finish();
499
500        assert_eq!(takes(&mut func, &names), 0);
501        assert_eq!(shape(&func, &names, block).len(), 2);
502    }
503
504    /// The case no rewrite rule can reach, which is the reason this pass is here at all. The
505    /// widening is in one block and the only thing that reads it is in another, so the two are
506    /// never operands of one term and no pattern three levels deep sees them both.
507    #[test]
508    fn a_widening_whose_narrow_reader_is_in_another_block_goes_too() {
509        let (mut names, mut func, block) = empty();
510        let next = func.create_block();
511        let byte = func.new_vreg(GPR);
512        let wide = func.new_vreg(GPR);
513        let arrived = func.new_vreg(GPR);
514        let address = func.new_vreg(GPR);
515        let widen = op(&mut names, "movzx_8_32");
516        let store = op(&mut names, "mov_mr_8");
517        func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
518        func.params_mut(next).push(mir::Param { reg: arrived, class: GPR });
519        *func.succs_mut(block) = vec![mir::BlockCall::with(next, vec![wide])];
520        func.build(next, store)
521            .uses(arrived, GPR)
522            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
523            .finish();
524
525        assert_eq!(takes(&mut func, &names), 1);
526
527        assert!(shape(&func, &names, block).is_empty(), "the widening is still there");
528        assert_eq!(func[block].succs[0].args, vec![byte], "the edge still carries the wide one");
529    }
530
531    /// And the same edge with a reader on the other side that wants the whole word, which is the
532    /// answer coming back across the boundary the other way.
533    #[test]
534    fn a_widening_whose_reader_in_another_block_is_wide_stays() {
535        let (mut names, mut func, block) = empty();
536        let next = func.create_block();
537        let byte = func.new_vreg(GPR);
538        let wide = func.new_vreg(GPR);
539        let arrived = func.new_vreg(GPR);
540        let address = func.new_vreg(GPR);
541        let widen = op(&mut names, "movzx_8_32");
542        let store = op(&mut names, "mov_mr_32");
543        func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
544        func.params_mut(next).push(mir::Param { reg: arrived, class: GPR });
545        *func.succs_mut(block) = vec![mir::BlockCall::with(next, vec![wide])];
546        func.build(next, store)
547            .uses(arrived, GPR)
548            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
549            .finish();
550
551        assert_eq!(takes(&mut func, &names), 0);
552        assert_eq!(shape(&func, &names, block).len(), 1);
553        assert_eq!(func[block].succs[0].args, vec![wide]);
554    }
555
556    /// A chain, which is what a narrow value widened for one operation and narrowed for the next
557    /// comes out as. The middle conversion is what makes the analysis a fixpoint rather than one
558    /// walk: how much of it is read depends on how much of the one after it is, and that number is
559    /// still being worked out when it is asked for.
560    #[test]
561    fn a_chain_of_conversions_goes_the_whole_way_and_its_reader_goes_to_the_first_source() {
562        let (mut names, mut func, block) = empty();
563        let byte = func.new_vreg(GPR);
564        let wide = func.new_vreg(GPR);
565        let narrowed = func.new_vreg(GPR);
566        let out = func.new_vreg(GPR);
567        let address = func.new_vreg(GPR);
568        let widen = op(&mut names, "movzx_8_64");
569        let low = op(&mut names, "low_32");
570        let narrow = op(&mut names, "low_8");
571        let store = op(&mut names, "mov_mr_8");
572        func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
573        func.build(block, low).def(narrowed, GPR).uses(wide, GPR).finish();
574        func.build(block, narrow).def(out, GPR).uses(narrowed, GPR).finish();
575        func.build(block, store)
576            .uses(out, GPR)
577            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
578            .finish();
579
580        assert_eq!(takes(&mut func, &names), 3);
581
582        let left = shape(&func, &names, block);
583        assert_eq!(left.len(), 1, "some of the three are still there: {left:?}");
584        let inst = func.insts(block).next().expect("the store is still there");
585        assert_eq!(reads(&func, inst)[0], byte, "the chain was not followed to its end");
586    }
587
588    /// A store of the whole word, which is section 37.7's warning: the bits go to memory and
589    /// something reads them from there, so a pass that thought a store read less than it stores
590    /// would take out a widening whose answer is in the program's output.
591    #[test]
592    fn a_store_reads_every_bit_of_what_it_stores() {
593        let (mut names, mut func, block) = empty();
594        let byte = func.new_vreg(GPR);
595        let wide = func.new_vreg(GPR);
596        let address = func.new_vreg(GPR);
597        let widen = op(&mut names, "movzx_8_64");
598        let store = op(&mut names, "mov_mr_64");
599        func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
600        func.build(block, store)
601            .uses(wide, GPR)
602            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
603            .finish();
604
605        assert_eq!(takes(&mut func, &names), 0);
606        assert_eq!(shape(&func, &names, block).len(), 2);
607    }
608
609    /// A widening whose result is read as an address. The registers a memory operand is made of
610    /// are read whole and the description says nothing about their width, so the answer is that
611    /// everything is read rather than that nothing is.
612    #[test]
613    fn a_widening_read_as_an_address_stays() {
614        let (mut names, mut func, block) = empty();
615        let byte = func.new_vreg(GPR);
616        let wide = func.new_vreg(GPR);
617        let out = func.new_vreg(GPR);
618        let widen = op(&mut names, "movzx_8_64");
619        let load = op(&mut names, "mov_rm_32");
620        func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
621        func.build(block, load)
622            .def(out, GPR)
623            .mem(mir::Mem::at(mir::Operand::read(wide, GPR)))
624            .finish();
625
626        assert_eq!(takes(&mut func, &names), 0);
627        assert_eq!(shape(&func, &names, block).len(), 2);
628    }
629
630    /// The operand an instruction of this shape reads and writes in the one place, which the
631    /// assembly names once and the description therefore has no separate width for. It is as wide
632    /// as the definition it is tied to, and an eight bit source is not enough for it.
633    #[test]
634    fn a_tied_operand_reads_as_much_as_the_definition_it_is_tied_to() {
635        let (mut names, mut func, block) = empty();
636        let byte = func.new_vreg(GPR);
637        let wide = func.new_vreg(GPR);
638        let other = func.new_vreg(GPR);
639        let sum = func.new_vreg(GPR);
640        let address = func.new_vreg(GPR);
641        let widen = op(&mut names, "movzx_8_32");
642        let add = op(&mut names, "add_rr_32");
643        let store = op(&mut names, "mov_mr_32");
644        func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
645        func.build(block, add)
646            .operand(mir::Operand::write(sum, GPR).with(Constraint::Reuse(1)))
647            .uses(wide, GPR)
648            .uses(other, GPR)
649            .finish();
650        func.build(block, store)
651            .uses(sum, GPR)
652            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
653            .finish();
654
655        assert_eq!(takes(&mut func, &names), 0);
656        assert_eq!(shape(&func, &names, block).len(), 3);
657    }
658
659    /// A physical register as the source. Sending the readers there would send them to a register
660    /// the convention hands out and a call is free to destroy, which is not what SSA promises
661    /// about the virtual one they were reading.
662    #[test]
663    fn a_widening_of_a_physical_register_stays() {
664        let (mut names, mut func, block) = empty();
665        let arrived = mir::Reg::physical(RDI);
666        let wide = func.new_vreg(GPR);
667        let address = func.new_vreg(GPR);
668        let widen = op(&mut names, "movzx_8_32");
669        let store = op(&mut names, "mov_mr_8");
670        func.build(block, widen).def(wide, GPR).uses(arrived, GPR).finish();
671        func.build(block, store)
672            .uses(wide, GPR)
673            .mem(mir::Mem::at(mir::Operand::read(address, GPR)))
674            .finish();
675
676        assert_eq!(takes(&mut func, &names), 0);
677        assert_eq!(shape(&func, &names, block).len(), 2);
678    }
679
680    /// An opcode from somewhere other than this target, which is what an instruction with no
681    /// prefix on it is. Nothing is known about how much of its operands it reads, and the answer
682    /// to knowing nothing is that it reads everything.
683    #[test]
684    fn an_opcode_this_target_does_not_describe_reads_everything() {
685        let (mut names, mut func, block) = empty();
686        let byte = func.new_vreg(GPR);
687        let wide = func.new_vreg(GPR);
688        let out = func.new_vreg(GPR);
689        let widen = op(&mut names, "movzx_8_32");
690        let foreign = mir::Opcode::new(names.intern("elsewhere.narrow"));
691        func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
692        func.build(block, foreign).def(out, GPR).uses(wide, GPR).finish();
693
694        assert_eq!(takes(&mut func, &names), 0);
695        assert_eq!(shape(&func, &names, block).len(), 2);
696    }
697
698    /// A conversion nothing reads at all, which is dead code rather than dead bits. It is left for
699    /// whatever removes instructions whose answers nobody wants, so that the number this gives
700    /// back is the number of widenings it found and not a count of two different things.
701    #[test]
702    fn a_conversion_nothing_reads_is_left_for_the_pass_that_owns_dead_code() {
703        let (mut names, mut func, block) = empty();
704        let byte = func.new_vreg(GPR);
705        let wide = func.new_vreg(GPR);
706        let widen = op(&mut names, "movzx_8_32");
707        func.build(block, widen).def(wide, GPR).uses(byte, GPR).finish();
708
709        assert_eq!(takes(&mut func, &names), 0);
710        assert_eq!(shape(&func, &names, block).len(), 1);
711    }
712}