Skip to content

Commit 6ecf8ce

Browse files
committed
gh-124951: Use SSSE3 for base64 in binascii on x86-64
Encode and decode blocks of standard-alphabet base64 with SSSE3 before handing the rest of the input to the existing scalar loops. Those loops still handle the tail, padding, invalid characters and errors, so results and exceptions are unchanged. SSSE3 is part of x86-64-v2. A build that already targets it calls the kernels directly; otherwise they are compiled with a function target attribute and selected at run time with __builtin_cpu_supports(). This covers GCC and Clang; other compilers keep the scalar code. For 64 KiB inputs on an AMD Zen 2 with GCC 15, b2a_base64() goes from 2.2 to 9.5 GB/s and a2b_base64() from 1.8 to 6.9 GB/s. test_base64_long_inputs is adapted from Justin Bennington's GH-162443. Co-authored with Claude Fable 5.2.
1 parent a32f37e commit 6ecf8ce

4 files changed

Lines changed: 199 additions & 2 deletions

File tree

‎Doc/whatsnew/3.16.rst‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1165,6 +1165,16 @@ ast
11651165
in :gh:`153568`.)
11661166

11671167

1168+
base64 and binascii
1169+
-------------------
1170+
1171+
* Base64 encoding and decoding with the standard alphabet use SSSE3
1172+
instructions on x86-64 CPUs that support them (everything since 2014).
1173+
For inputs of 64 KiB, :func:`base64.b64encode` and :func:`base64.b64decode`
1174+
are about 4 times faster.
1175+
(Contributed by Gregory P. Smith in :gh:`124951`.)
1176+
1177+
11681178
datetime and time
11691179
-----------------
11701180

‎Lib/test/test_binascii.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,43 @@ def test_base64_alphabet(self):
454454
with self.assertRaises(TypeError):
455455
binascii.a2b_base64(data, alphabet=bytearray(alphabet))
456456

457+
def test_base64_long_inputs(self):
458+
# Cover all lengths and positions of a bad character across the
459+
# block sizes of the vectorized code paths.
460+
alphabets = [
461+
(b'!"#$%&\'()*+,-012345689@'
462+
b'ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr'),
463+
bytes(range(0x80, 0xc0)),
464+
]
465+
raw = bytes(range(256)) * 2
466+
for n in range(len(raw) + 1):
467+
data = self.type2test(raw[:n])
468+
encoded = binascii.b2a_base64(data, newline=False)
469+
self.assertEqual(binascii.a2b_base64(encoded), raw[:n])
470+
for alphabet in alphabets:
471+
encoded = binascii.b2a_base64(data, newline=False,
472+
alphabet=alphabet)
473+
decoded = binascii.a2b_base64(encoded, alphabet=alphabet)
474+
self.assertEqual(decoded, raw[:n])
475+
476+
encoded = binascii.b2a_base64(raw[:150], newline=False)
477+
for i in range(len(encoded) + 1):
478+
for c in b'*', b'\x80':
479+
bad = self.type2test(encoded[:i] + c + encoded[i:])
480+
self.assertEqual(binascii.a2b_base64(bad), raw[:150])
481+
with self.assertRaises(binascii.Error):
482+
binascii.a2b_base64(bad, strict_mode=True)
483+
484+
# Every byte outside the alphabet in every position of a block.
485+
invalid = bytes(set(range(256)) - set(binascii.BASE64_ALPHABET)
486+
- set(b'='))
487+
for i in range(64, 80):
488+
for c in invalid:
489+
bad = self.type2test(encoded[:i] + bytes([c]) + encoded[i:])
490+
self.assertEqual(binascii.a2b_base64(bad), raw[:150])
491+
with self.assertRaises(binascii.Error):
492+
binascii.a2b_base64(bad, strict_mode=True)
493+
457494
def test_ascii85_valid(self):
458495
# Test Ascii85 with valid data
459496
ASCII85_PREFIX = b"<~"
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Speed up base64 encoding and decoding with the standard alphabet in
2+
:mod:`binascii` and :mod:`base64` on x86-64 CPUs that support SSSE3.
3+
Large inputs are up to 4 times faster.

‎Modules/binascii.c‎

Lines changed: 149 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@
6363
#ifdef USE_ZLIB_CRC32
6464
# include "zlib.h"
6565
#endif
66+
#if defined(__x86_64__) && defined(__GNUC__)
67+
# include <tmmintrin.h> // SSSE3 intrinsics
68+
# define BASE64_HAVE_SSSE3 1
69+
#endif
6670

