UTF-8 validation in x86-64: a scalar reference and an AVX2 version that checks 32 bytes per step. Every build fuzzes one against the other.
Stay a leaf: pad the tail in shadow space, not a stack frame
Browse filesThe push rbp / and rsp, -32 frame made utf8_valid_avx2 a frame function, and on Windows x64 a frame function needs unwind data in .pdata and .xdata. There was none, so a debugger, profiler or exception walking the stack through it would get lost. The caller's 32 bytes of shadow space hold exactly one block, so the frame can go. The function is 13 bytes shorter too.
failing
6 steps in 1 ms
1 file changed
+9−12
@@ -6,14 +6,17 @@
66 ; nibbles of the current and previous byte, flag every illegal pair of bytes
77 ; at once, and a saturating subtract checks the 3- and 4-byte lengths.
88 ;
9−; The last partial block is padded with spaces in an aligned slot on the
10−; stack.
9+; The function is a leaf and only touches volatile registers: ymm0-5 and
10+; rax, rcx, r8, r9. The last partial block is padded in the caller's shadow
11+; space.
1112 ;
1213 ; nasm -f win64 utf8_avx2.asm
1314
1415 default rel
1516 bits 64
1617
18+%define TAIL rsp + 8 ; 32 bytes of shadow space
19+
1720 section .rdata align=32
1821
1922 ; Error bits, one per kind of illegal sequence.
@@ -117,21 +120,15 @@ utf8_valid_avx2:
117120 .tail:
118121 test r9, r9
119122 jz .eof
120− push rbp ; an aligned slot for the last block
121− mov rbp, rsp
122− sub rsp, 32
123− and rsp, -32
124− vmovdqa ymm0, [spaces] ; pad it with ASCII
125− vmovdqa [rsp], ymm0
123+ vmovdqa ymm0, [spaces] ; pad the last block with ASCII
124+ vmovdqu [TAIL], ymm0
126125 xor eax, eax
127126 .copy: movzx ecx, byte [r8 + rax]
128− mov [rsp + rax], cl
127+ mov [TAIL + rax], cl
129128 inc rax
130129 cmp rax, r9
131130 jb .copy
132− vmovdqa ymm0, [rsp]
133− mov rsp, rbp
134− pop rbp
131+ vmovdqu ymm0, [TAIL]
135132 CHECK_BLOCK
136133 .eof:
137134 vpor ymm2, ymm2, ymm3 ; and the input may not stop mid-sequence