https://github.com/python/cpython/commit/e4dba41b6d6fcf2647b7359d5afeae41f296881d
commit: e4dba41b6d6fcf2647b7359d5afeae41f296881d
branch: main
author: Pieter Eendebak <[email protected]>
committer: StanFromIreland <[email protected]>
date: 2026-11-02T17:31:33Z
summary:

gh-161127: Let compilers vectorize `v_complement()` (#161128)

files:
M Objects/longobject.c

diff --git a/Objects/longobject.c b/Objects/longobject.c
index f5526213944011..564f9601bbfde4 100644
--- a/Objects/longobject.c
+++ b/Objects/longobject.c
@@ -5554,14 +5554,20 @@ _PyLong_Lshift(PyObject *a, int64_t shiftby)
 static void
 v_complement(digit *z, digit *a, Py_ssize_t m)
 {
-    Py_ssize_t i;
-    digit carry = 1;
-    for (i = 0; i < m; ++i) {
-        carry += a[i] ^ PyLong_MASK;
-        z[i] = carry & PyLong_MASK;
-        carry >>= PyLong_SHIFT;
+    Py_ssize_t i = 0;
+
+    /* -a is ~a + 1, and the +1 only carries through the trailing zero
+       digits: they stay zero, the first nonzero digit is negated, and the
+       digits above it are just inverted.  No carry is passed between
+       iterations of the last loop, so it can be vectorized. */
+    while (i < m && a[i] == 0) {
+        z[i++] = 0;
+    }
+    assert(i < m);
+    z[i] = (0U - a[i]) & PyLong_MASK;
+    for (++i; i < m; ++i) {
+        z[i] = a[i] ^ PyLong_MASK;
     }
-    assert(carry == 0);
 }
 
 /* Bitwise and/xor/or operations */

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to