Skip to content

Truly independent web browser

48.1 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

//! Runs code generated by the x86-64 `MacroAssembler` natively.

use super::Address;
use super::Condition;
use super::DoubleCondition;
use super::Fpr;
use super::FprSet;
use super::Gpr;
use super::GprSet;
use super::NegativeZero;
use super::PortableMacroAssembler;
use super::Scale;
use super::Width;
use super::executable_code::ExecutableCode;
use super::x86_64::*;

fn assemble(emit: impl FnOnce(&mut MacroAssembler)) -> ExecutableCode {
    let (mut code, work) = (crate::asm::test_code(), crate::asm::test_work());
    let mut masm = MacroAssembler::new(&mut code, &work);
    emit(&mut masm);
    masm.finish().expect("assembling failed");
    ExecutableCode::new(&code[..])
}

/// The two-register return value of JIT entry points.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Pair {
    value: u64,
    status: u64,
}

type Binary = extern "sysv64" fn(u64, u64) -> u64;
type BinaryPair = extern "sysv64" fn(u64, u64) -> Pair;

const VALUES: [u64; 16] = [
    0,
    1,
    2,
    31,
    32,
    63,
    0x7fff_ffff,
    0x8000_0000,
    0xffff_ffff,
    0x1_0000_0000,
    0x1234_5678_9abc_def0,
    0x7fff_ffff_ffff_ffff,
    0x8000_0000_0000_0000,
    0xffff_ffff_ffff_fffe,
    u64::MAX,
    0xfedc_ba98_7654_3210,
];

const OPERAND_REGISTERS: [Gpr; 3] = [RAX, RCX, RDX];

/// Calls `emit(masm, dst, lhs, rhs)` for every assignment of the operands to
/// registers (including aliasing), with `lhs` = first argument and `rhs` =
/// second argument, and checks the result in `dst` against `reference`.
fn check_binary(name: &str, emit: impl Fn(&mut MacroAssembler, Gpr, Gpr, Gpr), reference: impl Fn(u64, u64) -> u64) {
    for dst in OPERAND_REGISTERS {
        for lhs in OPERAND_REGISTERS {
            for rhs in OPERAND_REGISTERS {
                let code = assemble(|masm| {
                    masm.move64(R8, RDI);
                    masm.move64(R9, RSI);
                    masm.move64(lhs, R8);
                    masm.move64(rhs, R9);
                    emit(masm, dst, lhs, rhs);
                    masm.move64(RAX, dst);
                    masm.ret();
                });
                // SAFETY: The code implements `Binary`.
                let function: Binary = unsafe { code.function() };
                for a in VALUES {
                    for b in VALUES {
                        let b = if lhs == rhs { a } else { b };
                        assert_eq!(
                            function(a, b),
                            reference(a, b),
                            "{name}({a:#x}, {b:#x}) dst={dst:?} lhs={lhs:?} rhs={rhs:?}"
                        );
                    }
                }
            }
        }
    }
}

fn low32(value: u64) -> u32 {
    value as u32
}

#[test]
fn integer_arithmetic_and_logic() {
    type Emit = fn(&mut MacroAssembler, Gpr, Gpr, Gpr);
    type Reference = fn(u64, u64) -> u64;
    let operations: [(&str, Emit, Reference); 22] = [
        (
            "add32",
            |m, d, l, r| m.add32(d, l, r),
            |a, b| u64::from(low32(a).wrapping_add(low32(b))),
        ),
        ("add64", |m, d, l, r| m.add64(d, l, r), |a, b| a.wrapping_add(b)),
        (
            "sub32",
            |m, d, l, r| m.sub32(d, l, r),
            |a, b| u64::from(low32(a).wrapping_sub(low32(b))),
        ),
        ("sub64", |m, d, l, r| m.sub64(d, l, r), |a, b| a.wrapping_sub(b)),
        ("and32", |m, d, l, r| m.and32(d, l, r), |a, b| u64::from(low32(a & b))),
        ("and64", |m, d, l, r| m.and64(d, l, r), |a, b| a & b),
        ("or32", |m, d, l, r| m.or32(d, l, r), |a, b| u64::from(low32(a | b))),
        ("or64", |m, d, l, r| m.or64(d, l, r), |a, b| a | b),
        ("xor32", |m, d, l, r| m.xor32(d, l, r), |a, b| u64::from(low32(a ^ b))),
        ("xor64", |m, d, l, r| m.xor64(d, l, r), |a, b| a ^ b),
        (
            "mul32",
            |m, d, l, r| m.mul32(d, l, r),
            |a, b| u64::from(low32(a).wrapping_mul(low32(b))),
        ),
        ("mul64", |m, d, l, r| m.mul64(d, l, r), |a, b| a.wrapping_mul(b)),
        (
            "shl32",
            |m, d, l, r| m.shl32(d, l, r),
            |a, b| u64::from(low32(a) << (b & 31)),
        ),
        ("shl64", |m, d, l, r| m.shl64(d, l, r), |a, b| a << (b & 63)),
        (
            "shr32",
            |m, d, l, r| m.shr32(d, l, r),
            |a, b| u64::from(low32(a) >> (b & 31)),
        ),
        ("shr64", |m, d, l, r| m.shr64(d, l, r), |a, b| a >> (b & 63)),
        (
            "sar32",
            |m, d, l, r| m.sar32(d, l, r),
            |a, b| u64::from(((low32(a) as i32) >> (b & 31)) as u32),
        ),
        (
            "sar64",
            |m, d, l, r| m.sar64(d, l, r),
            |a, b| ((a as i64) >> (b & 63)) as u64,
        ),
        (
            "neg32",
            |m, d, l, _| m.neg32(d, l),
            |a, _| u64::from(low32(a).wrapping_neg()),
        ),
        ("neg64", |m, d, l, _| m.neg64(d, l), |a, _| a.wrapping_neg()),
        ("not32", |m, d, l, _| m.not32(d, l), |a, _| u64::from(!low32(a))),
        ("not64", |m, d, l, _| m.not64(d, l), |a, _| !a),
    ];
    for (name, emit, reference) in operations {
        check_binary(name, emit, reference);
    }
    check_binary("move32", |m, d, l, _| m.move32(d, l), |a, _| u64::from(low32(a)));
    check_binary(
        "sign_extend32_to_64",
        |m, d, l, _| m.sign_extend32_to_64(d, l),
        |a, _| i64::from(low32(a) as i32) as u64,
    );
}

