[PATCH v2 26/32] mpi: Add the RISC-V longlong.h from GCC.

Matt Turner mattst88 at gmail.com
Wed Nov 25 21:20:03 CET 2026


* mpi/longlong.h [__riscv && __riscv_zbb] (count_leading_zeros)
(count_trailing_zeros, COUNT_LEADING_ZEROS_0): New.
[__riscv && __riscv_mul] (__umulsidi3, __muluw3, umul_ppmm): New.

--

Take the RISC-V block from GCC, as of commit d1046d7fbb2 ("include:
Use mulhu for the RISC-V umul_ppmm in longlong.h").  With Zbb, GCC and
Clang turn the clz and ctz builtins into clz and ctz, where the
generic count_leading_zeros looks up _gcry_clz_tab.  With M,
umul_ppmm compiles to mul and mulhu, the same as the generic
umul_ppmm, with GCC and Clang for RV32 and RV64.

Leave out the umul_ppmm GCC uses without M, which builds the product
from four half-word multiplies.

The macros pass a runtime test under qemu-riscv32 and qemu-riscv64
with GCC and Clang.

Signed-off-by: Matt Turner <mattst88 at gmail.com>
---
 mpi/longlong.h | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)

diff --git a/mpi/longlong.h b/mpi/longlong.h
index 6e23018e..51bd8af6 100644
--- a/mpi/longlong.h
+++ b/mpi/longlong.h
@@ -1026,6 +1026,43 @@ typedef unsigned int UTItype __attribute__ ((mode (TI)));
   } while (0)
 #endif
 
+#if defined(__riscv)
+
+#ifdef __riscv_zbb
+#if W_TYPE_SIZE == 32
+#define count_leading_zeros(COUNT, X)   ((COUNT) = __builtin_clz (X))
+#define count_trailing_zeros(COUNT, X)   ((COUNT) = __builtin_ctz (X))
+#define COUNT_LEADING_ZEROS_0 32
+#endif /* W_TYPE_SIZE == 32 */
+#if W_TYPE_SIZE == 64
+#define count_leading_zeros(COUNT, X)   ((COUNT) = __builtin_clzll (X))
+#define count_trailing_zeros(COUNT, X)   ((COUNT) = __builtin_ctzll (X))
+#define COUNT_LEADING_ZEROS_0 64
+#endif /* W_TYPE_SIZE == 64 */
+#endif /* __riscv_zbb */
+
+#ifdef __riscv_mul
+#define __umulsidi3(u,v) ((UDWtype)(UWtype)(u) * (UWtype)(v))
+#define __muluw3(a, b) ((UWtype)(a) * (UWtype)(b))
+/* soft-fp does not define UDWtype, so do not use __umulsidi3 here.  */
+#if W_TYPE_SIZE == 32
+#define umul_ppmm(w1, w0, u, v) \
+  do {									\
+    UDItype __ll = (UDItype) (USItype) (u) * (USItype) (v);		\
+    (w1) = (USItype) (__ll >> 32);					\
+    (w0) = (USItype) __ll;						\
+  } while (0)
+#elif W_TYPE_SIZE == 64 && __riscv_xlen == 64
+#define umul_ppmm(w1, w0, u, v) \
+  do {									\
+    __uint128_t __ll = (__uint128_t) (UDItype) (u) * (UDItype) (v);	\
+    (w1) = (UDItype) (__ll >> 64);					\
+    (w0) = (UDItype) __ll;						\
+  } while (0)
+#endif
+#endif /* __riscv_mul */
+#endif /* __riscv */
+
 
 /***************************************
  **************  SH2  ******************

-- 
2.56.1



More information about the Gcrypt-devel mailing list