iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🛠

s_xbyak: An Xbyak-like static x64 assembly generator

に公開

Introduction

This is a tool I created in Python for those (myself included) who have grown accustomed to the x64 JIT assembler Xbyak and want to write static assembly language (ASM) in an Xbyak-like style.
The "s_" in s_xbyak stands for "static."

Features of s_xbyak

Background

I created Xbyak because I wanted to write JIT code in C++. I soon realized that being able to write ASM using C++ syntax was incredibly convenient, not just for JIT, but for static code as well. Existing assembler syntaxes are often restrictive, and memorizing pseudo-instructions is a hassle. Once I got used to Xbyak, I no longer wanted to use standard assemblers.

However, since Xbyak is for JIT code generation, the only way to use it for static ASM was a forced approach: dumping the JIT-generated binary and embedding it using db instructions. That's why I created s_xbyak, a static ASM generation tool. I chose Python instead of C++ for ease of use. I initially only planned to support NASM, but I later added GAS and MASM support because being able to use it just by having gcc or Visual Studio installed is quite convenient. In return, struggling to abstract away the differences has been quite a challenge—but that's a story for next time.

Example 1. Addition Function

Let's start with a sample addition function, add.py, to see what this can do.

# add.py
from s_xbyak import *

parser = getDefaultParser()
param = parser.parse_args()

init(param)
segment('text')
with FuncProc('add2'):
  with StackFrame(2) as sf:
    x = sf.p[0]
    y = sf.p[1]
    lea(rax, ptr(x + y))

term()

Explanation:

  • from s_xbyak import * : Imports s_xbyak.
  • getDefaultParser() : Sets default command-line arguments.
    • -win : Uses Win64 ABI (default is AMD64).
    • -m (gas|nasm|masm) : Sets the output ASM format (default is nasm).
  • parser.parse_args() : Parses command-line arguments and returns the result as a dictionary param.
    • param contains win : bool and mode : str.
  • init(param) : Initializes based on param.
  • segment('text') : Starts the text segment.
  • with FuncProc('add2'): : Declares a function named add2.
  • with StackFrame(2) as sf : Prepares a stack frame for a function with two integer arguments.
    • Note: Currently, 0 to 4 can be specified. Only integer or pointer types are supported for function arguments.
  • x = sf.p[0] : Names the first function argument register as x.
  • y = sf.p[1] : Names the second function argument register as y.
  • lea(rax, ptr(x + y)) : Assigns the result of x + y to rax.
    • In Xbyak, we used ptr[...] for memory references, but in s_xbyak, we use ptr(...) (a difference from Xbyak).
    • ret is inserted automatically when the StackFrame scope ends.
  • term() : Ends the output.

How to use add.py

python3 add.py [-win][-m mode]

Output for Linux GAS

python3 add.py -m gas > add_s.S
gcc -c add_s.S
# for gas
#ifdef __linux__
  #define PRE(x) x
  #define TYPE(x) .type x, @function
  #define SIZE(x) .size x, .-x
#else
  #ifdef _WIN32
    #define PRE(x) x
  #else
    #define PRE(x) _ ## x
  #endif
  #define TYPE(x)
  #define SIZE(x)
#endif
.text
.global PRE(add2)
PRE(add2):
TYPE(add2)
lea (%rdi,%rsi,1), %rax
ret
SIZE(add2)

The PRE, TYPE, and SIZE macros are used to absorb differences between Linux, Intel macOS, and Windows. Please use the uppercase extension *.S rather than *.s to ensure gcc recognizes the macros. The part corresponding to lea(rax, ptr(x + y)) in s_xbyak is rendered as lea (%rdi,%rsi,1), %rax.

Output for Windows MASM

python3 add.py -m masm > add_s.asm
ml64 /c add_s.asm
; for masm (ml64.exe)
_text segment
add2 proc export
lea rax, [rcx+rdx]
ret
add2 endp
_text ends
end

According to the Win64 ABI, lea(rax, ptr(x + y)) has been expanded to lea rax, [rcx+rdx].

Output for NASM

For AMD64 (Linux):

