From bd00df2324c1a473f8aa2d3b7db7da08dd037870 Mon Sep 17 00:00:00 2001 From: denn0x <55638248+denn0x@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:30:40 +0000 Subject: [PATCH] cpu: lower forward MOVS and STOS string instructions with REP The integer lifter now lowers movsb/movsw/movsd/movsq and stosb/stosw/stosd/stosq, with and without rep, plus cld. Elements are copied one at a time from low to high addresses, so a forward-overlapping copy repeats its first element as the hardware does instead of acting like memmove. rep counts RCX down to zero; RSI and RDI advance by the element size. cld lowers to nothing because the Windows x64 ABI enters with DF clear. std, repne, 32-bit address-size forms, FS/GS sources, cmps, scas, lods and the SSE movsd (same mnemonic, register operands) stay rejected. cpu_aot_string_ops builds ten MASM exports and compares memory, final RCX and the RSI/RDI advances against the native DLL and a sequential reference (385 cases, 36 forward-overlap cases asserted to differ from memmove). AI-assisted (Claude Code). --- CMakeLists.txt | 10 +++ docs/experiments.md | 2 + tests/cpu/string_ops.asm | 105 +++++++++++++++++++++++++ tests/cpu/string_ops.def | 11 +++ tests/cpu/string_ops.py | 157 +++++++++++++++++++++++++++++++++++++ tools/ffx_version_query.py | 20 +++++ tools/form_coverage.py | 1 + 7 files changed, 306 insertions(+) create mode 100644 tests/cpu/string_ops.asm create mode 100644 tests/cpu/string_ops.def create mode 100644 tests/cpu/string_ops.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 6cd646bd9..16a0bd5fb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -648,6 +648,16 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME cpu_aot_bmi1 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/bmi1.py" check "$" "$") set_tests_properties(cpu_aot_bmi1 PROPERTIES SKIP_RETURN_CODE 77) + cpu_asm_fixture(cpu_string_ops string_ops) + set(string_ops_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_string_ops_lifted.cpp") + add_custom_command(OUTPUT "${string_ops_fixture}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/string_ops.py" + emit "$" "${string_ops_fixture}" + DEPENDS cpu_string_ops tests/cpu/string_ops.py tools/ffx_version_query.py + tools/cpu_ranges.py tools/cpu_leaf_aot.py VERBATIM) + add_library(cpu_string_ops_lifted SHARED "${string_ops_fixture}") + add_test(NAME cpu_aot_string_ops COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/string_ops.py" + check "$" "$") cpu_translation(cpu_callback cpu_chained_aot call_context CALLBACK_OFFSET 8) cpu_asm_fixture(cpu_destroy destroy) target_link_libraries(cpu_destroy PRIVATE ucrt.lib) diff --git a/docs/experiments.md b/docs/experiments.md index e88a062d5..69993e08e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -414,6 +414,8 @@ An immediate SHL, SHR or SAR whose masked count is zero leaves the flags unchang The shared lowering also handles 32-bit and 64-bit BMI1 bit-manipulation forms (`andn`, `bextr`, `blsi`, `blsmsk`, `blsr`, `tzcnt`), including their zero-extending 32-bit writes and ZF/CF updates. `cpu_aot_bmi1` probes CPUID leaf 7 EBX bit 3 (`BMI1`) before invoking the native fixture and exits 77 (capability skip) on hosts without BMI1; on BMI1-capable hosts it builds all twelve 32-bit and 64-bit exports from MASM source (`tests/cpu/bmi1.asm`), translates them, compares both values and observed ZF/CF flags against the native DLL and an independent reference, and checks that 16-bit `tzcnt` is rejected. Run `cmake --build --preset dev --target cpu_bmi1_lifted` and `ctest --preset dev --no-tests=error -R '^cpu_aot_bmi1$' -V`. +The shared lowering also handles forward string moves and stores (`movsb`, `movsw`, `movsd`, `movsq`, `stosb`, `stosw`, `stosd`, `stosq`) with and without `rep`, and `cld`. Each element is copied in turn from low to high addresses, so an overlapping copy whose destination is one element above its source repeats the first element, as the hardware does, rather than acting like `memmove`; `rep` decrements RCX to zero and both forms advance RSI and RDI. `cld` lowers to nothing because the Windows x64 ABI enters with DF clear; `std`, `repne`, 32-bit address-size forms, FS/GS sources, `cmps`, `scas` and `lods` stay rejected. `cpu_aot_string_ops` builds ten exports from MASM source (`tests/cpu/string_ops.asm`), translates them, and compares memory, the final RCX and the RSI and RDI advances against the native DLL and a sequential reference for counts 0 to 9 and 17, with disjoint, forward-overlapping and backward-overlapping ranges and four fill values; it asserts that each forward-overlap case differs from a `memmove`, and checks the rejections. Run `cmake --build --preset dev --target cpu_string_ops_lifted` and `ctest --preset dev --no-tests=error -R '^cpu_aot_string_ops$' -V`. + ## Recompiling a direct x64 call The [caller and callee](../tests/cpu/direct.asm) each accept two unsigned 64-bit integers and an output pointer. The [translator](../tools/cpu_call_aot.py) starts at the caller export, follows the signed displacement in its E8 call and reads the target's runtime-function interval. It generates two C++ functions from the linked machine code. MSVC emits a separate x64 DLL with a non-inlined call. The Windows test checks the relative call against the two export addresses in both the input and output DLLs. diff --git a/tests/cpu/string_ops.asm b/tests/cpu/string_ops.asm new file mode 100644 index 000000000..326b8433b --- /dev/null +++ b/tests/cpu/string_ops.asm @@ -0,0 +1,105 @@ +; Source-owned differential fixture for forward string moves and stores (MOVS and STOS in +; byte, word, doubleword and quadword sizes, with and without REP) after CLD. +; Each export takes (dst, src_or_value, count), runs one string instruction with RDI = dst, +; RSI = src_or_value, RAX = src_or_value and RCX = count, and returns +; ((final RCX << 20) + (final RSI - RSI on entry)) << 20 + (final RDI - dst), +; so the element count, both pointer advances and the counter are observed as well as memory. +; RDI and RSI are nonvolatile; they are kept in R10 and R11 and restored before RET. +.code + +STRING_ENTRY MACRO + mov r10, rdi + mov r11, rsi + mov r9, rcx + mov rdi, rcx + mov rsi, rdx + mov rax, rdx + mov rcx, r8 + cld +ENDM + +STRING_RESULT MACRO + mov rax, rcx + shl rax, 20 + sub rsi, rdx + add rax, rsi + shl rax, 20 + sub rdi, r9 + add rax, rdi + mov rdi, r10 + mov rsi, r11 + ret +ENDM + +rep_movsb PROC FRAME + .endprolog + STRING_ENTRY + rep movsb + STRING_RESULT +rep_movsb ENDP + +rep_movsw PROC FRAME + .endprolog + STRING_ENTRY + rep movsw + STRING_RESULT +rep_movsw ENDP + +rep_movsd PROC FRAME + .endprolog + STRING_ENTRY + rep movsd + STRING_RESULT +rep_movsd ENDP + +rep_movsq PROC FRAME + .endprolog + STRING_ENTRY + rep movsq + STRING_RESULT +rep_movsq ENDP + +rep_stosb PROC FRAME + .endprolog + STRING_ENTRY + rep stosb + STRING_RESULT +rep_stosb ENDP + +rep_stosw PROC FRAME + .endprolog + STRING_ENTRY + rep stosw + STRING_RESULT +rep_stosw ENDP + +rep_stosd PROC FRAME + .endprolog + STRING_ENTRY + rep stosd + STRING_RESULT +rep_stosd ENDP + +rep_stosq PROC FRAME + .endprolog + STRING_ENTRY + rep stosq + STRING_RESULT +rep_stosq ENDP + +; Without REP one element moves and RCX is left unchanged. +movsq_once PROC FRAME + .endprolog + STRING_ENTRY + movsq + STRING_RESULT +movsq_once ENDP + +stosd_once PROC FRAME + .endprolog + STRING_ENTRY + stosd + STRING_RESULT +stosd_once ENDP + +END diff --git a/tests/cpu/string_ops.def b/tests/cpu/string_ops.def new file mode 100644 index 000000000..91be24c13 --- /dev/null +++ b/tests/cpu/string_ops.def @@ -0,0 +1,11 @@ +EXPORTS + rep_movsb + rep_movsw + rep_movsd + rep_movsq + rep_stosb + rep_stosw + rep_stosd + rep_stosq + movsq_once + stosd_once diff --git a/tests/cpu/string_ops.py b/tests/cpu/string_ops.py new file mode 100644 index 000000000..c679ccac9 --- /dev/null +++ b/tests/cpu/string_ops.py @@ -0,0 +1,157 @@ +"""Compare native and translated forward string moves and stores (MOVS/STOS, REP, CLD).""" +import ctypes +from pathlib import Path +import sys + +import pefile +from iced_x86 import Decoder + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import export_rva +from cpu_ranges import function_ranges +from ffx_version_query import INTEGER_HEADER, lower, region + +U64 = ctypes.c_uint64 +MASK64 = 0xffffffffffffffff + +# name: (element size, is a move, has REP) +EXPORTS = { + "rep_movsb": (1, True, True), "rep_movsw": (2, True, True), + "rep_movsd": (4, True, True), "rep_movsq": (8, True, True), + "rep_stosb": (1, False, True), "rep_stosw": (2, False, True), + "rep_stosd": (4, False, True), "rep_stosq": (8, False, True), + "movsq_once": (8, True, False), "stosd_once": (4, False, False), +} +COUNTS = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 17) +VALUES = (0, 0x1122334455667788, 0xfedcba9876543210, MASK64) +BUFFER = 512 +BASE = 128 # every access lies inside [BASE, BASE + 200 + 17 * 8), away from both buffer ends + + +def emit(image, output): + parts = [INTEGER_HEADER] + with pefile.PE(str(image), fast_load=True) as pe: + for name in EXPORTS: + (bounds,) = function_ranges(pe, export_rva(pe, name)) + body = region(pe, *bounds) + code = lower(body, ["rcx = dst; rdx = src; r8 = count;"], {}, {}, {}) + parts.append(f'extern "C" __declspec(dllexport) word {name}(word dst, word src, word count) {{\n{code}\n}}\n') + output.write_text("".join(parts), encoding="ascii") + + +def load_lib(path): + lib = ctypes.CDLL(str(Path(path).resolve())) + for name in EXPORTS: + fn = getattr(lib, name) + fn.argtypes, fn.restype = [U64, U64, U64], U64 + return lib + + +def pattern(): + return bytes((index * 37 + 11) & 0xff for index in range(BUFFER)) + + +def reference(memory, name, dst, src, count): + """Sequential model over a bytearray: one element per step, low addresses first.""" + size, move, rep = EXPORTS[name] + steps = count if rep else 1 + d, s = dst, src + for _ in range(steps): + if move: + memory[d:d + size] = memory[s:s + size] + s += size + else: + memory[d:d + size] = (src & MASK64).to_bytes(8, "little")[:size] + d += size + rcx = 0 if rep else count + rsi_advance = s - src if move else 0 + return ((((rcx << 20) + rsi_advance) << 20) + (d - dst)) & MASK64 + + +def run(lib, name, dst_offset, src, count): + """Call an export over a fresh patterned buffer. src is an offset for moves, a value for stores.""" + buffer = ctypes.create_string_buffer(pattern(), BUFFER) + base = ctypes.addressof(buffer) + move = EXPORTS[name][1] + source = base + src if move else src + # The return encodes RSI and RDI relative to their entry values, so it is independent of base. + result = getattr(lib, name)(base + dst_offset, source, count) + return result, bytes(buffer.raw) + + +def cases(): + for name, (size, move, _) in EXPORTS.items(): + for count in COUNTS: + if move: + # Disjoint, destination one element above the source (forward overlap), + # and destination one element below the source (backward overlap). + for dst, src in ((BASE + 200, BASE), (BASE + size, BASE), (BASE, BASE + size)): + yield name, dst, src, count + else: + for value in VALUES: + yield name, BASE, value, count + + +def check(native_path, lifted_path): + native, lifted = load_lib(native_path), load_lib(lifted_path) + checked = 0 + smeared = 0 + for name, dst, src, count in cases(): + size, move, rep = EXPORTS[name] + memory = bytearray(pattern()) + want = reference(memory, name, dst, src, count) + want_memory = bytes(memory) + for lib, label in ((native, "native"), (lifted, "lifted")): + got, got_memory = run(lib, name, dst, src, count) + if (got, got_memory) != (want, want_memory): + first = next((n for n, (a, b) in enumerate(zip(got_memory, want_memory)) if a != b), None) + raise AssertionError( + f"{label} {name}(dst={dst}, src={src:#x}, count={count}) = {got:#x}, " + f"expected {want:#x}; first differing byte {first}") + if move and rep and dst == src + size and count >= 2: + # A memmove of the same range differs from the element-by-element result, so this + # case would catch a block-copy lowering. + moved = bytearray(pattern()) + moved[dst:dst + size * count] = bytes(moved[src:src + size * count]) + if bytes(moved) == want_memory: + raise AssertionError(f"{name} forward-overlap case with count {count} does not discriminate memmove") + smeared += 1 + checked += 1 + print(f"{checked} string move/store cases ({smeared} forward-overlap) matched native and translated DLLs " + "in memory, RCX, RSI and RDI") + + +def expect_rejection(code, prefix, what): + try: + lower(list(Decoder(64, bytes.fromhex(code), ip=0x1000)), [], {}, {}, {}) + except ValueError as exc: + if not str(exc).startswith(prefix): + raise AssertionError(f"{what}: unexpected diagnostic {exc}") from exc + else: + raise AssertionError(f"accepted {what}") + + +def check_rejections(): + expect_rejection("f2 a4 c3", "unsupported REPNE string move at 0x1000", "repne movsb") + expect_rejection("67 f3 a4 c3", "unsupported 32-bit string addressing at 0x1000", "rep movsb with 32-bit addresses") + expect_rejection("67 aa c3", "unsupported 32-bit string addressing at 0x1000", "stosb with 32-bit addresses") + expect_rejection("64 a4 c3", "unsupported instruction prefix at 0x1000", "movsb with an FS source") + # Backward strings are not lowered; neither are the compare and load string forms. + expect_rejection("fd c3", "unsupported query operation at 0x1000", "std") + expect_rejection("f3 a6 c3", "unsupported query operation at 0x1000", "repe cmpsb") + expect_rejection("ac c3", "unsupported query operation at 0x1000", "lodsb") + expect_rejection("f2 ae c3", "unsupported query operation at 0x1000", "repne scasb") + # The SSE scalar move shares the MOVSD mnemonic but has register operands. + expect_rejection("f2 0f 10 c1 c3", "unsupported query operation at 0x1000", "movsd xmm0, xmm1") + print("REPNE, 32-bit addressing, FS, STD, CMPS, LODS, SCAS and SSE MOVSD were rejected") + + +if __name__ == "__main__": + mode, native, other = sys.argv[1:] + if mode == "emit": + emit(Path(native), Path(other)) + elif mode == "check": + check(native, other) + check_rejections() + else: + raise ValueError(mode) diff --git a/tools/ffx_version_query.py b/tools/ffx_version_query.py index 327d5ab8f..a9fa57f09 100644 --- a/tools/ffx_version_query.py +++ b/tools/ffx_version_query.py @@ -15,6 +15,9 @@ REGS = {getattr(R, n.upper()): n for n in "rax rbx rcx rdx rsi rdi rbp rsp r8 r9 r10 r11 r12 r13 r14 r15".split()} HIGH_BYTE = {R.AH, R.BH, R.CH, R.DH} UINT = {1: "uint8_t", 2: "uint16_t", 4: "uint32_t", 8: "uint64_t"} +# Element size of each string move and store. Backward strings (STD) are not lowered. +STRING_SIZES = {M.MOVSB: 1, M.MOVSW: 2, M.MOVSD: 4, M.MOVSQ: 8, M.STOSB: 1, M.STOSW: 2, M.STOSD: 4, M.STOSQ: 8} +STRING_MOVES = {M.MOVSB, M.MOVSW, M.MOVSD, M.MOVSQ} INTEGER_HEADER = """#include #include @@ -230,6 +233,23 @@ def write(expr): stmt = f"{xmm[i.op0_register]} = _mm_add_epi32({xmm[i.op1_register]}, {xmm[i.op2_register]});" elif op == M.VMOVD and i.op1_register in xmm: stmt = write(f"_mm_cvtsi128_si32({xmm[i.op1_register]})") + elif op in STRING_SIZES and i.op0_kind in (K.MEMORY_ESRDI, K.MEMORY_ESEDI): + # One element per step, forward, as the hardware does: overlapping copies repeat + # earlier elements rather than behaving like memmove. Flags are unchanged. + if i.op0_kind != K.MEMORY_ESRDI or (op in STRING_MOVES and i.op1_kind != K.MEMORY_SEG_RSI): + raise ValueError(f"unsupported 32-bit string addressing at {i.ip:#x}: {i}") + if i.has_repne_prefix: + raise ValueError(f"unsupported REPNE string move at {i.ip:#x}: {i}") + size = STRING_SIZES[op] + width = UINT[size] + if op in STRING_MOVES: + step = f"store<{width}>(rdi, load<{width}>(rsi)); rsi += {size}; rdi += {size};" + else: + step = f"store<{width}>(rdi, static_cast<{width}>(rax)); rdi += {size};" + stmt = f"while (rcx != 0) {{ {step} --rcx; }}" if i.has_rep_prefix else f"{{ {step} }}" + elif op == M.CLD: + # The Windows x64 ABI enters with DF clear, and only forward strings are lowered. + stmt = ";" elif op == M.NOP or (op == M.XCHG and i.op0_register == i.op1_register == R.AX): stmt = ";" elif op == M.SETE: diff --git a/tools/form_coverage.py b/tools/form_coverage.py index 8ca62ddf0..6c5f584c4 100644 --- a/tools/form_coverage.py +++ b/tools/form_coverage.py @@ -56,6 +56,7 @@ "address_size": "cpu_aot_address_size", "call_pair": "cpu_aot_call_pair", "bmi1": "cpu_aot_bmi1", + "string_ops": "cpu_aot_string_ops", "register_probe": None, # measurement harness "two_imports": None, # mapped and run unchanged by pe_map "exe_start": None, # mapped and run unchanged by pe_map