const IMMEDIATES: [i64; 12] = [
    0,
    1,
    -1,
    127,
    -128,
    0x7fff_ffff,
    -0x8000_0000,
    0xffff_ffff,
    0x1_0000_0000,
    0x1234_5678_9abc,
    i64::MAX,
    i64::MIN,
];

#[test]
fn integer_operations_with_immediates() {
    type Emit = fn(&mut MacroAssembler, Gpr, Gpr, i64);
    type Reference = fn(u64, i64) -> u64;
    let operations: [(&str, Emit, Reference); 23] = [
        (
            "add32_imm",
            |m, d, l, i| m.add32_imm(d, l, i as i32),
            |a, i| u64::from(low32(a).wrapping_add(i as u32)),
        ),
        (
            "add64_imm",
            |m, d, l, i| m.add64_imm(d, l, i),
            |a, i| a.wrapping_add(i as u64),
        ),
        (
            "sub32_imm",
            |m, d, l, i| m.sub32_imm(d, l, i as i32),
            |a, i| u64::from(low32(a).wrapping_sub(i as u32)),
        ),
        (
            "sub64_imm",
            |m, d, l, i| m.sub64_imm(d, l, i),
            |a, i| a.wrapping_sub(i as u64),
        ),
        (
            "and32_imm",
            |m, d, l, i| m.and32_imm(d, l, i as u32),
            |a, i| u64::from(low32(a) & i as u32),
        ),
        (
            "and64_imm",
            |m, d, l, i| m.and64_imm(d, l, i as u64),
            |a, i| a & i as u64,
        ),
        (
            "or32_imm",
            |m, d, l, i| m.or32_imm(d, l, i as u32),
            |a, i| u64::from(low32(a) | i as u32),
        ),
        ("or64_imm", |m, d, l, i| m.or64_imm(d, l, i as u64), |a, i| a | i as u64),
        (
            "mul32_imm",
            |m, d, l, i| m.mul32_imm(d, l, i as u32),
            |a, i| u64::from(low32(a).wrapping_mul(i as u32)),
        ),
        (
            "xor32_imm",
            |m, d, l, i| m.xor32_imm(d, l, i as u32),
            |a, i| u64::from(low32(a) ^ i as u32),
        ),
        (
            "xor64_imm",
            |m, d, l, i| m.xor64_imm(d, l, i as u64),
            |a, i| a ^ i as u64,
        ),
        (
            "shl32_imm",
            |m, d, l, i| m.shl32_imm(d, l, i as u8),
            |a, i| u64::from(low32(a) << (i & 31)),
        ),
        (
            "shl64_imm",
            |m, d, l, i| m.shl64_imm(d, l, i as u8),
            |a, i| a << (i & 63),
        ),
        (
            "shr32_imm",
            |m, d, l, i| m.shr32_imm(d, l, i as u8),
            |a, i| u64::from(low32(a) >> (i & 31)),
        ),
        (
            "shr64_imm",
            |m, d, l, i| m.shr64_imm(d, l, i as u8),
            |a, i| a >> (i & 63),
        ),
        (
            "sar32_imm",
            |m, d, l, i| m.sar32_imm(d, l, i as u8),
            |a, i| u64::from(((low32(a) as i32) >> (i & 31)) as u32),
        ),
        (
            "sar64_imm",
            |m, d, l, i| m.sar64_imm(d, l, i as u8),
            |a, i| ((a as i64) >> (i & 63)) as u64,
        ),
        (
            "move_imm32",
            |m, d, _, i| m.move_imm32(d, i as u32),
            |_, i| u64::from(i as u32),
        ),
        ("move_imm64", |m, d, _, i| m.move_imm64(d, i as u64), |_, i| i as u64),
        (
            "compare32_imm_set",
            |m, d, l, i| m.compare32_imm_set(Condition::LessThan, d, l, i as i32),
            |a, i| u64::from((low32(a) as i32) < (i as i32)),
        ),
        (
            "compare64_imm_set",
            |m, d, l, i| m.compare64_imm_set(Condition::Below, d, l, i),
            |a, i| u64::from(a < i as u64),
        ),
        (
            "load_effective_address",
            |m, d, l, i| m.load_effective_address(d, &Address::new(l, i as i32)),
            |a, i| a.wrapping_add(i as i32 as u64),
        ),
        (
            "load_effective_address_indexed",
            |m, d, l, i| {
                m.load_effective_address(d, &Address::indexed(l, l, Scale::Four, i as i32));
            },
            |a, i| a.wrapping_mul(5).wrapping_add(i as i32 as u64),
        ),
    ];
    for (name, emit, reference) in operations {
        for imm in IMMEDIATES {
            check_binary(name, |m, d, l, _| emit(m, d, l, imm), |a, _| reference(a, imm));
        }
    }
}