python3 add.py -m nasm > add_s.nasm
nasm -f elf64 add_s.nasm

For Windows:

python3 add.py -m nasm -win > add_s.nasm
nasm -f win64_s.nasm

Example 2. Using AVX

void add_avx(float *z, const float *x, const float *y, size_t n)
{
  assert(n > 0 && (n % 4) == 0);
  for (size_t i = 0; i < n; i++) z[i] = x[i] + y[i];
}

Let's implement this function using AVX. For simplicity, we will omit handling remainders (assume n is a positive multiple of 4). Here is the function body extracted:

  with FuncProc('add_avx'):
     with StackFrame(4, vNum=1, vType=T_XMM) as sf:
      pz = sf.p[0]
      px = sf.p[1]
      py = sf.p[2]
      n = sf.p[3]
      lpL = Label()

      L(lpL)
      vmovups(xmm0, ptr(px))
      vaddps(xmm0, xmm0, ptr(py))
      vmovups(ptr(pz), xmm0)
      add(px, 16)
      add(py, 16)
      add(pz, 16)
      sub(n, 4)
      jnz(lpL)

Explanation:

  • with StackFrame(4, vNum=1, vType=T_XMM) as sf:
    • vNum=1 : Uses 1 SIMD register.
    • vType=T_XMM : Uses XMM registers.
      • These values affect the saving/restoring of SIMD registers.

Similar to the addition function, if you generate assembly from this code and call it from C++, it will work as expected. Note that this example is for demonstrating AVX and is not optimized for speed.

Example 3. Memory References

mem.py

  init(param)
  segment('data')
  global_('g_x')
  dd_(123)
  segment('text')

  with FuncProc('inc_and_add'):
    with StackFrame(1) as sf:
      inc(dword(rip+'g_x'))
      y = sf.p[0]
      mov(eax, ptr(rip+'g_x'))
      add(rax, y)

  term()

Explanation:

  • segment('data') : Sets the data segment.
  • global_('g_x') : Makes the name g_x accessible from other files.
  • dd_(123) : Places a 32-bit integer.
    • db_ : 8-bit
    • dw_ : 16-bit
    • dd_ : 32-bit
    • dq_ : 64-bit
  • inc(dword(rip+'g_x')) : Specify dword instead of ptr for inc on memory to indicate the size.
    • byte : 1 byte
    • word : 2 bytes
    • dword : 4 bytes
    • qword : 8 bytes
  • Access variable g_x in the form rip + name. This uses RIP-relative addressing, allowing it to work across Linux/Windows/Intel macOS.

Example 4. AVX-512

Merging Masking

Mask registers k1 through k7 are used.

  • vaddps(xmm1 | k1, xmm2, xmm3)
  • vmovups(ptr(rax+rcx*4+123)|k1, zmm0)

Zeroing Masking

  • vsubps(ymm0 | k4 | T_z, ymm1, ymm2)

Broadcasting

  • vmulps(zmm0, zmm1, ptr_b(rax))
    • Similar to Xbyak, ptr_b automatically determines the {1toX} factor.

Rounding Control

  • vdivps(zmm0, zmm1, zmm2|T_rz_sae)

Exception Suppression

  • vmaxss(xmm1, xmm2, xmm3|T_sae)

Distinguishing m128 and m256

Use xword (128-bit), yword (256-bit), or zword (512-bit) instead of ptr or ptr_b when you need to specify memory size.

vcvtpd2dq(xmm16, xword (eax+32)) # m128
vcvtpd2dq(xmm0, yword (eax+32)) # m256
vcvtpd2dq(xmm21, ptr_b (eax+32)) # m128 + broadcast
vcvtpd2dq(xmm19, yword_b (eax+32)) # m256 + broadcast

Other Examples

For more detailed usage, please refer to test/misc.py or test/string.py.

Conclusion

I introduced s_xbyak, an assembly generation tool. I have already begun rewriting parts of my own projects, such as mcl and fmath, using s_xbyak.
There may be breaking changes in syntax until it stabilizes, but if you are interested, I would appreciate it if you could try it out and share your feedback.

GitHubで編集を提案

Discussion