diff --git a/crates/loader/src/arm64.rs b/crates/loader/src/arm64.rs index db9b885..f8daa67 100644 --- a/crates/loader/src/arm64.rs +++ b/crates/loader/src/arm64.rs @@ -306,6 +306,26 @@ impl Arm64Assembler { ); } + /// RBIT Xd, Xn: reverse the bit order of the source. + pub fn rbit_64(&mut self, xd: u8, xn: u8) { + self.emit(0xdac0_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f)); + } + + /// CLZ Xd, Xn: count the leading zero bits of the source. + pub fn clz_64(&mut self, xd: u8, xn: u8) { + self.emit(0xdac0_1000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f)); + } + + /// LSLV Xd, Xn, Xm: shift the source left by the amount in Xm. + pub fn lslv_64(&mut self, xd: u8, xn: u8, xm: u8) { + self.emit( + 0x9ac2_2000 + | ((u32::from(xm) & 0x1f) << 16) + | ((u32::from(xn) & 0x1f) << 5) + | (u32::from(xd) & 0x1f), + ); + } + /// LDR Qt, [Xn, #offset] (offset a multiple of 16) pub fn ldr_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) { self.emit( diff --git a/crates/loader/src/dbt.rs b/crates/loader/src/dbt.rs index 2fea459..4aba211 100644 --- a/crates/loader/src/dbt.rs +++ b/crates/loader/src/dbt.rs @@ -330,10 +330,18 @@ pub fn is_translatable(insn: &Insn) -> bool { /// [`DbtMetrics::interpreter_fallbacks`]. pub fn is_native(insn: &Insn) -> bool { let wide = matches!(insn.size, 4 | 8); + // The bit scans work on any register or memory source, and the bit test + // needs the index in a register. + let scanned = matches!(insn.size, 2 | 4 | 8); match insn.op { Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide, Op::Inc | Op::Dec | Op::Neg | Op::Not => wide, Op::Cmov => wide, + Op::Bsf | Op::Bsr => scanned, + // Only the `0F A3` form has the bit index in a register. The `0F BA` + // group form takes an immediate index and may write memory, so it + // stays on the shared semantics. + Op::Bt => scanned && insn.encoding == Encoding::RmReg, Op::Pop => insn.encoding == Encoding::OpReg, Op::Mov | Op::Movzx @@ -500,6 +508,18 @@ impl Emitter<'_> { } } + /// Zero-extend the low `size` bytes of `xd` to the full 64-bit register. + /// + /// An operation narrower than the register reads only the low bytes of its + /// source, so the bits above them must not take part in a bit scan. + fn zero_extend(&mut self, xd: u8, size: u8) { + match size { + 8 => {} + 4 => self.asm.mov_reg_32(xd, xd), + _ => self.asm.uxth_32(xd, xd), + } + } + /// Effective address into X1, clobbering X9. fn effective_address(&mut self, operand: &MemOperand, with_segment: bool) { let asm = &mut *self.asm; @@ -1032,6 +1052,71 @@ impl Emitter<'_> { self.load_condition(insn.condition); self.store_rm(insn, X12, completed); } + Op::Bsf | Op::Bsr => { + // BSF and BSR write the index of the lowest or the highest set + // bit of the source into the destination and set the zero flag + // when the source is zero (Intel SDM Volume 2B, "BSF" and + // "BSR"). A zero source leaves the destination undefined, so + // the destination keeps its value, which is the same rule the + // interpreter and the reference apply. + self.load_rm(X9, insn, completed); + self.zero_extend(X9, insn.size); + match insn.op { + // The lowest set bit is the highest set bit of the + // reversed value, so its index is the leading zero count + // of the reversed value. + Op::Bsf => { + self.asm.rbit_64(X10, X9); + self.asm.clz_64(X10, X10); + } + // The highest set bit sits at 63 minus the leading zero + // count. + _ => { + self.asm.clz_64(X10, X9); + self.asm.movz_64(X13, 63, 0); + self.asm.sub_reg_64(X10, X13, X10); + } + } + self.load_reg(X11, insn.reg); + self.asm.tst_reg_64(X9, X9); + // CSEL takes the first operand when the condition holds, so + // the index is the value that replaces the destination. + self.asm.csel_64(X11, X10, X11, Condition::Ne); + match insn.size { + // A 16-bit destination keeps the bits above it, so the + // register is merged rather than replaced. + 2 => self.store_reg(insn.reg, insn.size, X11), + // A 32-bit or 64-bit destination is written in full. The + // index has no bits above the operand width, so this + // matches the interpreter's 32-bit write, and a zero + // source keeps the whole register unchanged. + _ => self.asm.str_uoff_64(X11, X19, reg_offset(insn.reg.index)), + } + if flags { + // The zero flag is set when the source is zero. The other + // flags are undefined and keep their value. + self.asm.cset_32(X12, Condition::Eq); + self.asm.strb_uoff(X12, X19, ZF); + } + } + Op::Bt => { + // BT sets the carry flag from the tested bit and leaves the + // other flags undefined (Intel SDM Volume 2B, "BT"). The bit + // index comes from the register operand and is masked to the + // operand width. + self.load_rm(X9, insn, completed); + self.zero_extend(X9, insn.size); + self.load_reg(X10, insn.reg); + self.asm.load_imm_64(X13, u64::from(8 * insn.size - 1)); + self.asm.and_reg_64(X10, X10, X13); + self.asm.load_imm_64(X11, 1); + self.asm.lslv_64(X11, X11, X10); + self.asm.tst_reg_64(X9, X11); + if flags { + self.asm.cset_32(X12, Condition::Ne); + self.asm.strb_uoff(X12, X19, CF); + } + } Op::Cmov => { self.load_rm(X10, insn, completed); self.load_reg(X9, insn.reg); diff --git a/crates/loader/tests/x86_integer.rs b/crates/loader/tests/x86_integer.rs index 0dd7836..a31fd7b 100644 --- a/crates/loader/tests/x86_integer.rs +++ b/crates/loader/tests/x86_integer.rs @@ -1298,6 +1298,107 @@ fn division_accepts_exactly_the_representable_quotients() { } } +/// The bit scans and the bit test keep the destination and the flags where +/// the architecture puts them. +/// +/// The expectations come from the Intel SDM Volume 2B, "BSF", "BSR" and "BT": +/// BSF writes the index of the lowest set bit of the source and BSR the index +/// of the highest set bit, and both set the zero flag when the source is +/// zero, in which case the destination is undefined and keeps its value. BT +/// sets the carry flag from the tested bit, leaves the other flags alone and +/// masks the bit index to the operand width. +/// +/// The encodings are `bsf rbx, r9` (49 0F BC D9), `bsr rbx, r9` (49 0F BD +/// D9), `bt rbx, r9` (4C 0F A3 CB), `bsf ebx, r9d` (41 0F BC D9), +/// `bsr ebx, r9d` (41 0F BD D9), `bt ebx, r9d` (44 0F A3 CB), `bsf bx, r9w` +/// (66 41 0F BC D9) and `bt bx, r9w` (66 44 0F A3 CB), as produced by LLVM +/// 23.1.6 `llvm-mc -show-encoding`. +#[test] +fn bit_scans_and_bit_tests_follow_the_architecture() { + const BSF64: &[u8] = &[0x49, 0x0F, 0xBC, 0xD9]; // bsf rbx, r9 + const BSR64: &[u8] = &[0x49, 0x0F, 0xBD, 0xD9]; // bsr rbx, r9 + const BT64: &[u8] = &[0x4C, 0x0F, 0xA3, 0xCB]; // bt rbx, r9 + const BSF32: &[u8] = &[0x41, 0x0F, 0xBC, 0xD9]; // bsf ebx, r9d + const BSR32: &[u8] = &[0x41, 0x0F, 0xBD, 0xD9]; // bsr ebx, r9d + const BT32: &[u8] = &[0x44, 0x0F, 0xA3, 0xCB]; // bt ebx, r9d + const BSF16: &[u8] = &[0x66, 0x41, 0x0F, 0xBC, 0xD9]; // bsf bx, r9w + const BT16: &[u8] = &[0x66, 0x44, 0x0F, 0xA3, 0xCB]; // bt bx, r9w + + /// A machine with R9 and RBX set and every other register zero. + fn machine(source: u64, destination: u64) -> Machine { + let mut gpr = [0; 16]; + gpr[3] = destination; + gpr[9] = source; + Machine { + gpr, + flags: Flags::default(), + operand: 0, + pushed: 0, + top: STACK_TOP, + } + } + + // The lowest set bit of the source is the index BSF writes. + let (state, _, _) = run_both(&machine(0x0000_0000_0000_0028, 0xFFFF), BSF64, 1); + assert_eq!(state.gpr[3], 3); + assert!(!state.flags.zf); + + // The highest set bit of the source is the index BSR writes. + let (state, _, _) = run_both(&machine(0x8000_0000_0000_0028, 0xFFFF), BSR64, 1); + assert_eq!(state.gpr[3], 63); + assert!(!state.flags.zf); + + // A zero source sets the zero flag and leaves the destination alone. + let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSF64, 1); + assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF); + assert!(state.flags.zf); + let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSR64, 1); + assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF); + assert!(state.flags.zf); + + // A 32-bit destination holds a 32-bit index and clears the half above it. + let (state, _, _) = run_both(&machine(0x0000_0028, 0xFFFF_FFFF_FFFF_FFFF), BSF32, 1); + assert_eq!(state.gpr[3], 3); + let (state, _, _) = run_both(&machine(0x8000_0000, 0xFFFF_FFFF_FFFF_FFFF), BSR32, 1); + assert_eq!(state.gpr[3], 31); + + // A 16-bit destination keeps the bits above it. + let (state, _, _) = run_both(&machine(0x0100, 0xFFFF_FFFF_FFFF_FFFF), BSF16, 1); + assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_0008); + + // BT reports the tested bit in the carry flag and leaves the bit string + // alone. + let (state, _, _) = run_both(&machine(1, 0b1010), BT64, 1); + assert!(state.flags.cf); + assert_eq!(state.gpr[3], 0b1010); + let (state, _, _) = run_both(&machine(0, 0b1010), BT64, 1); + assert!(!state.flags.cf); + assert_eq!(state.gpr[3], 0b1010); + + // The bit index is masked to the operand width, so 64 selects bit 0 of a + // 64-bit bit string and 32 selects bit 0 of a 32-bit one. + let (state, _, _) = run_both(&machine(64, 0b1), BT64, 1); + assert!(state.flags.cf); + let (state, _, _) = run_both(&machine(32, 0b1), BT32, 1); + assert!(state.flags.cf); + let (state, _, _) = run_both(&machine(16, 0b1), BT16, 1); + assert!(state.flags.cf); + + // The bit scans and the register form of the bit test are lowered to + // ARM64 instead of falling back to the shared semantics. + for code in [BSF64, BSR64, BT64, BSF32, BSR32, BT32, BSF16, BT16] { + let insn = decode(ENTRY, |address| { + code.get((address - ENTRY) as usize).copied().ok_or(()) + }) + .expect("decode"); + assert!(is_native(&insn), "{code:02X?} is not native"); + let mut engine = DbtEngine::new(64 * 1024).unwrap(); + let (mut cpu, mut memory) = load(&machine(0x28, 0), code); + engine.run(&mut cpu, &mut memory, 1); + assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{code:02X?}"); + } +} + #[test] fn pop_rsp_and_push_rsp_use_the_architectural_stack_pointer() { let machine = Random(17).machine();