Modern CPU’s can perform extended multiplication between two native-size words and store the low and high result in separate registers. Similarly, when performing division, they store the quotient and the remainder in two different registers instead of discarding the unwanted part.
Is there some sort of portable gcc intrinsic which would take the following signature:
void extmul(size_t a, size_t b, size_t *lo, size_t *hi);
Or something like that, and for division:
void extdiv(size_t a, size_t b, size_t *q, size_t *r);
I know I could do it myself with inline assembly and shoehorn portability into it by throwing #ifdef’s in the code, or I could emulate the multiplication part using partial sums (which would be significantly slower) but I would like to avoid that for readability. Surely there exists some built-in function to do this?
For gcc since version 4.6 you can use
__int128. This works on most 64 bit hardware. For instanceTo get the 128 bit result of a 64×64 bit multiplication just use
On x86_64 gcc is smart enough to compile this to
No native 128 bit support or similar required, and after inlining only the
mulinstruction remains.Edit: On a 32 bit arch this works in a similar way, you need to replace
__int128_tbyuint64_tand the shift width by 32. The optimization will work on even older gccs.