iTranslated by AI
Implementing Arbitrary-Precision Integers Part 7: Assembly Code Generation via Xbyak-like Python DSL
Introduction
In my previous article, Implementation of Arbitrary-Precision Integers 6 (Multiply-Accumulate and Limits of Intrinsics), I introduced the limitations of compiler intrinsic functions. Since there is no other choice, we must implement these in assembly language (hereafter referred to as asm). This time, I will introduce a simple DSL I created in Python that helps with this task by generating assembly code. For a list of all articles in this series, see Implementation of Arbitrary-Precision Integers 1 (C/C++).
Motivation
I developed Xbyak because I wanted to perform runtime code generation at the assembly language level using C++. While JIT code generation is its main feature, it was unexpectedly convenient to be able to write asm code using the C++ syntax I am accustomed to. After 15 years of development and personal use, I can no longer bring myself to write assembly using standard tools like nasm or gas, because it is tedious to look up the individual pseudo-instructions and macro syntaxes for each one.
However, Xbyak performs runtime code generation, making it overkill for writing static code like in this project. Yet, even when writing static assembly, I still want to use the language syntax I know well (C++ or Python) rather than the syntax of individual assemblers. Therefore, I created a Python DSL that allows the use of only the minimum features necessary for implementing arbitrary-precision integers. That is gen_x86asm.py.
Introduction to gen_x86asm.py
As mentioned above, it only has the bare minimum features, but it can do the following:
- Support for Linux AMD64 and Win64 calling conventions
- Generation of code compatible with gas, NASM, and MASM (ml64.exe)
At first, I thought NASM alone would suffice, but I added support for gas and MASM because they are standard and quite useful during the build process (though reconciling their differences is rather tedious).
Example of add
Let's take a look at a sample.
from gen_x86asm import *
import argparse
def gen_add(N):
align(16)
with FuncProc(f'mclb_add{N}'):
with StackFrame(3) as sf:
z = sf.p[0]
x = sf.p[1]
y = sf.p[2]
for i in range(N):
mov(rax, ptr(x + 8 * i))
if i == 0:
add(rax, ptr(y + 8 * i))
else:
adc(rax, ptr(y + 8 * i))
mov(ptr(z + 8 * i), rax)
setc(al)
movzx(eax, al)
parser = argparse.ArgumentParser()
parser.add_argument('-win', '--win', help='output win64 abi', action='store_true')
parser.add_argument('-m', '--mode', help='output asm syntax', default='nasm')
param = parser.parse_args()
setWin64ABI(param.win)
init(param.mode)
segment('text')
gen_add(3)
term()
This is code to generate an addition function for N-digit numbers: Unit add(Unit *z, const Unit *x, const Unit *y);.
setWin64ABI(true or false)
Sets whether to use the Win64 ABI or the Linux AMD64 ABI.
init(mode) # mode in ['gas', 'nasm', 'masm']
Specifies the assembly language to output.
segment('text')
Specifies that functions (code) will be written from this point, and gen_add(3) generates an add function for 3-digit numbers.
with FuncProc(f'mclb_add{N}'):
Indicates the start of the function.
with StackFrame(3) as sf:
Generates a stack frame with 3 arguments.
z = sf.p[0]
x = sf.p[1]
y = sf.p[2]
sf.p[i] refers to the i-th register for the function. I give them names for readability.
for i in range(N):
mov(rax, ptr(x + 8 * i))
if i == 0:
add(rax, ptr(y + 8 * i))
else:
adc(rax, ptr(y + 8 * i))
mov(ptr(z + 8 * i), rax)
As introduced in Implementation of Arbitrary-Precision Integers 2 (Xbyak),
mov(rax, ptr(x + 8 * i))
loads the value of x[i] into rax. In Xbyak, it is ptr[...], but in this Python script, it is ptr(...).
setc(al)
movzx(eax, al)
Sets the output value. A ret instruction is inserted when exiting the sf block.
Output Example
If you run the following against this file (gen_add.py):
python3 gen_add.py -m gas
The output will be:
# for gas
.text
.align 16
.global mclb_add3
.global _mclb_add3
mclb_add3:
_mclb_add3:
mov (%rsi), %rax
add (%rdx), %rax
mov %rax, (%rdi)
mov 8(%rsi), %rax
adc 8(%rdx), %rax
mov %rax, 8(%rdi)
mov 16(%rsi), %rax
adc 16(%rdx), %rax
mov %rax, 16(%rdi)
setc %al
movzx %al, %eax
ret
.global mclb_add3
.global _mclb_add3
These lines make the mclb_add3 function accessible from outside. The presence or absence of an underscore is due to the different requirements between Linux and macOS. I debated whether to make this switchable via macros or options, but opted for simplicity.
mov (%rsi), %rax
add (%rdx), %rax
mov %rax, (%rdi)
mov 8(%rsi), %rax
adc 8(%rdx), %rax
...
As you can see, it correctly uses registers according to the AMD64 ABI. Next, if you run:
python3 gen_add.py -m masm -win
The output will be:
; for masm (ml64.exe)
_text segment
align 16
mclb_add3 proc export
mov rax, [rdx]
add rax, [r8]
mov [rcx], rax
mov rax, [rdx+8]
adc rax, [r8+8]
mov [rcx+8], rax
mov rax, [rdx+16]
adc rax, [r8+16]
mov [rcx+16], rax
setc al
movzx eax, al
ret
mclb_add3 endp
_text ends
end
Where it was .text for gas, it is now _text segment, and:
mclb_add3 proc export
You can see that the way the function is exported is different. The registers also conform to the Win64 ABI. The end of the code is also correctly output as:
mclb_add3 endp
_text ends
end
Convenient, isn't it? (Self-praise).
In the case of mulUnitAdd
The function mulUnitAdd(z, x, y) (meaning z[] += x[] * y), which I gave up on in Implementation of Arbitrary-Precision Integers 6 (Multiply-Accumulate and Limits of Intrinsics) and which combines mulx and adox, can be written as follows:
with FuncProc(f'mclb_mulUnitAdd{N}'):
with StackFrame(3, 2, useRDX=True) as sf:
z = sf.p[0]
x = sf.p[1]
y = sf.p[2]
t = sf.t[0]
L = sf.t[1]
mov(rdx, y)
xor_(eax, eax)
mov(t, ptr(z))
for i in range(N):
mulx(rax, L, ptr(x + i * 8))
adox(t, L)
mov(ptr(z + i * 8), t)
if i == N-1:
break
mov(t, ptr(z + (i+1) * 8))
adcx(t, rax)
mov(t, 0)
adcx(rax, t)
adox(rax, t)
I will explain StackFrame(3, 2, useRDX=True). This specifies that the function has 3 arguments and 2 temporary registers, and that rdx should be used explicitly. Temporary registers are used by giving them desired names as follows:
t = sf.t[0]
L = sf.t[1]
If you use a register that shouldn't be modified, it is automatically saved to and restored from the stack.
If you do not specify useRDX=True, it may conflict with the arguments assigned by the ABI (which use rdx), causing errors. For other examples, please refer to gen_bint_x64.py.
Usage in mcl
I have now implemented add, sub, mulUnit, and mulUnitAdd. In mcl, these functions can be used in forms such as addT<N> and mulUnitT<N> (the namespace is mcl::bint).
Multiplication of N-digit by N-digit numbers also works as is:
// z[2N] = x[N] * y[N]
template<size_t N>
void mulT(Unit *pz, const Unit *px, const Unit *py)
{
pz[N] = mulUnitT<N>(pz, px, py[0]);
for (size_t i = 1; i < N; i++) {
pz[N + i] = mulUnitAddT<N>(&pz[i], px, py[i]);
}
}
Benchmark
In pairing-based cryptography and elliptic curve cryptography, multiplications like 256bit×256bit→512bit or 384bit×384bit→768bit are used (corresponding to mulT<4> or mulT<6> above). Let's compare them with mpn_mul_n of GNU GMP, which is commonly used in cryptographic implementations.
The environment is:
- CPU: Xeon Platinum 8280 CPU 2.70GHz (turbo boost off)
- OS: Ubuntu 20.04.4 LTS
- compiler: gcc 9.4.0
| mulT<N> | GMP | mcl (clk) |
|---|---|---|
| N = 4 | 137 | 92 |
| N = 6 | 251 | 206 |
It is about 1.2 to 1.5 times faster. It is quite good performance for such a simple implementation (it can be made several times faster with a serious implementation; that's for another time).
Discussion