pgsql: Optimise non-native 128-bit addition in int128.h.

From: Dean Rasheed <dean(dot)a(dot)rasheed(at)gmail(dot)com>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Optimise non-native 128-bit addition in int128.h.
Date: 2025-08-07 08:23:22
Message-ID: E1ujvuD-001BxY-2T@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Optimise non-native 128-bit addition in int128.h.

On platforms without native 128-bit integer support, simplify the test
for carry in int128_add_uint64() by noting that the low-part addition
is unsigned integer arithmetic, which is just modular arithmetic.
Therefore the test for carry can simply be written as "new value < old
value" (i.e., a test for modular wrap-around). This can then be made
branchless so that on modern compilers it produces the same machine
instructions as native 128-bit addition, making it significantly
simpler and faster.

Similarly, the test for carry in int128_add_int64() can be written in
much the same way, but with an extra term to compensate for the sign
of the value being added. Again, on modern compilers this leads to
branchless code, often identical to the native 128-bit integer
addition machine code.

Author: Dean Rasheed <dean(dot)a(dot)rasheed(at)gmail(dot)com>
Reviewed-by: John Naylor <johncnaylorls(at)gmail(dot)com>
Discussion: https://postgr.es/m/CAEZATCWgBMc9ZwKMYqQpaQz2X6gaamYRB+RnMsUNcdMcL2Mj_w@mail.gmail.com

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/d9bb8ef093d62763cfd19d37e6bb8182998a3f88

Modified Files
--------------
src/include/common/int128.h | 36 ++++++++++++++++--------------------
1 file changed, 16 insertions(+), 20 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Dean Rasheed 2025-08-07 08:54:20 pgsql: Simplify non-native 64x64-bit multiplication in int128.h.
Previous Message Michael Paquier 2025-08-07 02:50:01 pgsql: Improve tests of date_trunc() with infinity and unsupported unit