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