How do I do a 64 bits mulhi in D?

deadalnix deadalnix at gmail.com
Sun Nov 27 14:22:28 UTC 2022


On Sunday, 27 November 2022 at 03:26:30 UTC, kinke wrote:
> On Sunday, 27 November 2022 at 01:55:45 UTC, deadalnix wrote:
>> That's a clever trick, but that only work on x86, but also 
>> will blind the optimizer as to what's going on.
>
> A solution with LDC, using inline-(LLVM-)IR:
>
> ```
> ulong mulhi(ulong a, ulong b)
> {
>     import ldc.llvmasm;
>     return __ir!(`
>         %a = zext i64 %0 to i128
>         %b = zext i64 %1 to i128
>         %r = mul i128 %a, %b
>         %r2 = lshr i128 %r, 64
>         %r3 = trunc i128 %r2 to i64
>         ret i64 %r3`, ulong)(a, b);
> }
> ```

I wasn't aware of that feature. Not very portable, but way more 
portable than the previous solution. Still compiler specific, but 
at least not plateform specific anymore.


More information about the Digitalmars-d mailing list