#[test]
fn overflow_checking_arithmetic() {
    type Emit = fn(&mut MacroAssembler, Gpr, Gpr, Gpr, super::Label);
    type Reference = fn(u64, u64) -> Option<u64>;
    let operations: [(&str, Emit, Reference); 8] = [
        (
            "branch_add32_overflow",
            |m, d, l, r, o| m.branch_add32_overflow(d, l, r, o),
            |a, b| {
                (low32(a) as i32)
                    .checked_add(low32(b) as i32)
                    .map(|v| u64::from(v as u32))
            },
        ),
        (
            "branch_sub32_overflow",
            |m, d, l, r, o| m.branch_sub32_overflow(d, l, r, o),
            |a, b| {
                (low32(a) as i32)
                    .checked_sub(low32(b) as i32)
                    .map(|v| u64::from(v as u32))
            },
        ),
        (
            "branch_mul32_overflow",
            |m, d, l, r, o| m.branch_mul32_overflow(d, l, r, o),
            |a, b| {
                (low32(a) as i32)
                    .checked_mul(low32(b) as i32)
                    .map(|v| u64::from(v as u32))
            },
        ),
        (
            "branch_neg32_overflow",
            |m, d, l, _, o| m.branch_neg32_overflow(d, l, o),
            |a, _| (low32(a) as i32).checked_neg().map(|v| u64::from(v as u32)),
        ),
        (
            "branch_add64_overflow",
            |m, d, l, r, o| m.branch_add64_overflow(d, l, r, o),
            |a, b| (a as i64).checked_add(b as i64).map(|v| v as u64),
        ),
        (
            "branch_sub64_overflow",
            |m, d, l, r, o| m.branch_sub64_overflow(d, l, r, o),
            |a, b| (a as i64).checked_sub(b as i64).map(|v| v as u64),
        ),
        (
            "branch_add32_imm_overflow(-7)",
            |m, d, l, _, o| m.branch_add32_imm_overflow(d, l, -7, o),
            |a, _| (low32(a) as i32).checked_add(-7).map(|v| u64::from(v as u32)),
        ),
        (
            "branch_sub32_imm_overflow(0x10000)",
            |m, d, l, _, o| m.branch_sub32_imm_overflow(d, l, 0x10000, o),
            |a, _| (low32(a) as i32).checked_sub(0x10000).map(|v| u64::from(v as u32)),
        ),
    ];
    let values = [
        0u64,
        1,
        2,
        0x7fff_ffff,
        0x8000_0000,
        0xffff_ffff,
        0x4000_0000,
        0xc000_0000,
        0x10000,
        0x7fff_ffff_ffff_ffff,
        1 << 63,
        u64::MAX,
    ];
    for (name, emit, reference) in operations {
        for dst in OPERAND_REGISTERS {
            for lhs in OPERAND_REGISTERS {
                for rhs in OPERAND_REGISTERS {
                    let code = assemble(|masm| {
                        let overflow = masm.new_label();
                        masm.move64(R8, RDI);
                        masm.move64(R9, RSI);
                        masm.move64(lhs, R8);
                        masm.move64(rhs, R9);
                        emit(masm, dst, lhs, rhs, overflow);
                        masm.move64(RAX, dst);
                        masm.move_imm64(RDX, 0);
                        masm.ret();
                        masm.bind(overflow);
                        masm.move_imm64(RAX, 0);
                        masm.move_imm64(RDX, 1);
                        masm.ret();
                    });
                    // SAFETY: The code implements `BinaryPair`.
                    let function: BinaryPair = unsafe { code.function() };
                    for a in values {
                        for b in values {
                            let b = if lhs == rhs { a } else { b };
                            let expected = match reference(a, b) {
                                Some(value) => Pair { value, status: 0 },
                                None => Pair { value: 0, status: 1 },
                            };
                            assert_eq!(
                                function(a, b),
                                expected,
                                "{name}({a:#x}, {b:#x}) dst={dst:?} lhs={lhs:?} rhs={rhs:?}"
                            );
                        }
                    }
                }
            }
        }
    }
}

const ALL_CONDITIONS: [Condition; 16] = [
    Condition::Equal,
    Condition::NotEqual,
    Condition::LessThan,
    Condition::LessThanOrEqual,
    Condition::GreaterThan,
    Condition::GreaterThanOrEqual,
    Condition::Below,
    Condition::BelowOrEqual,
    Condition::Above,
    Condition::AboveOrEqual,
    Condition::Overflow,
    Condition::NoOverflow,
    Condition::Zero,
    Condition::NonZero,
    Condition::Negative,
    Condition::PositiveOrZero,
];

/// The value of `condition` after comparing `lhs` with `rhs` at `width`.
fn evaluate_comparison(condition: Condition, width: Width, lhs: u64, rhs: u64) -> bool {
    let (lhs, rhs, signed_lhs, signed_rhs, difference_is_negative, overflow) = match width {
        Width::W32 => {
            let (l, r) = (low32(lhs), low32(rhs));
            (
                u64::from(l),
                u64::from(r),
                i64::from(l as i32),
                i64::from(r as i32),
                (l.wrapping_sub(r) as i32) < 0,
                (l as i32).checked_sub(r as i32).is_none(),
            )
        }
        Width::W64 => (
            lhs,
            rhs,
            lhs as i64,
            rhs as i64,
            (lhs.wrapping_sub(rhs) as i64) < 0,
            (lhs as i64).checked_sub(rhs as i64).is_none(),
        ),
    };
    match condition {
        Condition::Equal | Condition::Zero => lhs == rhs,
        Condition::NotEqual | Condition::NonZero => lhs != rhs,
        Condition::LessThan => signed_lhs < signed_rhs,
        Condition::LessThanOrEqual => signed_lhs <= signed_rhs,
        Condition::GreaterThan => signed_lhs > signed_rhs,
        Condition::GreaterThanOrEqual => signed_lhs >= signed_rhs,
        Condition::Below => lhs < rhs,
        Condition::BelowOrEqual => lhs <= rhs,
        Condition::Above => lhs > rhs,
        Condition::AboveOrEqual => lhs >= rhs,
        Condition::Overflow => overflow,
        Condition::NoOverflow => !overflow,
        Condition::Negative => difference_is_negative,
        Condition::PositiveOrZero => !difference_is_negative,
    }
}

#[test]
fn compares_and_branches() {
    for condition in ALL_CONDITIONS {
        assert_eq!(condition.invert().invert(), condition);
        for width in [Width::W32, Width::W64] {
            let branch = assemble(|masm| {
                let taken = masm.new_label();
                match width {
                    Width::W32 => masm.branch32(condition, RDI, RSI, taken),
                    Width::W64 => masm.branch64(condition, RDI, RSI, taken),
                }
                masm.move_imm32(RAX, 0);
                masm.ret();
                masm.bind(taken);
                masm.move_imm32(RAX, 1);
                masm.ret();
            });
            let set = assemble(|masm| {
                match width {
                    Width::W32 => masm.compare32_set(condition, RAX, RDI, RSI),
                    Width::W64 => masm.compare64_set(condition, RAX, RDI, RSI),
                }
                masm.ret();
            });
            let inverted = assemble(|masm| {
                match width {
                    Width::W32 => masm.compare32_set(condition.invert(), RDI, RDI, RSI),
                    Width::W64 => masm.compare64_set(condition.invert(), RDI, RDI, RSI),
                }
                masm.move64(RAX, RDI);
                masm.ret();
            });
            // SAFETY: All three implement `Binary`.
            let (branch, set, inverted): (Binary, Binary, Binary) =
                unsafe { (branch.function(), set.function(), inverted.function()) };
            for a in VALUES {
                for b in VALUES {
                    let expected = u64::from(evaluate_comparison(condition, width, a, b));
                    assert_eq!(branch(a, b), expected, "branch {condition:?} {width:?} {a:#x} {b:#x}");
                    assert_eq!(set(a, b), expected, "set {condition:?} {width:?} {a:#x} {b:#x}");
                    assert_eq!(
                        inverted(a, b),
                        1 - expected,
                        "inverted {condition:?} {width:?} {a:#x} {b:#x}"
                    );
                }
            }
        }
        for imm in IMMEDIATES {
            let branch = assemble(|masm| {
                let taken = masm.new_label();
                masm.branch64_imm(condition, RDI, imm, taken);
                masm.move_imm32(RAX, 0);
                masm.ret();
                masm.bind(taken);
                masm.move_imm32(RAX, 1);
                masm.ret();
            });
            let branch32 = assemble(|masm| {
                let taken = masm.new_label();
                masm.branch32_imm(condition, RDI, imm as i32, taken);
                masm.move_imm32(RAX, 0);
                masm.ret();
                masm.bind(taken);
                masm.move_imm32(RAX, 1);
                masm.ret();
            });
            // SAFETY: Both implement `Binary`.
            let (branch, branch32): (Binary, Binary) = unsafe { (branch.function(), branch32.function()) };
            for a in VALUES {
                let expected = u64::from(evaluate_comparison(condition, Width::W64, a, imm as u64));
                assert_eq!(branch(a, 0), expected, "branch64_imm {condition:?} {a:#x} {imm:#x}");
                let expected = u64::from(evaluate_comparison(condition, Width::W32, a, imm as u64));
                assert_eq!(branch32(a, 0), expected, "branch32_imm {condition:?} {a:#x} {imm:#x}");
            }
        }
    }
}