6771
typedef struct binascii_state {
6872
PyObject *Error;
@@ -127,13 +131,146 @@ base64_encode_trio(const unsigned char *in, unsigned char *out,
127131
out[3] = table[combined & 0x3f];
128132
}
129133

134+
#ifdef BASE64_HAVE_SSSE3
135+
/*
136+
* SSSE3 base64 kernels for x86-64, standard alphabet only.
137+
*
138+
* PSHUFB serves both as a byte shuffle and as a 16-entry lookup table,
139+
* which stands in for the per-character table lookups of the scalar code.
140+
* The method is described in W. Mula and D. Lemire, "Faster Base64 Encoding
141+
* and Decoding using AVX2 Instructions", ACM TOW 12(3), 2018.
142+
*
143+
* Each kernel handles a prefix of its input and returns how much of it was
144+
* consumed. The scalar loops finish the rest and remain the reference for
145+
* behaviour: padding, characters outside the alphabet and errors are never
146+
* handled here. Neither kernel reads outside [in, in + in_len) or writes
147+
* more than the scalar code would for the consumed prefix.
148+
*
149+
* SSSE3 is part of x86-64-v2. A build that does not target it compiles
150+
* the kernels with a function target attribute and checks the CPU at run
151+
* time.
152+
*/
153+
# ifdef __SSSE3__
154+
# define BASE64_SSSE3_TARGET
155+
# define base64_cpu_has_ssse3() 1
156+
# else
157+
# define BASE64_SSSE3_TARGET __attribute__((target("ssse3")))
158+
# define base64_cpu_has_ssse3() __builtin_cpu_supports("ssse3")
159+
# endif
160+
161+
/* Encode groups of 12 bytes into 16 characters. Every step loads 16
162+
* bytes, so at least the last 4 bytes of the input are left to the caller.
163+
* Returns the number of bytes consumed.
164+
*/
165+
BASE64_SSSE3_TARGET static Py_ssize_t
166+
base64_encode_ssse3(const unsigned char *in, Py_ssize_t in_len,
167+
unsigned char *out)
168+
{
169+
/* Put each group [b0 b1 b2] in a 32-bit lane as [b1 b0 b2 b1], so
170+
* that every 6-bit field lies within one 16-bit half of the lane. */
171+
const __m128i spread = _mm_setr_epi8(
172+
1, 0, 2, 1, 4, 3, 5, 4, 7, 6, 8, 7, 10, 9, 11, 10);
173+
/* The difference between a character and its 6-bit value. The index
174+
* is 13 for 0..25 (A-Z), 0 for 26..51 (a-z), 1..10 for 52..61 (0-9),
175+
* 11 for 62 (+) and 12 for 63 (/). */
176+
const __m128i offsets = _mm_setr_epi8(
177+
'a' - 26, '0' - 52, '0' - 52, '0' - 52, '0' - 52, '0' - 52,
178+
'0' - 52, '0' - 52, '0' - 52, '0' - 52, '0' - 52, '+' - 62,
179+
'/' - 63, 'A', 0, 0);
180+
Py_ssize_t done = 0;
181+
182+
for (; in_len - done >= 16; done += 12, out += 16) {
183+
__m128i x = _mm_loadu_si128((const __m128i *)(in + done));
184+
x = _mm_shuffle_epi8(x, spread);
185+
/* Move each 6-bit field into a byte of its own. A multiply shifts
186+
* the two 16-bit halves of a lane by different amounts: the high
187+
* product shifts right by 10 and 6, the low one left by 4 and 8. */
188+
__m128i ac = _mm_mulhi_epu16(
189+
_mm_and_si128(x, _mm_set1_epi32(0x0fc0fc00)),
190+
_mm_set1_epi32(0x04000040));
191+
__m128i bd = _mm_mullo_epi16(
192+
_mm_and_si128(x, _mm_set1_epi32(0x003f03f0)),
193+
_mm_set1_epi32(0x01000010));
194+
__m128i v = _mm_or_si128(ac, bd);
195+
__m128i idx = _mm_subs_epu8(v, _mm_set1_epi8(51));
196+
__m128i upper = _mm_cmpgt_epi8(_mm_set1_epi8(26), v);
197+
idx = _mm_or_si128(idx, _mm_and_si128(upper, _mm_set1_epi8(13)));
198+
v = _mm_add_epi8(v, _mm_shuffle_epi8(offsets, idx));
199+
_mm_storeu_si128((__m128i *)out, v);
200+
}
201+
return done;
202+
}
203+
204+
/* Decode blocks of 16 characters into 12 bytes. Stops before the first
205+
* block containing a character outside the alphabet, which is left for the
206+
* caller to deal with. Returns the number of characters consumed.
207+
*/
208+
BASE64_SSSE3_TARGET static Py_ssize_t
209+
base64_decode_ssse3(const unsigned char *in, Py_ssize_t in_len,
210+
unsigned char *out)
211+
{
212+
/* A character is in the alphabet iff the entries selected by its low
213+
* and high nibbles have no bit in common. */
214+
const __m128i lut_lo = _mm_setr_epi8(
215+
0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
216+
0x11, 0x11, 0x13, 0x1a, 0x1b, 0x1b, 0x1b, 0x1a);
217+
const __m128i lut_hi = _mm_setr_epi8(
218+
0x10, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08,
219+
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10);
220+
/* The difference between a 6-bit value and its character, indexed by
221+
* the high nibble. '/' shares its high nibble with '+' and uses
222+
* index 1 instead. */
223+
const __m128i lut_roll = _mm_setr_epi8(
224+
0, 16, 19, 4, -65, -65, -71, -71, 0, 0, 0, 0, 0, 0, 0, 0);
225+
/* Reverse the low 3 bytes of each 32-bit lane and drop the fourth. */
226+
const __m128i pack = _mm_setr_epi8(
227+
2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1);
228+
const __m128i nibble = _mm_set1_epi8(0x0f);
229+
Py_ssize_t done = 0;
230+
231+
for (; in_len - done >= 16; done += 16, out += 12) {
232+
__m128i x = _mm_loadu_si128((const __m128i *)(in + done));
233+
__m128i lo = _mm_and_si128(x, nibble);
234+
__m128i hi = _mm_and_si128(_mm_srli_epi32(x, 4), nibble);
235+
__m128i bad = _mm_and_si128(_mm_shuffle_epi8(lut_lo, lo),
236+
_mm_shuffle_epi8(lut_hi, hi));
237+
if (_mm_movemask_epi8(_mm_cmpgt_epi8(bad, _mm_setzero_si128()))) {
238+
break;
239+
}
240+
/* The comparison gives -1 for '/', which turns its index 2 into 1. */
241+
__m128i slash = _mm_cmpeq_epi8(x, _mm_set1_epi8('/'));
242+
x = _mm_add_epi8(x, _mm_shuffle_epi8(lut_roll,
243+
_mm_add_epi8(hi, slash)));
244+
/* Merge the 6-bit values pairwise into 12 bits, then 24 bits. */
245+
x = _mm_maddubs_epi16(x, _mm_set1_epi32(0x01400140));
246+
x = _mm_madd_epi16(x, _mm_set1_epi32(0x00011000));
247+
x = _mm_shuffle_epi8(x, pack);
248+
/* Store exactly 12 bytes. */
249+
_mm_storel_epi64((__m128i *)out, x);
250+
int last = _mm_cvtsi128_si32(_mm_srli_si128(x, 8));
251+
memcpy(out + 8, &last, 4);
252+
}
253+
return done;
254+
}
255+
#endif /* BASE64_HAVE_SSSE3 */
256+
130257
/* Encode multiple complete 3-byte groups.
131258
* Returns the number of input bytes processed (always a multiple of 3).
132259
*/
133260
static inline Py_ssize_t
134261
base64_encode_fast(const unsigned char *in, Py_ssize_t in_len,
135262
unsigned char *out, const unsigned char *table)
136263
{
264+
Py_ssize_t done = 0;
265+
#ifdef BASE64_HAVE_SSSE3
266+
if (table == table_b2a_base64 && in_len >= 16 && base64_cpu_has_ssse3()) {
267+
done = base64_encode_ssse3(in, in_len, out);
268+
in += done;
269+
out += done / 3 * 4;
270+
in_len -= done;
271+
}
272+
#endif
273+
137274
Py_ssize_t n_trios = in_len / 3;
138275
const unsigned char *in_end = in + n_trios * 3;
139276

@@ -143,7 +280,7 @@ base64_encode_fast(const unsigned char *in, Py_ssize_t in_len,
143280
out += 4;
144281
}
145282

146-
return n_trios * 3;
283+
return done + n_trios * 3;
147284
}
148285

149286
/* Decode 4 base64 characters into 3 bytes.
@@ -176,6 +313,16 @@ static inline Py_ssize_t
176313
base64_decode_fast(const unsigned char *in, Py_ssize_t in_len,
177314
unsigned char *out, const unsigned char *table)
178315
{
316+
Py_ssize_t done = 0;
317+
#ifdef BASE64_HAVE_SSSE3
318+
if (table == table_a2b_base64 && in_len >= 16 && base64_cpu_has_ssse3()) {
319+
done = base64_decode_ssse3(in, in_len, out);
320+
in += done;
321+
out += done / 4 * 3;
322+
in_len -= done;
323+
}
324+
#endif
325+
179326
Py_ssize_t n_quads = in_len / 4;
180327
Py_ssize_t i;
181328

@@ -185,7 +332,7 @@ base64_decode_fast(const unsigned char *in, Py_ssize_t in_len,
185332
}
186333
}
187334

188-
return i * 4;
335+
return done + i * 4;
189336
}
190337

191338

0 commit comments

Comments
 (0)