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.
AVX2: three nibble tables and a saturating subtract
Browse filesKeiser and Lemire's lookup algorithm, 32 bytes per step. The tables flag every illegal pair of adjacent bytes, and prev2 and prev3 minus 0x60 and 0x70 mark where a third or fourth byte has to be. The last partial block is padded with spaces in an aligned slot on the stack. Table 3-7 passes for both versions.
failing
6 steps in 1 ms
5 files changed
+171−13
@@ -1,9 +1,16 @@
11 # utf8-check
22
3−UTF-8 validation in x86-64 assembly. For now there is the reference: one byte at a time, with every range of Unicode table 3-7 spelled out.
3+UTF-8 validation in x86-64 assembly: a byte-at-a-time reference, and an AVX2 version that checks 32 bytes per step.
44
55 ```c
66 int utf8_valid_scalar(const uint8_t *buf, size_t len); // 1 = valid, 0 = not
7+int utf8_valid_avx2(const uint8_t *buf, size_t len);
78 ```
89
9−`test/test.c` checks it against the edges of the table: the first and last code point of every length, both sides of the surrogates, overlongs, and bytes that never appear.
10+`test/test.c` checks both against the edges of Unicode table 3-7. `bench/bench.c` times both on 64 MiB of ASCII and 64 MiB of mixed 1- to 4-byte text. The build runs both, so every build log has the numbers.
11+
12+## How the AVX2 version works
13+
14+Three 16-entry tables, indexed by the high and low nibbles of each byte's predecessor and by its own high nibble, give a bitmask of the errors that pair of bytes could be part of. ANDing the three leaves only the errors that actually happen. A saturating subtract of `0xE0 - 0x80` from the byte two back and `0xF0 - 0x80` from the byte three back marks where the third or fourth byte of a sequence must be, and an XOR with the tables' answer catches continuations that are missing or extra.
15+
16+The algorithm is Keiser and Lemire's, *Validating UTF-8 In Less Than One Instruction Per Byte* (2021).
@@ -3,15 +3,19 @@
33 [project]
44 isa = "x86-64"
55 assembler = "nasm"
6−target = "Windows x64 object"
6+target = "Windows x64 objects, AVX2"
77
88 [[step]]
99 name = "assemble the scalar reference"
1010 run = ["nasm", "-f", "win64", "-o", "build/utf8_scalar.obj", "src/utf8_scalar.asm"]
1111
12+[[step]]
13+name = "assemble AVX2"
14+run = ["nasm", "-f", "win64", "-o", "build/utf8_avx2.obj", "src/utf8_avx2.asm"]
15+
1216 [[step]]
1317 name = "build the tests"
14−run = ["gcc", "-O2", "-Wall", "-o", "build/test.exe", "test/test.c", "build/utf8_scalar.obj"]
18+run = ["gcc", "-O2", "-Wall", "-o", "build/test.exe", "test/test.c", "build/utf8_scalar.obj", "build/utf8_avx2.obj"]
1519
1620 [[step]]
1721 name = "table 3-7"
@@ -21,13 +25,14 @@ expect = "0 wrong"
2125
2226 [[step]]
2327 name = "build the benchmark"
24−run = ["gcc", "-O2", "-Wall", "-o", "build/bench.exe", "bench/bench.c", "build/utf8_scalar.obj"]
28+run = ["gcc", "-O2", "-Wall", "-o", "build/bench.exe", "bench/bench.c", "build/utf8_scalar.obj", "build/utf8_avx2.obj"]
2529
2630 [[step]]
27−name = "time it on 64 MiB"
31+name = "time both on 64 MiB"
2832 on = "windows"
2933 run = ["./build/bench.exe"]
3034 expect = "MiB of mixed text"
3135
3236 [artifact]
33−path = "build/utf8_scalar.obj"
37+path = "build/utf8_avx2.obj"
38+paths = ["build/utf8_scalar.obj"]
@@ -1,4 +1,4 @@
1−// bench.c: times the validator on 64 MiB of ASCII and 64 MiB of mixed
1+// bench.c: times both validators on 64 MiB of ASCII and 64 MiB of mixed
22 // 1- to 4-byte text, best of five runs each.
33 //
44 // build/bench.exe
@@ -9,6 +9,7 @@
99 #include <windows.h>
1010
1111 int utf8_valid_scalar(const uint8_t *buf, size_t len);
12+int utf8_valid_avx2(const uint8_t *buf, size_t len);
1213
1314 static uint64_t rng = 0x2545F4914F6CDD1Dull;
1415
@@ -78,7 +79,9 @@ static double best_of_five(int (*fn)(const uint8_t *, size_t), const uint8_t *bu
7879 static void race(const char *name, const uint8_t *buf, size_t n)
7980 {
8081 double scalar = best_of_five(utf8_valid_scalar, buf, n);
81− printf("%.1f MiB of %s: scalar %.2f GB/s\n", n / 1048576.0, name, n / scalar / 1e9);
82+ double avx2 = best_of_five(utf8_valid_avx2, buf, n);
83+ printf("%.1f MiB of %s: scalar %.2f GB/s, avx2 %.2f GB/s (%.1fx)\n",
84+ n / 1048576.0, name, n / scalar / 1e9, n / avx2 / 1e9, scalar / avx2);
8285 }
8386
8487 int main(void)
@@ -0,0 +1,136 @@
1+; utf8_avx2.asm: UTF-8 validation, 32 bytes per step.
2+;
3+; int utf8_valid_avx2(const uint8_t *buf, size_t len); 1 = valid, 0 = not
4+;
5+; The lookup algorithm of Keiser and Lemire: three 16-entry tables, indexed by
6+; nibbles of the current and previous byte, flag every illegal pair of bytes
7+; at once, and a saturating subtract checks the 3- and 4-byte lengths.
8+;
9+; The last partial block is padded with spaces in an aligned slot on the
10+; stack.
11+;
12+; nasm -f win64 utf8_avx2.asm
13+
14+ default rel
15+ bits 64
16+
17+ section .rdata align=32
18+
19+; Error bits, one per kind of illegal sequence.
20+%define TOO_SHORT 0x01
21+%define TOO_LONG 0x02
22+%define OVERLONG_3 0x04
23+%define TOO_LARGE 0x08
24+%define SURROGATE 0x10
25+%define OVERLONG_2 0x20
26+%define TOO_LARGE_1000 0x40
27+%define OVERLONG_4 0x40
28+%define TWO_CONTS 0x80
29+%define CARRY (TOO_SHORT | TOO_LONG | TWO_CONTS)
30+
31+ align 16
32+byte_1_high: ; indexed by the high nibble of the previous byte
33+ times 8 db TOO_LONG
34+ times 4 db TWO_CONTS
35+ db TOO_SHORT | OVERLONG_2
36+ db TOO_SHORT
37+ db TOO_SHORT | OVERLONG_3 | SURROGATE
38+ db TOO_SHORT | TOO_LARGE | TOO_LARGE_1000 | OVERLONG_4
39+
40+byte_1_low: ; indexed by the low nibble of the previous byte
41+ db CARRY | OVERLONG_3 | OVERLONG_2 | OVERLONG_4
42+ db CARRY | OVERLONG_2
43+ db CARRY
44+ db CARRY
45+ db CARRY | TOO_LARGE
46+ times 8 db CARRY | TOO_LARGE | TOO_LARGE_1000
47+ db CARRY | TOO_LARGE | TOO_LARGE_1000 | SURROGATE
48+ db CARRY | TOO_LARGE | TOO_LARGE_1000
49+ db CARRY | TOO_LARGE | TOO_LARGE_1000
50+
51+byte_2_high: ; indexed by the high nibble of the current byte
52+ times 8 db TOO_SHORT
53+ db TOO_LONG | OVERLONG_2 | TWO_CONTS | OVERLONG_3 | TOO_LARGE_1000 | OVERLONG_4
54+ db TOO_LONG | OVERLONG_2 | TWO_CONTS | OVERLONG_3 | TOO_LARGE
55+ db TOO_LONG | OVERLONG_2 | TWO_CONTS | SURROGATE | TOO_LARGE
56+ db TOO_LONG | OVERLONG_2 | TWO_CONTS | SURROGATE | TOO_LARGE
57+ times 4 db TOO_SHORT
58+
59+ align 32
60+nibble_mask: times 32 db 0x0F
61+third_byte: times 32 db 0xE0 - 0x80 ; only 111_____ stays >= 0x80
62+fourth_byte: times 32 db 0xF0 - 0x80 ; only 1111____ stays >= 0x80
63+high_bit: times 32 db 0x80
64+spaces: times 32 db 0x20
65+
66+ section .text
67+ global utf8_valid_avx2
68+
69+; One 32-byte block. In: ymm0 = block, ymm1 = previous block.
70+; Accumulates into ymm2 (errors).
71+%macro CHECK_BLOCK 0
72+ vperm2i128 ymm4, ymm1, ymm0, 0x21 ; [previous.hi | block.lo]
73+ vpalignr ymm5, ymm0, ymm4, 15 ; prev1: each byte's predecessor
74+ vpsrlw ymm3, ymm5, 4
75+ vpand ymm3, ymm3, [nibble_mask]
76+ vbroadcasti128 ymm4, [byte_1_high]
77+ vpshufb ymm3, ymm4, ymm3 ; byte_1_high[prev1 >> 4]
78+ vpand ymm5, ymm5, [nibble_mask]
79+ vbroadcasti128 ymm4, [byte_1_low]
80+ vpshufb ymm5, ymm4, ymm5 ; byte_1_low[prev1 & 15]
81+ vpand ymm3, ymm3, ymm5
82+ vpsrlw ymm5, ymm0, 4
83+ vpand ymm5, ymm5, [nibble_mask]
84+ vbroadcasti128 ymm4, [byte_2_high]
85+ vpshufb ymm5, ymm4, ymm5 ; byte_2_high[block >> 4]
86+ vpand ymm3, ymm3, ymm5 ; special cases
87+ vperm2i128 ymm4, ymm1, ymm0, 0x21
88+ vpalignr ymm5, ymm0, ymm4, 14 ; prev2
89+ vpsubusb ymm5, ymm5, [third_byte]
90+ vpalignr ymm4, ymm0, ymm4, 13 ; prev3
91+ vpsubusb ymm4, ymm4, [fourth_byte]
92+ vpor ymm4, ymm4, ymm5
93+ vpand ymm4, ymm4, [high_bit] ; must be a 2nd or 3rd continuation
94+ vpxor ymm4, ymm4, ymm3 ; ...exactly where the tables expect one
95+ vpor ymm2, ymm2, ymm4
96+%endmacro
97+
98+utf8_valid_avx2:
99+ mov r8, rcx ; cursor
100+ mov r9, rdx ; bytes left
101+ vpxor xmm1, xmm1, xmm1 ; the block before the first is all zeros
102+ vpxor xmm2, xmm2, xmm2
103+ cmp r9, 32
104+ jb .tail
105+.loop:
106+ vmovdqu ymm0, [r8]
107+ CHECK_BLOCK
108+ vmovdqa ymm1, ymm0
109+ add r8, 32
110+ sub r9, 32
111+ cmp r9, 32
112+ jae .loop
113+.tail:
114+ test r9, r9
115+ jz .eof
116+ push rbp ; an aligned slot for the last block
117+ mov rbp, rsp
118+ sub rsp, 32
119+ and rsp, -32
120+ vmovdqa ymm0, [spaces] ; pad it with ASCII
121+ vmovdqa [rsp], ymm0
122+ xor eax, eax
123+.copy: movzx ecx, byte [r8 + rax]
124+ mov [rsp + rax], cl
125+ inc rax
126+ cmp rax, r9
127+ jb .copy
128+ vmovdqa ymm0, [rsp]
129+ mov rsp, rbp
130+ pop rbp
131+ CHECK_BLOCK
132+.eof:
133+ vptest ymm2, ymm2
134+ setz al
135+ movzx eax, al
136+ ret
@@ -1,4 +1,4 @@
1−// test.c: the boundaries of Unicode table 3-7.
1+// test.c: the boundaries of Unicode table 3-7, for both versions.
22 //
33 // build/test.exe
44
@@ -7,6 +7,7 @@
77 #include <string.h>
88
99 int utf8_valid_scalar(const uint8_t *buf, size_t len);
10+int utf8_valid_avx2(const uint8_t *buf, size_t len);
1011
1112 static const struct {
1213 const char *bytes;
@@ -41,13 +42,19 @@ static const struct {
4142
4243 int main(void)
4344 {
45+ if (!__builtin_cpu_supports("avx2")) {
46+ puts("this CPU has no AVX2; nothing to test");
47+ return 2;
48+ }
4449 int wrong = 0;
4550 for (size_t i = 0; i < SAMPLES; i++) {
46− int got = utf8_valid_scalar((const uint8_t *)samples[i].bytes, strlen(samples[i].bytes));
47− if (got == samples[i].valid)
51+ const uint8_t *p = (const uint8_t *)samples[i].bytes;
52+ size_t n = strlen(samples[i].bytes);
53+ int a = utf8_valid_scalar(p, n), b = utf8_valid_avx2(p, n);
54+ if (a == samples[i].valid && b == samples[i].valid)
4855 continue;
4956 wrong++;
50− printf("wrong: %s: got %d\n", samples[i].what, got);
57+ printf("wrong: %s: scalar %d, avx2 %d\n", samples[i].what, a, b);
5158 }
5259 printf("cases: %zu samples, %d wrong\n", SAMPLES, wrong);
5360 return wrong != 0;