#[test]
fn memory_compares() {
    type Memory = extern "sysv64" fn(*const u64, u64) -> u64;
    for condition in [
        Condition::Equal,
        Condition::NotEqual,
        Condition::LessThan,
        Condition::Above,
    ] {
        for imm in IMMEDIATES {
            let code = assemble(|masm| {
                let taken = masm.new_label();
                let not_taken = masm.new_label();
                masm.branch64_memory_imm(condition, &Address::new(RDI, 8), imm, taken);
                masm.jump(not_taken);
                masm.bind(taken);
                masm.move_imm32(RAX, 1);
                masm.ret();
                masm.bind(not_taken);
                masm.move_imm32(RAX, 0);
                masm.ret();
            });
            let code32 = assemble(|masm| {
                let taken = masm.new_label();
                masm.branch32_memory_imm(
                    condition,
                    &Address::indexed(RDI, RSI, Scale::Eight, 0),
                    imm as i32,
                    taken,
                );
                masm.move_imm32(RAX, 0);
                masm.ret();
                masm.bind(taken);
                masm.move_imm32(RAX, 1);
                masm.ret();
            });
            let code_register = assemble(|masm| {
                let taken = masm.new_label();
                masm.move_imm64(RCX, imm as u64);
                masm.branch64_memory(condition, &Address::new(RDI, 8), RCX, taken);
                masm.move_imm32(RAX, 0);
                masm.ret();
                masm.bind(taken);
                masm.move_imm32(RAX, 1);
                masm.ret();
            });
            // SAFETY: All implement `Memory`.
            let (function, function32, function_register): (Memory, Memory, Memory) =
                unsafe { (code.function(), code32.function(), code_register.function()) };
            for value in VALUES {
                let memory = [0, value];
                let expected = u64::from(evaluate_comparison(condition, Width::W64, value, imm as u64));
                assert_eq!(
                    function(memory.as_ptr(), 0),
                    expected,
                    "{condition:?} {value:#x} {imm:#x}"
                );
                assert_eq!(
                    function_register(memory.as_ptr(), 0),
                    expected,
                    "{condition:?} {value:#x} {imm:#x}"
                );
                let expected = u64::from(evaluate_comparison(condition, Width::W32, value, imm as u64));
                assert_eq!(
                    function32(memory.as_ptr(), 1),
                    expected,
                    "32 {condition:?} {value:#x} {imm:#x}"
                );
            }
        }
    }
}

#[test]
fn additions_to_memory() {
    type Add = extern "sysv64" fn(*mut u64);
    for imm in IMMEDIATES.map(|imm| imm as i32) {
        let code = assemble(|masm| {
            masm.add32_to_memory_imm(&Address::new(RDI, 8), imm);
            masm.add64_to_memory_imm(&Address::new(RDI, 16), imm);
            masm.ret();
        });
        // SAFETY: The code implements `Add`.
        let function: Add = unsafe { code.function() };
        for value in VALUES {
            let mut memory = [value, value, value, value];
            function(memory.as_mut_ptr());
            let low = u64::from(low32(value).wrapping_add(imm as u32));
            assert_eq!(memory[1], (value & !0xffff_ffff) | low, "32 {value:#x} {imm:#x}");
            assert_eq!(
                memory[2],
                value.wrapping_add(i64::from(imm) as u64),
                "64 {value:#x} {imm:#x}"
            );
            assert_eq!([memory[0], memory[3]], [value, value]);
        }
    }
}

#[test]
fn loads_and_stores_of_128_bit_constants() {
    type Store = extern "sysv64" fn(*mut u64);
    let first = 0x0123_4567_89ab_cdef_fedc_ba98_7654_3210u128;
    let second = u128::MAX - 7;
    let code = assemble(|masm| {
        masm.load_imm128(XMM0, first);
        masm.store128(&Address::new(RDI, 8), XMM0);
        masm.load_imm128(XMM15, second);
        masm.store128(&Address::new(RDI, 24), XMM15);
        // The same constant again, from the same pool entry.
        masm.load_imm128(XMM1, first);
        masm.store128(&Address::new(RDI, 40), XMM1);
        masm.ret();
    });
    // SAFETY: The code implements `Store`.
    let function: Store = unsafe { code.function() };
    let mut memory = [7u64; 8];
    function(memory.as_mut_ptr());
    let halves = |value: u128| [value as u64, (value >> 64) as u64];
    assert_eq!(memory[0], 7);
    assert_eq!(memory[1..3], halves(first));
    assert_eq!(memory[3..5], halves(second));
    assert_eq!(memory[5..7], halves(first));
    assert_eq!(memory[7], 7);
}

