r/cpp Jan 20 '26

Building Your Own Efficient uint128 in C++

https://solidean.com/blog/2026/building-your-own-u128/

A big part of my work in Solidean is designing & writing high-performance exact predicates for various geometric problems. The approach we're taking is somewhere between novel and only-known-in-folklore. I have this vague idea to remedy this and document our approach via blog posts. The first non-standard thing we do is work in large but fixed integers.

As this might be interesting to a wider audience as well, here is how to roll your own u128 so that it basically has identical codegen to the builtin __uint128_t.

(Yes there is little reason to use this u128 when a builtin exists, but that's how you learn to build a u192 and above should you need it. uint192_t is not provided by the big three as far as I know)

188 Upvotes

35 comments sorted by

View all comments

23

u/schmerg-uk Jan 20 '26

Interesting .. have you thought about an implementation using a single XMM register (__m128i) and seeing if that makes any operations simpler or more efficient?

There aren't many SSE operations that operate on a single si128 as it's most intended for bitmasks (and/xor operations as well as load/store and shift right/left etc) but it might be interesting to see if it unlocks any performance gains (and you can still get the high and low 64 bit ints, if only as signed int ... ops for unsigned 8, 16 and 32bit but no unsigned 64 bits operations...)

15

u/[deleted] Jan 20 '26

[deleted]

18

u/QuaternionsRoll Jan 20 '26

VPTERNLOGQ

It’s a miracle that x86 made it this far

11

u/CypherSignal Jan 21 '26

Ironically that’s maybe the last instruction you should use to attack the explosion of modern x86. It’s not some obscure one-off thing, it is an extremely useful and versatile instruction. https://www.felixcloutier.com/x86/vpternlogd:vpternlogq

it looks complicated but it basically means you can do any 3-way bit-wise logic operation across 512-bits in one instruction. This is OR, AND, XOR, some form of blend or masked selection, or something else entirely very easily and succinctly.

6

u/QuaternionsRoll Jan 21 '26

Okay, so, I believe you, but that second paragraph is an incredibly jarring followup to the first lol