Skip to main content

rucc_regalloc/
assign.rs

1//! Which register each value lives in, and which values live on the stack instead.
2//!
3//! Design: `spec/10-backend.md` section 10.4.
4//!
5//! This is the `-O0` allocator's decision and nothing else. It is linear scan over the line
6//! [`crate::order`] lays the function out in: the values are taken in the order they are written,
7//! each is given a register that nothing else live at the same time is in, and when there is no
8//! such register one of the values in flight goes to the stack instead. There is no splitting and
9//! no coalescing, so a value gets one place for the whole of its range and keeps it. That produces
10//! mediocre code quickly, which is what `-O0` is for, and the allocator that produces good code
11//! slowly is a separate one, in M4.
12//!
13//! Which value is sent to the stack is the one whose range ends last, counting the value being
14//! placed among the candidates. A value wanted for a long time is the cheapest to spill per
15//! instruction it frees a register over, and it is the only heuristic here. What is picked is
16//! really a register and not a value, since two values that are never both wanted share one, and
17//! then every value in that register which is in this one's way goes.
18//!
19//! # Where the line is not the function
20//!
21//! The line is the order the blocks arrived in, and `crate::layout` puts them in a different one
22//! afterwards, so being between two blocks on the line says nothing about being between them in
23//! the code. A value live in one loop and live again in a later one is written down with
24//! everything in between inside the interval around it, and it is not live in any of it.
25//!
26//! Which is why what decides anything here is the area from `crate::live`, and the interval is
27//! only the sweep's bookkeeping: it says which values to compare and the areas say which of them
28//! actually collide. Three loops one after another in a function put a dozen values in flight at
29//! the same instant of the line and never at the same instant of the program, and asking the
30//! interval would spill the one this loop is walking for the sake of eleven values in the other
31//! two. tamnd/rucc#982.
32//!
33//! The same holds for a register an instruction insists on. A call destroys seven registers on
34//! x86-64, and a function whose blocks happen to arrive with a call written between the blocks of
35//! a loop would otherwise lose all seven for every value in that loop, for a call the loop never
36//! reaches, so that question is asked of the area and not of the interval either.
37//!
38//! Allowed is not the same as free, though, so the registers are offered in two passes. First the
39//! ones nothing insists on anywhere the range reaches, then the ones something insists on somewhere
40//! the value never goes. The second kind costs: the instruction that insists has to be handed the
41//! register in the end, and what hands it over is a move. A function that gives a value back has an
42//! operand fixed to `rax` at the end of it, and putting the busiest value in the function in `rax`
43//! because no path reaches the return with it live buys one register and pays a move at every
44//! return. Ordering the two passes is what keeps the register and drops the moves.
45//!
46//! The hint below is asked the first question rather than the second for the same reason. A value
47//! taking the register its own operand asked for saves a move, and taking one somebody else's
48//! operand asked for somewhere it never goes costs one, so a hint is worth following when the
49//! register is clear and not worth following when it is merely allowed.
50//!
51//! # What it does with a register an instruction insists on
52//!
53//! Two things. It stays out of that register for everybody else, and it tries that register first
54//! for the value the operand names. A division wants its dividend in `rax`, so `rax` is
55//! unavailable to every other value that is live where the division reads, and it is the first
56//! register offered to the dividend itself. When the dividend gets it there is no move on the way
57//! in, and when it does not the rewrite writes one and nothing else changes.
58//!
59//! That second half is the hint, and without it the register an instruction insists on is the one
60//! register the value in it can never have, since the value's own operand is what makes the
61//! register look busy. The effect is largest on returns, because a function that gives a value
62//! back has an operand fixed to `rax` at the end of it and most functions give a value back.
63//!
64//! What makes the hint safe is asking about the register at each of the instruction's two points
65//! rather than across the whole of it. An instruction reads at the first and writes at the second,
66//! so a register it insists on is one value's at the first, another value's at the second, and
67//! nobody else's at either. A division reads its dividend from `rax` and writes its quotient to
68//! `rax`, and those are different values that can both live there. A value passed to a call in
69//! `rdi` and wanted again afterwards cannot, because nothing writes `rdi` at the second point and
70//! a register the call does not write is a register the call is assumed to destroy.
71//!
72//! An operand that has to be in memory is the other way round. The value it names goes on the
73//! stack whatever else is true of it, because that is the only place the instruction could read it
74//! from.
75//!
76//! # What it does with a two address instruction
77//!
78//! An `add` on x86-64 writes one of the registers it reads, which the operand says as a reuse of
79//! another operand. The rewrite can always make that true by copying the source into the
80//! destination first, but only if the destination is a register the instruction does not otherwise
81//! read, so a value written by a reuse is treated here as live from where the instruction reads
82//! rather than from where it writes. Then the copy is always safe.
83//!
84//! The copy is also usually unnecessary, and the one place this looks past the interval it is
85//! placing is to see that: if the value being reused is read here for the last time and the value
86//! being written starts here, the second may have the first's register, and the instruction is
87//! already two address without anything being moved anywhere. That is the whole of the coalescing
88//! this allocator does, and it is worth the dozen lines, because otherwise every piece of
89//! arithmetic in the output carries a move in front of it.
90//!
91//! Both halves of that are needed. The second is the one a loop breaks: an instruction at the
92//! bottom of a loop can write a value the top of the loop reads on the next turn, and such a value
93//! is live on the way into the instruction that writes it as well as after. It is then wanted at
94//! the same time as the value it reuses, whatever is true of the reuse, and giving it the same
95//! register makes an addition read the answer to the last one instead of its own operand.
96//!
97//! # What it does not do
98//!
99//! It does not touch the function. What comes out is a table saying where each value went, and the
100//! pass that rewrites the operands and writes the moves reads it. Keeping the decision and the
101//! rewrite apart is what lets the decision be checked by looking at it, and it is the shape
102//! `spec/10-backend.md` section 10.4 asks for: an allocator is a function from a program to an
103//! assignment and the moves that make it true.
104
105use std::cmp::Reverse;
106
107use rucc_mir::{Constraint, Flags, Func, Inst, Operand, Reg, Role};
108use rucc_target::{PhysReg, RegClass};
109
110use crate::live::{Area, Live, Range};
111use crate::order::{Order, Point};
112
113/// Where a value lives.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
115pub enum Place {
116    /// In a register, for the whole of its range.
117    Reg(PhysReg),
118    /// In a slot of the frame, which is what a value the allocator ran out of registers for gets,
119    /// and what a value an instruction can only read from memory gets.
120    Slot(u32),
121}
122
123/// What the allocator is allowed to use.
124///
125/// The order is the calling convention's, because which register to hand out first follows from
126/// which ones a call destroys, and `rucc-target` is where a convention says so. The scratch
127/// registers are held back out of the order and are what a spilled value is read into at each
128/// instruction that wants it, so a class needs as many of them as one of its instructions has
129/// register operands. Nothing here uses them, since a spilled value is only read once the rewrite
130/// is writing the instruction that reads it, but they are held back here because this is what
131/// decides what everything else may have.
132#[derive(Debug, Clone, Default)]
133pub struct Env {
134    classes: Vec<Class>,
135}
136
137/// What one class of registers offers.
138#[derive(Debug, Clone, Default)]
139struct Class {
140    order: Vec<PhysReg>,
141    scratch: Vec<PhysReg>,
142}
143
144impl Env {
145    /// An environment offering nothing, which is what a target that has said nothing offers.
146    #[must_use]
147    pub fn new() -> Self {
148        Self::default()
149    }
150
151    /// The same environment, with that class described.
152    #[must_use]
153    pub fn with(mut self, class: RegClass, order: &[PhysReg], scratch: &[PhysReg]) -> Self {
154        let index = usize::from(class.number());
155        if self.classes.len() <= index {
156            self.classes.resize(index + 1, Class::default());
157        }
158        self.classes[index] = Class { order: order.to_vec(), scratch: scratch.to_vec() };
159        self
160    }
161
162    /// The registers it may hand out in a class, in the order it prefers them.
163    #[must_use]
164    pub fn order(&self, class: RegClass) -> &[PhysReg] {
165        self.classes.get(usize::from(class.number())).map_or(&[], |class| &class.order)
166    }
167
168    /// The registers it may hand out, by class number, empty for a class it says nothing about.
169    pub(crate) fn offered(&self) -> impl Iterator<Item = &[PhysReg]> + '_ {
170        self.classes.iter().map(|class| class.order.as_slice())
171    }
172
173    /// The registers held back in a class for reading a spilled value into.
174    #[must_use]
175    pub fn scratch(&self, class: RegClass) -> &[PhysReg] {
176        self.classes.get(usize::from(class.number())).map_or(&[], |class| &class.scratch)
177    }
178}
179
180/// Where every value in a function went.
181#[derive(Debug, Clone)]
182pub struct Assignment {
183    places: Vec<Option<Place>>,
184    slots: Vec<RegClass>,
185    commuted: Vec<Inst>,
186}
187
188impl Assignment {
189    /// Records that the sources of `inst` are to be swapped, for an answer written over the second.
190    pub(crate) fn commute(&mut self, inst: Inst) {
191        self.commuted.push(inst);
192    }
193
194    /// An assignment that says nothing yet about a function with that many values.
195    ///
196    /// This and [`Assignment::put`] and [`Assignment::take_slot`] are how an allocator says what
197    /// it decided. There will be a second one in M4 and it will not reach its answer this way, so
198    /// what an assignment is has to be separable from how this file arrives at one, and the
199    /// checker in [`crate::check`] reads an assignment without caring which allocator wrote it.
200    #[must_use]
201    pub fn empty(vregs: usize) -> Self {
202        Self { places: vec![None; vregs], slots: Vec::new(), commuted: Vec::new() }
203    }
204
205    /// The two address instructions whose answer went into the register of their second source.
206    ///
207    /// Each has to have its two sources swapped before anything reads the assignment against the
208    /// function, which [`crate::run`] does. After that the answer reuses what is then the first
209    /// source, as every two address instruction does. tamnd/rucc#1895.
210    #[must_use]
211    pub fn commuted(&self) -> &[Inst] {
212        &self.commuted
213    }
214
215    /// Records where a value went.
216    ///
217    /// # Panics
218    ///
219    /// Panics on a physical register, which is somewhere already, and on a virtual one the
220    /// function never handed out.
221    pub fn put(&mut self, reg: Reg, place: Place) {
222        self.places[index(reg)] = Some(place);
223    }
224
225    /// Takes a slot of the frame, of that class, and gives back which one it is.
226    ///
227    /// # Panics
228    ///
229    /// Panics past four billion slots, which is a frame no machine has room for.
230    pub fn take_slot(&mut self, class: RegClass) -> u32 {
231        let slot = u32::try_from(self.slots.len()).expect("too many spilled values");
232        self.slots.push(class);
233        slot
234    }
235
236    /// Where a value lives, or `None` for a virtual register this function never mentions and for
237    /// a physical one, which is already where it is.
238    #[must_use]
239    pub fn place(&self, reg: Reg) -> Option<Place> {
240        self.places.get(usize::try_from(reg.number()?).ok()?).copied().flatten()
241    }
242
243    /// The class of each slot of the frame, which is what says how wide it has to be.
244    #[must_use]
245    pub fn slots(&self) -> &[RegClass] {
246        &self.slots
247    }
248
249    /// Every value that went somewhere, and where it went.
250    ///
251    /// The assignment read the other way round, which is what a caller wants when the question is
252    /// about the places rather than about the values. The stack slot allocator asks it that way,
253    /// since what it needs is which value is in each slot and the assignment is stored by value.
254    pub fn placed(&self) -> impl Iterator<Item = (Reg, Place)> + '_ {
255        self.places.iter().enumerate().filter_map(|(number, place)| {
256            let number = u32::try_from(number).ok()?;
257            Some((Reg::virtual_reg(number), (*place)?))
258        })
259    }
260
261    /// How many values went to the stack.
262    #[must_use]
263    pub fn spilled(&self) -> usize {
264        self.slots.len()
265    }
266
267    /// Puts a value on the stack, in a slot of its own.
268    pub(crate) fn spill(&mut self, reg: Reg, class: RegClass) {
269        let slot = self.take_slot(class);
270        self.put(reg, Place::Slot(slot));
271    }
272}
273
274/// One value waiting for a place.
275#[derive(Debug, Clone, Copy)]
276struct Interval<'a> {
277    reg: Reg,
278    class: RegClass,
279    /// The interval around the area, which is what the sweep below reads and what says which value
280    /// is wanted for longest when one of them has to go.
281    range: Range,
282    /// Everywhere the value is really live, which is what says whether two of them fit in one
283    /// register.
284    area: Area<'a>,
285}
286
287/// One value that has a register, for as long as it still wants it.
288#[derive(Debug, Clone, Copy)]
289struct Held<'a> {
290    reg: Reg,
291    class: RegClass,
292    range: Range,
293    area: Area<'a>,
294    at: PhysReg,
295    /// How many values were given a register before this one, which is the order the values in
296    /// flight are looked at in when one register has to be taken back.
297    since: usize,
298}
299
300/// The values that have a register, kept by the register each is in.
301///
302/// Nearly every question asked of them is about one register: whether it is free for an interval,
303/// or whether a value is still in it. They used to be one list walked from the start for every
304/// register tried, and on a function with a thousand values in flight that walk was most of the
305/// time the allocator took. Keeping them by register means asking about one reads only the values
306/// that are in it. Registers are numbered within their class, so two classes can share a list and
307/// the class is still checked.
308#[derive(Default)]
309struct Active<'a> {
310    by: Vec<Vec<Held<'a>>>,
311    /// For each register, a point no value in it ends before. Values are let go of at the start of
312    /// every interval, and most of those times nothing in most registers has ended, so a register
313    /// whose values all end at or after the point is not walked at all.
314    soonest: Vec<Point>,
315    /// How many values have been given a register so far.
316    count: usize,
317    /// The pieces of the values in each register, by class and then by register number, which is
318    /// what [`available`] asks about.
319    pieces: Vec<Vec<Pieces>>,
320}
321
322impl<'a> Active<'a> {
323    /// The values in one register, in the order they were given it.
324    fn at(&self, at: PhysReg) -> &[Held<'a>] {
325        self.by.get(usize::from(at.number())).map_or(&[], Vec::as_slice)
326    }
327
328    fn push(&mut self, reg: Reg, class: RegClass, range: Range, area: Area<'a>, at: PhysReg) {
329        let slot = usize::from(at.number());
330        if self.by.len() <= slot {
331            self.by.resize_with(slot + 1, Vec::new);
332            self.soonest.resize(slot + 1, Point::MAX);
333        }
334        self.by[slot].push(Held { reg, class, range, area, at, since: self.count });
335        self.soonest[slot] = self.soonest[slot].min(range.end);
336        self.count += 1;
337        let held = &self.by[slot];
338        let pieces = pieces_mut(&mut self.pieces, class, slot);
339        if pieces.kept {
340            pieces.drop_before(range.start);
341            for piece in area.pieces() {
342                pieces.insert(piece, reg);
343            }
344        } else if held.len() > FEW {
345            // Enough values to be worth a list, which starts with what is already there.
346            pieces.kept = true;
347            for held in held.iter().filter(|held| held.class == class) {
348                for piece in held.area.pieces() {
349                    pieces.insert(piece, held.reg);
350                }
351            }
352        }
353    }
354
355    /// Whether a value of the class in `at` other than `except` is live anywhere the area is.
356    fn taken(&self, class: RegClass, at: PhysReg, area: Area<'_>, except: Option<Reg>) -> bool {
357        let held = self.at(at);
358        if held.len() > FEW {
359            if let Some(answer) = self.listed(class, at, area, except) {
360                return answer;
361            }
362        }
363        held.iter()
364            .any(|held| held.class == class && Some(held.reg) != except && held.area.overlaps(area))
365    }
366
367    /// What the list of `at`'s pieces says, or nothing when it is not kept or not in order. Out of
368    /// line so that the walk above, which is all most registers ever need, stays small enough to
369    /// be put inline where it is asked.
370    #[inline(never)]
371    fn listed(
372        &self,
373        class: RegClass,
374        at: PhysReg,
375        area: Area<'_>,
376        except: Option<Reg>,
377    ) -> Option<bool> {
378        let by = self.pieces.get(usize::from(class.number()))?;
379        let pieces = by.get(usize::from(at.number()))?;
380        (pieces.kept && !pieces.broken).then(|| pieces.touch(area, except))
381    }
382
383    /// The values of the class in register number `slot` that touch the area, from its list of
384    /// pieces, or nothing when the list is not kept or not in order.
385    #[inline(never)]
386    fn owners(&self, class: RegClass, slot: usize, area: Area<'_>) -> Option<Vec<Reg>> {
387        let pieces = self.pieces.get(usize::from(class.number()))?.get(slot)?;
388        if pieces.kept { pieces.owners(area) } else { None }
389    }
390
391    /// Takes the values of the class in `at` whose areas `goes` says to, and hands each to `gone`.
392    fn evict(
393        &mut self,
394        class: RegClass,
395        at: PhysReg,
396        goes: impl Fn(&Held<'a>) -> bool,
397        mut gone: impl FnMut(&Held<'a>),
398    ) {
399        let slot = usize::from(at.number());
400        let mut taken = Vec::new();
401        self.by[slot].retain(|held| {
402            let out = held.class == class && goes(held);
403            if out {
404                gone(held);
405                taken.push((held.reg, held.area));
406            }
407            !out
408        });
409        let pieces = pieces_mut(&mut self.pieces, class, slot);
410        if pieces.kept {
411            for (reg, area) in taken {
412                for piece in area.pieces() {
413                    pieces.remove(piece, reg);
414                }
415            }
416        }
417    }
418
419    /// Lets go of every value whose interval ends before a point.
420    ///
421    /// Taking a value out of a register anywhere else leaves that register's soonest end where it
422    /// was, which is still a point nothing in it ends before, so only this and [`Active::push`]
423    /// have to keep it.
424    fn expire(&mut self, point: Point) {
425        for (held, soonest) in self.by.iter_mut().zip(&mut self.soonest) {
426            if *soonest >= point {
427                continue;
428            }
429            held.retain(|held| held.range.end >= point);
430            *soonest = held.iter().map(|held| held.range.end).min().unwrap_or(Point::MAX);
431        }
432    }
433}
434
435/// How many values a register can hold before its pieces are kept in a list. A register with no
436/// more than this in it, which is most of them without optimization, is quicker to ask about by
437/// walking its values, and keeping a list for every one of those cost more than it saved.
438pub(crate) const FEW: usize = 4;
439
440/// The list for one class and register number, made when it is first asked for.
441fn pieces_mut(pieces: &mut Vec<Vec<Pieces>>, class: RegClass, slot: usize) -> &mut Pieces {
442    let class = usize::from(class.number());
443    if pieces.len() <= class {
444        pieces.resize_with(class + 1, Vec::new);
445    }
446    let by = &mut pieces[class];
447    if by.len() <= slot {
448        by.resize_with(slot + 1, Pieces::default);
449    }
450    &mut by[slot]
451}
452
453/// The pieces of every value of one class in one register, sorted by where they start.
454///
455/// Asking whether a register is free for a value used to compare the value with every other value
456/// in the register, a walk over both lists of pieces for each one, and with a few dozen values
457/// in each register that was a large part of an optimized build of a large file. Two values in
458/// one register are never live at once, bar the one point a value written over the one it reuses
459/// shares with it, so in start order the pieces end in order too. Then the only piece that can
460/// touch one of the value's is the last one that starts before that piece ends, and asking is a
461/// search for each piece of the value rather than a walk over everything in the register.
462///
463/// Whether the ends really are in order is checked as each piece goes in, and a register where
464/// they are not is answered by the walk over its values instead, so the answer is the same either
465/// way.
466#[derive(Default)]
467pub(crate) struct Pieces {
468    /// Start, end and whose, sorted by start and then by end.
469    list: Vec<(Point, Point, Reg)>,
470    /// Whether a piece went in that ends before one in front of it.
471    broken: bool,
472    /// Whether the list is kept at all, which it is from the first time the register holds more
473    /// than [`FEW`] values.
474    pub(crate) kept: bool,
475}
476
477impl Pieces {
478    #[inline(never)]
479    pub(crate) fn insert(&mut self, piece: Range, reg: Reg) {
480        let key = (piece.start, piece.end);
481        let at = self.list.partition_point(|&(start, end, _)| (start, end) <= key);
482        let after = at == 0 || self.list[at - 1].1 <= piece.end;
483        let before = self.list.get(at).is_none_or(|next| piece.end <= next.1);
484        if !(after && before) {
485            self.broken = true;
486        }
487        self.list.insert(at, (piece.start, piece.end, reg));
488    }
489
490    pub(crate) fn remove(&mut self, piece: Range, reg: Reg) {
491        let from = self.list.partition_point(|&(start, _, _)| start < piece.start);
492        let found = self.list[from..]
493            .iter()
494            .take_while(|&&(start, _, _)| start == piece.start)
495            .position(|&(_, end, owner)| end == piece.end && owner == reg);
496        if let Some(offset) = found {
497            self.list.remove(from + offset);
498        }
499    }
500
501    /// Lets go of the pieces that end before a point, which no value starting there can touch.
502    /// They are the ones at the front while the ends are in order.
503    fn drop_before(&mut self, point: Point) {
504        if !self.broken {
505            let gone = self.list.partition_point(|&(_, end, _)| end < point);
506            self.list.drain(..gone);
507        }
508    }
509
510    /// Whether a piece of a value other than `except` touches the area.
511    fn touch(&self, area: Area<'_>, except: Option<Reg>) -> bool {
512        area.pieces().any(|piece| {
513            let below = self.list.partition_point(|&(start, _, _)| start <= piece.end);
514            self.list[..below]
515                .iter()
516                .rev()
517                .find(|&&(_, _, owner)| Some(owner) != except)
518                .is_some_and(|&(_, end, _)| end >= piece.start)
519        })
520    }
521
522    /// Every value with a piece that touches the area, each once and in order, or `None` for a
523    /// list whose ends are out of order. With the ends in order the pieces that touch one of the
524    /// area's are the last few that start before it ends, back to the first that ends before it
525    /// starts.
526    pub(crate) fn owners(&self, area: Area<'_>) -> Option<Vec<Reg>> {
527        if self.broken {
528            return None;
529        }
530        let mut owners = Vec::new();
531        for piece in area.pieces() {
532            let below = self.list.partition_point(|&(start, _, _)| start <= piece.end);
533            let touching =
534                self.list[..below].iter().rev().take_while(|&&(_, end, _)| end >= piece.start);
535            owners.extend(touching.map(|&(_, _, owner)| owner));
536        }
537        owners.sort_unstable();
538        owners.dedup();
539        Some(owners)
540    }
541}
542
543/// A register an instruction insists on, and where it insists on it.
544#[derive(Debug, Clone, Copy)]
545struct Blocked {
546    class: RegClass,
547    at: PhysReg,
548    /// One of the instruction's two points. Every register an instruction insists on has an entry
549    /// at each of them, because a register held at one of the two is a register nothing else may
550    /// be in across the instruction.
551    point: Point,
552    /// The one value that may be in it there, which is the value of an operand the instruction
553    /// reads at that point or writes at it. `None` means nothing may: an operand naming a physical
554    /// register outright claims it against everything, and a point no operand covers is a point
555    /// the instruction has the register to itself at.
556    by: Option<Reg>,
557    /// The byte the instruction writes the register from, when it leaves the bottom of it alone,
558    /// which is what a call does to a register AArch64 keeps the low half of. A value that fits
559    /// below it is not in the way. See [`Constraint::Above`].
560    above: Option<u8>,
561}
562
563impl Blocked {
564    /// Whether this is in the way of a value of that width, which it is unless it writes only
565    /// above everything the value takes.
566    fn reaches(&self, width: Option<u8>) -> bool {
567        match (self.above, width) {
568            (Some(above), Some(width)) => width > above,
569            _ => true,
570        }
571    }
572}
573
574/// A value written into the register another operand of the same instruction was read from.
575#[derive(Debug, Clone, Copy)]
576pub(crate) struct Reuse {
577    /// The value being read, which is the one whose register would do.
578    pub(crate) source: Reg,
579    /// The other value the instruction reads, when the instruction reads the two either way round
580    /// and so could write its answer over this one instead.
581    pub(crate) second: Option<Reg>,
582    /// Where the instruction reads it.
583    pub(crate) at: Point,
584    /// The instruction, which is swapped round if the answer takes the second value's register.
585    pub(crate) inst: Inst,
586}
587
588/// Decides where every value in a function lives.
589///
590/// # Panics
591///
592/// Panics if a class has no registers to hand out and something in the function is in that class,
593/// since that is a target description that does not describe the target the function is for.
594#[must_use]
595pub fn assign(func: &Func, order: &Order, live: &Live, env: &Env) -> Assignment {
596    let blocked = blocked(func, order);
597    let forced = forced(func);
598    let reuses = reuses(func, order);
599    let hints = hints(func);
600    let passed = passed(func);
601
602    let mut intervals = Vec::with_capacity(func.vregs());
603    for (number, reuse) in reuses.iter().enumerate() {
604        let reg = Reg::virtual_reg(u32::try_from(number).expect("a register number"));
605        let (Some(mut area), Some(class)) = (live.area(reg), func.class_of(reg)) else {
606            continue;
607        };
608        if let Some(reuse) = reuse {
609            area = area.with(reuse.at);
610        }
611        intervals.push(Interval { reg, class, range: area.hull(), area });
612    }
613    intervals.sort_by_key(|interval| (interval.range.start, interval.reg));
614
615    let mut assignment = Assignment::empty(func.vregs());
616    let mut active = Active::default();
617    for interval in intervals {
618        active.expire(interval.range.start);
619        if forced.contains(&interval.reg) {
620            assignment.spill(interval.reg, interval.class);
621            continue;
622        }
623        // A class with no order is one the target says nothing allocates from, which on x86-64 is
624        // the x87 stack. A value of such a class is a mistake at the point it was made rather than
625        // a value with nowhere to go: what the target means is that the value lives in memory and
626        // that whatever operates on it takes an address. See `ClassInfo::allocatable`.
627        assert!(
628            !env.order(interval.class).is_empty(),
629            "a value in class {}, which the target hands out no registers from",
630            interval.class.number()
631        );
632        let reuse = reuses[index(interval.reg)];
633        let coalesced = |source| coalesce(&assignment, &active, &blocked, live, interval, source);
634        let first = reuse.and_then(|reuse| coalesced(reuse.source));
635        let second = reuse.and_then(|reuse| reuse.second).and_then(coalesced);
636        // An instruction that reads its sources either way round can write over the second one
637        // instead, which is what it needs when the first is read again later and the second is
638        // not. When both would do, the first is kept unless only the second is where something
639        // wants the answer, which saves the move in front of that reader.
640        //
641        // A block the answer is passed to wants it where that block's parameter already is. That
642        // has to count as much as an instruction asking for a register. A sum a loop carries is
643        // passed back to the parameter it was read from, and taking the register of the other
644        // source because the sum is also printed at the end moves the copy onto the back edge,
645        // where it runs every turn instead of once.
646        let hinted_at = |at: Option<PhysReg>| {
647            at.is_some_and(|at| {
648                hints[index(interval.reg)].contains(&at)
649                    || passed[index(interval.reg)]
650                        .iter()
651                        .any(|&param| assignment.place(param) == Some(Place::Reg(at)))
652            })
653        };
654        let commute =
655            second.is_some() && (first.is_none() || hinted_at(second) && !hinted_at(first));
656        let two_address = if commute { second } else { first };
657        if let (true, Some(reuse)) = (commute, reuse) {
658            assignment.commuted.push(reuse.inst);
659        }
660        // The reuse comes first, because a two address instruction that has to copy its left
661        // operand in pays for the copy whatever the hint says, and taking the hint here would buy
662        // one move at the cost of another.
663        let hinted = hints[index(interval.reg)].iter().copied().find(|&at| {
664            env.order(interval.class).contains(&at)
665                && available(&active, &blocked, interval, at, None, Want::Clear)
666        });
667        // A register nobody else wants anywhere near this value first, and one somebody wants
668        // somewhere the value never goes only when there is no other. Both are correct and the
669        // second is the worse buy, since the instruction that wants it has to be handed it and
670        // whatever this value is doing there has to move out of the way first.
671        let scan = |want| {
672            env.order(interval.class)
673                .iter()
674                .copied()
675                .find(|&at| available(&active, &blocked, interval, at, None, want))
676        };
677        let chosen =
678            two_address.or(hinted).or_else(|| scan(Want::Clear)).or_else(|| scan(Want::Allowed));
679        match chosen {
680            Some(at) => {
681                assignment.places[index(interval.reg)] = Some(Place::Reg(at));
682                active.push(interval.reg, interval.class, interval.range, interval.area, at);
683            }
684            None => spill_one(&mut assignment, &mut active, &blocked, interval),
685        }
686    }
687    assignment
688}
689
690/// How much a register suits an interval.
691#[derive(Debug, Clone, Copy, PartialEq, Eq)]
692pub(crate) enum Want {
693    /// Nothing insists on it anywhere the range reaches, so taking it costs nobody anything.
694    Clear,
695    /// Something insists on it somewhere the range reaches and nowhere the value is live, so taking
696    /// it is allowed and may still cost: the instruction that insists wants the register for a
697    /// value of its own, and that value now has to be moved into it.
698    Allowed,
699}
700
701/// Every register every instruction in the function insists on, arranged to be asked about.
702///
703/// Built once and never changed afterwards, and there is only one question ever asked of it: of the
704/// constraints naming one register of one class, is there one at a point some interval covers. So
705/// the entries are ordered by the register they name and then by the point, and the question is a
706/// binary search for the start of the interval followed by a walk that stops at its end.
707///
708/// It used to be a flat list walked from one end for every candidate register of every interval,
709/// which is quadratic in the size of a function and is most of the compile on a large one. See
710/// tamnd/rucc#1003 for the profile that found it.
711///
712/// The search is over the points alone and only among the one register's entries. A search over
713/// the whole list compares three fields of an entry several times its size at every step, and on a
714/// large function that is most of what asking costs, since every candidate register of every
715/// interval asks.
716pub(crate) struct Blocks {
717    /// The constraints, sorted by class, then by register, then by point.
718    all: Vec<Blocked>,
719    /// The point of each constraint, in the same order, which is what the search reads.
720    points: Vec<Point>,
721    /// Where each register's constraints start and end in the list, by class times `stride` plus
722    /// the register's number.
723    spans: Vec<(usize, usize)>,
724    /// One more than the highest register number anything insists on.
725    stride: usize,
726    /// How many bytes of its register each virtual register's value takes, by number, which is
727    /// what [`Blocked::reaches`] asks.
728    widths: Vec<Option<u8>>,
729}
730
731impl Blocks {
732    /// Whether an instruction insists on `at` where a value over `area` would be in its way: at any
733    /// point the value's range reaches when the register is wanted clear, and only at a point the
734    /// value is live at when it is merely wanted allowed. The value's own operands never count.
735    pub(crate) fn insists(
736        &self,
737        reg: Reg,
738        class: RegClass,
739        area: Area<'_>,
740        range: Range,
741        at: PhysReg,
742        want: Want,
743    ) -> bool {
744        self.over(class, at, range).any(|one| {
745            one.by != Some(reg)
746                && one.reaches(self.width(reg))
747                && (want == Want::Clear || area.covers(one.point))
748        })
749    }
750
751    /// How many bytes of its register a value takes, or `None` for all of it.
752    fn width(&self, reg: Reg) -> Option<u8> {
753        let number = usize::try_from(reg.number()?).ok()?;
754        self.widths.get(number).copied().flatten()
755    }
756
757    /// Every register an instruction takes for itself where no value may be in it, with the class
758    /// and the point, sorted by class, then by register, then by point.
759    ///
760    /// Not one it writes only the top of, since a value narrow enough may still be in that.
761    pub(crate) fn taken(&self) -> impl Iterator<Item = (RegClass, PhysReg, Point)> + '_ {
762        self.all
763            .iter()
764            .filter(|one| one.by.is_none() && one.above.is_none())
765            .map(|one| (one.class, one.at, one.point))
766    }
767
768    /// The constraints on one register of one class at the points an interval covers.
769    ///
770    /// Both ends of the walk come from the ordering rather than from a test, so what comes back is
771    /// exactly what the old `covers` call used to keep and in the same order.
772    #[inline]
773    fn over(
774        &self,
775        class: RegClass,
776        at: PhysReg,
777        range: Range,
778    ) -> impl Iterator<Item = &Blocked> + '_ {
779        let (low, high) = if usize::from(at.number()) < self.stride {
780            let key = usize::from(class.number()) * self.stride + usize::from(at.number());
781            self.spans.get(key).copied().unwrap_or((0, 0))
782        } else {
783            (0, 0)
784        };
785        let first = low + self.points[low..high].partition_point(|&point| point < range.start);
786        self.all[first..high].iter().take_while(move |one| one.point <= range.end)
787    }
788}
789
790/// Whether a register is one this interval could have.
791///
792/// The exception is the value a reuse is coalescing with, which holds the register right up to the
793/// point the new value takes it over and is the one thing that may overlap.
794///
795/// The sweep only keeps a value in `active` while the interval around it reaches this one, so the
796/// areas still have to be compared: two values whose intervals cross can have holes that let them
797/// share a register anyway, which on a function with several loops in it is most of them.
798fn available(
799    active: &Active<'_>,
800    blocked: &Blocks,
801    interval: Interval<'_>,
802    at: PhysReg,
803    except: Option<Reg>,
804    want: Want,
805) -> bool {
806    let taken = active.taken(interval.class, at, interval.area, except);
807    let width = blocked.width(interval.reg);
808    let insisted = blocked.over(interval.class, at, interval.range).any(|one| {
809        one.by != Some(interval.reg)
810            && one.reaches(width)
811            && (want == Want::Clear || interval.area.covers(one.point))
812    });
813    !taken && !insisted
814}
815
816/// The register the value being reused is in, when the value being written is never live at the
817/// same time as it and the register is otherwise free.
818fn coalesce(
819    assignment: &Assignment,
820    active: &Active<'_>,
821    blocked: &Blocks,
822    live: &Live,
823    interval: Interval<'_>,
824    source: Reg,
825) -> Option<PhysReg> {
826    let Some(Place::Reg(at)) = assignment.place(source) else { return None };
827    active.at(at).iter().find(|held| held.reg == source)?;
828    // The two have to be apart everywhere, asked of the areas liveness worked out and without the
829    // point the reuse adds, since that point is the one they are allowed to share.
830    //
831    // That covers both ways it can go wrong. A value read again later needs its register after
832    // this instruction would have overwritten it. And a value being written that is live where the
833    // instruction reads already is what a loop carrying its own result round looks like: the
834    // instruction writes it at the bottom and the top of the loop reads what the last turn wrote.
835    // Either way the two are wanted at once, and no register holds both.
836    //
837    // It used to be asked of the end of the interval around the value being read, and that is not
838    // the same question. A block laid out after this instruction where the value is still live,
839    // such as the default arm of a `switch` that joins back in above it, stretches the interval
840    // past this point when nothing past it reads the value at all. The sum a loop carries round
841    // then went into a new register and was copied back at the bottom of every turn.
842    // tamnd/rucc#1965.
843    let free = available(active, blocked, interval, at, Some(source), Want::Allowed);
844    (apart(live, source, interval.reg) && free).then_some(at)
845}
846
847/// Whether two values are never live at the same time, going by what liveness worked out.
848pub(crate) fn apart(live: &Live, first: Reg, second: Reg) -> bool {
849    match (live.area(first), live.area(second)) {
850        (Some(first), Some(second)) => !first.overlaps(second),
851        _ => false,
852    }
853}
854
855/// Sends values to the stack to free a register: the ones wanted for longest, since a register
856/// held that long pays for itself over the most instructions.
857///
858/// What is chosen is a register rather than a value, because two values whose areas miss each
859/// other share one and taking it means every value in it this one is really on top of has to go.
860/// A register holding two of those costs twice as much to take as one holding a single value, so
861/// the cheap ones are looked at first and the reach only settles ties.
862fn spill_one<'a>(
863    assignment: &mut Assignment,
864    active: &mut Active<'a>,
865    blocked: &Blocks,
866    interval: Interval<'a>,
867) {
868    // What each register would cost: how many values would go, and the furthest any of them
869    // reaches. The list is one entry per register of the class, so walking it for each value in
870    // flight is the same shape as everything else here. The first number is when the earliest of
871    // them was given the register, and sorting by it puts the registers in the order the values
872    // were given them, which is what settles a tie.
873    let mut costs: Vec<(usize, PhysReg, usize, Point)> = Vec::new();
874    for (slot, values) in active.by.iter().enumerate() {
875        // A register with a list of its pieces says which values touch the area, which is quicker
876        // than asking each value in it when it holds many.
877        let owners = if values.len() > FEW {
878            active.owners(interval.class, slot, interval.area)
879        } else {
880            None
881        };
882        for held in values {
883            if held.class != interval.class {
884                continue;
885            }
886            let touches = match &owners {
887                Some(owners) => owners.binary_search(&held.reg).is_ok(),
888                None => held.area.overlaps(interval.area),
889            };
890            if !touches {
891                continue;
892            }
893            match costs.iter_mut().find(|(_, at, _, _)| *at == held.at) {
894                Some((first, _, count, reach)) => {
895                    *first = (*first).min(held.since);
896                    *count += 1;
897                    *reach = (*reach).max(held.range.end);
898                }
899                None => costs.push((held.since, held.at, 1, held.range.end)),
900            }
901        }
902    }
903    costs.sort_unstable_by_key(|&(first, _, _, _)| first);
904    // A register the instructions in the way insist on for themselves is no use, because taking it
905    // over would put this value in a register it may not have.
906    let none = Active::default();
907    let chosen = costs
908        .iter()
909        .filter(|&&(_, at, _, reach)| {
910            reach > interval.range.end
911                && available(&none, blocked, interval, at, None, Want::Allowed)
912        })
913        .min_by_key(|&&(_, _, count, reach)| (count, Reverse(reach)))
914        .map(|&(_, at, _, _)| at);
915    match chosen {
916        Some(at) => {
917            active.evict(
918                interval.class,
919                at,
920                |held| held.area.overlaps(interval.area),
921                |held| assignment.spill(held.reg, held.class),
922            );
923            assignment.places[index(interval.reg)] = Some(Place::Reg(at));
924            active.push(interval.reg, interval.class, interval.range, interval.area, at);
925        }
926        None => assignment.spill(interval.reg, interval.class),
927    }
928}
929
930/// The registers the instructions insist on, and where.
931///
932/// A physical register an operand names outright counts the same way. Nothing before allocation
933/// writes one except an instruction that has to, and it has to for the length of that one
934/// instruction, which is the same statement a fixed constraint makes.
935pub(crate) fn blocked(func: &Func, order: &Order) -> Blocks {
936    let mut blocked = Vec::new();
937    let mut claimed: Vec<(RegClass, PhysReg)> = Vec::new();
938    for block in func.blocks() {
939        for inst in func.insts(block) {
940            let operands = &func[func[inst].operands];
941            claimed.clear();
942            for operand in operands {
943                if let Some(at) = insisted(operand) {
944                    let key = (operand.class, at);
945                    if !claimed.contains(&key) {
946                        claimed.push(key);
947                    }
948                }
949            }
950            for &(class, at) in &claimed {
951                // Both points, whether or not an operand is at them. A register an instruction
952                // reads and does not write is still gone by the time the instruction is done as far
953                // as anything here knows, which is what stops the value a call is passed in `rdi`
954                // from staying in `rdi` over the call.
955                for (point, role) in [(order.early(inst), Role::Use), (order.late(inst), Role::Def)]
956                {
957                    let mut named = false;
958                    for operand in operands {
959                        let mine = insisted(operand) == Some(at) && operand.class == class;
960                        if !mine || !(operand.role == role || operand.role == Role::EarlyDef) {
961                            continue;
962                        }
963                        named = true;
964                        let by = operand.reg.is_virtual().then_some(operand.reg);
965                        let above = match operand.constraint {
966                            Constraint::Above(above) => Some(above),
967                            _ => None,
968                        };
969                        blocked.push(Blocked { class, at, point, by, above });
970                    }
971                    // A register no operand names where the operands are read is one the
972                    // instruction writes and does not read, which is what a clobber is, and the
973                    // seven registers a call destroys are the whole of why that case is worth
974                    // separating. Such a register is free right up to the point it is written, so a
975                    // value whose last read is this instruction may sit in one: it is read before
976                    // the instruction writes anything, the way any other operand is. Blocking it
977                    // where the operands are read as well would take every caller saved register
978                    // away from the value a call is passed, which is a value that dies at the call
979                    // and pays for a callee saved register it holds for two instructions. Anything
980                    // living past the instruction is still refused, by the block below.
981                    //
982                    // This is where a target's early definitions are paid for. An instruction that
983                    // fills a register before it has finished reading has to say so, because that
984                    // is the one thing a plain definition here no longer covers: a division on
985                    // x86-64 is a sign extension and then the division itself, so `rdx` is gone
986                    // before the divisor is read, and a divisor that went there would be read as
987                    // the dividend's own sign bits. `rucc_target::x86_64` writes both of them down
988                    // as early definitions for exactly that reason.
989                    if !named && role == Role::Def {
990                        blocked.push(Blocked { class, at, point, by: None, above: None });
991                    }
992                }
993            }
994        }
995    }
996    // Program order already has the points ascending, but the registers one instruction claims are
997    // walked outside the two points rather than inside them, so the list arrives in order by
998    // instruction and not by register. A sort by the key the lookup searches on is what makes it
999    // searchable, and it is stable so two constraints on one register at one point keep the order
1000    // the instruction wrote them in.
1001    blocked.sort_by_key(|one: &Blocked| (one.class, one.at, one.point));
1002    let widths = (0..func.vregs())
1003        .map(|number| func.width(Reg::virtual_reg(u32::try_from(number).ok()?)))
1004        .collect();
1005    let points = blocked.iter().map(|one| one.point).collect();
1006    let stride = blocked.iter().map(|one| usize::from(one.at.number()) + 1).max().unwrap_or(0);
1007    let classes = blocked.last().map_or(0, |one| usize::from(one.class.number()) + 1);
1008    let mut spans = vec![(0, 0); classes * stride];
1009    for (index, one) in blocked.iter().enumerate() {
1010        let key = usize::from(one.class.number()) * stride + usize::from(one.at.number());
1011        let span = &mut spans[key];
1012        if span.1 == 0 {
1013            span.0 = index;
1014        }
1015        span.1 = index + 1;
1016    }
1017    Blocks { all: blocked, points, spans, stride, widths }
1018}
1019
1020/// The register an operand has to be in, which is the one a constraint asks for or the one the
1021/// operand names outright.
1022fn insisted(operand: &Operand) -> Option<PhysReg> {
1023    match operand.constraint {
1024        Constraint::Fixed(at) => Some(at),
1025        _ => operand.reg.phys(),
1026    }
1027}
1028
1029/// The registers each value would rather be in, which are the ones the operands naming it insist on.
1030///
1031/// In the order the function writes them down, so the definition comes first where there is one,
1032/// since a value written into a fixed register and then moved somewhere else pays for the move at
1033/// the top of its life rather than at the bottom. The ones after it are worth keeping for the same
1034/// reason the first one is, and the value a call is passed is where that shows: its definition may
1035/// insist on the register a parameter arrived in, which the call it is handed to has usually taken
1036/// back for an argument of its own by then, and behind that is the register the convention passes
1037/// it in, which is free and is exactly where the value wants to end up.
1038pub(crate) fn hints(func: &Func) -> Vec<Vec<PhysReg>> {
1039    let mut hints = vec![Vec::new(); func.vregs()];
1040    for block in func.blocks() {
1041        for inst in func.insts(block) {
1042            for operand in &func[func[inst].operands] {
1043                let Constraint::Fixed(at) = operand.constraint else { continue };
1044                let number = operand.reg.number().and_then(|number| usize::try_from(number).ok());
1045                let Some(number) = number else { continue };
1046                let wanted: &mut Vec<PhysReg> = &mut hints[number];
1047                if func.class_of(operand.reg) == Some(operand.class) && !wanted.contains(&at) {
1048                    wanted.push(at);
1049                }
1050            }
1051        }
1052    }
1053    hints
1054}
1055
1056/// The block parameters each value is passed to, by the virtual register passed.
1057pub(crate) fn passed(func: &Func) -> Vec<Vec<Reg>> {
1058    let mut passed = vec![Vec::new(); func.vregs()];
1059    for block in func.blocks() {
1060        for call in &func[block].succs {
1061            for (&arg, param) in call.args.iter().zip(&func[call.block].params) {
1062                let number = arg.number().and_then(|number| usize::try_from(number).ok());
1063                let Some(number) = number else { continue };
1064                let to: &mut Vec<Reg> = &mut passed[number];
1065                if !to.contains(&param.reg) {
1066                    to.push(param.reg);
1067                }
1068            }
1069        }
1070    }
1071    passed
1072}
1073
1074/// The values that have to be on the stack whatever else is true of them.
1075pub(crate) fn forced(func: &Func) -> Vec<Reg> {
1076    let mut forced = Vec::new();
1077    for block in func.blocks() {
1078        for inst in func.insts(block) {
1079            for operand in &func[func[inst].operands] {
1080                if operand.constraint == Constraint::Stack
1081                    && operand.reg.is_virtual()
1082                    && !forced.contains(&operand.reg)
1083                {
1084                    forced.push(operand.reg);
1085                }
1086            }
1087        }
1088    }
1089    forced
1090}
1091
1092/// The value each two address instruction reuses, by the virtual register it writes.
1093pub(crate) fn reuses(func: &Func, order: &Order) -> Vec<Option<Reuse>> {
1094    let mut reuses = vec![None; func.vregs()];
1095    for block in func.blocks() {
1096        for inst in func.insts(block) {
1097            let operands = &func[func[inst].operands];
1098            for operand in operands {
1099                let Constraint::Reuse(other) = operand.constraint else { continue };
1100                let number = operand.reg.number().and_then(|number| usize::try_from(number).ok());
1101                let Some(number) = number else { continue };
1102                let source = operands[usize::from(other)].reg;
1103                let second = if func[inst].flags.contains(Flags::COMMUTES) {
1104                    swappable(operands, usize::from(other))
1105                } else {
1106                    None
1107                };
1108                reuses[number] = Some(Reuse { source, second, at: order.early(inst), inst });
1109            }
1110        }
1111    }
1112    reuses
1113}
1114
1115/// The second source of an instruction that reads its two sources either way round, when the
1116/// answer could go over it instead of over the first.
1117///
1118/// Only the shape of a two address instruction with two sources, the answer and then the two, with
1119/// the answer reusing the first. The second has to be a value of the same class that asks for
1120/// nothing more than a register, since after the swap it is the one the answer reuses.
1121fn swappable(operands: &[Operand], other: usize) -> Option<Reg> {
1122    let [answer, first, second] = operands else { return None };
1123    let same = second.class == first.class && second.class == answer.class;
1124    let plain = second.role == Role::Use && second.constraint == Constraint::Reg;
1125    (other == 1 && same && plain && second.reg.is_virtual() && second.reg != first.reg)
1126        .then_some(second.reg)
1127}
1128
1129/// A virtual register's number as a table index.
1130fn index(reg: Reg) -> usize {
1131    usize::try_from(reg.number().expect("a virtual register")).expect("a register number")
1132}
1133
1134#[cfg(test)]
1135mod tests {
1136    use rucc_base::Interner;
1137    use rucc_mir::{BlockCall, Opcode, Operand, Param};
1138    use rucc_target::x86_64::{GPR, R13, R14, R15, RAX, RCX, RDX, REGS, RSI, SYSV};
1139
1140    use super::*;
1141
1142    /// The x86-64 environment, with the last three of the allocation order held back as scratch.
1143    fn env() -> Env {
1144        let (order, scratch) = SYSV.int_order.split_at(SYSV.int_order.len() - 3);
1145        Env::new().with(GPR, order, scratch)
1146    }
1147
1148    /// An environment with that many general purpose registers, for putting a function under
1149    /// pressure without writing a hundred instructions.
1150    fn narrow(count: usize) -> Env {
1151        Env::new().with(GPR, &SYSV.int_order[..count], &SYSV.int_order[count..count + 1])
1152    }
1153
1154    /// What a place is called, which is what an assertion reads.
1155    fn named(place: Option<Place>) -> String {
1156        match place {
1157            Some(Place::Reg(reg)) => REGS.name(GPR, reg).expect("a register").to_string(),
1158            Some(Place::Slot(slot)) => format!("slot {slot}"),
1159            None => "nowhere".to_string(),
1160        }
1161    }
1162
1163    /// Where every value in a function went.
1164    fn places(func: &Func, env: &Env) -> Vec<String> {
1165        let order = Order::of(func);
1166        let live = Live::of(func, &order);
1167        let assignment = assign(func, &order, &live, env);
1168        (0..func.vregs())
1169            .map(|number| {
1170                let reg = Reg::virtual_reg(u32::try_from(number).expect("a register number"));
1171                named(assignment.place(reg))
1172            })
1173            .collect()
1174    }
1175
1176    #[test]
1177    fn two_values_that_are_never_both_wanted_share_a_register() {
1178        let mut names = Interner::new();
1179        let mut func = Func::new(names.intern("f"));
1180        let opcode = Opcode::new(names.intern("x64.nop"));
1181        let block = func.create_block();
1182        let first = func.new_vreg(GPR);
1183        let second = func.new_vreg(GPR);
1184        func.build(block, opcode).def(first, GPR).finish();
1185        func.build(block, opcode).uses(first, GPR).finish();
1186        func.build(block, opcode).def(second, GPR).finish();
1187        func.build(block, opcode).uses(second, GPR).finish();
1188
1189        // The first register in the order, twice, because the first value is finished with before
1190        // the second one is written.
1191        assert_eq!(places(&func, &env()), ["rax", "rax"]);
1192    }
1193
1194    /// A value held over an instruction that writes the whole of the first register and the top
1195    /// of the second, which is a call on AArch64 and `v8` in small, with the value as wide as that.
1196    fn over_the_top(width: u32) -> Func {
1197        let mut names = Interner::new();
1198        let mut func = Func::new(names.intern("f"));
1199        let opcode = Opcode::new(names.intern("x64.nop"));
1200        let block = func.create_block();
1201        let held = func.new_vreg(GPR);
1202        func.set_width(held, width);
1203        func.build(block, opcode).def(held, GPR).finish();
1204        func.build(block, opcode)
1205            .operand(Operand::write(Reg::physical(RAX), GPR))
1206            .operand(Operand::write(Reg::physical(RCX), GPR).with(Constraint::Above(8)))
1207            .finish();
1208        func.build(block, opcode).uses(held, GPR).finish();
1209        func
1210    }
1211
1212    #[test]
1213    fn a_value_that_fits_under_what_an_instruction_writes_stays_in_the_register() {
1214        assert_eq!(places(&over_the_top(8), &narrow(2)), ["rcx"]);
1215        assert_eq!(places(&over_the_top(4), &narrow(2)), ["rcx"]);
1216    }
1217
1218    #[test]
1219    fn a_value_wider_than_that_or_of_no_known_width_does_not() {
1220        assert_eq!(places(&over_the_top(16), &narrow(2)), ["slot 0"]);
1221        assert_eq!(places(&over_the_top(0), &narrow(2)), ["slot 0"]);
1222    }
1223
1224    #[test]
1225    fn two_values_that_are_both_wanted_do_not() {
1226        let mut names = Interner::new();
1227        let mut func = Func::new(names.intern("f"));
1228        let opcode = Opcode::new(names.intern("x64.nop"));
1229        let block = func.create_block();
1230        let first = func.new_vreg(GPR);
1231        let second = func.new_vreg(GPR);
1232        func.build(block, opcode).def(first, GPR).finish();
1233        func.build(block, opcode).def(second, GPR).finish();
1234        func.build(block, opcode).uses(first, GPR).finish();
1235        func.build(block, opcode).uses(second, GPR).finish();
1236
1237        assert_eq!(places(&func, &env()), ["rax", "rcx"]);
1238    }
1239
1240    #[test]
1241    fn a_value_written_early_that_nothing_reads_still_holds_its_register() {
1242        let mut names = Interner::new();
1243        let mut func = Func::new(names.intern("f"));
1244        let opcode = Opcode::new(names.intern("x64.nop"));
1245        let block = func.create_block();
1246        let wanted = func.new_vreg(GPR);
1247        let spare = func.new_vreg(GPR);
1248        // A division: a remainder somebody wants, and a quotient nobody does. Both are written by
1249        // the one instruction and the quotient is written before the operands have been read.
1250        func.build(block, opcode)
1251            .def(wanted, GPR)
1252            .operand(Operand::write_early(spare, GPR))
1253            .finish();
1254        func.build(block, opcode).uses(wanted, GPR).finish();
1255
1256        // Two registers, not one. A value nothing reads is still somewhere, and the instruction
1257        // that wrote it wrote the other one too, so the two cannot be the same place. Handing them
1258        // the same register loses the remainder, because the copy that takes the quotient out of
1259        // the register the machine insisted on goes on top of it. The quotient gets the first
1260        // register because it is written first, which is the whole of what early means.
1261        assert_eq!(places(&func, &env()), ["rcx", "rax"]);
1262    }
1263
1264    #[test]
1265    fn the_value_wanted_longest_is_the_one_that_goes_to_the_stack() {
1266        let mut names = Interner::new();
1267        let mut func = Func::new(names.intern("f"));
1268        let opcode = Opcode::new(names.intern("x64.nop"));
1269        let block = func.create_block();
1270        let long = func.new_vreg(GPR);
1271        let short = func.new_vreg(GPR);
1272        let third = func.new_vreg(GPR);
1273        func.build(block, opcode).def(long, GPR).finish();
1274        func.build(block, opcode).def(short, GPR).finish();
1275        func.build(block, opcode).def(third, GPR).finish();
1276        func.build(block, opcode).uses(short, GPR).finish();
1277        func.build(block, opcode).uses(third, GPR).finish();
1278        func.build(block, opcode).uses(long, GPR).finish();
1279
1280        // Two registers between three values. The one still wanted at the end of the function is
1281        // the one whose register is worth the most to everybody else, so it is the one that goes.
1282        assert_eq!(places(&func, &narrow(2)), ["slot 0", "rcx", "rax"]);
1283    }
1284
1285    #[test]
1286    fn a_register_an_instruction_insists_on_goes_to_the_values_that_asked_for_it() {
1287        let mut names = Interner::new();
1288        let mut func = Func::new(names.intern("f"));
1289        let opcode = Opcode::new(names.intern("x64.nop"));
1290        let block = func.create_block();
1291        let across = func.new_vreg(GPR);
1292        let dividend = func.new_vreg(GPR);
1293        let quotient = func.new_vreg(GPR);
1294        let remainder = func.new_vreg(GPR);
1295        func.build(block, opcode).def(across, GPR).finish();
1296        func.build(block, opcode).def(dividend, GPR).finish();
1297        func.build(block, opcode)
1298            .operand(Operand::write(quotient, GPR).with(Constraint::Fixed(RAX)))
1299            .operand(Operand::write_early(remainder, GPR).with(Constraint::Fixed(RDX)))
1300            .operand(Operand::read(dividend, GPR).with(Constraint::Fixed(RAX)))
1301            .finish();
1302        func.build(block, opcode).uses(across, GPR).finish();
1303
1304        // The value that has to be across the division is nowhere near `rax` or `rdx`, and each of
1305        // the three the division names is in the register the division asked for it in. The
1306        // dividend and the quotient share `rax` because the first is read where the second is
1307        // written, which is what a division does.
1308        assert_eq!(places(&func, &env()), ["rcx", "rax", "rax", "rdx"]);
1309    }
1310
1311    /// A value read by an instruction that fills a register before it reads is kept out of that
1312    /// register, even though the read is the last thing the value is wanted for.
1313    ///
1314    /// The divisor of a division is the case. What the machine runs is `cltd` and then `idivl`, so
1315    /// `rdx` holds the top half of the dividend by the time the divisor is read, and a divisor
1316    /// sitting in `rdx` is read as the dividend's own sign bits. An early definition is how the
1317    /// target says a register goes before the operands are read, and this is where the allocator
1318    /// has to hear it, since a value dying at an instruction is otherwise free to sit in a
1319    /// register that instruction writes. tamnd/rucc#1232.
1320    #[test]
1321    fn a_value_that_dies_at_an_instruction_stays_out_of_what_it_fills_first() {
1322        let mut names = Interner::new();
1323        let mut func = Func::new(names.intern("f"));
1324        let opcode = Opcode::new(names.intern("x64.nop"));
1325        let block = func.create_block();
1326        let across = func.new_vreg(GPR);
1327        let dividend = func.new_vreg(GPR);
1328        let divisor = func.new_vreg(GPR);
1329        let remainder = func.new_vreg(GPR);
1330        func.build(block, opcode).def(across, GPR).finish();
1331        func.build(block, opcode).def(dividend, GPR).finish();
1332        func.build(block, opcode).def(divisor, GPR).finish();
1333        func.build(block, opcode)
1334            .operand(Operand::write_early(remainder, GPR).with(Constraint::Fixed(RDX)))
1335            .operand(Operand::read(dividend, GPR).with(Constraint::Fixed(RAX)))
1336            .operand(Operand::read(divisor, GPR))
1337            .finish();
1338        func.build(block, opcode).uses(across, GPR).uses(remainder, GPR).finish();
1339
1340        // Four registers for four values, and the divisor takes the fourth. `rdx` is free
1341        // everywhere in this function except at the instruction that is about to fill it, which is
1342        // the one instruction the divisor is wanted at.
1343        assert_eq!(places(&func, &narrow(4)), ["rcx", "rax", "rsi", "rdx"]);
1344    }
1345
1346    #[test]
1347    fn a_value_wanted_after_the_instruction_that_insists_does_not_get_that_register() {
1348        let mut names = Interner::new();
1349        let mut func = Func::new(names.intern("f"));
1350        let opcode = Opcode::new(names.intern("x64.nop"));
1351        let block = func.create_block();
1352        let dividend = func.new_vreg(GPR);
1353        let quotient = func.new_vreg(GPR);
1354        func.build(block, opcode).def(dividend, GPR).finish();
1355        func.build(block, opcode)
1356            .operand(Operand::write(quotient, GPR).with(Constraint::Fixed(RAX)))
1357            .operand(Operand::read(dividend, GPR).with(Constraint::Fixed(RAX)))
1358            .finish();
1359        func.build(block, opcode).uses(dividend, GPR).finish();
1360
1361        // The hint is a preference and not a claim. The dividend would rather be in `rax` and
1362        // cannot be, because the division writes `rax` and the dividend is wanted afterwards, so
1363        // it takes the next register and the quotient keeps the one it was promised.
1364        assert_eq!(places(&func, &env()), ["rcx", "rax"]);
1365    }
1366
1367    #[test]
1368    fn a_value_an_instruction_can_only_read_from_memory_is_on_the_stack() {
1369        let mut names = Interner::new();
1370        let mut func = Func::new(names.intern("f"));
1371        let opcode = Opcode::new(names.intern("x64.nop"));
1372        let block = func.create_block();
1373        let value = func.new_vreg(GPR);
1374        func.build(block, opcode).def(value, GPR).finish();
1375        func.build(block, opcode)
1376            .operand(Operand::read(value, GPR).with(Constraint::Stack))
1377            .finish();
1378
1379        assert_eq!(places(&func, &env()), ["slot 0"]);
1380    }
1381
1382    #[test]
1383    fn a_two_address_instruction_writes_the_register_it_read_when_it_can() {
1384        let mut names = Interner::new();
1385        let mut func = Func::new(names.intern("f"));
1386        let opcode = Opcode::new(names.intern("x64.nop"));
1387        let block = func.create_block();
1388        let left = func.new_vreg(GPR);
1389        let right = func.new_vreg(GPR);
1390        let sum = func.new_vreg(GPR);
1391        func.build(block, opcode).def(left, GPR).finish();
1392        func.build(block, opcode).def(right, GPR).finish();
1393        func.build(block, opcode)
1394            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
1395            .uses(left, GPR)
1396            .uses(right, GPR)
1397            .finish();
1398        func.build(block, opcode).uses(right, GPR).finish();
1399
1400        // The addition reads the left value for the last time, so the answer goes where that was
1401        // and the instruction is two address without a move in front of it.
1402        assert_eq!(places(&func, &env()), ["rax", "rcx", "rax"]);
1403    }
1404
1405    #[test]
1406    fn a_two_address_instruction_that_cannot_gets_a_register_nothing_it_reads_is_in() {
1407        let mut names = Interner::new();
1408        let mut func = Func::new(names.intern("f"));
1409        let opcode = Opcode::new(names.intern("x64.nop"));
1410        let block = func.create_block();
1411        let left = func.new_vreg(GPR);
1412        let right = func.new_vreg(GPR);
1413        let sum = func.new_vreg(GPR);
1414        func.build(block, opcode).def(left, GPR).finish();
1415        func.build(block, opcode).def(right, GPR).finish();
1416        func.build(block, opcode)
1417            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
1418            .uses(left, GPR)
1419            .uses(right, GPR)
1420            .finish();
1421        func.build(block, opcode).uses(left, GPR).finish();
1422
1423        // The left value is wanted afterwards, so the answer cannot have its register. It cannot
1424        // have the right one's either, because the rewrite is about to write a move into it before
1425        // the addition has read anything.
1426        assert_eq!(places(&func, &env()), ["rax", "rcx", "rdx"]);
1427    }
1428
1429    #[test]
1430    fn an_answer_that_commutes_goes_over_the_source_that_is_finished_with() {
1431        let mut names = Interner::new();
1432        let mut func = Func::new(names.intern("f"));
1433        let opcode = Opcode::new(names.intern("x64.nop"));
1434        let block = func.create_block();
1435        let left = func.new_vreg(GPR);
1436        let right = func.new_vreg(GPR);
1437        let sum = func.new_vreg(GPR);
1438        func.build(block, opcode).def(left, GPR).finish();
1439        func.build(block, opcode).def(right, GPR).finish();
1440        let add = func
1441            .build(block, opcode)
1442            .flags(Flags::COMMUTES)
1443            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
1444            .uses(left, GPR)
1445            .uses(right, GPR)
1446            .finish();
1447        func.build(block, opcode).uses(left, GPR).uses(sum, GPR).finish();
1448
1449        // The same shape as the one above where the answer got a register of its own, except that
1450        // the addition reads its sources either way round, so the answer goes where the right one
1451        // was and the instruction is marked to be swapped.
1452        assert_eq!(places(&func, &env()), ["rax", "rcx", "rcx"]);
1453        let order = Order::of(&func);
1454        let live = Live::of(&func, &order);
1455        let assignment = assign(&func, &order, &live, &env());
1456        assert_eq!(assignment.commuted(), [add]);
1457
1458        // Once swapped, the instruction is an ordinary reuse of its first source, the checker and
1459        // the trace agree with it, and nothing has to be moved in front of it. The rewrite has put
1460        // the registers in by then, so the right one is `rcx` and the left one `rax`.
1461        let allocation = crate::run(&mut func, &env(), "f", true);
1462        assert!(allocation.edits.is_empty());
1463        let operands = &func[func[add].operands];
1464        let (first, second) = (operands[1].reg.phys(), operands[2].reg.phys());
1465        assert_eq!((first, second), (Some(RCX), Some(RAX)));
1466    }
1467
1468    #[test]
1469    fn an_answer_that_commutes_takes_the_source_something_after_it_wants() {
1470        let mut names = Interner::new();
1471        let mut func = Func::new(names.intern("f"));
1472        let opcode = Opcode::new(names.intern("x64.nop"));
1473        let block = func.create_block();
1474        let left = func.new_vreg(GPR);
1475        let right = func.new_vreg(GPR);
1476        let sum = func.new_vreg(GPR);
1477        func.build(block, opcode).def(left, GPR).finish();
1478        func.build(block, opcode)
1479            .operand(Operand::write(right, GPR).with(Constraint::Fixed(RAX)))
1480            .finish();
1481        let add = func
1482            .build(block, opcode)
1483            .flags(Flags::COMMUTES)
1484            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
1485            .uses(left, GPR)
1486            .uses(right, GPR)
1487            .finish();
1488        func.build(block, opcode)
1489            .operand(Operand::read(sum, GPR).with(Constraint::Fixed(RAX)))
1490            .finish();
1491
1492        // Both sources are finished with, so either register would do for the answer. The one
1493        // reading it wants it in `rax`, which is where the right one already is, so it goes there
1494        // and nothing is moved in front of that reader.
1495        let names = places(&func, &env());
1496        assert_eq!(names[2], "rax");
1497        assert_ne!(names[0], "rax");
1498        let allocation = crate::run(&mut func, &env(), "f", true);
1499        assert!(allocation.edits.is_empty());
1500        assert_eq!(func[func[add].operands][1].reg.phys(), Some(RAX));
1501    }
1502
1503    #[test]
1504    fn an_answer_that_commutes_stays_where_the_loop_passes_it() {
1505        let mut names = Interner::new();
1506        let mut func = Func::new(names.intern("f"));
1507        let opcode = Opcode::new(names.intern("x64.nop"));
1508        let entry = func.create_block();
1509        let head = func.create_block();
1510        let out = func.create_block();
1511        let seed = func.new_vreg(GPR);
1512        let total = func.new_vreg(GPR);
1513        let term = func.new_vreg(GPR);
1514        let next = func.new_vreg(GPR);
1515        func.build(entry, opcode).def(seed, GPR).finish();
1516        *func.succs_mut(entry) = vec![BlockCall::with(head, vec![seed])];
1517        func.params_mut(head).push(Param { reg: total, class: GPR });
1518        func.build(head, opcode).def(term, GPR).finish();
1519        let add = func
1520            .build(head, opcode)
1521            .flags(Flags::COMMUTES)
1522            .operand(Operand::write(next, GPR).with(Constraint::Reuse(1)))
1523            .uses(total, GPR)
1524            .uses(term, GPR)
1525            .finish();
1526        func.build(head, opcode)
1527            .operand(Operand::read(next, GPR).with(Constraint::Fixed(RSI)))
1528            .finish();
1529        *func.succs_mut(head) = vec![BlockCall::with(head, vec![next]), BlockCall::to(out)];
1530
1531        // Both sources are finished with and the sum is wanted in `rsi` as well, but the loop
1532        // passes it back to `total`, so it goes where `total` is and the back edge has nothing to
1533        // copy.
1534        let order = Order::of(&func);
1535        let live = Live::of(&func, &order);
1536        let assignment = assign(&func, &order, &live, &env());
1537        assert_eq!(assignment.place(next), assignment.place(total));
1538        assert!(!assignment.commuted().contains(&add));
1539    }
1540
1541    #[test]
1542    fn an_answer_that_does_not_commute_leaves_its_sources_where_they_are() {
1543        let mut names = Interner::new();
1544        let mut func = Func::new(names.intern("f"));
1545        let opcode = Opcode::new(names.intern("x64.nop"));
1546        let block = func.create_block();
1547        let left = func.new_vreg(GPR);
1548        let right = func.new_vreg(GPR);
1549        let sum = func.new_vreg(GPR);
1550        func.build(block, opcode).def(left, GPR).finish();
1551        func.build(block, opcode).def(right, GPR).finish();
1552        func.build(block, opcode)
1553            .flags(Flags::COMMUTES)
1554            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
1555            .uses(left, GPR)
1556            .uses(right, GPR)
1557            .finish();
1558        func.build(block, opcode).uses(right, GPR).finish();
1559
1560        // The left one is finished with, so the answer goes over it as it always did, and there is
1561        // nothing to swap.
1562        assert_eq!(places(&func, &env()), ["rax", "rcx", "rax"]);
1563        let order = Order::of(&func);
1564        let live = Live::of(&func, &order);
1565        assert!(assign(&func, &order, &live, &env()).commuted().is_empty());
1566    }
1567
1568    #[test]
1569    fn a_value_live_across_a_whole_loop_holds_its_register_over_all_of_it() {
1570        let mut names = Interner::new();
1571        let mut func = Func::new(names.intern("f"));
1572        let opcode = Opcode::new(names.intern("x64.nop"));
1573        let head = func.create_block();
1574        let body = func.create_block();
1575        let carried = func.new_vreg(GPR);
1576        let inside = func.new_vreg(GPR);
1577        func.build(head, opcode).def(carried, GPR).finish();
1578        *func.succs_mut(head) = vec![BlockCall::to(body)];
1579        func.build(body, opcode).def(inside, GPR).finish();
1580        func.build(body, opcode).uses(inside, GPR).uses(carried, GPR).finish();
1581        *func.succs_mut(body) = vec![BlockCall::to(body)];
1582
1583        // The value inside the loop cannot have the carried one's register, even though nothing
1584        // between the two definitions says so.
1585        assert_eq!(places(&func, &env()), ["rax", "rcx"]);
1586    }
1587
1588    #[test]
1589    fn a_two_address_answer_already_live_does_not_take_the_register_it_read() {
1590        let mut names = Interner::new();
1591        let mut func = Func::new(names.intern("f"));
1592        let opcode = Opcode::new(names.intern("x64.nop"));
1593        let head = func.create_block();
1594        let latch = func.create_block();
1595        let out = func.create_block();
1596        let source = func.new_vreg(GPR);
1597        let carried = func.new_vreg(GPR);
1598        func.build(head, opcode).def(source, GPR).finish();
1599        func.build(head, opcode).def(carried, GPR).finish();
1600        *func.succs_mut(head) = vec![BlockCall::to(latch)];
1601        // The bottom of the loop adds the source to the carried value and writes the answer back
1602        // over it, reusing the register the source is in. The next turn round redefines both.
1603        func.build(latch, opcode)
1604            .operand(Operand::write(carried, GPR).with(Constraint::Reuse(1)))
1605            .uses(source, GPR)
1606            .uses(carried, GPR)
1607            .finish();
1608        *func.succs_mut(latch) = vec![BlockCall::to(head), BlockCall::to(out)];
1609        func.build(out, opcode).uses(carried, GPR).finish();
1610
1611        // The source is read here for the last time, which on its own is the shape the two address
1612        // shortcut is for, and taking it would be wrong. The carried value was written by the same
1613        // instruction on the last turn and is read by this one, so the two are both wanted where
1614        // the instruction reads and one register cannot hold both.
1615        assert_eq!(places(&func, &env()), ["rax", "rcx"]);
1616
1617        // And the checker has to agree, since it excused this pair on the same reasoning and so
1618        // would have let the answer through.
1619        let order = Order::of(&func);
1620        let live = Live::of(&func, &order);
1621        let assignment = assign(&func, &order, &live, &env());
1622        assert!(crate::check::check(&func, &order, &live, &assignment).is_empty());
1623    }
1624
1625    #[test]
1626    fn a_two_address_answer_with_a_hole_in_front_of_it_does_not_take_its_other_operand() {
1627        let mut names = Interner::new();
1628        let mut func = Func::new(names.intern("f"));
1629        let nop = Opcode::new(names.intern("x64.nop"));
1630        let add = Opcode::new(names.intern("x64.add"));
1631        let entry = func.create_block();
1632        let head = func.create_block();
1633        let arm = func.create_block();
1634        let latch = func.create_block();
1635        let out = func.create_block();
1636        let seed = func.new_vreg(GPR);
1637        let sum = func.new_vreg(GPR);
1638        let inside = func.new_vreg(GPR);
1639        let loaded = func.new_vreg(GPR);
1640        func.build(entry, nop).def(seed, GPR).finish();
1641        func.build(entry, nop).def(sum, GPR).finish();
1642        *func.succs_mut(entry) = vec![BlockCall::to(head)];
1643        func.build(head, nop).uses(sum, GPR).finish();
1644        *func.succs_mut(head) = vec![BlockCall::to(arm), BlockCall::to(latch)];
1645        func.build(arm, nop).def(inside, GPR).finish();
1646        func.build(arm, nop).uses(inside, GPR).finish();
1647        *func.succs_mut(arm) = vec![BlockCall::to(out)];
1648        func.build(latch, nop).def(loaded, GPR).finish();
1649        func.build(latch, add)
1650            .operand(Operand::write(sum, GPR).with(Constraint::Reuse(1)))
1651            .uses(seed, GPR)
1652            .uses(loaded, GPR)
1653            .finish();
1654        *func.succs_mut(latch) = vec![BlockCall::to(head), BlockCall::to(out)];
1655
1656        // The answer is live in the entry and the head as well, and the arm between them is a hole
1657        // in it, so the piece the addition writes is not the first one. The value the addition reads
1658        // out of memory is still wanted where the addition reads, so it may not be in the register
1659        // the answer is about to be copied into, holes or no holes. tamnd/rucc#982.
1660        let places = places(&func, &env());
1661        assert_ne!(places[index(sum)], places[index(loaded)]);
1662
1663        let order = Order::of(&func);
1664        let live = Live::of(&func, &order);
1665        let assignment = assign(&func, &order, &live, &env());
1666        assert!(crate::check::check(&func, &order, &live, &assignment).is_empty());
1667    }
1668
1669    #[test]
1670    fn a_sum_a_loop_carries_round_keeps_its_register_past_an_arm_laid_out_after_it() {
1671        let mut names = Interner::new();
1672        let mut func = Func::new(names.intern("f"));
1673        let nop = Opcode::new(names.intern("x64.nop"));
1674        let add = Opcode::new(names.intern("x64.add"));
1675        let entry = func.create_block();
1676        let head = func.create_block();
1677        let join = func.create_block();
1678        let arm = func.create_block();
1679        let out = func.create_block();
1680        let seed = func.new_vreg(GPR);
1681        let term = func.new_vreg(GPR);
1682        let next = func.new_vreg(GPR);
1683        func.build(entry, nop).def(seed, GPR).finish();
1684        *func.succs_mut(entry) = vec![BlockCall::with(head, vec![seed])];
1685        let total = func.append_param(head, GPR);
1686        func.build(head, nop).def(term, GPR).finish();
1687        *func.succs_mut(head) = vec![BlockCall::to(join), BlockCall::to(arm)];
1688        func.build(join, add)
1689            .operand(Operand::write(next, GPR).with(Constraint::Reuse(1)))
1690            .uses(total, GPR)
1691            .uses(term, GPR)
1692            .finish();
1693        *func.succs_mut(join) =
1694            vec![BlockCall::with(head, vec![next]), BlockCall::with(out, vec![next])];
1695        // The default arm of a `switch`, laid out after the addition it joins back in above. The
1696        // sum is live in it and nothing in it or after it reads the sum again.
1697        func.build(arm, nop).def(term, GPR).finish();
1698        *func.succs_mut(arm) = vec![BlockCall::to(join)];
1699        let result = func.append_param(out, GPR);
1700        func.build(out, nop).uses(result, GPR).finish();
1701
1702        // The addition reads the sum for the last time, so the new sum goes where the old one was
1703        // and the edge back to the top of the loop has nothing to move. tamnd/rucc#1965.
1704        let places = places(&func, &env());
1705        assert_eq!(places[index(next)], places[index(total)]);
1706
1707        let order = Order::of(&func);
1708        let live = Live::of(&func, &order);
1709        let assignment = assign(&func, &order, &live, &env());
1710        assert!(crate::check::check(&func, &order, &live, &assignment).is_empty());
1711    }
1712
1713    /// Two blocks the entry chooses between, with the one the clobber is in written first. The two
1714    /// values written in the entry block are read in the other one, so their ranges cover the
1715    /// clobber whether or not either of them ever reaches it.
1716    fn arms(reaches: bool) -> Func {
1717        let mut names = Interner::new();
1718        let mut func = Func::new(names.intern("f"));
1719        let opcode = Opcode::new(names.intern("x64.nop"));
1720        let entry = func.create_block();
1721        let arm = func.create_block();
1722        let tail = func.create_block();
1723        let first = func.new_vreg(GPR);
1724        let second = func.new_vreg(GPR);
1725        func.build(entry, opcode).def(first, GPR).finish();
1726        func.build(entry, opcode).def(second, GPR).finish();
1727        *func.succs_mut(entry) = vec![BlockCall::to(arm), BlockCall::to(tail)];
1728        // What a call looks like here: an instruction writing the registers the convention says it
1729        // destroys, named outright so that nothing else may be in them.
1730        func.build(arm, opcode).operand(Operand::write(Reg::physical(RAX), GPR)).finish();
1731        *func.succs_mut(arm) = if reaches { vec![BlockCall::to(tail)] } else { Vec::new() };
1732        func.build(tail, opcode).uses(first, GPR).uses(second, GPR).finish();
1733        func
1734    }
1735
1736    #[test]
1737    fn a_register_a_clobber_takes_beats_the_stack_for_a_value_not_live_in_that_block() {
1738        let func = arms(false);
1739
1740        // Two registers between two values, and a clobber in the arm that takes the first of them.
1741        // The intervals around both values cover the clobber, since the arm is written between the
1742        // two blocks they are live in, and the arm is a hole in both of their areas. So the second
1743        // value has `rax` rather than a stack slot: the arm is a block its own path never goes
1744        // through. tamnd/rucc#982.
1745        assert_eq!(places(&func, &narrow(2)), ["rcx", "rax"]);
1746
1747        let order = Order::of(&func);
1748        let live = Live::of(&func, &order);
1749        let assignment = assign(&func, &order, &live, &narrow(2));
1750        assert!(crate::check::check(&func, &order, &live, &assignment).is_empty());
1751    }
1752
1753    #[test]
1754    fn a_register_a_clobber_takes_is_not_free_to_a_value_that_is_live_there() {
1755        let func = arms(true);
1756
1757        // The same blocks with an edge from the arm to the tail, which is all it takes: both values
1758        // now arrive at the read either way, so the clobber is on a path they are live over and the
1759        // one register left has to do for both of them.
1760        assert_eq!(places(&func, &narrow(2)), ["rcx", "slot 0"]);
1761    }
1762
1763    /// A value and the instruction that destroys a register, written one after the other, with the
1764    /// value read by that instruction or by the one after it.
1765    fn dies_at_the_clobber(here: bool) -> Func {
1766        let mut names = Interner::new();
1767        let mut func = Func::new(names.intern("f"));
1768        let opcode = Opcode::new(names.intern("x64.nop"));
1769        let entry = func.create_block();
1770        let value = func.new_vreg(GPR);
1771        func.build(entry, opcode).def(value, GPR).finish();
1772        let call = func.build(entry, opcode).operand(Operand::write(Reg::physical(RAX), GPR));
1773        if here {
1774            call.uses(value, GPR).finish();
1775        } else {
1776            call.finish();
1777            func.build(entry, opcode).uses(value, GPR).finish();
1778        }
1779        func
1780    }
1781
1782    /// A value whose last read is the instruction that destroys a register may be in that register,
1783    /// because the instruction reads what it is handed before it writes anything.
1784    ///
1785    /// The call is what this is about, and the value a call is passed is the case: seven registers
1786    /// on this machine are destroyed by one, every argument dies at the call that reads it, and
1787    /// refusing all seven to those values left them taking a callee saved register for a life two
1788    /// instructions long and paying for it in the prologue and the epilogue. tamnd/rucc#1232.
1789    #[test]
1790    fn a_value_that_dies_where_a_register_is_destroyed_may_be_in_that_register() {
1791        let func = dies_at_the_clobber(true);
1792        assert_eq!(places(&func, &narrow(1)), ["rax"]);
1793
1794        let order = Order::of(&func);
1795        let live = Live::of(&func, &order);
1796        let assignment = assign(&func, &order, &live, &narrow(1));
1797        assert!(crate::check::check(&func, &order, &live, &assignment).is_empty());
1798    }
1799
1800    /// And one read later than that is one the instruction really does destroy, which is the same
1801    /// function with the read moved down by one instruction.
1802    #[test]
1803    fn a_value_read_after_the_instruction_that_destroys_a_register_is_not_in_it() {
1804        let func = dies_at_the_clobber(false);
1805        assert_eq!(places(&func, &narrow(1)), ["slot 0"]);
1806    }
1807
1808    #[test]
1809    fn a_hint_is_followed_when_the_register_is_clear_and_not_when_it_is_merely_allowed() {
1810        let mut names = Interner::new();
1811        let mut func = Func::new(names.intern("f"));
1812        let opcode = Opcode::new(names.intern("x64.nop"));
1813        let entry = func.create_block();
1814        let mid = func.create_block();
1815        let tail = func.create_block();
1816        let first = func.new_vreg(GPR);
1817        let second = func.new_vreg(GPR);
1818        func.build(entry, opcode).def(first, GPR).finish();
1819        func.build(entry, opcode).def(second, GPR).finish();
1820        *func.succs_mut(entry) = vec![BlockCall::to(mid), BlockCall::to(tail)];
1821        // Two arms, each ending in an instruction that wants its own value in `rax`, which is what
1822        // a return out of either side of a branch looks like.
1823        func.build(mid, opcode)
1824            .operand(Operand::read(second, GPR).with(Constraint::Fixed(RAX)))
1825            .finish();
1826        func.build(tail, opcode)
1827            .operand(Operand::read(first, GPR).with(Constraint::Fixed(RAX)))
1828            .finish();
1829
1830        // The first value is hinted at `rax` and does not get it, because the other arm wants `rax`
1831        // for the other value and the first value's range reaches that far. Following the hint here
1832        // would save a move in the tail and cost one in the middle, and the second value gets `rax`
1833        // with nothing moved anywhere instead.
1834        assert_eq!(places(&func, &env()), ["rcx", "rax"]);
1835    }
1836
1837    #[test]
1838    fn a_value_living_in_a_hole_of_another_gets_the_same_register() {
1839        let mut names = Interner::new();
1840        let mut func = Func::new(names.intern("f"));
1841        let opcode = Opcode::new(names.intern("x64.nop"));
1842        let entry = func.create_block();
1843        let arm = func.create_block();
1844        let tail = func.create_block();
1845        let across = func.new_vreg(GPR);
1846        let inside = func.new_vreg(GPR);
1847        func.build(entry, opcode).def(across, GPR).finish();
1848        *func.succs_mut(entry) = vec![BlockCall::to(arm), BlockCall::to(tail)];
1849        func.build(arm, opcode).def(inside, GPR).finish();
1850        func.build(arm, opcode).uses(inside, GPR).finish();
1851        func.build(tail, opcode).uses(across, GPR).finish();
1852
1853        // One register between the two of them, and one register is enough. Nothing in the arm can
1854        // reach the read in the tail, so the value the arm makes is welcome to the register the
1855        // value crossing the function is in. The interval around that value covers the arm and the
1856        // value is nowhere near it, which is what used to send one of the two to the stack.
1857        // tamnd/rucc#982.
1858        assert_eq!(places(&func, &narrow(1)), ["rax", "rax"]);
1859
1860        let order = Order::of(&func);
1861        let live = Live::of(&func, &order);
1862        let assignment = assign(&func, &order, &live, &narrow(1));
1863        assert_eq!(assignment.spilled(), 0);
1864        assert!(crate::check::check(&func, &order, &live, &assignment).is_empty());
1865    }
1866
1867    #[test]
1868    fn a_register_a_clobber_takes_is_the_last_one_offered_rather_than_the_first() {
1869        let func = arms(false);
1870
1871        // With a register to spare the value takes the spare one. Being allowed a register some
1872        // instruction insists on is not the same as it being free: the instruction has to be handed
1873        // it in the end, and what hands it over is a move.
1874        assert_eq!(places(&func, &narrow(3)), ["rcx", "rdx"]);
1875    }
1876
1877    #[test]
1878    fn a_frame_says_what_each_of_its_slots_is_for() {
1879        let mut names = Interner::new();
1880        let mut func = Func::new(names.intern("f"));
1881        let opcode = Opcode::new(names.intern("x64.nop"));
1882        let block = func.create_block();
1883        let first = func.new_vreg(GPR);
1884        let second = func.new_vreg(GPR);
1885        func.build(block, opcode).def(first, GPR).finish();
1886        func.build(block, opcode).def(second, GPR).finish();
1887        func.build(block, opcode).uses(first, GPR).uses(second, GPR).finish();
1888
1889        let order = Order::of(&func);
1890        let live = Live::of(&func, &order);
1891        let assignment = assign(&func, &order, &live, &narrow(1));
1892        assert_eq!(assignment.spilled(), 1);
1893        assert_eq!(assignment.slots(), [GPR]);
1894        // A register that is already a register is where it is, and this has nothing to say about
1895        // it.
1896        assert_eq!(assignment.place(Reg::physical(RCX)), None);
1897        assert_eq!(env().scratch(GPR), [R13, R14, R15]);
1898    }
1899
1900    /// Pieces of a value, from pairs of points.
1901    fn ranges(pairs: &[(Point, Point)]) -> Vec<Range> {
1902        pairs.iter().map(|&(start, end)| Range { start, end }).collect()
1903    }
1904
1905    #[test]
1906    fn the_pieces_of_a_register_answer_what_a_walk_over_its_values_would() {
1907        // Three values that take turns in one register, the first with a hole the third sits in.
1908        let held = [
1909            (Reg::virtual_reg(0), ranges(&[(0, 4), (20, 30)])),
1910            (Reg::virtual_reg(1), ranges(&[(5, 9)])),
1911            (Reg::virtual_reg(2), ranges(&[(10, 19), (31, 40)])),
1912        ];
1913        let mut pieces = Pieces::default();
1914        for (reg, list) in &held {
1915            for &piece in list {
1916                pieces.insert(piece, *reg);
1917            }
1918        }
1919        assert!(!pieces.broken);
1920        let asked = [
1921            ranges(&[(41, 50)]),
1922            ranges(&[(40, 50)]),
1923            ranges(&[(9, 9)]),
1924            ranges(&[(3, 3), (41, 42)]),
1925            ranges(&[(50, 60)]),
1926            ranges(&[(15, 15)]),
1927        ];
1928        for list in &asked {
1929            let area = Area::of_pieces(list);
1930            for except in [None, Some(Reg::virtual_reg(0)), Some(Reg::virtual_reg(2))] {
1931                let walked = held.iter().any(|(reg, pieces)| {
1932                    Some(*reg) != except && Area::of_pieces(pieces).overlaps(area)
1933                });
1934                assert_eq!(pieces.touch(area, except), walked, "{list:?} except {except:?}");
1935            }
1936        }
1937    }
1938
1939    #[test]
1940    fn the_owners_of_the_pieces_an_area_touches_are_the_values_a_walk_would_find() {
1941        let held = [
1942            (Reg::virtual_reg(0), ranges(&[(0, 4), (20, 30)])),
1943            (Reg::virtual_reg(1), ranges(&[(5, 9)])),
1944            (Reg::virtual_reg(2), ranges(&[(10, 19), (30, 40)])),
1945        ];
1946        let mut pieces = Pieces::default();
1947        for (reg, list) in &held {
1948            for &piece in list {
1949                pieces.insert(piece, *reg);
1950            }
1951        }
1952        let asked = [
1953            ranges(&[(41, 50)]),
1954            ranges(&[(30, 30)]),
1955            ranges(&[(3, 12)]),
1956            ranges(&[(3, 3), (25, 42)]),
1957            ranges(&[(0, 50)]),
1958        ];
1959        for list in &asked {
1960            let area = Area::of_pieces(list);
1961            let walked: Vec<Reg> = held
1962                .iter()
1963                .filter(|(_, pieces)| Area::of_pieces(pieces).overlaps(area))
1964                .map(|&(reg, _)| reg)
1965                .collect();
1966            assert_eq!(pieces.owners(area), Some(walked), "{list:?}");
1967        }
1968        pieces.insert(Range { start: 2, end: 3 }, Reg::virtual_reg(3));
1969        assert_eq!(pieces.owners(Area::of_pieces(&asked[0])), None);
1970    }
1971
1972    #[test]
1973    fn pieces_that_end_out_of_order_are_marked() {
1974        let mut pieces = Pieces::default();
1975        pieces.insert(Range { start: 0, end: 10 }, Reg::virtual_reg(0));
1976        pieces.insert(Range { start: 12, end: 20 }, Reg::virtual_reg(1));
1977        assert!(!pieces.broken);
1978        // Inside the first, which two values in one register never are.
1979        pieces.insert(Range { start: 2, end: 3 }, Reg::virtual_reg(2));
1980        assert!(pieces.broken);
1981    }
1982
1983    #[test]
1984    fn a_value_taken_out_of_a_register_leaves_its_pieces_with_it() {
1985        let mut pieces = Pieces::default();
1986        let (first, second) = (Reg::virtual_reg(0), Reg::virtual_reg(1));
1987        pieces.insert(Range { start: 0, end: 10 }, first);
1988        pieces.insert(Range { start: 12, end: 20 }, second);
1989        let asked = ranges(&[(15, 16)]);
1990        assert!(pieces.touch(Area::of_pieces(&asked), None));
1991        pieces.remove(Range { start: 12, end: 20 }, second);
1992        assert!(!pieces.touch(Area::of_pieces(&asked), None));
1993        pieces.drop_before(11);
1994        assert!(pieces.list.is_empty());
1995    }
1996}