#[test]
fn stack_pointer_comparisons() {
    type Compare = extern "sysv64" fn(*const u64) -> u64;
    let code = assemble(|masm| {
        let below = masm.new_label();
        masm.branch_if_stack_pointer_below(&Address::new(RDI, 8), below);
        masm.move_imm32(RAX, 0);
        masm.ret();
        masm.bind(below);
        masm.move_imm32(RAX, 1);
        masm.ret();
    });
    // SAFETY: The code implements `Compare`.
    let function: Compare = unsafe { code.function() };
    let local = 0u64;
    let near_stack_pointer = std::ptr::from_ref(&local) as u64;
    let compare = |limit: u64| function([0, limit].as_ptr());
    assert_eq!(compare(u64::MAX), 1);
    assert_eq!(compare(near_stack_pointer + 0x10000), 1);
    assert_eq!(compare(near_stack_pointer - 0x10000), 0);
    assert_eq!(compare(0), 0);
}

#[test]
fn bit_tests_and_select() {
    let masks = [
        1u64,
        0x80,
        0x8000_0000,
        0xffff_ffff,
        0x1_0000_0000,
        1 << 63,
        0xffff_0000_0000_0000,
        u64::MAX,
    ];
    for condition in [
        Condition::Zero,
        Condition::NonZero,
        Condition::Negative,
        Condition::PositiveOrZero,
    ] {
        for mask in masks {
            let make = |width: Width| {
                assemble(|masm| {
                    let taken = masm.new_label();
                    match width {
                        Width::W32 => masm.branch_test32(condition, RDI, mask as u32, taken),
                        Width::W64 => masm.branch_test64(condition, RDI, mask, taken),
                    }
                    masm.move_imm32(RAX, 0);
                    masm.ret();
                    masm.bind(taken);
                    masm.move_imm32(RAX, 1);
                    masm.ret();
                })
            };
            let (code32, code64) = (make(Width::W32), make(Width::W64));
            // SAFETY: Both implement `Binary`.
            let (function32, function64): (Binary, Binary) = unsafe { (code32.function(), code64.function()) };
            for value in VALUES {
                let evaluate = |masked: u64, sign_bit: u64| match condition {
                    Condition::Zero => masked == 0,
                    Condition::NonZero => masked != 0,
                    Condition::Negative => masked & sign_bit != 0,
                    _ => masked & sign_bit == 0,
                };
                let masked32 = value & mask & 0xffff_ffff;
                if mask as u32 != 0 {
                    assert_eq!(
                        function32(value, 0),
                        u64::from(evaluate(masked32, 1 << 31)),
                        "{condition:?} {value:#x} {mask:#x}"
                    );
                }
                assert_eq!(
                    function64(value, 0),
                    u64::from(evaluate(value & mask, 1 << 63)),
                    "{condition:?} {value:#x} {mask:#x}"
                );
            }
        }
    }

    type Select = extern "sysv64" fn(u64, u64, u64, u64) -> u64;
    let registers = [RDI, RSI, RDX, RCX];
    for condition in [Condition::LessThan, Condition::Equal, Condition::Above] {
        for dst in [RAX, RDI, RSI, RDX, RCX] {
            let code = assemble(|masm| {
                masm.select64(condition, RDI, RSI, dst, registers[2], registers[3]);
                masm.move64(RAX, dst);
                masm.ret();
            });
            // SAFETY: The code implements `Select`.
            let function: Select = unsafe { code.function() };
            for a in VALUES {
                for b in VALUES {
                    let expected = if evaluate_comparison(condition, Width::W64, a, b) {
                        111
                    } else {
                        222
                    };
                    assert_eq!(
                        function(a, b, 111, 222),
                        expected,
                        "{condition:?} {a:#x} {b:#x} dst={dst:?}"
                    );
                }
            }
        }
    }

    for condition in [Condition::LessThan, Condition::GreaterThan, Condition::Below] {
        for dst in [RAX, RDI, RSI, RDX, RCX] {
            let code = assemble(|masm| {
                masm.select32(condition, RDI, RSI, dst, registers[2], registers[3]);
                masm.move32(RAX, dst);
                masm.ret();
            });
            // SAFETY: The code implements `Select`.
            let function: Select = unsafe { code.function() };
            for a in VALUES {
                for b in VALUES {
                    let expected = if evaluate_comparison(condition, Width::W32, a, b) {
                        0xffff_fff1
                    } else {
                        2
                    };
                    assert_eq!(
                        function(a, b, 0xdead_0000_ffff_fff1, 0xdead_0000_0000_0002),
                        expected,
                        "{condition:?} {a:#x} {b:#x} dst={dst:?}"
                    );
                }
            }
        }
    }
}

