Skip to main content

rucc_codegen/
wide.rs

1//! The integer that is wider than a register, as the two registers it is held in.
2//!
3//! `__int128` is the one integer a C program on this machine writes that no register holds.
4//! Everything else the front end produces is a width the machine has, or is a width
5//! [`crate::widths`] rounds up into one, and neither of those is true here: there is nothing to
6//! round up into above sixty four bits. What there is, is two registers, and the convention already
7//! says so. System V classifies a `__int128` as two eightbytes of class INTEGER, so it travels in a
8//! pair of general purpose registers, comes back in the pair a return comes back in, and sits in
9//! memory as two words with the low one first. That is what this pass writes down.
10//!
11//! Every value a hundred and twenty eight bits wide becomes two values of sixty four, a low half
12//! and a high half, and every instruction over such a value becomes instructions over the halves.
13//! After it there is no value of that width left anywhere in the function, which is what lets the
14//! rest of the back end stay written about widths the machine has. Nothing below this knows the
15//! type existed.
16//!
17//! # Why a pass and not a rule
18//!
19//! A rule matches a term and rewrites it into instructions of the machine, and the selector works a
20//! value at a time. There is no register a value this wide can be selected into, so there is
21//! nothing for a rule to produce, and a rule that produced a pair would have to say which register
22//! each half landed in, which is the allocator's answer and not a rule's. So the splitting happens
23//! before selection, in the IR, where a value is still something a pass may make two of. That is
24//! the same reasoning [`crate::widths`] follows from the other end, and the two are the two halves
25//! of one sentence: nothing reaching the selector is at a width the machine has no register for.
26//!
27//! # What crosses the boundary
28//!
29//! A parameter and a return value are agreed with something this compilation is not looking at, so
30//! splitting one is a claim about where the two halves are. The claim is true when both halves land
31//! in registers, because the convention hands out argument registers in order and two halves in a
32//! row take the two registers the whole value would have taken. It is not true when they do not: a
33//! value the convention could not fit in registers travels in the argument area as sixteen bytes
34//! aligned to sixteen and leaves the register it could not use to whatever comes after it, and two
35//! independent words in a row would put the first one in that register and the second a word up
36//! from wherever the area had got to.
37//!
38//! So a signature with such a parameter is laid out again rather than split in place. Where every
39//! parameter is meant to be is worked out first, and then the split signature is put in the order
40//! that makes the ordinary walk over it arrive at the same places: the ones in registers first,
41//! then the ones in the argument area by how far up it they are, with a filler that carries nothing
42//! wherever the convention leaves a register or a word empty. Both ends of a call are built from the
43//! same layout, a function's own parameters and every call it makes, so nothing below this has to
44//! know a parameter was ever in any other order, and the IR needs no form of parameter it did not
45//! have.
46//!
47//! A call to a variadic function is laid out the same way over everything it passes, the arguments
48//! past the `...` included, because System V puts each of those where it would have gone had it
49//! been named. What the ABI asks of each of them moves onto the parameter it becomes, so the call
50//! names all its arguments afterwards and still says the callee is variadic, which is what sets the
51//! count of vector registers the callee is told about. A variadic function's own signature with a
52//! wide named parameter that goes in memory is still refused, because its named parameters are what
53//! `va_start` counts from, and so is any of this on a convention that counts the two register files
54//! as one run, where a float past the `...` travels in both. The `va_arg` of one is read in
55//! `rucc-lower` as a pair of words, which is the walk [`crate::varargs`] already has for a small
56//! structure.
57//!
58//! # Dividing and converting are calls into the runtime
59//!
60//! Every other operation at this width is the same operation over the halves with whatever crossed
61//! between them put back. A quotient is not. The halves of a quotient are not a function of the
62//! halves of its operands taken apart, at this width or at any other, which is why every compiler's
63//! runtime has a division routine in it and none of them has an addition one. So a divide and a
64//! remainder become a call to the routines `runtime/builtins/div.c` defines, which are libgcc's four
65//! names and libgcc's signatures, and `spec/12-abi-and-runtime.md` section 12.8 is what they are.
66//!
67//! A conversion to or from a floating point value is the other one, for a plainer reason: the
68//! machine's own conversion reaches sixty four bits and no further, so there is no instruction to
69//! split into. Those are the eight names `runtime/builtins/convert.c` defines, one for each of a
70//! signed and an unsigned integer against a `float` and a `double` in each direction, and the four
71//! `runtime/builtins/quad.c` defines for a `_Float128`, which has no instruction of its own at any
72//! width and so is a call here for both reasons at once. An eighty bit float is not among them,
73//! because this machine has no register that holds one and the back end says so, which is
74//! tamnd/rucc#326, so a function converting at that width is left alone here and refused below the
75//! way every function of this width used to be.
76//!
77//! The call is asked for with the halves already in it, four parameters of sixty four bits for the
78//! two operands of a divide and two results for the answer, or two parameters and a float, or a
79//! float and two results, which is the shape this pass gives a call it found in the program anyway.
80//! Both ends agree because the convention puts a `__int128` argument in two registers in a row and
81//! hands out argument registers in order, which is the same sentence the section below about
82//! crossing the boundary is.
83//!
84//! That is the shape on every convention that has registers for a value this wide and it is not the
85//! shape on Windows x64, where such a value travels as the address of a copy the caller made and an
86//! integer this wide comes back whole in a vector register. The one place the two are told apart is
87//! where the call is built, by asking the ABI the same question a call in the program is asked, so
88//! everything above it goes on describing the call in halves and nothing above it names a target.
89
90use rucc_base::Interner;
91use rucc_base::hash::{Map, Set};
92use rucc_ir::{
93    Abi, Block, BlockCall, CallInfo, Def, Extra, Flags, Float, Func, Imm, Inst, InstData, IntPred,
94    MemInfo, MemOrder, Opcode, Param, Restrict, Signature, Type, Value,
95};
96use rucc_target::{AbiDescription, CallRegs, Convention, Places, Variadic, Where};
97
98use crate::capability;
99use crate::expand;
100
101/// The width this pass is about, which is the one width a C program writes that no register holds.
102const WIDE: u32 = 128;
103
104/// What the capability table calls that width, which is how the rule language spells one.
105const MODE: &str = "i128";
106
107/// The width each half is, which is a register on every target this pass runs for.
108const HALF: u32 = 64;
109
110/// How many bytes one half takes in memory, which is how far the high one sits above the low one.
111const STEP: u64 = 8;
112
113/// Whether a type is the width this pass splits.
114fn is_wide(ty: Type) -> bool {
115    ty.is_int() && ty.is_scalar() && ty.bits() == WIDE
116}
117
118/// The type each half has.
119fn half() -> Type {
120    Type::int(HALF)
121}
122
123/// Splits every integer the machine holds in two registers into the two halves it holds it in.
124///
125/// Gives back whether it changed anything, which is what a test asks and what tells a reader of a
126/// dump that the function the selector saw is not the one the middle end produced.
127///
128/// The function is left exactly as it was when there is nothing at that width, when something at
129/// that width is reached by an instruction this does not understand, and when a half would cross
130/// the function's boundary somewhere the convention has no register for it. All three leave the
131/// refusal to the passes below, which name the construct they could not lower, rather than
132/// rewriting into something that guessed.
133pub fn halves(func: &mut Func, names: &mut Interner, conv: &CallRegs) -> bool {
134    if !func.values().any(|value| is_wide(func[value].ty)) {
135        return false;
136    }
137    let insts: Vec<Inst> =
138        walk(func).into_iter().flat_map(|block| func.insts(block).collect::<Vec<_>>()).collect();
139    let order: Map<Inst, usize> = insts.iter().enumerate().map(|(at, &inst)| (inst, at)).collect();
140    if !insts.iter().enumerate().all(|(at, &inst)| can_split(func, conv, &order, at, inst)) {
141        return false;
142    }
143    let Some(arriving) = plan(func.signature(), conv) else { return false };
144    if !func.signatures().all(|signature| plan(signature, conv).is_some()) {
145        return false;
146    }
147
148    let mut halves: Halves = Map::default();
149    let mut forward: Map<Value, Value> = Map::default();
150    let entry = func.entry();
151    for block in func.blocks().collect::<Vec<_>>() {
152        if Some(block) == entry {
153            arrive(func, block, &arriving, &mut halves, &mut forward);
154        } else {
155            params(func, block, &mut halves, &mut forward);
156        }
157    }
158    for &inst in &insts {
159        rewrite(func, names, conv, &mut halves, &mut forward, inst);
160    }
161    substitute(func, &forward);
162    let signature = planned(func.signature(), &arriving);
163    func.set_signature(signature);
164    true
165}
166
167/// Every block, in an order where a block comes after everything that dominates it.
168///
169/// Reverse postorder from the entry, then whatever the walk did not reach, in the order the
170/// function holds them. The order is what the rule below about a use and its definition is read
171/// against, and the two together are the whole of why this is not simply the order the function
172/// holds the blocks in: a value is defined in a block that dominates every block reading it, a
173/// dominator is on every path from the entry, so a depth first walk finishes it last and reverse
174/// postorder puts it first. The order the function holds blocks in says nothing of the kind. It is
175/// the order they were made in, and every pass in the optimizer that makes a block, which is every
176/// pass that gives a loop a preheader or copies a header in front of one, puts a block that runs
177/// early at the end of that list. So the same program compiled at `-O0` and at `-O1` gave two
178/// different answers to whether this pass understood it, and above `-O0` the answer was often no.
179/// tamnd/rucc#1054.
180///
181/// A block nothing reaches cannot be walked to and is put at the end rather than dropped, because
182/// deciding a block is unreachable is not this pass's business. Two of them in the wrong order
183/// refuse the function the way they always did.
184fn walk(func: &Func) -> Vec<Block> {
185    let Some(entry) = func.entry() else { return func.blocks().collect() };
186    let mut seen: Set<Block> = Set::default();
187    let mut order: Vec<Block> = Vec::new();
188    // A postorder without recursion: the second time a block comes off the stack every block below
189    // it has been finished, so that is where it belongs in the postorder.
190    let mut stack: Vec<(Block, bool)> = vec![(entry, false)];
191    seen.insert(entry);
192    while let Some((block, done)) = stack.pop() {
193        if done {
194            order.push(block);
195            continue;
196        }
197        stack.push((block, true));
198        let Some(term) = func.terminator(block) else { continue };
199        for call in func.successors(term) {
200            if seen.insert(call.block) {
201                stack.push((call.block, false));
202            }
203        }
204    }
205    order.reverse();
206    order.extend(func.blocks().filter(|block| !seen.contains(block)));
207    order
208}
209
210/// The two halves each wide value became, low first.
211type Halves = Map<Value, (Value, Value)>;
212
213/// The opcodes this pass knows how to split.
214///
215/// An instruction that touches a value of this width and is not one of these is why the whole
216/// function is left alone, so this list is the pass's own statement of what it has thought about.
217/// Adding to it is adding an arm to [`rewrite`] as well.
218///
219/// The four divisions and the four conversions to and from a floating point value are here, and they
220/// are the entries that become a call rather than arithmetic over the halves. Which float formats
221/// those conversions are understood at is a separate question, asked in [`can_split`], because it is
222/// about the type rather than about the opcode.
223fn understood(opcode: Opcode) -> bool {
224    matches!(
225        opcode,
226        Opcode::IConst
227            | Opcode::Load
228            | Opcode::Store
229            | Opcode::Add
230            | Opcode::Sub
231            | Opcode::Mul
232            | Opcode::UDiv
233            | Opcode::SDiv
234            | Opcode::URem
235            | Opcode::SRem
236            | Opcode::Shl
237            | Opcode::LShr
238            | Opcode::AShr
239            | Opcode::And
240            | Opcode::Or
241            | Opcode::Xor
242            | Opcode::ICmp
243            | Opcode::Select
244            | Opcode::SIToFP
245            | Opcode::UIToFP
246            | Opcode::FPToSI
247            | Opcode::FPToUI
248            | Opcode::Trunc
249            | Opcode::SExt
250            | Opcode::ZExt
251            | Opcode::Call
252            | Opcode::CallIndirect
253            | Opcode::Return
254            | Opcode::Jump
255            | Opcode::BrIf
256    )
257}
258
259/// Whether one instruction is one this pass can split, given where it is in the walk.
260///
261/// Asked of every instruction, and answered yes at once for the ones that never see a value this
262/// wide, which in a function that has one at all is still most of them.
263fn can_split(
264    func: &Func,
265    conv: &CallRegs,
266    order: &Map<Inst, usize>,
267    at: usize,
268    inst: Inst,
269) -> bool {
270    let data = func[inst];
271    let reads = operands(func, inst);
272    let wide = |&value: &Value| is_wide(func[value].ty);
273    if !reads.iter().any(wide) && !data.results().any(|value| is_wide(func[value].ty)) {
274        return true;
275    }
276    if !understood(data.opcode) {
277        return false;
278    }
279    // Memory SSA threads a version of memory through each access, and splitting one access into two
280    // makes a version this pass would have to name. Nothing hands this crate a function carrying it
281    // today, and leaving one alone costs less than being wrong about it later.
282    if func.carries_mem(inst) {
283        return false;
284    }
285    // The machine sign extends from a byte and no narrower, so a truth value widened into the high
286    // half would become an instruction with no rule behind it. Zero extending one is fine, which is
287    // why only the signed side is asked about.
288    if data.opcode == Opcode::SExt && reads.iter().any(|&value| func[value].ty.bits() < 8) {
289        return false;
290    }
291    // The runtime has a conversion for a `float`, for a `double` and for a `_Float128`, and for
292    // nothing else, so every other format is refused here rather than turned into a call to a name
293    // nothing defines. An eighty bit float is the one a program reaches without asking for it, since
294    // `long double` is that type on this target, and it is tamnd/rucc#326 rather than an oversight.
295    if matches!(data.opcode, Opcode::SIToFP | Opcode::UIToFP | Opcode::FPToSI | Opcode::FPToUI)
296        && converted(func, inst).is_none()
297    {
298        return false;
299    }
300    // Splitting an argument makes two of them, and which parameter an argument stands for is how a
301    // variadic call knows what the ABI asks of the ones its signature does not name. So a variadic
302    // call is laid out as a whole, with the arguments past the `...` named as parameters, and that
303    // is only right where naming them changes nothing. On a convention that counts the two files as
304    // one run it does, because a float past the `...` goes in both files and one before it does
305    // not, and on Apple's AArch64 it does too, because everything past the `...` goes in memory.
306    if matches!(data.opcode, Opcode::Call | Opcode::CallIndirect) {
307        let Some((site, variadic)) = site(func, inst) else { return false };
308        let Some(conv) = conv.under(site.convention) else { return false };
309        let in_memory = conv.abi.variadic == Variadic::AlwaysMemory;
310        if variadic && (conv.shared_positions || in_memory || plan(&site, conv).is_none()) {
311            return false;
312        }
313    }
314    // The halves of a value are written where the value was, so a use this pass reaches before the
315    // definition is a use whose halves do not exist yet. A value arriving as a block parameter is
316    // always ready, since every block's parameters are split before any instruction is.
317    reads.iter().filter(|value| wide(value)).all(|&value| match func[value].def {
318        Def::Result { inst, .. } => order.get(&inst).is_some_and(|&def| def < at),
319        Def::Param { .. } => true,
320    })
321}
322
323/// The format of the floating point side of a conversion, when the runtime has a routine for it.
324///
325/// One float type is in such an instruction, the result of a conversion going up and the operand of
326/// one coming down, so both ends are looked at and the one is found. `None` means the function is
327/// left alone, and it covers a format with no routine, no float at all, and a float on both ends,
328/// which are three shapes that have nothing to be turned into rather than one.
329fn converted(func: &Func, inst: Inst) -> Option<Float> {
330    let data = func[inst];
331    let mut floats = func[data.args]
332        .iter()
333        .copied()
334        .chain(data.results())
335        .map(|value| func[value].ty)
336        .filter(|ty| ty.is_float());
337    let only = floats.next()?;
338    if floats.next().is_some() {
339        return None;
340    }
341    match only.format() {
342        Some(format @ (Float::F32 | Float::F64 | Float::F128)) => Some(format),
343        _ => None,
344    }
345}
346
347/// Everything an instruction reads: its own operands, and the arguments it passes along its edges.
348///
349/// The arguments of a `jump` and of a `br_if` hang on the block call rather than on the
350/// instruction, so an instruction whose own operands are all narrow may still be handing a wide one
351/// to the block it branches to.
352fn operands(func: &Func, inst: Inst) -> Vec<Value> {
353    let mut reads = func[func[inst].args].to_vec();
354    for call in func.successors(inst).collect::<Vec<_>>() {
355        reads.extend_from_slice(&func[call.args]);
356    }
357    reads
358}
359
360/// What one parameter of a split signature is.
361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
362enum Slot {
363    /// The parameter at that index of the whole signature, which is not wide, as it was.
364    Whole(usize),
365    /// The low half of the wide parameter at that index.
366    Low(usize),
367    /// The high half of it.
368    High(usize),
369    /// A value of that type that carries nothing and is there to take a place nothing else takes.
370    Filler(Type),
371}
372
373/// The parameters of one signature once every wide one is two halves, in the order that puts each
374/// of them where the convention puts the whole signature.
375///
376/// The walk is the one [`crate::abi::entry`] and [`crate::abi::call`] make, because the answer has
377/// to be the one that walk will give: it hands out places in the order the signature holds the
378/// parameters. When both halves of every wide parameter land in registers, two halves in a row in
379/// the place of the whole take the two registers the whole value would have taken, and the order
380/// is the order the signature had.
381///
382/// When one does not, System V puts the whole value in the argument area as sixteen bytes aligned
383/// to sixteen and leaves the registers it did not take to the parameters after it. Two words in a
384/// row go somewhere else: the first takes whatever register is left, and a word only has to be
385/// aligned to eight. So the order is built from where everything is meant to be rather than from
386/// the signature. The ones in general purpose registers come first in register order, then the
387/// ones in vector registers, then the ones in the argument area by how far up it they are. A filler
388/// takes a register a wide value skipped, since a word of the argument area is only handed out once
389/// the registers of its kind have run out, and a filler takes each word the alignment of a wide
390/// value leaves empty. The walk is made again over what was built, and anything that did not land
391/// where it was meant to is `None`, as is a variadic signature, whose named parameters have to stay
392/// in front of the rest, and a convention that counts the two register files as one run, which
393/// passes a value this wide some other way.
394///
395/// A return value is not asked about. What comes back comes back in the registers a return uses,
396/// which is a sequence of its own with two in it on this convention, and a signature wanting more
397/// than it has is refused by name in [`crate::lower`] already.
398///
399/// `conv` is the convention of the function being split, and the signature is laid out under the
400/// convention it names itself, found through it: a function of one convention calls functions of
401/// the other, and each call is laid out the way its callee reads it. A convention the platform
402/// does not have is no layout at all, and the function is left alone.
403fn plan(signature: &Signature, conv: &CallRegs) -> Option<Vec<Slot>> {
404    let conv = conv.under(signature.convention)?;
405    let word = Param::new(half());
406    let mut places = Places::new(conv);
407    let mut meant: Vec<(Slot, Param, Where)> = Vec::new();
408    let mut moved = false;
409    for (index, &param) in signature.params.iter().enumerate() {
410        if !is_wide(param.ty) {
411            meant.push((Slot::Whole(index), param, place(&mut places, param, conv)));
412            continue;
413        }
414        let scalars = conv.abi.scalars;
415        let mut ahead = places.clone();
416        // AAPCS64 starts the pair at an even register, and a filler takes the odd one it skips.
417        let skipped = (scalars.wide_integer_starts_even && ahead.integers() % 2 == 1)
418            .then(|| ahead.integer(HALF / 8));
419        if let (low @ Where::Reg(_), high @ Where::Reg(_)) =
420            (ahead.integer(HALF / 8), ahead.integer(HALF / 8))
421        {
422            places = ahead;
423            if let Some(at) = skipped {
424                meant.push((Slot::Filler(word.ty), word, at));
425            }
426            meant.push((Slot::Low(index), word, low));
427            meant.push((Slot::High(index), word, high));
428            continue;
429        }
430        if scalars.wide_integer_drains {
431            places.drain_integers();
432        }
433        let Where::Stack(at) = places.on_stack(WIDE / 8, WIDE / 8) else { return None };
434        meant.push((Slot::Low(index), word, Where::Stack(at)));
435        meant.push((Slot::High(index), word, Where::Stack(at + HALF / 8)));
436        moved = true;
437    }
438    if !moved {
439        return Some(meant.into_iter().map(|(slot, _, _)| slot).collect());
440    }
441    if signature.variadic || conv.shared_positions {
442        return None;
443    }
444
445    let in_reg = |at: &Where| matches!(at, Where::Reg(_));
446    let mut stacked: Vec<&(Slot, Param, Where)> =
447        meant.iter().filter(|(_, _, at)| !in_reg(at)).collect();
448    stacked.sort_by_key(|(_, _, at)| match at {
449        Where::Stack(up) => *up,
450        Where::Reg(_) => 0,
451    });
452    let mut order: Vec<(Slot, Param, Option<Where>)> = Vec::new();
453    for float in [false, true] {
454        let kind = |param: &Param| scalar(*param) && param.ty.is_float() == float;
455        order.extend(
456            meant
457                .iter()
458                .filter(|(_, param, at)| kind(param) && in_reg(at))
459                .map(|&(slot, param, at)| (slot, param, Some(at))),
460        );
461        let (count, filler) = match float {
462            false => (conv.int_args.len(), word),
463            true => (conv.sse_args.len(), Param::new(Type::float(Float::F64))),
464        };
465        if stacked.iter().any(|(_, param, _)| kind(param)) {
466            let took = order.iter().filter(|(_, param, _)| kind(param)).count();
467            let padding = count.saturating_sub(took);
468            order.extend((0..padding).map(|_| (Slot::Filler(filler.ty), filler, None)));
469        }
470    }
471
472    let mut places = Places::new(conv);
473    let mut slots = Vec::with_capacity(order.len() + stacked.len());
474    for (slot, param, meant) in order {
475        let at = place(&mut places, param, conv);
476        if !in_reg(&at) || meant.is_some_and(|meant| meant != at) {
477            return None;
478        }
479        slots.push(slot);
480    }
481    for &&(slot, param, meant) in &stacked {
482        let Where::Stack(up) = meant else { return None };
483        while places.size() < up {
484            if in_reg(&place(&mut places, word, conv)) {
485                return None;
486            }
487            slots.push(Slot::Filler(word.ty));
488        }
489        if place(&mut places, param, conv) != meant {
490            return None;
491        }
492        slots.push(slot);
493    }
494    Some(slots)
495}
496
497/// Where the next parameter goes, asked the way [`crate::abi::entry`] asks.
498fn place(places: &mut Places<'_>, param: Param, conv: &CallRegs) -> Where {
499    // A structure the classification put in the argument area, which is the one parameter whose
500    // place is bytes rather than a register. Everything else is a value, the pointer an `sret`
501    // hands over included, and a value takes the next register of its own kind.
502    if let Abi::ByVal { size, align, drains } = param.abi {
503        let at = places.object(u32::try_from(size).unwrap_or(u32::MAX), align);
504        crate::abi::drain(places, drains);
505        at
506    } else if crate::abi::on_the_stack(param.ty) {
507        let (size, align) = crate::abi::X87_AREA;
508        places.on_stack(size, align)
509    } else if param.ty.is_float() {
510        places.float(crate::abi::float_bytes(param.ty))
511    } else {
512        places.integer(crate::abi::int_bytes(param.ty, conv))
513    }
514}
515
516/// Whether a parameter is a value that takes a register of its kind while there is one left.
517fn scalar(param: Param) -> bool {
518    !matches!(param.abi, Abi::ByVal { .. }) && !crate::abi::on_the_stack(param.ty)
519}
520
521/// A signature laid out the way [`plan`] said, with every wide return value as two halves.
522fn planned(signature: &Signature, slots: &[Slot]) -> Signature {
523    let params = slots
524        .iter()
525        .map(|&slot| match slot {
526            Slot::Whole(index) => signature.params[index],
527            Slot::Low(_) | Slot::High(_) => Param::new(half()),
528            Slot::Filler(ty) => Param::new(ty),
529        })
530        .collect();
531    Signature { params, ..split_signature(signature) }
532}
533
534/// One block's parameters, with each wide one replaced by its two halves in the same position.
535///
536/// Every parameter of such a block is made again rather than only the wide ones, because a
537/// parameter's position is its identity to the branches that feed it and appending is the only way
538/// to add one. The narrow ones are made again as themselves and pointed at the copy, which costs
539/// nothing once the substitution below has run.
540fn params(func: &mut Func, block: Block, halves: &mut Halves, forward: &mut Map<Value, Value>) {
541    let old: Vec<Value> = func[block].params.clone();
542    if !old.iter().any(|&value| is_wide(func[value].ty)) {
543        return;
544    }
545    for &value in &old {
546        if is_wide(func[value].ty) {
547            let low = func.append_param(block, half());
548            let high = func.append_param(block, half());
549            halves.insert(value, (low, high));
550        } else {
551            let again = func.append_param(block, func[value].ty);
552            forward.insert(value, again);
553        }
554    }
555    func.retain_params(block, |value| !old.contains(&value));
556}
557
558/// The entry block's parameters, laid out the way [`plan`] said the function's own are.
559fn arrive(
560    func: &mut Func,
561    block: Block,
562    slots: &[Slot],
563    halves: &mut Halves,
564    forward: &mut Map<Value, Value>,
565) {
566    let old: Vec<Value> = func[block].params.clone();
567    if !old.iter().any(|&value| is_wide(func[value].ty)) {
568        return;
569    }
570    let mut lows = Map::default();
571    for &slot in slots {
572        match slot {
573            Slot::Whole(index) => {
574                let again = func.append_param(block, func[old[index]].ty);
575                forward.insert(old[index], again);
576            }
577            Slot::Low(index) => {
578                lows.insert(index, func.append_param(block, half()));
579            }
580            Slot::High(index) => {
581                let high = func.append_param(block, half());
582                halves.insert(old[index], (lows[&index], high));
583            }
584            Slot::Filler(ty) => {
585                func.append_param(block, ty);
586            }
587        }
588    }
589    func.retain_params(block, |value| !old.contains(&value));
590}
591
592/// One instruction, as instructions over halves.
593fn rewrite(
594    func: &mut Func,
595    names: &mut Interner,
596    conv: &CallRegs,
597    halves: &mut Halves,
598    forward: &mut Map<Value, Value>,
599    inst: Inst,
600) {
601    // The runtime's routines are ordinary functions of the platform, whatever convention the
602    // function calling them was written in, so a call to one is shaped by the platform's own.
603    let abi = conv.under(Convention::Target).unwrap_or(conv).abi;
604    let data = func[inst];
605    let produces = data.results().any(|value| is_wide(func[value].ty));
606    let takes = func[data.args].iter().any(|&value| is_wide(func[value].ty));
607    match data.opcode {
608        Opcode::IConst if produces => constant(func, halves, inst),
609        Opcode::Load if produces => load(func, halves, inst),
610        Opcode::Store if takes => store(func, halves, inst),
611        Opcode::Add | Opcode::Sub if produces => carried(func, halves, inst, data.opcode),
612        Opcode::Mul if produces => multiply(func, halves, inst),
613        Opcode::UDiv | Opcode::SDiv | Opcode::URem | Opcode::SRem if produces => {
614            divide(func, names, abi, halves, inst, data.opcode);
615        }
616        Opcode::Shl | Opcode::LShr | Opcode::AShr if produces => {
617            shifted(func, halves, inst, data.opcode);
618        }
619        Opcode::And | Opcode::Or | Opcode::Xor if produces => {
620            bitwise(func, halves, inst, data.opcode);
621        }
622        Opcode::SIToFP | Opcode::UIToFP if takes => {
623            to_float(func, names, abi, halves, forward, inst, data.opcode == Opcode::SIToFP);
624        }
625        Opcode::FPToSI | Opcode::FPToUI if produces => {
626            from_float(func, names, abi, halves, inst, data.opcode == Opcode::FPToSI);
627        }
628        Opcode::ICmp if takes => compare(func, halves, forward, inst),
629        Opcode::Select if produces => choose(func, halves, inst),
630        Opcode::Trunc if takes => truncate(func, halves, forward, inst),
631        Opcode::SExt | Opcode::ZExt if produces => {
632            extend(func, halves, inst, data.opcode == Opcode::SExt);
633        }
634        Opcode::Call | Opcode::CallIndirect if produces || takes => {
635            call(func, conv, halves, forward, inst);
636        }
637        Opcode::Return if takes => flatten(func, halves, inst),
638        Opcode::Jump | Opcode::BrIf => edges(func, halves, inst),
639        _ => {}
640    }
641}
642
643/// A constant, as the two halves of its bits with the low one first.
644fn constant(func: &mut Func, halves: &mut Halves, inst: Inst) {
645    let Extra::Imm(imm) = func[inst].extra else { return };
646    let bits = func[imm].unsigned();
647    #[expect(clippy::cast_possible_truncation, reason = "the halves are what this is taking")]
648    let (low, high) = (bits as u64, (bits >> HALF) as u64);
649    let low = ahead_const(func, inst, i128::from(low));
650    let high = ahead_const(func, inst, i128::from(high));
651    replace(func, halves, inst, low, high);
652}
653
654/// A read, as the two words of it with the low one first.
655///
656/// Little endian is the order, which is what every target this back end has is. The high word knows
657/// less about its alignment than the low one when the low one knew more than a word, since a
658/// sixteen byte object aligned to sixteen has its high word aligned to eight.
659fn load(func: &mut Func, halves: &mut Halves, inst: Inst) {
660    let data = func[inst];
661    let Extra::Mem(mem) = data.extra else { return };
662    let info = func[mem];
663    let Some(&from) = func[data.args].first() else { return };
664    let low = read(func, inst, from, word(info, 0), data.flags);
665    let up = stepped(func, inst, from);
666    let high = read(func, inst, up, word(info, STEP), data.flags);
667    replace(func, halves, inst, low, high);
668}
669
670/// A write, as the two words of it.
671fn store(func: &mut Func, halves: &mut Halves, inst: Inst) {
672    let data = func[inst];
673    let Extra::Mem(mem) = data.extra else { return };
674    let info = func[mem];
675    let args = func[data.args].to_vec();
676    let [value, into] = args[..] else { return };
677    let Some(&(low, high)) = halves.get(&value) else { return };
678    write(func, inst, low, into, word(info, 0), data.flags);
679    let up = stepped(func, inst, into);
680    write(func, inst, high, up, word(info, STEP), data.flags);
681    func.remove_inst(inst);
682}
683
684/// An add or a subtract, as the same over the low halves and the same again over the high ones with
685/// what the low halves carried between them.
686///
687/// The carry is a comparison and not a flag. An unsigned sum comes out below either operand exactly
688/// when it wrapped, and an unsigned difference wrapped exactly when the left operand was below the
689/// right, which are the two tests [`crate::expand`] writes for the overflow builtins and are what
690/// the machine's own carry flag stands for. Whether the pair is put back together into an `adc` and
691/// an `sbb` is a question for what reads flags rather than for this, and the answer here is correct
692/// either way.
693fn carried(func: &mut Func, halves: &mut Halves, inst: Inst, opcode: Opcode) {
694    let args = func[func[inst].args].to_vec();
695    let [a, b] = args[..] else { return };
696    let (Some(&(a_low, a_high)), Some(&(b_low, b_high))) = (halves.get(&a), halves.get(&b)) else {
697        return;
698    };
699    let low = ahead(func, inst, opcode, &[a_low, b_low]);
700    let carried = if opcode == Opcode::Add {
701        compared(func, inst, IntPred::Ult, low, a_low)
702    } else {
703        compared(func, inst, IntPred::Ult, a_low, b_low)
704    };
705    let carry = ahead(func, inst, Opcode::ZExt, &[carried]);
706    let high = ahead(func, inst, opcode, &[a_high, b_high]);
707    let high = ahead(func, inst, opcode, &[high, carry]);
708    replace(func, halves, inst, low, high);
709}
710
711/// A multiply, which is long multiplication in base two to the sixty fourth with everything that
712/// lands above the width thrown away.
713///
714/// The low half of the answer is the low halves multiplied together. The high half is what that
715/// multiply carried out of its own top, plus the two cross products, each of which starts at bit
716/// sixty four. The fourth partial product is the two high halves against each other and it starts
717/// at bit one hundred and twenty eight, so the whole of it is above the width and it is never
718/// worked out, which is why a wide multiply is three multiplies and not four.
719///
720/// Nothing here asks whether the operands are signed, because the low hundred and twenty eight bits
721/// of a product are the same bits either way. The sign only matters to the bits that are being
722/// thrown away.
723///
724/// The carry out of the low halves is the high half of a sixty four bit product, which this machine
725/// has an instruction for and this compiler has no way to ask for. [`crate::expand`] already writes
726/// that out as long multiplication one level further down, for the overflow builtins, so this calls
727/// it rather than keeping a second copy of the same arithmetic. It is the expensive part of a wide
728/// multiply by a long way, and `tamnd/rucc#309` is the rule that would make it one instruction for
729/// both callers at once.
730fn multiply(func: &mut Func, halves: &mut Halves, inst: Inst) {
731    let args = func[func[inst].args].to_vec();
732    let [a, b] = args[..] else { return };
733    let (Some(&(a_low, a_high)), Some(&(b_low, b_high))) = (halves.get(&a), halves.get(&b)) else {
734        return;
735    };
736    let low = ahead(func, inst, Opcode::Mul, &[a_low, b_low]);
737    let carried = expand::high_half(func, inst, a_low, b_low, false, half());
738    let cross = ahead(func, inst, Opcode::Mul, &[a_low, b_high]);
739    let other = ahead(func, inst, Opcode::Mul, &[a_high, b_low]);
740    let high = ahead(func, inst, Opcode::Add, &[carried, cross]);
741    let high = ahead(func, inst, Opcode::Add, &[high, other]);
742    replace(func, halves, inst, low, high);
743}
744
745/// A divide or a remainder, as a call to the routine in the compiler runtime that works it out.
746///
747/// The four names are libgcc's, and the archive `runtime/builtins/div.c` builds into defines them for
748/// a target that has no libgcc, which is every target this compiler links without gcc's driver. What
749/// picks one of the four is the opcode and nothing else: the sign is in the name because it is in the
750/// answer, since a quotient rounds towards zero and a remainder takes the sign of the dividend, and
751/// neither is the unsigned answer with bits reinterpreted the way a sum is.
752///
753/// The call is created with the halves in it rather than with the wide values, which would then be
754/// split by [`call`] on the next instruction of the walk. Four parameters and two results, in the
755/// order the operands were in and low half first, because that is where the convention puts the two
756/// eightbytes of a value this wide and [`split_signature`] is what the routine's own definition went
757/// through on the way in.
758///
759/// Nothing here is conditional on the divisor. Dividing by zero is undefined in C, the machine traps
760/// on it at every width it has, and a test written in front of the call would be this pass deciding
761/// what an undefined program does.
762fn divide(
763    func: &mut Func,
764    names: &mut Interner,
765    abi: &'static AbiDescription,
766    halves: &mut Halves,
767    inst: Inst,
768    opcode: Opcode,
769) {
770    let args = func[func[inst].args].to_vec();
771    let [a, b] = args[..] else { return };
772    let (Some(&(a_low, a_high)), Some(&(b_low, b_high))) = (halves.get(&a), halves.get(&b)) else {
773        return;
774    };
775    // The four that need the whole value at once, which is why they are calls rather than a pair
776    // of half width instructions like everything else in this pass. Which call each one is, is in
777    // the capability table, since a routine name is a fact about what this target cannot do.
778    let Some(routine) = capability::libcall(opcode, MODE) else { return };
779    let args = [Operand::Split(a_low, a_high), Operand::Split(b_low, b_high)];
780    let made = runtime(func, names, abi, inst, routine, &args, &[half(), half()]);
781    let [low, high] = made[..] else { return };
782    replace(func, halves, inst, low, high);
783}
784
785/// A conversion from one of these to a float, as a call to the routine that works it out.
786///
787/// Two parameters of sixty four bits and one float result. The answer is not a wide value, so the
788/// instruction's own result is pointed at the call's rather than halved, which is what [`compare`]
789/// and [`truncate`] do with a narrow answer as well.
790///
791/// The sign is in the name because it is in the answer: the same hundred and twenty eight bits are
792/// two different numbers depending on it, and unlike a sum the float they become is two different
793/// floats.
794fn to_float(
795    func: &mut Func,
796    names: &mut Interner,
797    abi: &'static AbiDescription,
798    halves: &Halves,
799    forward: &mut Map<Value, Value>,
800    inst: Inst,
801    signed: bool,
802) {
803    let Some(&arg) = func[func[inst].args].first() else { return };
804    let Some(&(low, high)) = halves.get(&arg) else { return };
805    let (Some(result), Some(format)) = (func[inst].first_result, converted(func, inst)) else {
806        return;
807    };
808    let routine = going_up(signed, format);
809    let args = [Operand::Split(low, high)];
810    let made = runtime(func, names, abi, inst, routine, &args, &[func[result].ty]);
811    if let [answer] = made[..] {
812        forward.insert(result, answer);
813    }
814    func.remove_inst(inst);
815}
816
817/// A conversion from a float to one of these, as a call to the routine that works it out.
818///
819/// One float parameter and two results of sixty four bits, which is the divide's shape with the
820/// operands and the answer the other way round. The operand is a float and so was never split, and
821/// it is passed along as it is.
822///
823/// A value the integer cannot hold, an infinity and a not a number are all undefined in C, and
824/// nothing is written in front of the call about any of them, for the reason [`divide`] writes
825/// nothing in front of itself about a zero divisor.
826fn from_float(
827    func: &mut Func,
828    names: &mut Interner,
829    abi: &'static AbiDescription,
830    halves: &mut Halves,
831    inst: Inst,
832    signed: bool,
833) {
834    let Some(&arg) = func[func[inst].args].first() else { return };
835    let Some(format) = converted(func, inst) else { return };
836    let routine = coming_down(signed, format);
837    let args = [Operand::Whole(arg)];
838    let made = runtime(func, names, abi, inst, routine, &args, &[half(), half()]);
839    let [low, high] = made[..] else { return };
840    replace(func, halves, inst, low, high);
841}
842
843/// The routine that turns an integer this wide into a float of that format.
844///
845/// Three formats, since [`converted`] answers with no others, and the quad is the last arm rather
846/// than a named one so that a format added to that list arrives here as a routine that does not
847/// exist rather than as a name that is wrong.
848fn going_up(signed: bool, format: Float) -> &'static str {
849    let mode = match format {
850        Float::F32 => "i128.f32",
851        Float::F64 => "i128.f64",
852        _ => "i128.f128",
853    };
854    routine(if signed { Opcode::SIToFP } else { Opcode::UIToFP }, mode)
855}
856
857/// The routine that turns a float of that format into an integer this wide.
858fn coming_down(signed: bool, format: Float) -> &'static str {
859    let mode = match format {
860        Float::F32 => "f32.i128",
861        Float::F64 => "f64.i128",
862        _ => "f128.i128",
863    };
864    routine(if signed { Opcode::FPToSI } else { Opcode::FPToUI }, mode)
865}
866
867/// The routine the capability table names for this operation at this width.
868///
869/// Every mode this pass asks about is one this machine has no register wide enough for, so the
870/// table always has an answer and a missing one is the table and this pass having gone out of step.
871fn routine(opcode: Opcode, mode: &str) -> &'static str {
872    capability::libcall(opcode, mode)
873        .unwrap_or_else(|| panic!("no routine for `{}` at `{mode}`", opcode.name()))
874}
875
876/// One operand of a call to a runtime routine, as this pass has it in hand.
877///
878/// A wide integer is two halves here because two halves is what this pass has turned every one of
879/// them into, and whether the routine is handed the two of them or the address of the one value
880/// they are is the convention's answer rather than this pass's.
881#[derive(Clone, Copy)]
882enum Operand {
883    /// A value of a type the machine holds, given as itself.
884    Whole(Value),
885    /// A wide integer, given as the low half and the high half it became.
886    Split(Value, Value),
887}
888
889/// A call to a routine in the compiler runtime, written in front of an instruction, with the values
890/// it answers.
891///
892/// Where the convention hands everything over in registers the signature is made out of the types
893/// of the values being handed over, because the values are already the halves at this point and the
894/// routine's own definition went through [`split_signature`] on the way in, so the two descriptions
895/// are the same one arrived at from the two ends.
896///
897/// Windows x64 does not hand a value of this width over in registers. A scalar of a size no register
898/// holds travels as the address of a copy the caller made, which is the rule `tamnd/rucc#1331` put
899/// in the ABI description, and it applies to a call this pass writes exactly as it applies to a call
900/// the program wrote: libgcc's `__floattitf` on that target reads its `__int128` out of the address
901/// in `rdx` and writes its answer through the address in `rcx`. So an operand the convention passes
902/// by address becomes a frame slot with a copy of the value in it, a slot per operand because a
903/// routine may write through an address it was handed, and a single answer that comes back by
904/// address becomes a slot passed as the leading `sret` argument with the load out of it standing for
905/// the call's result.
906///
907/// An answer at this width is the third shape and the one that reads strangely. mingw brings a
908/// sixteen byte integer back in `xmm0` rather than through an address, which is gcc's answer to a
909/// convention that has no integer that size in it, so the call is written as returning one value at
910/// the quad float format and the two halves are read back out of a slot it is stored into. The
911/// format is a name for sixteen bytes in a vector register and says nothing about what is in them,
912/// which is the same thing the routine's own `movaps` says.
913fn runtime(
914    func: &mut Func,
915    names: &mut Interner,
916    abi: &'static AbiDescription,
917    inst: Inst,
918    routine: &str,
919    args: &[Operand],
920    results: &[Type],
921) -> Vec<Value> {
922    let mut params: Vec<Param> = Vec::new();
923    let mut values: Vec<Value> = Vec::new();
924    let mut answer = Answer::Registers;
925    // The answer first, because an address it comes back through is the first argument.
926    match *results {
927        [ty] if abi.scalar_is_by_reference(bytes(ty)) => {
928            let size = bytes(ty);
929            let align = align(size);
930            let slot = room(func, inst, size, align);
931            params.push(Param::with_abi(Type::PTR, Abi::Sret { size, align }));
932            values.push(slot);
933            answer = Answer::Slot(slot, ty);
934        }
935        [low, high] if low == half() && high == half() => {
936            if let Some(format) = packed(abi) {
937                answer = Answer::Packed(format);
938            }
939        }
940        _ => {}
941    }
942    for &arg in args {
943        handed(func, abi, inst, arg, &mut params, &mut values);
944    }
945    let answers = match answer {
946        Answer::Registers => results.to_vec(),
947        Answer::Slot(..) => Vec::new(),
948        Answer::Packed(format) => vec![Type::float(format)],
949    };
950    let returns = answers.iter().map(|&ty| Param::new(ty)).collect();
951    // The platform's own convention, as the routine is an ordinary function of the platform.
952    let signature = func.add_signature(Signature { params, returns, ..Signature::new() });
953    let callee = Some(names.intern(routine));
954    let varargs = func.push_abis(&[]);
955    let extra = Extra::Call(func.add_call(CallInfo { callee, signature, varargs }));
956    let pushed = func.push_values(&values);
957    let span = func.span(inst);
958    let data = InstData { args: pushed, extra, ..InstData::new(Opcode::Call) };
959    let made = func.create_inst(data, &answers, span);
960    func.insert_before(made, inst);
961    match answer {
962        Answer::Registers => func[made].results().collect(),
963        Answer::Slot(slot, ty) => {
964            let size = bytes(ty);
965            let info = whole(size, align(size));
966            let extra = Extra::Mem(func.add_mem(info));
967            let args = func.push_values(&[slot]);
968            let data = InstData { args, extra, ..InstData::new(Opcode::Load) };
969            vec![written(func, inst, data, ty)]
970        }
971        Answer::Packed(format) => unpacked(func, inst, made, format),
972    }
973}
974
975/// Where the answer of such a call is, once the convention has been asked about it.
976#[derive(Clone, Copy)]
977enum Answer {
978    /// In the registers the signature's own result types name, which is every convention that has
979    /// registers for a value of the width being asked about.
980    Registers,
981    /// In a frame slot whose address went over as the leading `sret` argument, with the type the
982    /// call was meant to answer with.
983    Slot(Value, Type),
984    /// Whole in a vector register, at a format that is this many bytes and is not what is in them.
985    Packed(Float),
986}
987
988/// The format a wide integer answer comes back in on this convention, where it comes back in a
989/// register at all, as the IR spells a format.
990///
991/// [`None`] everywhere but Windows x64. The question is asked of the ABI rather than of the target
992/// name for the reason the rest of this pass asks it there: a second list of which targets do this
993/// is a list that can disagree with the one the classifier reads.
994fn packed(abi: &'static AbiDescription) -> Option<Float> {
995    let format = abi.wide_integer_returns_in(u64::from(WIDE / 8))?;
996    Float::from_bits(format.width())
997}
998
999/// The two halves of an answer that came back whole in a register, read out of a slot it is stored
1000/// into.
1001///
1002/// A store and two loads rather than anything cleverer because the value in hand is at a float
1003/// format and the halves wanted are integers, and the frame is the only place this compiler moves
1004/// bits between the two files without saying something about them. It is what gcc writes for the
1005/// same call.
1006fn unpacked(func: &mut Func, inst: Inst, call: Inst, format: Float) -> Vec<Value> {
1007    let Some(value) = func[call].first_result else { return Vec::new() };
1008    let size = bytes(Type::float(format));
1009    let align = align(size);
1010    let slot = room(func, inst, size, align);
1011    let info = whole(size, align);
1012    write(func, inst, value, slot, info, Flags::NONE);
1013    let low = read(func, inst, slot, word(info, 0), Flags::NONE);
1014    let up = stepped(func, inst, slot);
1015    let high = read(func, inst, up, word(info, STEP), Flags::NONE);
1016    vec![low, high]
1017}
1018
1019/// One operand of such a call, in the form the convention hands it over in.
1020fn handed(
1021    func: &mut Func,
1022    abi: &'static AbiDescription,
1023    inst: Inst,
1024    arg: Operand,
1025    params: &mut Vec<Param>,
1026    values: &mut Vec<Value>,
1027) {
1028    match arg {
1029        Operand::Whole(value) => {
1030            let ty = func[value].ty;
1031            let size = bytes(ty);
1032            if !abi.scalar_is_by_reference(size) {
1033                params.push(Param::new(ty));
1034                values.push(value);
1035                return;
1036            }
1037            let align = align(size);
1038            let slot = room(func, inst, size, align);
1039            write(func, inst, value, slot, whole(size, align), Flags::NONE);
1040            params.push(Param::new(Type::PTR));
1041            values.push(slot);
1042        }
1043        Operand::Split(low, high) => {
1044            let size = u64::from(WIDE / 8);
1045            if !abi.scalar_is_by_reference(size) {
1046                params.push(Param::new(half()));
1047                values.push(low);
1048                params.push(Param::new(half()));
1049                values.push(high);
1050                return;
1051            }
1052            let align = align(size);
1053            let slot = room(func, inst, size, align);
1054            let info = whole(size, align);
1055            write(func, inst, low, slot, word(info, 0), Flags::NONE);
1056            let up = stepped(func, inst, slot);
1057            write(func, inst, high, up, word(info, STEP), Flags::NONE);
1058            params.push(Param::new(Type::PTR));
1059            values.push(slot);
1060        }
1061    }
1062}
1063
1064/// How many bytes a value of this type takes.
1065fn bytes(ty: Type) -> u64 {
1066    u64::from(ty.bits().div_ceil(8))
1067}
1068
1069/// How far a value of that size is aligned, which at these sizes is the size itself.
1070fn align(size: u64) -> u32 {
1071    u32::try_from(size).unwrap_or(u32::MAX)
1072}
1073
1074/// An ordinary access of the whole of one value of that size.
1075fn whole(size: u64, align: u32) -> MemInfo {
1076    MemInfo {
1077        size,
1078        align,
1079        order: MemOrder::NotAtomic,
1080        tbaa: None,
1081        owns: 0,
1082        restrict: Restrict::NONE,
1083    }
1084}
1085
1086/// A frame slot of that size, written in front of an instruction.
1087fn room(func: &mut Func, inst: Inst, size: u64, align: u32) -> Value {
1088    let extra = Extra::Mem(func.add_mem(whole(size, align)));
1089    written(func, inst, InstData { extra, ..InstData::new(Opcode::Alloca) }, Type::PTR)
1090}
1091
1092/// A shift, as each half shifted by the count with the bits that crossed between them put back, and
1093/// a second answer for a count that reached a whole half.
1094///
1095/// A count below sixty four moves each half by the count, and the bits that left one half are the
1096/// ones that arrive in the other. A count of sixty four or more empties one half completely, and
1097/// what lands in the other is the first half moved by the count less sixty four. Taking the sixty
1098/// four bit off a count in range is the same as subtracting sixty four from it, so both cases shift
1099/// by the same number of places and differ only in which value ends up where, which means one shift
1100/// each and a choice rather than two of everything. The choice is a `select` and not a branch, for
1101/// the reason [`choose`] gives.
1102///
1103/// The bits that cross move the other way by sixty four less the count. That is a shift of sixty
1104/// four places when the count is zero, which is not a distance this width has. Moving one place and
1105/// then sixty three less the count is the same distance for every count from one to sixty three,
1106/// and for a count of zero it shifts a value whose top bit is already gone all the way down to
1107/// nothing, which is the right answer: a half that did not move carries nothing into the other one.
1108///
1109/// A count of a hundred and twenty eight or more is undefined in C and nothing here goes out of its
1110/// way about it, the same as at every other width.
1111fn shifted(func: &mut Func, halves: &mut Halves, inst: Inst, opcode: Opcode) {
1112    let args = func[func[inst].args].to_vec();
1113    let [a, b] = args[..] else { return };
1114    let (Some(&(a_low, a_high)), Some(&(count, _))) = (halves.get(&a), halves.get(&b)) else {
1115        return;
1116    };
1117    let top = ahead_const(func, inst, i128::from(HALF - 1));
1118    let places = ahead(func, inst, Opcode::And, &[count, top]);
1119    let back = ahead(func, inst, Opcode::Sub, &[top, places]);
1120    let one = ahead_const(func, inst, 1);
1121    let zero = ahead_const(func, inst, 0);
1122    let bit = ahead_const(func, inst, i128::from(HALF));
1123    let reach = ahead(func, inst, Opcode::And, &[count, bit]);
1124    let whole = compared(func, inst, IntPred::Ne, reach, zero);
1125
1126    let (low, high) = if opcode == Opcode::Shl {
1127        let moved = ahead(func, inst, Opcode::Shl, &[a_low, places]);
1128        let edge = ahead(func, inst, Opcode::LShr, &[a_low, one]);
1129        let across = ahead(func, inst, Opcode::LShr, &[edge, back]);
1130        let above = ahead(func, inst, Opcode::Shl, &[a_high, places]);
1131        let joined = ahead(func, inst, Opcode::Or, &[above, across]);
1132        let low = ahead(func, inst, Opcode::Select, &[whole, zero, moved]);
1133        let high = ahead(func, inst, Opcode::Select, &[whole, moved, joined]);
1134        (low, high)
1135    } else {
1136        let moved = ahead(func, inst, opcode, &[a_high, places]);
1137        let edge = ahead(func, inst, Opcode::Shl, &[a_high, one]);
1138        let across = ahead(func, inst, Opcode::Shl, &[edge, back]);
1139        let below = ahead(func, inst, Opcode::LShr, &[a_low, places]);
1140        let joined = ahead(func, inst, Opcode::Or, &[below, across]);
1141        // What is left behind when the whole low half is gone: zeroes for a logical shift, and for
1142        // an arithmetic one the sign bit spread over the half it came from.
1143        let spent = if opcode == Opcode::AShr {
1144            ahead(func, inst, Opcode::AShr, &[a_high, top])
1145        } else {
1146            zero
1147        };
1148        let low = ahead(func, inst, Opcode::Select, &[whole, moved, joined]);
1149        let high = ahead(func, inst, Opcode::Select, &[whole, spent, moved]);
1150        (low, high)
1151    };
1152    replace(func, halves, inst, low, high);
1153}
1154
1155/// An `and`, an `or` or an `xor`, which is the same operation on each half and nothing between
1156/// them.
1157fn bitwise(func: &mut Func, halves: &mut Halves, inst: Inst, opcode: Opcode) {
1158    let args = func[func[inst].args].to_vec();
1159    let [a, b] = args[..] else { return };
1160    let (Some(&(a_low, a_high)), Some(&(b_low, b_high))) = (halves.get(&a), halves.get(&b)) else {
1161        return;
1162    };
1163    let low = ahead(func, inst, opcode, &[a_low, b_low]);
1164    let high = ahead(func, inst, opcode, &[a_high, b_high]);
1165    replace(func, halves, inst, low, high);
1166}
1167
1168/// A comparison, which produces one bit and so is pointed at its answer rather than halved.
1169///
1170/// An equality is the two halves differing in neither place, which is one `or` over two `xor`s
1171/// against zero and is shorter than comparing twice and combining. An ordering is the high halves
1172/// settling it outright, or the low halves settling it when the high halves are equal, and the low
1173/// halves are compared without a sign because the low half of a signed number is unsigned whatever
1174/// the number is.
1175///
1176/// The high halves are asked a strict question even when the predicate is not strict. A predicate
1177/// that lets the two be equal is true of two equal high halves whatever the low halves say, and
1178/// what decides it there is the low halves, so `a >= b` is `a.hi > b.hi` or the high halves being
1179/// equal and `a.lo >= b.lo` unsigned. Asking `a.hi >= b.hi` instead makes every value with a high
1180/// half of its own greater than or equal to every other, which is the shape of this that a
1181/// differential run against GCC caught.
1182fn compare(func: &mut Func, halves: &Halves, forward: &mut Map<Value, Value>, inst: Inst) {
1183    let Extra::IntPred(pred) = func[inst].extra else { return };
1184    let args = func[func[inst].args].to_vec();
1185    let [a, b] = args[..] else { return };
1186    let (Some(&(a_low, a_high)), Some(&(b_low, b_high))) = (halves.get(&a), halves.get(&b)) else {
1187        return;
1188    };
1189    let answer = if matches!(pred, IntPred::Eq | IntPred::Ne) {
1190        let low = ahead(func, inst, Opcode::Xor, &[a_low, b_low]);
1191        let high = ahead(func, inst, Opcode::Xor, &[a_high, b_high]);
1192        let both = ahead(func, inst, Opcode::Or, &[low, high]);
1193        let zero = ahead_const(func, inst, 0);
1194        compared(func, inst, pred, both, zero)
1195    } else {
1196        let above = compared(func, inst, strict(pred), a_high, b_high);
1197        let below = compared(func, inst, unsigned(pred), a_low, b_low);
1198        let same = compared(func, inst, IntPred::Eq, a_high, b_high);
1199        let tail = bit(func, inst, Opcode::And, same, below);
1200        bit(func, inst, Opcode::Or, above, tail)
1201    };
1202    if let Some(result) = func[inst].first_result {
1203        forward.insert(result, answer);
1204    }
1205    func.remove_inst(inst);
1206}
1207
1208/// The same ordering with the equal case taken out of it, which is what the high halves are asked.
1209fn strict(pred: IntPred) -> IntPred {
1210    match pred {
1211        IntPred::Sle => IntPred::Slt,
1212        IntPred::Sge => IntPred::Sgt,
1213        IntPred::Ule => IntPred::Ult,
1214        IntPred::Uge => IntPred::Ugt,
1215        other => other,
1216    }
1217}
1218
1219/// The same ordering with no sign in it, which is how the low halves of two signed numbers compare.
1220fn unsigned(pred: IntPred) -> IntPred {
1221    match pred {
1222        IntPred::Slt => IntPred::Ult,
1223        IntPred::Sle => IntPred::Ule,
1224        IntPred::Sgt => IntPred::Ugt,
1225        IntPred::Sge => IntPred::Uge,
1226        other => other,
1227    }
1228}
1229
1230/// A choice between two wide values, which is the same choice made on each half.
1231///
1232/// Two of them rather than one, with the condition read twice. What that costs is one more
1233/// conditional move, and what the alternative costs is a branch, which is the more expensive of the
1234/// two on anything that predicts.
1235fn choose(func: &mut Func, halves: &mut Halves, inst: Inst) {
1236    let args = func[func[inst].args].to_vec();
1237    let [cond, then, other] = args[..] else { return };
1238    let (Some(&(then_low, then_high)), Some(&(other_low, other_high))) =
1239        (halves.get(&then), halves.get(&other))
1240    else {
1241        return;
1242    };
1243    let low = ahead(func, inst, Opcode::Select, &[cond, then_low, other_low]);
1244    let high = ahead(func, inst, Opcode::Select, &[cond, then_high, other_high]);
1245    replace(func, halves, inst, low, high);
1246}
1247
1248/// Keeping the low bits of a wide value, which is the low half and then whatever is left to do.
1249///
1250/// Down to sixty four there is nothing left to do and the low half is the answer, so the truncation
1251/// goes and its readers read the half. Down to anything narrower the machine's own truncation still
1252/// happens, out of the half rather than out of the value that is no longer there.
1253fn truncate(func: &mut Func, halves: &Halves, forward: &mut Map<Value, Value>, inst: Inst) {
1254    let Some(&arg) = func[func[inst].args].first() else { return };
1255    let Some(&(low, _)) = halves.get(&arg) else { return };
1256    let Some(result) = func[inst].first_result else { return };
1257    if func[result].ty.bits() == HALF {
1258        forward.insert(result, low);
1259        func.remove_inst(inst);
1260        return;
1261    }
1262    becomes(func, inst, Opcode::Trunc, &[low]);
1263}
1264
1265/// Widening into a wide value, which is the value in the low half and its own sign or zero above.
1266fn extend(func: &mut Func, halves: &mut Halves, inst: Inst, signed: bool) {
1267    let Some(&arg) = func[func[inst].args].first() else { return };
1268    let low = if func[arg].ty.bits() == HALF {
1269        arg
1270    } else {
1271        let opcode = if signed { Opcode::SExt } else { Opcode::ZExt };
1272        ahead(func, inst, opcode, &[arg])
1273    };
1274    let high = if signed {
1275        let top = ahead_const(func, inst, i128::from(HALF - 1));
1276        ahead(func, inst, Opcode::AShr, &[low, top])
1277    } else {
1278        ahead_const(func, inst, 0)
1279    };
1280    replace(func, halves, inst, low, high);
1281}
1282
1283/// A call, as a call passing and receiving halves.
1284///
1285/// The instruction is made again rather than edited, because how many values a call gives back is
1286/// settled when it is created and a wide return value is two where it was one. Its signature is
1287/// made again for the same reason, since the signature is what each end of the call lays itself out
1288/// against and both ends are split the same way.
1289fn call(
1290    func: &mut Func,
1291    conv: &CallRegs,
1292    halves: &mut Halves,
1293    forward: &mut Map<Value, Value>,
1294    inst: Inst,
1295) {
1296    let data = func[inst];
1297    let Extra::Call(info) = data.extra else { return };
1298    let info = func[info];
1299    let Some((whole, variadic)) = site(func, inst) else { return };
1300    let old = func[data.args].to_vec();
1301    // An indirect call's first operand is the address it calls, and the arguments come after it.
1302    let skip = usize::from(data.opcode == Opcode::CallIndirect);
1303    let Some(slots) = plan(&whole, conv) else { return };
1304    let mut args = spread(&old[..skip], halves);
1305    for slot in slots.iter().copied() {
1306        let value = match slot {
1307            Slot::Whole(index) => old[skip + index],
1308            Slot::Low(index) => halves[&old[skip + index]].0,
1309            Slot::High(index) => halves[&old[skip + index]].1,
1310            Slot::Filler(ty) if ty.is_float() => {
1311                let extra = Extra::Imm(func.add_imm(Imm::from_bits(0)));
1312                written(func, inst, InstData { extra, ..InstData::new(Opcode::FConst) }, ty)
1313            }
1314            Slot::Filler(_) => ahead_const(func, inst, 0),
1315        };
1316        args.push(value);
1317    }
1318    let results: Vec<Type> = data
1319        .results()
1320        .map(|value| func[value].ty)
1321        .flat_map(|ty| if is_wide(ty) { vec![half(), half()] } else { vec![ty] })
1322        .collect();
1323    let signature = func.add_signature(planned(&Signature { variadic, ..whole }, &slots));
1324    // What the ABI asks of each argument past the `...` is on the parameter it became now, so the
1325    // call names none of them any more and the list it kept that in is empty.
1326    let varargs = if variadic { func.push_abis(&[]) } else { info.varargs };
1327    let extra = Extra::Call(func.add_call(CallInfo { signature, varargs, ..info }));
1328    let args = func.push_values(&args);
1329    let span = func.span(inst);
1330    let made = func.create_inst(InstData { args, extra, ..data }, &results, span);
1331    func.insert_before(made, inst);
1332    let mut fresh = func[made].results();
1333    for old in data.results() {
1334        if is_wide(func[old].ty) {
1335            let (Some(low), Some(high)) = (fresh.next(), fresh.next()) else { return };
1336            halves.insert(old, (low, high));
1337        } else if let Some(again) = fresh.next() {
1338            forward.insert(old, again);
1339        }
1340    }
1341    func.remove_inst(inst);
1342}
1343
1344/// Everything one call passes as the one list of parameters it is laid out as, and whether the
1345/// callee is variadic.
1346///
1347/// A variadic callee's signature names the parameters in front of the `...` and nothing else, and
1348/// what the ABI asks of each argument behind it is on the call. Here those become parameters too,
1349/// each with what the call said about it, which is the list the convention lays out anyway: on
1350/// System V an argument past the `...` goes where it would have gone had it been named, and the
1351/// one thing the callee is told is how many vector registers were used, which is a count over all
1352/// of them. The list comes back not variadic so [`plan`] lays it out as a whole, and the flag is
1353/// handed back beside it for the signature the call is made against.
1354fn site(func: &Func, inst: Inst) -> Option<(Signature, bool)> {
1355    let data = func[inst];
1356    let Extra::Call(info) = data.extra else { return None };
1357    let info = func[info];
1358    let mut whole = func[info.signature].clone();
1359    let skip = usize::from(data.opcode == Opcode::CallIndirect);
1360    let args = &func[data.args];
1361    let named = skip + whole.params.len();
1362    if args.len() < named {
1363        return None;
1364    }
1365    let beyond = &func[info.varargs];
1366    for (index, &value) in args[named..].iter().enumerate() {
1367        let abi = beyond.get(index).copied().unwrap_or_default();
1368        whole.params.push(Param { ty: func[value].ty, abi });
1369    }
1370    let variadic = whole.variadic;
1371    whole.variadic = false;
1372    Some((whole, variadic))
1373}
1374
1375/// A `return`, whose operands are the values the signature says and so are halves now.
1376fn flatten(func: &mut Func, halves: &Halves, inst: Inst) {
1377    let args = spread(&func[func[inst].args], halves);
1378    func[inst].args = func.push_values(&args);
1379}
1380
1381/// A branch, whose arguments hang on the edge rather than on the instruction.
1382fn edges(func: &mut Func, halves: &Halves, inst: Inst) {
1383    for at in func.target_list(inst).iter() {
1384        let call = func[at];
1385        let args = func[call.args].to_vec();
1386        if !args.iter().any(|value| halves.contains_key(value)) {
1387            continue;
1388        }
1389        let args = func.push_values(&spread(&args, halves));
1390        func.set_block_call(at, BlockCall { args, ..call });
1391    }
1392}
1393
1394/// A list of values with each wide one replaced by its two halves in the same position.
1395fn spread(args: &[Value], halves: &Halves) -> Vec<Value> {
1396    args.iter()
1397        .flat_map(|value| match halves.get(value) {
1398            Some(&(low, high)) => vec![low, high],
1399            None => vec![*value],
1400        })
1401        .collect()
1402}
1403
1404/// One signature with every wide parameter and return value as two halves in its place.
1405///
1406/// Each half is plain. What the ABI asks beyond a type is about the bits above a narrow value and
1407/// about an object whose address travels, and a half is neither: it is exactly a register wide and
1408/// it is the value itself.
1409fn split_signature(signature: &Signature) -> Signature {
1410    let split = |params: &[Param]| -> Vec<Param> {
1411        params
1412            .iter()
1413            .flat_map(|param| {
1414                if is_wide(param.ty) {
1415                    vec![Param::new(half()), Param::new(half())]
1416                } else {
1417                    vec![*param]
1418                }
1419            })
1420            .collect()
1421    };
1422    Signature {
1423        params: split(&signature.params),
1424        returns: split(&signature.returns),
1425        variadic: signature.variadic,
1426        convention: signature.convention,
1427    }
1428}
1429
1430/// Records the two halves an instruction became and takes the instruction out.
1431fn replace(func: &mut Func, halves: &mut Halves, inst: Inst, low: Value, high: Value) {
1432    if let Some(result) = func[inst].first_result {
1433        halves.insert(result, (low, high));
1434    }
1435    func.remove_inst(inst);
1436}
1437
1438/// Points every reader of a value this pass replaced at what replaced it.
1439///
1440/// The arguments of each instruction and the arguments of the blocks it branches to, which between
1441/// them are everywhere a value can be read. Nothing chases, because every value this map answers
1442/// with is one made here and so is never itself a key.
1443fn substitute(func: &mut Func, forward: &Map<Value, Value>) {
1444    if forward.is_empty() {
1445        return;
1446    }
1447    let with = |value: Value| forward.get(&value).copied().unwrap_or(value);
1448    for block in func.blocks().collect::<Vec<_>>() {
1449        for inst in func.insts(block).collect::<Vec<Inst>>() {
1450            let args = func[inst].args;
1451            func.rewrite(args, with);
1452            for call in func.successors(inst).collect::<Vec<_>>() {
1453                func.rewrite(call.args, with);
1454            }
1455        }
1456    }
1457}
1458
1459/// The access one word of a wide access is, that many bytes into it.
1460fn word(info: MemInfo, at: u64) -> MemInfo {
1461    let align = if at == 0 { info.align } else { info.align.min(8) };
1462    MemInfo { size: STEP, align, ..info }
1463}
1464
1465/// The address one word past another, written in front of an instruction.
1466fn stepped(func: &mut Func, inst: Inst, from: Value) -> Value {
1467    let step = ahead_const(func, inst, i128::from(STEP));
1468    let args = func.push_values(&[from, step]);
1469    written(func, inst, InstData { args, ..InstData::new(Opcode::PtrAdd) }, Type::PTR)
1470}
1471
1472/// A load put in front of an instruction, and the half it reads.
1473fn read(func: &mut Func, inst: Inst, from: Value, info: MemInfo, flags: Flags) -> Value {
1474    let extra = Extra::Mem(func.add_mem(info));
1475    let args = func.push_values(&[from]);
1476    let data = InstData { args, flags, extra, ..InstData::new(Opcode::Load) };
1477    written(func, inst, data, half())
1478}
1479
1480/// A store put in front of an instruction, which produces nothing and is only its effect.
1481fn write(func: &mut Func, inst: Inst, value: Value, into: Value, info: MemInfo, flags: Flags) {
1482    let span = func.span(inst);
1483    let extra = Extra::Mem(func.add_mem(info));
1484    let args = func.push_values(&[value, into]);
1485    let data = InstData { args, flags, extra, ..InstData::new(Opcode::Store) };
1486    let made = func.create_inst(data, &[], span);
1487    func.insert_before(made, inst);
1488}
1489
1490/// A comparison written in front of an instruction, which carries its predicate where everything
1491/// else carries nothing.
1492fn compared(func: &mut Func, inst: Inst, pred: IntPred, lhs: Value, rhs: Value) -> Value {
1493    let args = func.push_values(&[lhs, rhs]);
1494    let extra = Extra::IntPred(pred);
1495    written(func, inst, InstData { args, extra, ..InstData::new(Opcode::ICmp) }, Type::I1)
1496}
1497
1498/// An `and` or an `or` over two truth values, which is the same instruction at the width of one.
1499fn bit(func: &mut Func, inst: Inst, opcode: Opcode, lhs: Value, rhs: Value) -> Value {
1500    let args = func.push_values(&[lhs, rhs]);
1501    written(func, inst, InstData { args, ..InstData::new(opcode) }, Type::I1)
1502}
1503
1504/// An instruction over these operands put in front of another one, producing a half.
1505fn ahead(func: &mut Func, inst: Inst, opcode: Opcode, args: &[Value]) -> Value {
1506    let args = func.push_values(args);
1507    written(func, inst, InstData { args, ..InstData::new(opcode) }, half())
1508}
1509
1510/// A constant half put in front of an instruction.
1511fn ahead_const(func: &mut Func, inst: Inst, value: i128) -> Value {
1512    let extra = Extra::Imm(func.add_imm(Imm::int(value, half())));
1513    written(func, inst, InstData { extra, ..InstData::new(Opcode::IConst) }, half())
1514}
1515
1516/// Creates the instruction, puts it in front of another, and reads its value back out.
1517fn written(func: &mut Func, inst: Inst, data: InstData, ty: Type) -> Value {
1518    let span = func.span(inst);
1519    let made = func.create_inst(data, &[ty], span);
1520    func.insert_before(made, inst);
1521    func[made].first_result.expect("an instruction created with one result has one")
1522}
1523
1524/// Turns an instruction into a different one over different operands, in place.
1525fn becomes(func: &mut Func, inst: Inst, opcode: Opcode, args: &[Value]) {
1526    let args = func.push_values(args);
1527    let data = &mut func[inst];
1528    data.opcode = opcode;
1529    data.args = args;
1530    data.extra = Extra::None;
1531    data.flags = data.flags.intersection(Flags::legal_on(opcode));
1532}
1533
1534#[cfg(test)]
1535mod tests {
1536    use rucc_base::Interner;
1537    use rucc_ir::{
1538        Abi, Block, Builder, Flags, Float, Func, MemOrder, Module, Restrict, Signature, Type, Value,
1539    };
1540    use rucc_target::x86_64::{MINGW64, SYSV};
1541    use rucc_target::{Arch, Env, Os, TargetInfo, Triple};
1542
1543    use super::{Def, Extra, HALF, IntPred, MemInfo, Opcode, halves};
1544
1545    /// The width the pass is about, as a type, which is what every test builds with.
1546    fn wide() -> Type {
1547        Type::int(super::WIDE)
1548    }
1549
1550    fn target() -> TargetInfo {
1551        TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu))
1552    }
1553
1554    fn printed(func: &Func, names: &mut Interner) -> String {
1555        let module = Module::new(names.intern("w.c"), &target());
1556        rucc_ir::print_func(&module, func, names)
1557    }
1558
1559    /// A function of those parameters returning that, with its entry block and its parameters.
1560    fn shell(names: &mut Interner, params: &[Type], returns: &[Type]) -> (Func, Block, Vec<Value>) {
1561        let signature = Signature::new().with_params(params).with_returns(returns);
1562        let mut func = Func::new(names.intern("f"), signature);
1563        let entry = func.create_block();
1564        let values = params.iter().map(|&ty| func.append_param(entry, ty)).collect();
1565        (func, entry, values)
1566    }
1567
1568    /// An ordinary access of that many bytes, aligned that far.
1569    fn info(size: u64, align: u32) -> MemInfo {
1570        MemInfo {
1571            size,
1572            align,
1573            order: MemOrder::NotAtomic,
1574            tbaa: None,
1575            owns: 0,
1576            restrict: Restrict::NONE,
1577        }
1578    }
1579
1580    #[test]
1581    fn an_add_carries_from_the_low_half_into_the_high_one() {
1582        let mut names = Interner::new();
1583        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1584        let mut build = Builder::new(&mut func, entry);
1585        let sum = build.binary(Opcode::Add, params[0], params[1], Flags::NONE);
1586        build.ret(&[sum]);
1587
1588        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1589        let text = printed(&func, &mut names);
1590        assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1591        // Two adds for the halves, one more for the carry, and the carry itself is the unsigned
1592        // comparison that says the low half wrapped.
1593        assert_eq!(text.matches(" = add ").count(), 3, "three adds: {text}");
1594        assert_eq!(text.matches("icmp ult").count(), 1, "one carry: {text}");
1595        assert_eq!(text.matches(" = zext.i64 ").count(), 1, "the carry as a number: {text}");
1596    }
1597
1598    #[test]
1599    fn a_subtract_borrows_the_other_way_round() {
1600        let mut names = Interner::new();
1601        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1602        let mut build = Builder::new(&mut func, entry);
1603        let difference = build.binary(Opcode::Sub, params[0], params[1], Flags::NONE);
1604        build.ret(&[difference]);
1605
1606        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1607        let text = printed(&func, &mut names);
1608        assert_eq!(text.matches(" = sub ").count(), 3, "three subtracts: {text}");
1609        // The borrow is the operands compared, not the answer, which is what tells a reader the
1610        // two directions were thought about separately.
1611        assert!(text.contains("icmp ult %0, %2"), "the operands are compared: {text}");
1612    }
1613
1614    #[test]
1615    fn the_signature_and_the_entry_block_say_the_same_thing() {
1616        let mut names = Interner::new();
1617        let (mut func, entry, params) = shell(&mut names, &[Type::int(32), wide()], &[wide()]);
1618        let mut build = Builder::new(&mut func, entry);
1619        build.ret(&[params[1]]);
1620
1621        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1622        assert_eq!(
1623            func.signature().param_types().collect::<Vec<_>>(),
1624            [Type::int(32), Type::int(HALF), Type::int(HALF)],
1625            "the wide parameter became two where it stood"
1626        );
1627        assert_eq!(
1628            func.signature().return_types().collect::<Vec<_>>(),
1629            [Type::int(HALF), Type::int(HALF)],
1630            "and so did what comes back"
1631        );
1632        let text = printed(&func, &mut names);
1633        assert!(text.contains("block0(%0: i32, %1: i64, %2: i64)"), "the block agrees: {text}");
1634        assert!(text.contains("return %1, %2"), "both halves go back: {text}");
1635        let _ = entry;
1636    }
1637
1638    #[test]
1639    fn a_read_takes_the_high_word_a_word_above_the_low_one() {
1640        let mut names = Interner::new();
1641        let (mut func, entry, params) = shell(&mut names, &[Type::PTR], &[wide()]);
1642        let mut build = Builder::new(&mut func, entry);
1643        let value = build.load(wide(), params[0], info(16, 16), Flags::NONE);
1644        build.ret(&[value]);
1645
1646        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1647        let text = printed(&func, &mut names);
1648        assert_eq!(text.matches(" = load.i64 ").count(), 2, "two reads: {text}");
1649        assert!(text.contains("ptr_add"), "the high word is a word up: {text}");
1650        // The object is aligned to sixteen and its high word is not, which is the one thing
1651        // splitting an access can get wrong quietly.
1652        assert!(text.contains("align 16"), "the low word keeps what the object had: {text}");
1653        assert!(text.contains("align 8"), "the high word knows less: {text}");
1654    }
1655
1656    #[test]
1657    fn an_equality_asks_once_about_both_halves() {
1658        let mut names = Interner::new();
1659        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[Type::int(32)]);
1660        let mut build = Builder::new(&mut func, entry);
1661        let same = build.icmp(IntPred::Eq, params[0], params[1]);
1662        let answer = build.unary(Opcode::ZExt, same, Type::int(32));
1663        build.ret(&[answer]);
1664
1665        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1666        let text = printed(&func, &mut names);
1667        assert_eq!(text.matches("icmp").count(), 1, "one comparison: {text}");
1668        assert_eq!(text.matches(" = xor ").count(), 2, "the halves differ or they do not: {text}");
1669    }
1670
1671    #[test]
1672    fn an_ordering_reads_the_low_halves_without_a_sign() {
1673        let mut names = Interner::new();
1674        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[Type::int(32)]);
1675        let mut build = Builder::new(&mut func, entry);
1676        let below = build.icmp(IntPred::Slt, params[0], params[1]);
1677        let answer = build.unary(Opcode::ZExt, below, Type::int(32));
1678        build.ret(&[answer]);
1679
1680        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1681        let text = printed(&func, &mut names);
1682        assert!(text.contains("icmp slt"), "the high halves keep the sign: {text}");
1683        assert!(text.contains("icmp ult"), "the low halves have none: {text}");
1684        assert!(
1685            text.contains("icmp eq"),
1686            "and the low halves only matter when the high tie: {text}"
1687        );
1688    }
1689
1690    /// An ordering that allows the two to be equal still asks the high halves a strict question.
1691    ///
1692    /// Two values whose high halves are equal are ordered by their low halves alone, and a high
1693    /// half that is greater than or equal to the other says nothing about that. Asking the high
1694    /// halves the predicate as it stands makes every ordering that is not strict answer yes on a
1695    /// tie, which is the mistake a run against GCC caught.
1696    #[test]
1697    fn an_ordering_that_allows_equality_asks_the_high_halves_a_strict_question() {
1698        let mut names = Interner::new();
1699        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[Type::int(32)]);
1700        let mut build = Builder::new(&mut func, entry);
1701        let at_least = build.icmp(IntPred::Sge, params[0], params[1]);
1702        let answer = build.unary(Opcode::ZExt, at_least, Type::int(32));
1703        build.ret(&[answer]);
1704
1705        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1706        let text = printed(&func, &mut names);
1707        assert!(text.contains("icmp sgt"), "the high halves settle it outright: {text}");
1708        assert!(!text.contains("icmp sge"), "a tie in the high halves settles nothing: {text}");
1709        assert!(text.contains("icmp uge"), "the low halves are the ones allowed to tie: {text}");
1710    }
1711
1712    #[test]
1713    fn a_widening_puts_the_sign_of_the_value_in_the_high_half() {
1714        let mut names = Interner::new();
1715        let (mut func, entry, params) = shell(&mut names, &[Type::int(32)], &[wide()]);
1716        let mut build = Builder::new(&mut func, entry);
1717        let value = build.unary(Opcode::SExt, params[0], wide());
1718        build.ret(&[value]);
1719
1720        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1721        let text = printed(&func, &mut names);
1722        assert!(text.contains("sext.i64"), "the value fills the low half: {text}");
1723        assert!(text.contains("ashr"), "and its sign fills the high one: {text}");
1724    }
1725
1726    #[test]
1727    fn a_block_parameter_becomes_two_and_every_branch_passes_two() {
1728        let mut names = Interner::new();
1729        let (mut func, entry, params) = shell(&mut names, &[wide(), Type::int(32)], &[wide()]);
1730        let tail = func.create_block();
1731        let carried = func.append_param(tail, wide());
1732        let mut build = Builder::new(&mut func, entry);
1733        let zero = build.iconst(Type::int(32), 0);
1734        let taken = build.icmp(IntPred::Ne, params[1], zero);
1735        let other = build.iconst(wide(), 7);
1736        build.br_if(taken, tail, &[params[0]], tail, &[other]);
1737        let mut build = Builder::new(&mut func, tail);
1738        build.ret(&[carried]);
1739
1740        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1741        let text = printed(&func, &mut names);
1742        assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1743        assert!(text.contains("block1(%7: i64, %8: i64)"), "the block takes two: {text}");
1744        assert_eq!(text.matches("block1(").count(), 3, "and both edges pass two: {text}");
1745    }
1746
1747    /// A multiply is the low halves, the two cross products, and nothing for the fourth corner.
1748    ///
1749    /// Three at the top, and four more inside the carry out of the low halves, which is a product
1750    /// at half the width again worked out the same way. What the count is really saying is that the
1751    /// two high halves are never multiplied together, because the whole of that partial product
1752    /// lands above the width.
1753    #[test]
1754    fn a_multiply_is_three_multiplies_and_the_carry_out_of_the_low_ones() {
1755        let mut names = Interner::new();
1756        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1757        let mut build = Builder::new(&mut func, entry);
1758        let product = build.binary(Opcode::Mul, params[0], params[1], Flags::NONE);
1759        build.ret(&[product]);
1760
1761        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1762        let text = printed(&func, &mut names);
1763        assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1764        assert_eq!(text.matches(" = mul ").count(), 7, "three and the carry's four: {text}");
1765    }
1766
1767    /// Each of the four divisions becomes a call to the routine of that name in the runtime.
1768    ///
1769    /// The sign is in the name because it is in the answer. A quotient rounds towards zero and a
1770    /// remainder takes the sign of the dividend, so the signed routine and the unsigned one work out
1771    /// two different numbers, where a wide add is one computation that two signednesses read the
1772    /// same bits of.
1773    #[test]
1774    fn each_of_the_four_divisions_calls_the_routine_of_that_name() {
1775        for (opcode, routine) in [
1776            (Opcode::UDiv, "__udivti3"),
1777            (Opcode::SDiv, "__divti3"),
1778            (Opcode::URem, "__umodti3"),
1779            (Opcode::SRem, "__modti3"),
1780        ] {
1781            let mut names = Interner::new();
1782            let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1783            let mut build = Builder::new(&mut func, entry);
1784            let answer = build.binary(opcode, params[0], params[1], Flags::NONE);
1785            build.ret(&[answer]);
1786
1787            assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1788            let text = printed(&func, &mut names);
1789            assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1790            assert!(text.contains(&format!("call @{routine}")), "{routine} is called: {text}");
1791        }
1792    }
1793
1794    /// The call hands over four halves and takes two back, which is the shape of the routine.
1795    ///
1796    /// Low half first and the dividend first, which is what the definition of the routine was split
1797    /// into by the same code on the way in. The operands here are the entry block's parameters, so
1798    /// the four values the call passes are the four the block now takes, in order.
1799    #[test]
1800    fn a_divide_hands_over_four_halves_and_takes_two_back() {
1801        let mut names = Interner::new();
1802        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1803        let mut build = Builder::new(&mut func, entry);
1804        let quotient = build.binary(Opcode::UDiv, params[0], params[1], Flags::NONE);
1805        build.ret(&[quotient]);
1806
1807        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1808        let text = printed(&func, &mut names);
1809        assert!(text.contains("@__udivti3(%0, %1, %2, %3)"), "four halves go over: {text}");
1810        assert!(text.contains("return %4, %5"), "and two come back: {text}");
1811    }
1812
1813    /// A divide whose operands were worked out in the function calls with the halves of those.
1814    ///
1815    /// The other direction of the same rule the walk is for: the call is built where the divide was,
1816    /// so the halves of a sum computed above it exist by then, and what reaches the routine is the
1817    /// two values the sum became rather than anything at the old width.
1818    #[test]
1819    fn a_divide_of_something_computed_calls_with_the_halves_of_it() {
1820        let mut names = Interner::new();
1821        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1822        let mut build = Builder::new(&mut func, entry);
1823        let sum = build.binary(Opcode::Add, params[0], params[1], Flags::NONE);
1824        let quotient = build.binary(Opcode::SDiv, sum, params[1], Flags::NONE);
1825        build.ret(&[quotient]);
1826
1827        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1828        let text = printed(&func, &mut names);
1829        assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1830        assert_eq!(text.matches(" = add ").count(), 3, "the sum is still a sum: {text}");
1831        assert_eq!(text.matches("call @__divti3").count(), 1, "one call: {text}");
1832    }
1833
1834    /// Each conversion between this width and a float becomes a call to the routine of that name.
1835    ///
1836    /// Twelve of them, which is a signed and an unsigned integer against a `float`, a `double` and a
1837    /// `_Float128` in each direction, and the table is here rather than in a comment because the
1838    /// names are the whole of what this has to get right.
1839    #[test]
1840    fn each_conversion_between_this_width_and_a_float_calls_the_routine_of_that_name() {
1841        let double = Type::float(Float::F64);
1842        let single = Type::float(Float::F32);
1843        let quad = Type::float(Float::F128);
1844        for (opcode, float, routine) in [
1845            (Opcode::SIToFP, double, "__floattidf"),
1846            (Opcode::SIToFP, single, "__floattisf"),
1847            (Opcode::UIToFP, double, "__floatuntidf"),
1848            (Opcode::UIToFP, single, "__floatuntisf"),
1849            (Opcode::SIToFP, quad, "__floattitf"),
1850            (Opcode::UIToFP, quad, "__floatuntitf"),
1851        ] {
1852            let mut names = Interner::new();
1853            let (mut func, entry, params) = shell(&mut names, &[wide()], &[float]);
1854            let mut build = Builder::new(&mut func, entry);
1855            let answer = build.unary(opcode, params[0], float);
1856            build.ret(&[answer]);
1857
1858            assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1859            let text = printed(&func, &mut names);
1860            assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1861            assert!(text.contains(&format!("call @{routine}")), "{routine} is called: {text}");
1862        }
1863        for (opcode, float, routine) in [
1864            (Opcode::FPToSI, double, "__fixdfti"),
1865            (Opcode::FPToSI, single, "__fixsfti"),
1866            (Opcode::FPToUI, double, "__fixunsdfti"),
1867            (Opcode::FPToUI, single, "__fixunssfti"),
1868            (Opcode::FPToSI, quad, "__fixtfti"),
1869            (Opcode::FPToUI, quad, "__fixunstfti"),
1870        ] {
1871            let mut names = Interner::new();
1872            let (mut func, entry, params) = shell(&mut names, &[float], &[wide()]);
1873            let mut build = Builder::new(&mut func, entry);
1874            let answer = build.unary(opcode, params[0], wide());
1875            build.ret(&[answer]);
1876
1877            assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1878            let text = printed(&func, &mut names);
1879            assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1880            assert!(text.contains(&format!("call @{routine}")), "{routine} is called: {text}");
1881        }
1882    }
1883
1884    /// A conversion up hands over two halves and takes one float back, and one coming down is the
1885    /// same call the other way round.
1886    ///
1887    /// The answer going up is not a wide value, so it is one result and the readers of the
1888    /// conversion read it, the way they read the answer of a comparison.
1889    #[test]
1890    fn a_conversion_hands_over_halves_one_way_and_takes_them_back_the_other() {
1891        let double = Type::float(Float::F64);
1892        let mut names = Interner::new();
1893        let (mut func, entry, params) = shell(&mut names, &[wide()], &[double]);
1894        let mut build = Builder::new(&mut func, entry);
1895        let answer = build.unary(Opcode::SIToFP, params[0], double);
1896        build.ret(&[answer]);
1897
1898        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1899        let text = printed(&func, &mut names);
1900        assert!(text.contains("@__floattidf(%0, %1)"), "two halves go over: {text}");
1901        assert!(text.contains("return %2"), "and one float comes back: {text}");
1902
1903        let mut names = Interner::new();
1904        let (mut func, entry, params) = shell(&mut names, &[double], &[wide()]);
1905        let mut build = Builder::new(&mut func, entry);
1906        let answer = build.unary(Opcode::FPToSI, params[0], wide());
1907        build.ret(&[answer]);
1908
1909        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1910        let text = printed(&func, &mut names);
1911        assert!(text.contains("@__fixdfti(%0)"), "the float goes over as it is: {text}");
1912        assert!(text.contains("return %1, %2"), "and two halves come back: {text}");
1913    }
1914
1915    /// A conversion against a quad is that same shape, with the quad crossing whole.
1916    ///
1917    /// Worth its own test because the two sides of it are wide for different reasons. The integer is
1918    /// a pair here because no register holds a hundred and twenty eight bits of integer, and the
1919    /// quad is one value because a vector register holds all of it, so the call this pass writes has
1920    /// two operands and one result going up and one operand and two results coming down.
1921    #[test]
1922    fn a_conversion_against_a_quad_hands_over_the_pair_and_the_quad_whole() {
1923        let quad = Type::float(Float::F128);
1924        let mut names = Interner::new();
1925        let (mut func, entry, params) = shell(&mut names, &[wide()], &[quad]);
1926        let mut build = Builder::new(&mut func, entry);
1927        let answer = build.unary(Opcode::UIToFP, params[0], quad);
1928        build.ret(&[answer]);
1929
1930        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1931        let text = printed(&func, &mut names);
1932        assert!(text.contains("@__floatuntitf(%0, %1)"), "two halves go over: {text}");
1933        assert!(text.contains("return %2"), "and one quad comes back: {text}");
1934
1935        let mut names = Interner::new();
1936        let (mut func, entry, params) = shell(&mut names, &[quad], &[wide()]);
1937        let mut build = Builder::new(&mut func, entry);
1938        let answer = build.unary(Opcode::FPToSI, params[0], wide());
1939        build.ret(&[answer]);
1940
1941        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1942        let text = printed(&func, &mut names);
1943        assert!(text.contains("@__fixtfti(%0)"), "the quad goes over as it is: {text}");
1944        assert!(text.contains("return %1, %2"), "and two halves come back: {text}");
1945    }
1946
1947    /// A conversion at a float width the runtime has no routine for leaves the function alone.
1948    ///
1949    /// `long double` is the eighty bit float on this target and the runtime has no conversion for
1950    /// it, because the back end has no register that holds one, which is tamnd/rucc#326. So the
1951    /// function keeps its wide values and is refused below by name, rather than being turned into a
1952    /// call to a routine nothing defines.
1953    #[test]
1954    fn a_conversion_at_a_width_the_runtime_has_no_routine_for_is_left_alone() {
1955        let long = Type::float(Float::F80);
1956        let mut names = Interner::new();
1957        let (mut func, entry, params) = shell(&mut names, &[wide()], &[long]);
1958        let mut build = Builder::new(&mut func, entry);
1959        let answer = build.unary(Opcode::SIToFP, params[0], long);
1960        build.ret(&[answer]);
1961
1962        assert!(!halves(&mut func, &mut names, &SYSV), "the pass does not understand this one");
1963        let text = printed(&func, &mut names);
1964        assert!(text.contains("i128"), "the width is still there: {text}");
1965    }
1966
1967    /// A shift left moves each half and chooses between the count having crossed a half and not.
1968    ///
1969    /// Two shifts left, one per half, and the low one does for both cases: a count that reached a
1970    /// whole half puts exactly that value in the high half and nothing in the low one, so the only
1971    /// thing the far case needs is the shift the near case already did. Two right shifts carry the
1972    /// crossing bits, two selects pick a half each, and there is no branch anywhere.
1973    #[test]
1974    fn a_shift_left_chooses_between_a_count_that_crossed_a_half_and_one_that_did_not() {
1975        let mut names = Interner::new();
1976        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
1977        let mut build = Builder::new(&mut func, entry);
1978        let moved = build.binary(Opcode::Shl, params[0], params[1], Flags::NONE);
1979        build.ret(&[moved]);
1980
1981        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
1982        let text = printed(&func, &mut names);
1983        assert!(!text.contains("i128"), "nothing that wide is left: {text}");
1984        assert_eq!(
1985            text.matches(" = shl ").count(),
1986            2,
1987            "one per half, and the far case reuses one: {text}"
1988        );
1989        assert_eq!(text.matches(" = select.i64 ").count(), 2, "one choice per half: {text}");
1990        assert_eq!(text.matches(" = lshr ").count(), 2, "the crossing bits, in two steps: {text}");
1991    }
1992
1993    /// The bits that cross move one place and then the rest, so a count of zero carries nothing.
1994    ///
1995    /// Sixty four less a count of zero is sixty four, which is not a distance a sixty four bit shift
1996    /// has. One place first and sixty three less the count after is the same distance everywhere the
1997    /// question is asked, and for a count of zero it moves a value whose top bit has already gone
1998    /// all the way out, which leaves the zero a half that did not move should carry.
1999    #[test]
2000    fn the_bits_that_cross_move_one_place_and_then_the_rest_of_the_way() {
2001        let mut names = Interner::new();
2002        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
2003        let mut build = Builder::new(&mut func, entry);
2004        let moved = build.binary(Opcode::LShr, params[0], params[1], Flags::NONE);
2005        build.ret(&[moved]);
2006
2007        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2008        let text = printed(&func, &mut names);
2009        assert!(text.contains("iconst.i64 63"), "sixty three is the distance left: {text}");
2010        assert!(text.contains("iconst.i64 1"), "after the one place that comes first: {text}");
2011        assert!(text.contains(" = sub "), "the rest of the way is worked out: {text}");
2012        assert!(
2013            !text.contains("iconst.i64 127"),
2014            "and the count is not masked to the width: {text}"
2015        );
2016    }
2017
2018    /// An arithmetic shift right leaves the sign bit behind where a logical one leaves zeroes.
2019    ///
2020    /// What the two differ in is only the half the count moved out of entirely. A logical shift puts
2021    /// zeroes there, which is a constant already in hand, and an arithmetic one puts the sign bit
2022    /// spread across the half it came from, which is one more shift.
2023    #[test]
2024    fn an_arithmetic_shift_right_leaves_the_sign_bit_where_a_logical_one_leaves_zeroes() {
2025        let mut names = Interner::new();
2026        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
2027        let mut build = Builder::new(&mut func, entry);
2028        let moved = build.binary(Opcode::AShr, params[0], params[1], Flags::NONE);
2029        build.ret(&[moved]);
2030
2031        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2032        let text = printed(&func, &mut names);
2033        assert!(!text.contains("i128"), "nothing that wide is left: {text}");
2034        // The high half by the count, and the high half by sixty three for the half left empty.
2035        assert_eq!(text.matches(" = ashr ").count(), 2, "the count and the sign: {text}");
2036        assert_eq!(text.matches(" = lshr ").count(), 1, "the low half is not signed: {text}");
2037        assert_eq!(text.matches(" = select.i64 ").count(), 2, "one choice per half: {text}");
2038    }
2039
2040    /// A wide parameter that gets no register pair, as the function's own parameter.
2041    ///
2042    /// The whole value goes in the argument area and the register it could not use stays empty,
2043    /// so the split signature has a filler where that register is and the two halves after it.
2044    /// What the function reads from the low half is the parameter the filler is followed by.
2045    fn arrived(params: &[Type], wide_at: usize) -> (Signature, usize) {
2046        let mut names = Interner::new();
2047        let word = Type::int(HALF);
2048        let (mut func, entry, values) = shell(&mut names, params, &[word]);
2049        let mut build = Builder::new(&mut func, entry);
2050        let low = build.unary(Opcode::Trunc, values[wide_at], word);
2051        build.ret(&[low]);
2052
2053        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2054        let ret = func.insts(entry).last().expect("the block ends in a return");
2055        let read = func[func[ret].args][0];
2056        let at = func[entry].params.iter().position(|&value| value == read);
2057        (func.signature().clone(), at.expect("the low half is a parameter"))
2058    }
2059
2060    fn types(signature: &Signature) -> Vec<Type> {
2061        signature.params.iter().map(|param| param.ty).collect()
2062    }
2063
2064    #[test]
2065    fn a_parameter_with_one_register_left_goes_in_memory_and_the_register_stays_empty() {
2066        let word = Type::int(HALF);
2067        let (signature, low) = arrived(&[word, word, word, word, word, wide()], 5);
2068        assert_eq!(types(&signature), vec![word; 8], "five, a filler and two halves");
2069        assert_eq!(low, 6, "the halves come after the register the value skipped");
2070    }
2071
2072    #[test]
2073    fn the_register_a_wide_parameter_skipped_goes_to_the_parameter_after_it() {
2074        let word = Type::int(HALF);
2075        let (signature, low) = arrived(&[word, word, word, word, word, wide(), word], 5);
2076        assert_eq!(types(&signature), vec![word; 8], "six registers and two words, no filler");
2077        assert_eq!(low, 6, "the word after the wide value took the sixth register");
2078    }
2079
2080    #[test]
2081    fn a_wide_parameter_in_memory_starts_on_a_sixteen_byte_boundary() {
2082        let word = Type::int(HALF);
2083        let params = [word, word, word, word, word, word, word, wide()];
2084        let (signature, low) = arrived(&params, 7);
2085        assert_eq!(types(&signature), vec![word; 10], "the seventh word, a filler, the halves");
2086        assert_eq!(low, 8, "the filler takes the word the alignment leaves empty");
2087    }
2088
2089    /// The same layout on the calling side, with a constant in the place of the filler.
2090    #[test]
2091    fn a_call_passes_a_wide_argument_in_memory_the_way_the_callee_reads_it() {
2092        let mut names = Interner::new();
2093        let word = Type::int(HALF);
2094        let (mut func, entry, _) = shell(&mut names, &[], &[]);
2095        let callee = names.intern("g");
2096        let params = [word, word, word, word, word, wide()];
2097        let signature = func.add_signature(Signature::new().with_params(&params));
2098        let mut build = Builder::new(&mut func, entry);
2099        let one = build.iconst(word, 1);
2100        let big = build.iconst(wide(), 4);
2101        build.call(callee, signature, &[one, one, one, one, one, big]);
2102        build.ret(&[]);
2103
2104        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2105        let call = func.insts(entry).find(|&inst| func[inst].opcode == Opcode::Call);
2106        let call = call.expect("the call is still there");
2107        let Extra::Call(info) = func[call].extra else { unreachable!("a call has call info") };
2108        let passed = func[func[call].args].to_vec();
2109        assert_eq!(types(&func[func[info].signature]), vec![word; 8], "as the callee has it");
2110        assert_eq!(passed.len(), 8, "one argument for each parameter");
2111        assert_eq!(passed[..5], [one; 5], "the words keep their registers");
2112        let constant = |value: Value| {
2113            let Def::Result { inst, .. } = func[value].def else { return None };
2114            let Extra::Imm(imm) = func[inst].extra else { return None };
2115            Some(func[imm].unsigned())
2116        };
2117        assert_eq!(constant(passed[6]), Some(4), "the low half is the first word in memory");
2118        assert_eq!(constant(passed[7]), Some(0), "and the high half the second");
2119    }
2120
2121    /// A variadic callee's named parameters have to stay in front of the rest, so a wide one that
2122    /// would go in memory is still refused there, by leaving the function as it was.
2123    #[test]
2124    fn a_variadic_call_with_a_wide_argument_in_memory_leaves_the_function_alone() {
2125        let mut names = Interner::new();
2126        let word = Type::int(HALF);
2127        let (mut func, entry, _) = shell(&mut names, &[], &[]);
2128        let callee = names.intern("g");
2129        let params = [word, word, word, word, word, wide()];
2130        let signature = Signature { variadic: true, ..Signature::new().with_params(&params) };
2131        let signature = func.add_signature(signature);
2132        let mut build = Builder::new(&mut func, entry);
2133        let one = build.iconst(word, 1);
2134        let big = build.iconst(wide(), 4);
2135        build.call(callee, signature, &[one, one, one, one, one, big]);
2136        build.ret(&[]);
2137        let before = printed(&func, &mut names);
2138
2139        assert!(!halves(&mut func, &mut names, &SYSV), "the named parameters cannot move");
2140        assert_eq!(printed(&func, &mut names), before, "so nothing moved");
2141    }
2142
2143    /// A wide argument past the `...` is laid out as if it had been named, which is what System V
2144    /// does with it, and the call names every argument afterwards so the list of what the ABI asks
2145    /// of the unnamed ones is empty.
2146    #[test]
2147    fn a_wide_argument_past_the_dots_goes_where_a_named_one_would() {
2148        let mut names = Interner::new();
2149        let word = Type::int(HALF);
2150        let (mut func, entry, _) = shell(&mut names, &[], &[]);
2151        let callee = names.intern("g");
2152        let params = [word, word, word, word, word];
2153        let signature = Signature { variadic: true, ..Signature::new().with_params(&params) };
2154        let signature = func.add_signature(signature);
2155        let mut build = Builder::new(&mut func, entry);
2156        let one = build.iconst(word, 1);
2157        let big = build.iconst(wide(), 4);
2158        build.call_varargs(callee, signature, &[one, one, one, one, one, big], &[Abi::Plain]);
2159        build.ret(&[]);
2160
2161        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2162        let call = func.insts(entry).find(|&inst| func[inst].opcode == Opcode::Call);
2163        let call = call.expect("the call is still there");
2164        let Extra::Call(info) = func[call].extra else { unreachable!("a call has call info") };
2165        let made = &func[func[info].signature];
2166        assert!(made.variadic, "the callee is still variadic");
2167        assert_eq!(types(made), vec![word; 8], "five words, a filler and the two halves");
2168        assert!(func[func[info].varargs].is_empty(), "every argument is named now");
2169        assert_eq!(func[func[call].args].len(), 8, "one argument for each parameter");
2170    }
2171
2172    /// The same call on a convention that counts both files as one run is left alone, because
2173    /// naming a float past the `...` there changes which registers it goes in.
2174    #[test]
2175    fn a_wide_argument_past_the_dots_on_windows_leaves_the_function_alone() {
2176        let mut names = Interner::new();
2177        let word = Type::int(HALF);
2178        let (mut func, entry, _) = shell(&mut names, &[], &[]);
2179        let callee = names.intern("g");
2180        let signature = Signature { variadic: true, ..Signature::new().with_params(&[word]) };
2181        let signature = func.add_signature(signature);
2182        let mut build = Builder::new(&mut func, entry);
2183        let one = build.iconst(word, 1);
2184        let big = build.iconst(wide(), 4);
2185        build.call_varargs(callee, signature, &[one, big], &[Abi::Plain]);
2186        build.ret(&[]);
2187
2188        assert!(!halves(&mut func, &mut names, &MINGW64), "the call is left for a refusal");
2189    }
2190
2191    /// The order the function holds its blocks in is not the order they run in.
2192    ///
2193    /// This is what the optimizer produced and `-O0` did not. A block that runs early is made late
2194    /// by whichever pass needed it, so the list the function keeps had a use of a wide value in it
2195    /// before the instruction defining that value, and the walk that asks whether every definition
2196    /// comes first said no and left the whole function alone. Then the selector met an instruction
2197    /// at a width it has no register for and refused the program. The blocks here are made in the
2198    /// order that produces, which is the tail before the middle. tamnd/rucc#1054.
2199    #[test]
2200    fn a_block_made_after_the_one_it_runs_before_is_still_split() {
2201        let mut names = Interner::new();
2202        let (mut func, entry, params) = shell(&mut names, &[wide()], &[wide()]);
2203        let tail = func.create_block();
2204        let middle = func.create_block();
2205        let mut build = Builder::new(&mut func, entry);
2206        build.jump(middle, &[]);
2207        let mut build = Builder::new(&mut func, middle);
2208        let doubled = build.binary(Opcode::Add, params[0], params[0], Flags::NONE);
2209        build.jump(tail, &[]);
2210        let mut build = Builder::new(&mut func, tail);
2211        let again = build.binary(Opcode::Add, doubled, doubled, Flags::NONE);
2212        build.ret(&[again]);
2213
2214        assert!(
2215            halves(&mut func, &mut names, &SYSV),
2216            "the definition runs before the use whatever the list says"
2217        );
2218        let text = printed(&func, &mut names);
2219        assert!(!text.contains("i128"), "nothing that wide is left: {text}");
2220    }
2221
2222    #[test]
2223    fn a_function_with_nothing_that_wide_is_not_touched() {
2224        let mut names = Interner::new();
2225        let word = Type::int(HALF);
2226        let (mut func, entry, params) = shell(&mut names, &[word, word], &[word]);
2227        let mut build = Builder::new(&mut func, entry);
2228        let sum = build.binary(Opcode::Add, params[0], params[1], Flags::NONE);
2229        build.ret(&[sum]);
2230
2231        assert!(!halves(&mut func, &mut names, &SYSV), "there is nothing to split");
2232    }
2233
2234    /// The operands of a runtime call go over the way the target's convention passes them.
2235    ///
2236    /// Windows x64 passes a scalar of a size no register holds as the address of a copy the caller
2237    /// made, so libgcc's `__floattitf` there reads its integer out of the address in `rdx` and
2238    /// writes its answer through the address in `rcx`. Handing it two halves in registers instead is
2239    /// not a worse encoding of the same call, it is a routine reading registers nothing was put in.
2240    #[test]
2241    fn on_windows_a_wide_operand_goes_over_as_the_address_of_a_copy() {
2242        let mut names = Interner::new();
2243        let quad = Type::float(Float::F64);
2244        let (mut func, entry, params) = shell(&mut names, &[wide()], &[quad]);
2245        let mut build = Builder::new(&mut func, entry);
2246        let answer = build.unary(Opcode::SIToFP, params[0], quad);
2247        build.ret(&[answer]);
2248
2249        assert!(halves(&mut func, &mut names, &MINGW64), "there is a width to split");
2250        let text = printed(&func, &mut names);
2251        assert!(text.contains("call @__floattidf"), "{text}");
2252        // One slot with the two halves written into it, and the address of it is the argument.
2253        assert_eq!(text.matches("alloca").count(), 1, "one slot: {text}");
2254        assert_eq!(text.matches("store").count(), 2, "a half at a time: {text}");
2255        assert_eq!(text.matches("ptr_add").count(), 1, "the high half eight bytes up: {text}");
2256        assert!(!text.contains("__floattidf(%0, %1)"), "not the two halves: {text}");
2257    }
2258
2259    /// An answer the convention brings back through an address is the leading argument.
2260    #[test]
2261    fn on_windows_a_wide_answer_at_this_format_comes_back_through_a_slot() {
2262        let mut names = Interner::new();
2263        let quad = Type::float(Float::F128);
2264        let (mut func, entry, params) = shell(&mut names, &[wide()], &[quad]);
2265        let mut build = Builder::new(&mut func, entry);
2266        let answer = build.unary(Opcode::SIToFP, params[0], quad);
2267        build.ret(&[answer]);
2268
2269        assert!(halves(&mut func, &mut names, &MINGW64), "there is a width to split");
2270        let text = printed(&func, &mut names);
2271        assert!(text.contains("call @__floattitf"), "{text}");
2272        // The slot for the answer and the slot for the operand.
2273        assert_eq!(text.matches("alloca").count(), 2, "two slots: {text}");
2274        assert_eq!(text.matches(" = call").count(), 0, "the call answers nothing: {text}");
2275        assert_eq!(text.matches(" = load").count(), 1, "the answer is the load after it: {text}");
2276    }
2277
2278    /// The convention that hands the halves over in registers is left exactly as it was.
2279    #[test]
2280    fn the_convention_with_registers_for_both_halves_puts_nothing_on_the_frame() {
2281        let mut names = Interner::new();
2282        let double = Type::float(Float::F64);
2283        let (mut func, entry, params) = shell(&mut names, &[wide()], &[double]);
2284        let mut build = Builder::new(&mut func, entry);
2285        let answer = build.unary(Opcode::SIToFP, params[0], double);
2286        build.ret(&[answer]);
2287
2288        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2289        let text = printed(&func, &mut names);
2290        assert!(text.contains("@__floattidf(%0, %1)"), "both halves in registers: {text}");
2291        assert!(!text.contains("alloca"), "nothing goes through the frame: {text}");
2292    }
2293
2294    /// An answer at this width on Windows, which comes back whole in a vector register and is taken
2295    /// apart through a slot rather than read out of two of them.
2296    #[test]
2297    fn on_windows_a_wide_answer_comes_back_in_one_register_and_is_split_on_the_frame() {
2298        let mut names = Interner::new();
2299        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
2300        let mut build = Builder::new(&mut func, entry);
2301        let answer = build.binary(Opcode::SDiv, params[0], params[1], Flags::NONE);
2302        build.ret(&[answer]);
2303
2304        assert!(halves(&mut func, &mut names, &MINGW64), "there is a width to split");
2305        let text = printed(&func, &mut names);
2306        // The call answers one value and it is at the quad format, which is the name this compiler
2307        // has for sixteen bytes in a vector register.
2308        assert!(text.contains("call @__divti3(%4, %7) : (ptr, ptr) -> f128"), "{text}");
2309        assert_eq!(text.matches(" = call").count(), 1, "one answer: {text}");
2310        // Two slots for the two operands and one more to take the answer apart in.
2311        assert_eq!(text.matches("alloca").count(), 3, "three slots: {text}");
2312        assert_eq!(text.matches(" = load").count(), 2, "the two halves: {text}");
2313    }
2314
2315    /// The same division where the convention has a pair of registers for the answer.
2316    #[test]
2317    fn the_convention_with_registers_for_the_answer_reads_both_halves_out_of_them() {
2318        let mut names = Interner::new();
2319        let (mut func, entry, params) = shell(&mut names, &[wide(), wide()], &[wide()]);
2320        let mut build = Builder::new(&mut func, entry);
2321        let answer = build.binary(Opcode::SDiv, params[0], params[1], Flags::NONE);
2322        build.ret(&[answer]);
2323
2324        assert!(halves(&mut func, &mut names, &SYSV), "there is a width to split");
2325        let text = printed(&func, &mut names);
2326        assert!(text.contains("@__divti3(%0, %1, %2, %3)"), "four halves over: {text}");
2327        assert!(!text.contains("alloca"), "nothing goes through the frame: {text}");
2328    }
2329}