#[test]
fn loads_and_stores() {
    type Access = extern "sysv64" fn(*mut u8, u64) -> u64;
    let mut memory = [0u8; 64];
    for (i, byte) in memory.iter_mut().enumerate() {
        *byte = (i as u8).wrapping_mul(37).wrapping_add(0x81);
    }
    let read = |memory: &[u8; 64], offset: usize, size: usize| {
        let mut bytes = [0u8; 8];
        bytes[..size].copy_from_slice(&memory[offset..offset + size]);
        u64::from_le_bytes(bytes)
    };
    type Load = fn(&mut MacroAssembler, Gpr, &Address);
    let loads: [(Load, usize, bool); 7] = [
        (|m, d, a| m.load8(d, a), 1, false),
        (|m, d, a| m.load8_sign_extend(d, a), 1, true),
        (|m, d, a| m.load16(d, a), 2, false),
        (|m, d, a| m.load16_sign_extend(d, a), 2, true),
        (|m, d, a| m.load32(d, a), 4, false),
        (|m, d, a| m.load32_sign_extend(d, a), 4, true),
        (|m, d, a| m.load64(d, a), 8, false),
    ];
    for (load, size, sign_extend) in loads {
        for (scale, scale_bytes) in [(Scale::One, 1), (Scale::Two, 2), (Scale::Four, 4), (Scale::Eight, 8)] {
            for displacement in [0, 3, -8] {
                // dst aliases the base register.
                let code = assemble(|masm| {
                    load(masm, RDI, &Address::indexed(RDI, RSI, scale, displacement));
                    masm.move64(RAX, RDI);
                    masm.ret();
                });
                // SAFETY: The code implements `Access`.
                let function: Access = unsafe { code.function() };
                for index in 0..3u64 {
                    let offset = (16 + index as i64 * scale_bytes + i64::from(displacement)) as usize;
                    let mut expected = read(&memory, offset, size);
                    if sign_extend {
                        let shift = 64 - 8 * size;
                        expected = (((expected << shift) as i64) >> shift) as u64;
                    }
                    // SAFETY: Offsets stay inside `memory`.
                    let base = unsafe { memory.as_mut_ptr().add(16) };
                    assert_eq!(
                        function(base, index),
                        expected,
                        "size {size} scale {scale:?} disp {displacement}"
                    );
                }
            }
        }
    }

    type Store = fn(&mut MacroAssembler, &Address, Gpr);
    let stores: [(Store, usize); 4] = [
        (|m, a, s| m.store8(a, s), 1),
        (|m, a, s| m.store16(a, s), 2),
        (|m, a, s| m.store32(a, s), 4),
        (|m, a, s| m.store64(a, s), 8),
    ];
    for (store, size) in stores {
        // Use a value register that needs a REX prefix for byte stores.
        let code = assemble(|masm| {
            masm.move64(RSI, RSI);
            store(masm, &Address::new(RDI, 5), RSI);
            masm.ret();
        });
        // SAFETY: The code implements `Access`.
        let function: Access = unsafe { code.function() };
        let mut target = [0xaau8; 16];
        function(target.as_mut_ptr(), 0x1122_3344_5566_7788);
        let mut expected = [0xaau8; 16];
        expected[5..5 + size].copy_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes()[..size]);
        assert_eq!(target, expected, "store size {size}");
    }

    for imm in [0u64, 7, 0xffff_ffff_ffff_fff0, 0x1234_5678_9abc_def0] {
        let code = assemble(|masm| {
            masm.store_imm64(&Address::new(RDI, 0), imm);
            masm.store_imm32(&Address::new(RDI, 8), imm as u32);
            masm.store_imm16(&Address::new(RDI, 12), imm as u16);
            masm.store_imm8(&Address::new(RDI, 14), imm as u8);
            masm.ret();
        });
        // SAFETY: The code implements `Access`.
        let function: Access = unsafe { code.function() };
        let mut target = [0xaau8; 16];
        function(target.as_mut_ptr(), 0);
        assert_eq!(u64::from_le_bytes(target[..8].try_into().unwrap()), imm);
        assert_eq!(u32::from_le_bytes(target[8..12].try_into().unwrap()), imm as u32);
        assert_eq!(u16::from_le_bytes(target[12..14].try_into().unwrap()), imm as u16);
        assert_eq!(target[14..], [imm as u8, 0xaa]);
    }

    // Doubles through memory.
    let code = assemble(|masm| {
        masm.load_double(XMM3, &Address::indexed(RDI, RSI, Scale::Eight, 0));
        masm.add_double(XMM3, XMM3, XMM3);
        masm.store_double(&Address::new(RDI, 0), XMM3);
        masm.ret();
    });
    // SAFETY: The code implements `Access`.
    let function: Access = unsafe { code.function() };
    let mut doubles = [0.0f64, 1.25];
    function(doubles.as_mut_ptr().cast(), 1);
    assert_eq!(doubles, [2.5, 1.25]);

    // Floats widened to doubles and doubles rounded to floats.
    let code = assemble(|masm| {
        masm.load_float_as_double(XMM3, &Address::indexed(RDI, RSI, Scale::Four, 0));
        masm.store_double(&Address::new(RDI, 8), XMM3);
        masm.move_double_imm(XMM4, 0.1);
        masm.store_double_as_float(&Address::new(RDI, 0), XMM4);
        masm.ret();
    });
    // SAFETY: The code implements `Access`.
    let function: Access = unsafe { code.function() };
    let mut words = [0u32, 1.5f32.to_bits(), 0, 0];
    function(words.as_mut_ptr().cast(), 1);
    assert_eq!(f32::from_bits(words[0]), 0.1f32);
    assert_eq!(f64::from_bits(u64::from(words[2]) | u64::from(words[3]) << 32), 1.5);
}

const DOUBLES: [f64; 16] = [
    0.0,
    -0.0,
    1.0,
    -1.5,
    0.1,
    -0.3,
    2.5,
    2147483647.0,
    -2147483648.0,
    2147483648.0,
    4294967296.5,
    1e300,
    f64::INFINITY,
    f64::NEG_INFINITY,
    f64::NAN,
    f64::MIN_POSITIVE,
];

/// `Math.min` or `Math.max` of two doubles: NaN if either is, and -0 below +0.
fn js_min_max(max: bool, a: f64, b: f64) -> f64 {
    if a.is_nan() || b.is_nan() {
        return f64::NAN;
    }
    if a == 0.0 && b == 0.0 {
        let negative = if max {
            a.is_sign_negative() && b.is_sign_negative()
        } else {
            a.is_sign_negative() || b.is_sign_negative()
        };
        return if negative { -0.0 } else { 0.0 };
    }
    if max { a.max(b) } else { a.min(b) }
}

fn same_double(a: f64, b: f64) -> bool {
    a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan())
}

#[test]
fn double_arithmetic() {
    type DoubleBinary = extern "sysv64" fn(f64, f64) -> f64;
    type Emit = fn(&mut MacroAssembler, Fpr, Fpr, Fpr);
    type Reference = fn(f64, f64) -> f64;
    let operations: [(&str, Emit, Reference); 12] = [
        ("add", |m, d, l, r| m.add_double(d, l, r), |a, b| a + b),
        ("sub", |m, d, l, r| m.sub_double(d, l, r), |a, b| a - b),
        ("mul", |m, d, l, r| m.mul_double(d, l, r), |a, b| a * b),
        ("div", |m, d, l, r| m.div_double(d, l, r), |a, b| a / b),
        ("sqrt", |m, d, l, _| m.sqrt_double(d, l), |a, _| a.sqrt()),
        ("floor", |m, d, l, _| m.floor_double(d, l), |a, _| a.floor()),
        ("ceil", |m, d, l, _| m.ceil_double(d, l), |a, _| a.ceil()),
        ("neg", |m, d, l, _| m.neg_double(d, l), |a, _| -a),
        ("abs", |m, d, l, _| m.abs_double(d, l), |a, _| a.abs()),
        (
            "min",
            |m, d, l, r| m.min_double(d, l, r),
            |a, b| js_min_max(false, a, b),
        ),
        ("max", |m, d, l, r| m.max_double(d, l, r), |a, b| js_min_max(true, a, b)),
        ("move", |m, d, l, _| m.move_double(d, l), |a, _| a),
    ];
    let registers = [XMM0, XMM1, XMM2];
    for (name, emit, reference) in operations {
        for dst in registers {
            for lhs in registers {
                for rhs in registers {
                    let code = assemble(|masm| {
                        masm.move_double(XMM8, XMM0);
                        masm.move_double(XMM9, XMM1);
                        masm.move_double(lhs, XMM8);
                        masm.move_double(rhs, XMM9);
                        emit(masm, dst, lhs, rhs);
                        masm.move_double(XMM0, dst);
                        masm.ret();
                    });
                    // SAFETY: The code implements `DoubleBinary`.
                    let function: DoubleBinary = unsafe { code.function() };
                    for a in DOUBLES {
                        for b in DOUBLES {
                            let b = if lhs == rhs { a } else { b };
                            let (actual, expected) = (function(a, b), reference(a, b));
                            assert!(
                                same_double(actual, expected),
                                "{name}({a}, {b}) = {actual}, expected {expected}"
                            );
                        }
                    }
                }
            }
        }
    }

    for value in DOUBLES {
        let code = assemble(|masm| {
            masm.move_double_imm(XMM5, value);
            masm.move_double(XMM0, XMM5);
            masm.ret();
        });
        // SAFETY: The code implements `DoubleBinary`.
        let function: DoubleBinary = unsafe { code.function() };
        assert!(same_double(function(1.0, 2.0), value), "{value}");
    }
}

#[test]
fn double_conversions() {
    type ToDouble = extern "sysv64" fn(u64) -> f64;
    type FromDouble = extern "sysv64" fn(f64) -> u64;
    type FromDoublePair = extern "sysv64" fn(f64) -> Pair;

    let int32 = assemble(|masm| {
        masm.convert_int32_to_double(XMM0, RDI);
        masm.ret();
    });
    let int64 = assemble(|masm| {
        masm.convert_int64_to_double(XMM0, RDI);
        masm.ret();
    });
    let bits = assemble(|masm| {
        masm.move_gpr_to_double(XMM7, RDI);
        masm.move_double(XMM0, XMM7);
        masm.ret();
    });
    // SAFETY: All implement `ToDouble`.
    let (int32, int64, bits): (ToDouble, ToDouble, ToDouble) =
        unsafe { (int32.function(), int64.function(), bits.function()) };
    for value in VALUES {
        assert_eq!(int32(value), f64::from(low32(value) as i32));
        assert_eq!(int64(value), value as i64 as f64);
        assert_eq!(bits(value).to_bits(), value);
    }

    let to_bits = assemble(|masm| {
        masm.move_double_to_gpr(RAX, XMM0);
        masm.ret();
    });
    let truncate = assemble(|masm| {
        masm.truncate_double_to_int64(RAX, XMM0);
        masm.ret();
    });
    // SAFETY: Both implement `FromDouble`.
    let (to_bits, truncate): (FromDouble, FromDouble) = unsafe { (to_bits.function(), truncate.function()) };
    for value in DOUBLES {
        assert_eq!(to_bits(value), value.to_bits());
        if value.is_finite() && value.abs() < 9e18 {
            assert_eq!(truncate(value), value.trunc() as i64 as u64, "{value}");
        }
    }

    for negative_zero in [NegativeZero::Allow, NegativeZero::Fail] {
        let code = assemble(|masm| {
            let fail = masm.new_label();
            masm.branch_convert_double_to_int32(RAX, XMM0, fail, negative_zero);
            masm.move_imm64(RDX, 0);
            masm.ret();
            masm.bind(fail);
            masm.move_imm64(RAX, 0);
            masm.move_imm64(RDX, 1);
            masm.ret();
        });
        // SAFETY: The code implements `FromDoublePair`.
        let function: FromDoublePair = unsafe { code.function() };
        let cases = DOUBLES.iter().copied().chain([5.0, -7.0, 0.5, -0.5, 2147483647.5]);
        for value in cases {
            let exact = value.fract() == 0.0 && (-2147483648.0..=2147483647.0).contains(&value);
            let is_negative_zero = value == 0.0 && value.is_sign_negative();
            let expected = if exact && !(is_negative_zero && negative_zero == NegativeZero::Fail) {
                Pair {
                    value: u64::from(value as i32 as u32),
                    status: 0,
                }
            } else {
                Pair { value: 0, status: 1 }
            };
            assert_eq!(function(value), expected, "{value} {negative_zero:?}");
        }
    }
}

const ALL_DOUBLE_CONDITIONS: [DoubleCondition; 14] = [
    DoubleCondition::Equal,
    DoubleCondition::NotEqual,
    DoubleCondition::LessThan,
    DoubleCondition::LessThanOrEqual,
    DoubleCondition::GreaterThan,
    DoubleCondition::GreaterThanOrEqual,
    DoubleCondition::EqualOrUnordered,
    DoubleCondition::NotEqualOrUnordered,
    DoubleCondition::LessThanOrUnordered,
    DoubleCondition::LessThanOrEqualOrUnordered,
    DoubleCondition::GreaterThanOrUnordered,
    DoubleCondition::GreaterThanOrEqualOrUnordered,
    DoubleCondition::Ordered,
    DoubleCondition::Unordered,
];

#[test]
fn double_compares() {
    type Compare = extern "sysv64" fn(f64, f64) -> u64;
    for condition in ALL_DOUBLE_CONDITIONS {
        assert_eq!(condition.invert().invert(), condition);
        let branch = assemble(|masm| {
            let taken = masm.new_label();
            masm.branch_double(condition, XMM0, XMM1, taken);
            masm.move_imm32(RAX, 0);
            masm.ret();
            masm.bind(taken);
            masm.move_imm32(RAX, 1);
            masm.ret();
        });
        let set = assemble(|masm| {
            masm.move_imm64(RAX, u64::MAX);
            masm.compare_double_set(condition, RAX, XMM0, XMM1);
            masm.ret();
        });
        // SAFETY: Both implement `Compare`.
        let (branch, set): (Compare, Compare) = unsafe { (branch.function(), set.function()) };
        for a in DOUBLES {
            for b in DOUBLES {
                let expected = u64::from(condition.evaluate(a, b));
                assert_eq!(branch(a, b), expected, "branch {condition:?} {a} {b}");
                assert_eq!(set(a, b), expected, "set {condition:?} {a} {b}");
                assert_eq!(condition.invert().evaluate(a, b), !condition.evaluate(a, b));
            }
        }
    }
}

extern "sysv64" fn helper(a: u64, b: u64, c: u64, d: u64, e: u64, f: u64) -> u64 {
    #[repr(align(16))]
    struct Aligned(u8);
    let local = Aligned(0);
    // The ABI requires a 16-byte aligned stack at calls; an aligned local's
    // address shows whether the caller kept it.
    let misaligned = std::hint::black_box(&raw const local) as usize % 16;
    std::hint::black_box(local.0);
    a + 2 * b + 3 * c + 4 * d + 5 * e + 6 * f + 1000 * misaligned as u64
}

#[test]
fn calls_with_frames() {
    type Call = extern "sysv64" fn(u64) -> Pair;
    let frame = MacroAssembler::frame(GprSet::of(&[RBX, R12]), FprSet::EMPTY, 24);
    assert_eq!(frame.locals_size % 8, 0);
    let code = assemble(|masm| {
        masm.emit_prologue(&frame);
        // Keep the argument in a callee-saved register across the call.
        masm.move64(RBX, RDI);
        masm.store64(&frame.local(RSP, 8), RDI);
        let arguments = <MacroAssembler as PortableMacroAssembler>::ARGUMENT_GPRS;
        for (i, register) in arguments.iter().enumerate() {
            masm.move_imm64(*register, i as u64 + 1);
        }
        masm.call_absolute(helper as *const () as u64);
        masm.move64(RDX, RBX);
        masm.load64(RCX, &frame.local(RSP, 8));
        masm.add64(RDX, RDX, RCX);
        masm.emit_epilogue(&frame);
        masm.ret();
    });
    // SAFETY: The code implements `Call`.
    let function: Call = unsafe { code.function() };
    assert_eq!(
        function(21),
        Pair {
            value: 1 + 4 + 9 + 16 + 25 + 36,
            status: 42
        }
    );

    // A tail jump to the helper returns straight to our caller.
    type Six = extern "sysv64" fn(u64, u64, u64, u64, u64, u64) -> u64;
    let code = assemble(|masm| {
        masm.add64_imm(RDI, RDI, 100);
        masm.jump_absolute(helper as *const () as u64);
    });
    // SAFETY: The code implements `Six`.
    let function: Six = unsafe { code.function() };
    assert_eq!(function(1, 0, 0, 0, 0, 0), 101);

    // Local calls through a label and a register.
    let code = assemble(|masm| {
        let callee = masm.new_label();
        let frame = MacroAssembler::frame(GprSet::EMPTY, FprSet::EMPTY, 0);
        masm.emit_prologue(&frame);
        masm.call(callee);
        masm.move64(RCX, RAX);
        masm.assembler.lea_label(R8, callee);
        masm.call_register(R8);
        masm.add64(RAX, RAX, RCX);
        masm.emit_epilogue(&frame);
        masm.ret();
        masm.bind(callee);
        masm.move_imm64(RAX, 7);
        masm.ret();
    });
    // SAFETY: The code implements `Binary`.
    let function: Binary = unsafe { code.function() };
    assert_eq!(function(0, 0), 14);
}

#[test]
fn prologue_and_epilogue_preserve_callee_saved_registers() {
    type Run = extern "sysv64" fn() -> u64;
    let callee_saved = <MacroAssembler as PortableMacroAssembler>::CALLEE_SAVED_GPRS;
    let checked: Vec<Gpr> = callee_saved.without(RSP).iter().collect();
    assert_eq!(checked, [RBX, RBP, R12, R13, R14, R15]);
    let magic = |register: Gpr| 0x5a5a_0000_0000_0000 | (u64::from(register.0) * 0x0101_0101);

    for locals in [0, 8, 24, 4096] {
        for saved_fprs in [FprSet::EMPTY, FprSet::of(&[XMM8, XMM9, XMM10])] {
            let frame = MacroAssembler::frame(callee_saved, saved_fprs, locals);
            let code = assemble(|masm| {
                let inner = masm.new_label();
                // Outer harness (hand-written so it does not depend on the
                // code under test): save callee-saved registers, load magic
                // values, call the inner function, and report differences.
                for register in &checked {
                    masm.assembler.push(*register);
                }
                masm.assembler.sub_ri(Width::W64, RSP, 8);
                for register in &checked {
                    masm.move_imm64(*register, magic(*register));
                }
                masm.move_double_imm(XMM8, 3.0);
                masm.call(inner);
                // The inner function returns its stack misalignment in RAX.
                for register in &checked {
                    masm.move_imm64(RCX, magic(*register));
                    masm.xor64(RCX, RCX, *register);
                    masm.or64(RAX, RAX, RCX);
                }
                if !saved_fprs.is_empty() {
                    masm.move_double_to_gpr(RCX, XMM8);
                    masm.xor64_imm(RCX, RCX, 3.0f64.to_bits());
                    masm.or64(RAX, RAX, RCX);
                }
                masm.assembler.add_ri(Width::W64, RSP, 8);
                for register in checked.iter().rev() {
                    masm.assembler.pop(*register);
                }
                masm.ret();

                // Inner function: clobber every callee-saved register.
                masm.bind(inner);
                masm.emit_prologue(&frame);
                for register in &checked {
                    masm.move_imm64(*register, 0xbad);
                }
                for register in saved_fprs.iter() {
                    masm.move_double_imm(register, 13.0);
                }
                if locals > 0 {
                    masm.store_imm64(&frame.local(RSP, 0), 0xbad);
                    masm.store_imm64(&frame.local(RSP, frame.locals_size - 8), 0xbad);
                }
                masm.move64(RAX, RSP);
                masm.and64_imm(RAX, RAX, 15);
                masm.emit_epilogue(&frame);
                masm.ret();
            });
            // SAFETY: The code implements `Run` and preserves the callee-saved
            // registers itself.
            let function: Run = unsafe { code.function() };
            assert_eq!(function(), 0, "locals {locals} fprs {saved_fprs:?}");
        }
    }
}

#[test]
fn loops_with_backward_branches() {
    let code = assemble(|masm| {
        let head = masm.new_label();
        let done = masm.new_label();
        masm.move_imm64(RAX, 0);
        masm.bind(head);
        masm.branch64_imm(Condition::Equal, RDI, 0, done);
        masm.add64(RAX, RAX, RDI);
        masm.sub64_imm(RDI, RDI, 1);
        masm.jump(head);
        masm.bind(done);
        masm.ret();
    });
    // SAFETY: The code implements `Binary`.
    let function: Binary = unsafe { code.function() };
    assert_eq!(function(100, 0), 5050);
    assert_eq!(function(0, 0), 0);
}