Repository navigation
lib/math32: fix division helpers and add portable 128-bit integer support - #21491
Merged
Merged
Conversation
Fix-Point
requested review from
Donny9,
GUIDINGLI,
jerpelea,
xiaoxiang781216,
yamt and
yf13
as code owners
November 5, 2026 12:08
Fix-Point
force-pushed
the
nuttx-math32-sync
branch
from
November 5, 2026 12:26
af10b04 to
c9e0dc1
Compare
|
Fix-Point
force-pushed
the
nuttx-math32-sync
branch
from
November 6, 2026 09:31
c9e0dc1 to
156619b
Compare
🔗 Cross-repo PR dependenciesThe read-only Build run reported the following dependent PR(s) and fetched head SHA(s): |
casaroli
requested changes
Nov 6, 2026
Fix-Point
force-pushed
the
nuttx-math32-sync
branch
from
November 9, 2026 06:16
32c7723 to
1bbf822
Compare
Fix-Point
requested review from
eren-terzioglu,
fdcavalcanti and
tmedicci
as code owners
November 9, 2026 06:16
p = 1 << LOG2_FLOOR(b) shifts a signed int literal by up to 31 bits, which is undefined behavior. Use 1u instead, and add DEBUGASSERT(b > 1) to enforce the divisor contract before LOG2_FLOOR(b) is evaluated (b == 0 would make it undefined as well). Also use unsigned literals for the remaining integer constants in div64_const32() and for the rounding bias arithmetic of div_const_roundup() and div_const_roundnearest() so that the intermediate arithmetic matches the unsigned contract of div64_const(). Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
div64_const() took uint32_t base, silently truncating any wider divisor: div_const(n, 1ULL << 40) passed 0 as the divisor and divided by zero at runtime. Widen the parameter to uint64_t and handle the full range: - Compute the power-of-two shift count with LOG2_FLOOR(), which is 64-bit safe on all hosts (see the previous commit). - Call div64_const32() only when base actually fits in 32 bits (explicitly narrowed); larger divisors fall back to plain division. - Assert the divisor contract (base > 0) at entry. Widening the parameter is source compatible with existing callers. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
The magic number setup in div64_const() is only a win when it is folded away at compile time: unfolded per call it contains several divisions and is far slower than a plain division. When CONFIG_DEBUG_NOOPT is enabled the build runs without optimization, so just define div64_const() as a plain division there. Cast the division result to uint64_t so div_const() keeps the same type in every build: without the cast the NOOPT build gave (n) / (base) its plain arithmetic type while every other build returned uint64_t, which made the PRIu64 format used at the tick-conversion call sites a format mismatch in NOOPT builds. The cast is on the result, not the operands: casting the dividend to uint64_t first would widen the division itself and turn a single 32-bit divide into a 64-bit soft division at runtime. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
invdiv_umulh64() computes the high 64 bits of a 64x64 product -- the UMULH primitive that some architectures implement in a single instruction and that others best provide in assembly when the compiler lacks uint128_t -- but it was a fixed static inline with no override point. Give it the up_umulh64() name, following the up_* convention for architecture-provided primitives, and let an architecture decide how to provide it. The portable form stays as the fallback. Behavior is unchanged: the fallback passes edge cases and 1M randomized differential tests against the native 128-bit computation on both the uint128_t path and the software decomposition path. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
The width dispatch of div_const()/div_const_roundup()/ div_const_roundnearest() probed the dividend with sizeof(typeof(n)), a GNU extension: compilers without typeof (SDCC, IAR, TASKING classic, z88dk) fail to build the time conversion macros in <nuttx/clock.h> and the call sites in sched/wdog. sizeof((n)) probes the same type without evaluating the argument and is plain C99. Note that sizeof() cannot probe bit-fields; widen them at the call site if needed (there are none in tree). Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
div_const_roundup() and div_const_roundnearest() each duplicated the width dispatch and the magic-number call of div_const(), the only difference being the rounding bias folded into the dividend. Route both through div_const() with the biased dividend ((n) + (base) - 1 and (n) + (base) / 2), so the width dispatch and the div64_const() machinery live in one place and later dispatch changes only need to touch div_const(). The bias constants take the essential type of the divisor through MATH32_ONE() (base / base): a plain literal breaks MISRA C Rule 10.4 for the other argument kind, and an unsigned literal wraps negative signed dividends. Result values are unchanged on every path; the mixed narrow-dividend case now shares the magic path and returns the identical value. Evidence: differential test against a snapshot of the old macro expansions, 1804 checks over 12 constant bases x 4 dividend/divisor width combos x edge and pseudo-random dividends, 0 mismatches on gcc -m64, gcc -m32 and clang -m64, each with and without CONFIG_DEBUG_NOOPT. qemu-intel64 build passes. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
is_constexpr() was (0) everywhere except the GNU section, so any
constant-folding dispatch built on it silently lost its compile-time
path on non-GNU toolchains, and a shared fallback would claim support
no one verified. Give each compiler section only the definition that
is proven on a real toolchain or documented by the compiler vendor:
- GCC/Clang: __builtin_constant_p().
- SDCC: keep (0). The classic sizeof(void) trick was verified
to give correct values on SDCC 4.0.0 (z80 at all scopes; mcs51 at
expression, array and file-scope static-init scope), but on mcs51
it cannot be used inside enum constant initializers ("error 174:
enumeration constant not an integer"), each mcs51 expansion warns
88/127 (generic-pointer casts), and its payoff on 8/16-bit targets
is unproven. A plain (0) keeps every constant-expression scope
working and div_const() falls back to plain division.
- TASKING: __builtin_constant_p(), listed as a compiler intrinsic in
the TASKING VX-toolset for TriCore User Guide (MA160-800, v6.4r1),
"Intrinsic Functions" - "Miscellaneous Intrinsic Functions":
"int __builtin_constant_p( type exp ); During compilation, constant
propagation returns 1 if exp is a constant expression. Otherwise,
it returns 0. Note that type can be int, long, long long, double
or long double."
https://www.tasking.com/documentation/tricore/ctc/reference/clang_intrinsics_misc.html
- IAR: __builtin_constant_p(), listed under "Supported GCC built-in
functions", IAR Embedded Workbench for Arm 10.10.x:
https://docs.iar.com/ewarm/10.1x/en/iar-c-c---development/intrinsic-functions/supported-gcc-built-in-functions.html
That page documents a deviation from GCC: the result does not
depend on the optimization level and may be 0 for expressions the
compiler later constant-folds, which is the safe direction for
this macro (a 0 answer just takes the plain-arithmetic path).
- Zilog/MSVC/generic: keep (0). The trick was rejected at parse
level by z88dk sccz80 and no real MSVC compiler was obtainable.
Neither TASKING nor IAR was available locally, so those two entries
rest on the vendor documentation cited above rather than on a local
toolchain run. Cross-compiler probe evidence for the SDCC entry
(gcc -m64/-m32 and clang run output; SDCC z80/mcs51 asm constants;
literal/enum/global/local/volatile at expression scope; the nested
ternary with a function-call dead branch in static initializers) is
recorded in .review-tmp/is-constexpr-verify.md.
Assisted-By: mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <[email protected]>
div_const() picked the magic path purely from the dividend width, which
had two bad cases: a runtime divisor ran the unfolded magic setup at
every call (measured 6-17x slower than a plain division), and a
non-constant argument kept the expression from being an integer
constant expression, so static initializers with constant arguments
failed to compile ("initializer element is not constant").
Dispatch on is_constexpr() instead. A non-constant divisor takes the
plain division directly, and a constant dividend with a constant divisor
also takes the plain division so the whole expression stays an ICE.
Only a runtime dividend with a compile-time constant divisor keeps the
magic path, gated by the dividend and pointer width: only on 32-bit
targets, where a plain division would become a __udivdi3 call. On
64-bit targets the compiler's own division-by-constant sequence is
smaller and faster than the portable magic (aarch64 GCC 14 -O2 compiles
div_const(n, 1000) to 8 instructions with one umulh versus 26 with four
umaddl; rv64gc grows 30 to 108 bytes the other way), so plain division
is kept there, matching the original div64_const() design. The family
takes non-negative arguments only; negative
values are outside the contract and unspecified, so no sign gating is
needed in the dispatch. The call sites were audited against this
contract: the direct callers pass uint64_t/clkcnt_t values, and the
*2TICK() conversions see only constants, unsigned ioctl arguments
and timespec values within their POSIX domain (a negative tv_nsec
is an invalid timespec), so every in-tree use is inside the domain.
Compilers whose is_constexpr() is (0) always
take the plain division: correct, just without the optimization.
Evidence: static initializers with constant arguments now compile and
fold to the hand-computed values on gcc -m64/-m32, clang and TCC (run
output) and on SDCC z80/mcs51 (asm constants 100/142/143/143/6); with
gcc -O2 a runtime divisor disassembles to a single div instruction with
no magic setup while the constant-divisor path disassembles to the
folded multiply-shift sequence with zero div instructions; the
differential test against the pre-change macro snapshots stays at 0
mismatches over 1804 non-negative checks; qemu-intel64 build passes.
Assisted-By: mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <[email protected]>
Define _int128_t/_uint128_t and __INT128_DEFINED in the per-architecture types.h when the compiler provides __int128 (__SIZEOF_INT128__). These are the implementation-reserved base names; no public typedefs are added to include/stdint.h, because uint128_t is not a standard name and would clash with third-party code that defines its own (e.g. vendored HACL/KrML code in apps). Assisted-By: mimo-v2.6-pro Co-authored-by: ouyangxiangzhen <[email protected]> Signed-off-by: buxiasen <[email protected]> Signed-off-by: ouyangxiangzhen <[email protected]>
Use the _uint128_t base type from <arch/types.h> instead of the compiler-specific __uint128_t, and switch the availability checks to __INT128_DEFINED so the software fallback is used whenever the architecture does not provide the 128-bit type. Assisted-By: mimo-v2.6-pro Co-authored-by: ouyangxiangzhen <[email protected]> Signed-off-by: buxiasen <[email protected]> Signed-off-by: ouyangxiangzhen <[email protected]>
FLS() only examined the high 32 bits when UINTPTR_MAX > UINT32_MAX, because that branch shifted a size_t: on 32-bit hosts FLS() returned wrong results for inputs above 2^32 (e.g. FLS(1ULL << 40) returned 0 instead of 41), silently breaking LOG2_FLOOR()/LOG2_CEIL() for 64-bit values. Split the bit scan into width layers (FLS32 is the shared building block of FLS64 and FLS128) so that every argument width is handled correctly on every host. FLS() is FLS64 directly when the compiler provides no uint128_t; otherwise sizeof() selects FLS128 for arguments wider than 64 bits. The wider layers widen the argument before shifting, so narrower types never see an oversized shift count. Negative signed values are scanned as their widened two's-complement bit pattern. Like before, the macros evaluate their argument multiple times, so the argument must be free of side effects. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
arch/avr/src/avr32/Toolchain.defs never set any -O level and never consumed CONFIG_DEBUG_OPTLEVEL, so avr32 builds compiled at the GCC default -O0 even with CONFIG_DEBUG_FULLOPT selected. Combined with the always_inline math32 helpers this exploded: at -O0 the magic-number setup of div64_const() is force-inlined unfolded at every 64-bit clock conversion call site (avr32-gcc 4.4.7 measurement: about 18KB per site with 13 __avr32_udiv64 and 3 __avr32_umod64 calls; avr32dev1:nsh grew 90444 bytes of text across 5 call sites and overflowed the flash region by 20312 bytes in CI). The same toolchain folds the setup away at -O2 and -Os (224 bytes per site), so the cause is the silent -O0 build, not a compiler limitation. Replace the optimization handling with the same three-level chain the other architectures use (NOOPT -> -O0, CUSTOMOPT -> CONFIG_DEBUG_OPTLEVEL, FULLOPT -> -Os), merged with the existing -fno-strict-aliasing flag. -Os matches the GCC convention of the other architectures (x86_64, arm, arm64, tricore, misoc) and suits a flash constrained target. Verified at the flag level with make -n on avr32dev1:nsh: the compile command line gains "-fno-strict-aliasing -Os" where it previously had no -O option at all. The CI avr32dev1:nsh build is the final confirmation. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
…parity] Nine toolchain definitions translate only the CONFIG_DEBUG_NOOPT half of the "Optimization Level" choice: arch/x86/src/common/Toolchain.defs passes -O2 for any non-NOOPT selection and the board-local toolchain blocks used by the hc/m9s12 and renesas m16c/rx65n/sh1 boards pass -Os plus -fno-strict-aliasing/-fomit-frame-pointer, while CONFIG_DEBUG_CUSTOMOPT and CONFIG_DEBUG_OPTLEVEL are never consulted. This is the same wiring gap class as the avr32 one fixed in "arch/avr: wire optimization level into the avr32 toolchain flags" (there it degenerated into a silent -O0 build that blew up avr32dev1's flash; here the reachable selections happen to keep an optimization level, so the defect stays latent until an arch in this group selects ARCH_HAVE_CUSTOMOPT). Replace the two-way handling with the same three-level chain the mainstream toolchains use: NOOPT -> -O0, CUSTOMOPT -> CONFIG_DEBUG_OPTLEVEL, FULLOPT -> -Os (hc/renesas) or -O2 (x86), each keeping the file's previous full-optimization choice and its existing flags. The FULLOPT output is unchanged; NOOPT builds now spell -O0 explicitly instead of relying on the compiler default. Evidence (make -n V=1 on a scratch worktree of "arch/avr: wire optimization level into the avr32 toolchain flags" + this patch): rx65n:nsh FULLOPT compiles with "-fno-strict-aliasing -fomit-frame-pointer -Os" (same as before) and NOOPT compiles with -O0 (before: no -O option at all); qemu-i486:nsh FULLOPT compiles with -O2 (same as before). Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
div_const() and friends now evaluate to uint64_t (the ?: composite type with div64_const()), where master expanded to the plain arithmetic type of the arguments. The wlerr() calls in the ESP BLE adapters logged MSEC2TICK() results with %" PRIu32 "/%lu, which became a format/type mismatch (CI: "format '%lu' expects argument of type 'long unsigned int', but argument 3 has type 'uint64_t'") on esp32c3, esp32 and esp32s3. Log the value with %" PRIu64 " at the four wlerr() call sites (esp32c3-legacy included): clock_t is int64_t, so the tick domain is 64-bit wide and the uint64_t macro result now matches the format exactly -- no cast, no truncation, and for values below 2^32 the printed output is unchanged. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
ceil(log2 n) is fls(n - 1) for n >= 1, so log2ceil() and LOG2_CEIL() can drop the power-of-two test and become a single fls() (or FLS) evaluation of n - 1. This also fixes the multiple evaluation of n in the old ternary macros (n appeared four times in log2ceil()). fls() of 0 is undefined: CONFIG_HAVE_BUILTIN_CLZ makes it __builtin_clz(), which the GCC manual defines only for non-zero arguments. n == 1 is exactly that input, so keep the zero away arithmetically -- flsx(((n) - 1) | 1) - ((n) == 1) -- instead of a ternary: it costs no branch on Thumb-1, where the conditional form degrades to a jump, and it stays an integer constant expression on clang, which folds __builtin_clz(0) to a non-constant. log2() itself is undefined for 0 and for negative arguments: outside n >= 1 the old macros' behavior was accidental, not a contract (n = 0 simply changes from returning 0 to returning the bit width). All callers pass n >= 1 -- the invdiv initializer requires d > 1, mm.h uses sizeof(), lib_fdcheck.c uses OPEN_MAX, nx_start.c uses CONFIG_PID_INITIAL_COUNT and the RISC-V MPU sites use region sizes -- and the precondition is now stated next to the macros. Verified: the new macro agrees with the pre-series power-of-two form on every n in 1..2^24 and on the 64-bit boundary set (2^32-1, 2^32, 2^40, 2^62, 2^63, 2^63+1, 2^64-1), 0 differences; it is an integer constant expression on gcc and clang for n = 1, 2, 3, 8, 9, 1024, 1025; the cortex-m3 and cortex-m0 images of the macro contain no conditional branch. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
* invdiv_init_param32(): the description named a triple "(multiplier, right shift number 1, right shift number 2)" from an older two-shift design; the parameters are a multiplier and one shift. * The Granlund-Montgomery usage note named APIs that do not exist (invdiv_init_param(d, param), invdiv(n, param)); it now points at invdiv_init_param32()/invdiv_init_param64() and invdiv_u32()/invdiv_u64(). * Two kernel descriptions said the divisor is "converted to invdiv_param_t", a type that does not exist; the real struct names are invdiv_param32_t and invdiv_param64_t. * log2ceil()/log2floor() claimed to return "the power-of-two for the argument"; they return the base-2 logarithm. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
The portable limb form of up_umulh64() is inlined at every user of the primitive, about twenty instructions per expansion in every kernel that divides or scales by a runtime value, and an architecture has no way to replace it. Declare up_umulh64() in math32.h itself. When the compiler has a native 128-bit multiply (_uint128_t, __INT128_DEFINED) it is a static inline that compiles to a single UMULH, so 64-bit targets need nothing else. Otherwise math32.h only declares it, and the definition is one out-of-line copy per image in libs/libc/machine: the architecture form in libs/libc/machine/<arch>/arch_umulh64.c, plus a weak portable fallback in libs/libc/machine/up_umulh64.c for the architectures that provide none. The weak fallback is listed after the per-architecture sources in both Make.defs and CMakeLists.txt: libc.a members are scanned in order, and a weak definition listed first would satisfy the reference before the strong one is reached. Only the declaration and the fallback land here; the ARM form follows in "libs/libc/machine/arm: implement up_umulh64() in UMULL assembly". Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
The portable limb form of up_umulh64() is too large to inline at every user of the primitive on 32-bit targets: each expansion costs some twenty instructions in every kernel that divides or scales by a runtime value. ARM provides one shared copy per image in libs/libc/machine/arm/ instead, overriding the weak fallback from "lib/math32: declare up_umulh64() in math32.h with a weak fallback". The ARM form chains four UMULL products with adc to collect the middle carries of the four-product decomposition. UMULL exists in the ARM and Thumb-2 instruction sets only, so a Thumb-1 target keeps the portable fallback instead and this file compiles to nothing there. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
…v_udiv128 Replace the 128-step soft-division loop of invdiv_udiv_soft() with the non-looped invdiv_udiv128() and compute the u64 invariant multiplier with it. One 128-by-64 division implementation now serves every path, and the division becomes constant-foldable: with a literal divisor the compiler evaluates the whole setup to a literal magic number, so div64_const() and div64_const32() cost one multiply and a shift at run time instead of keeping a division. A loop cannot be folded that way; this is the reason the loop goes. * invdiv_udiv128(hi, lo, d, s): the __int128 single expression when available, otherwise invdiv_udiv128_soft(), the two-digit Knuth-D expansion in base 2^32 -- long division by hand with the quotient's two digits and their rounding written out step by step. It contains no loop on any target. * The normalizer s = clz(d) is passed in and derived from l as the branch-free 64 - l - (((d - 1) & d) == 0), l = ceil(log2 d). * The old invdiv_init_param_dispatch64() closed form and the d <= 2^32 split are gone: KD2 is exact for every divisor. Verified: invdiv_udiv128 differential 2,713,524 boundary/random samples x (-O0/-O1/-O2/-Os) 0 mismatch on both arms; the invdiv_init_param64() + invdiv_u64() battery 4,000,998 samples 0 mismatch against n/d for d in [2, 2^63), the inherited d >= 2^63 shift band counted as before; t_divconst dispatch fails=0. Constant folding, measured with the NuttX arm-none-eabi-gcc 10.3.1 flags for cortex-m0 at -O2 and without CONFIG_DEBUG_NOOPT: a thread that returns div64_const(n, 1000), div64_const(n, 1000003) and div64_const32(n, 1000) compiles to 23 instructions each with no division helper among the undefined symbols, and div64_const(n, 4096) compiles to 6 instructions with no undefined symbol at all. The one runtime difference is the one-time setup cost of invdiv_init_param64() for d <= 2^32 (10.52 -> 14.09 ns/op; the setup runs once per divisor). Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
The invdiv setup had no shared entry: callers named the width-specific
initializer (invdiv_init_param32/64()) themselves, so every call site
carried the width knowledge of its parameter block, and each init
computed ceil(log2 d) with log2ceil() while the header had just
standardized the value on LOG2_CEIL() ("lib/math32: pick the
LOG2_CEIL()/LOG2_FLOOR() form by toolchain"). A separate foldable
constant entry would only be needed because ceil(log2 d) once had two
spellings; with one spelling per toolchain the split buys nothing.
Add one dispatch and drop the rest: invdiv_init_param(d, ip) is a
ternary on sizeof((ip)->mult) that casts the block to
invdiv_param32_t or invdiv_param64_t and selects the initializer at
compile time, and invdiv_init_param32/64() keep the (d, ip) signature
with l = LOG2_CEIL(d) computed inside as the first statement. A
run-time divisor and a constant divisor now share one entry; the
separate constant entry (invdiv_init_param_const()) is retired and not
carried. The call sites in include/nuttx/timers/oneshot.h and
arch/tricore/src/common/tricore_perf.c go through the dispatch instead
of naming an initializer.
No functional change: LOG2_CEIL(d) and the former log2ceil(d) agree by
the pick above, and at both call sites the parameter block is
invdiv_param64_t (oneshot lower->invdiv_freq, tricore g_invdiv_param),
so the dispatch selects invdiv_init_param64() exactly as the direct
call did. Host battery at this commit, 4000000 random (n, b) pairs
checking div64_const32() and invdiv_u32() against native division:
"u64 4M fail=0 u32 4M fail=0", with and without
CONFIG_HAVE_BUILTIN_CLZ.
Assisted-By: mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <[email protected]>
div64_const32() expanded the Granlund-Montgomery magic setup at every
call site: the inline carried the whole magic computation, several
u64 divisions in its setup paths, plus umul64_const(), a limb
multiply-high helper whose only user it was, while the shared
invdiv_u64() kernel next door went unused. Trigger: any use of
div_const()/div64_const() with a non-power-of-two constant base on a
32-bit target. Root cause: the magic form predates the invdiv kernel
and kept a parallel division path alive next to it.
Rewrite div64_const32() as the constant setup plus the shared kernel:
invdiv_init_param(b, &ip) then invdiv_u64(n, &ip) ("lib/math32: unify
the invdiv init behind invdiv_init_param()"). For a literal divisor
the setup folds at compile time, so a site keeps only the folded
constants and the kernel; umul64_const() loses its last user with the
magic form and is deleted. Trade-off: the GM bias tuning goes away
with it; the kernel divides exactly like the magic form did and is
now the single division path to maintain, and power-of-two divisors
still short-circuit in div64_const().
No functional change: 4000000 random (n, b) pairs with b >= 2 check
div64_const32() against n / b and the u32 initializer against n32 / b
with 0 mismatches ("u64 4M fail=0 u32 4M fail=0", also without
CONFIG_HAVE_BUILTIN_CLZ). Size evidence, measured earlier on this
work: on lm3s6965-ek/qemu-protected the magic form overflowed the
128K kflash by 84B where this form fits, and per call site x86-64 -O2
counts the folded body at 63B/18 instructions against the magic
form's 110B/30 -- the 18-insn body is itself the evidence that the
setup folds.
Assisted-By: mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <[email protected]>
MISRA C Rule 7.2 wants a "u" or "U" suffix on every integer constant that is represented in an unsigned type, and Rule 10.4 wants both operands of an operator to share an essential type category. The constants in invdiv_init_param64() were plain int literals while every operand around them is uint64_t (d, t, ip->mult) or _uint128_t, so the suffixes make the conversions explicit. The suffix is added where the unsigned type is certain: the normalizer computations (d - 1u, == 0u), the contract assertions (d > 1u, b > 1u, base > 0u), the biases (+ 1u), the 128-bit path (one128 = 1u, + 1u), the 64-bit unit shifts of both initializers ((uint64_t)1u << l) and the shift constant of invdiv_u64() (sh1 = 1u). Shift counts themselves keep their plain type: a shift does not perform the usual arithmetic conversions, so Rule 10.4 does not apply to it, and Rule 12.2 only requires the count to be smaller than the width. Left as plain int on purpose: the FLS(), LOG2_FLOOR(), LOG2_CEIL() and IS_POWER_OF_2() macros, whose argument may be signed -- OPEN_MAX and CONFIG_PID_INITIAL_COUNT are int -- and where a suffix would break Rule 10.4 for those callers instead of fixing it. Verified: the normalizer is unchanged for every d in [2, 5000000] and on the 2^63 boundaries (0 differences), s still equals clz(d) on the same set, and the 32-bit and 64-bit invdiv differential batteries keep 0 mismatches. nucleo-f072rb:nsh and rv-virt:smp64 (with CONFIG_ONESHOT_FAST_DIVISION, which instantiates invdiv_init_param64) build with no new warnings. Assisted-By: mimo-v2.6-pro Signed-off-by: ouyangxiangzhen <[email protected]>
Fix-Point
force-pushed
the
nuttx-math32-sync
branch
from
November 19, 2026 01:44
f696c45 to
11745d0
Compare
jerpelea
approved these changes
Nov 19, 2026
xiaoxiang781216
approved these changes
Nov 19, 2026
Contributor
|
@casaroli please review this pr. |
casaroli
approved these changes
Nov 19, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Note: Please adhere to Contributing Guidelines.
Summary
This series fixes compile-time, correctness and portability problems in
include/nuttx/lib/math32.h, reworks thediv_const()family to dispatch on compile-time constantness, adds implementation-reserved 128-bit integer base types with an arch hook for the 64x64 high multiply, and wires the optimization level into toolchain flags that silently ignored it.Correctness and portability fixes
Make the constant-division helpers usable in static initializers:
div64_const()was a braced-group statement expression and failed with "braced-group within expression allowed only inside a function" (boards/arm/cxd56xx/spresense/src/cxd56_automount.cinitializes fields withMSEC2TICK(CONFIG_...)); it is now astatic inlinefunction, andumul64_const()/div64_const32()were converted from macros tostatic inlinefunctions because the old macros expandedLOG2_FLOOR()at every use site into enormous token sequences (e.g.nxglib/nxglib_setpixel_1bpp.c) that disabled column tracking and broke-Wmisleading-indentation. 32-bit constant expressions fold to a plain division and therefore stay integer constant expressions; 64-bit constant expressions remain runtime-only because a function call is not an ICE.umul64_const()now returns its 64-bit result instead of assigning through an output parameter (no callers outsidemath32.h), and the never-definedCONFIG_HAVE_EXPRESSION_STATEMENTfallback is removed.Harden the divisor contract and remove undefined behavior:
invdiv_init_param32()/invdiv_init_param64()gainedDEBUGASSERT(d > 1u)to cover the documented contract (a Coverity divide-by-zero finding);div64_const32()no longer shifts a signedintliteral by up to 31 bits (p = 1 << LOG2_FLOOR(b)is UB; now1u, withDEBUGASSERT(b > 1u)guardingLOG2_FLOOR()) and its remaining constants plus the rounding bias arithmetic carry explicit unsigned literals matching the unsigned contract;div64_const()widened its base fromuint32_ttouint64_tbecause the truncation turneddiv_const(n, 1ULL << 40)into a division by zero at runtime —LOG2_FLOOR()computes the power-of-two shift 64-bit safely,div64_const32()is only called with an explicitly narrowed 32-bit divisor, larger divisors fall back to plain division, andbase > 0uis asserted at entry. The widening is source compatible with existing callers.Give up the magic-number setup when the build cannot fold it away: unfolded per call the Granlund-Montgomery setup contains several divisions and is far slower than a plain division (later measured at 6-17x); with
CONFIG_DEBUG_NOOPTdiv64_const()is now defined as a plain division.Unify the rounding variants and drop the GNU
typeofextension:div_const_roundup()/div_const_roundnearest()duplicated the width dispatch and the magic call ofdiv_const()and now delegate to it with the biased dividend ((n) + (base) - 1and(n) + (base) / 2), so the dispatch and magic machinery live in one place; the bias constants take the essential type of the divisor throughMATH32_ONE()((base) / (base)) because a plain literal breaks MISRA C Rule 10.4 for the other argument kind and an unsigned literal wraps negative signed dividends. The width dispatch probes the dividend withsizeof((n))instead ofsizeof(typeof(n)), a GNU extension that broke SDCC/IAR/TASKING-classic/z88dk builds of<nuttx/clock.h>andsched/wdog; result values are unchanged for every non-negative input.Make
FLS()width-generic and 64-bit safe on all hosts: on 32-bit hostsFLS()returned wrong results for inputs above 2^32 (FLS(1ULL << 40)returned 0 instead of 41), silently breakingLOG2_FLOOR()/LOG2_CEIL()for 64-bit values. The bit scan is layeredFLS32/FLS64/FLS128(FLS32is the shared building block),FLS()maps toFLS64directly when the compiler provides no 128-bit type, otherwisesizeof()selectsFLS128for wider arguments, and every layer widens before shifting so narrow types never see an oversized shift count. Like before, the macros evaluate their argument multiple times (no side effects).Constness dispatch and 128-bit plumbing
Dispatch
div_const()on compile-time constness instead of dividend width: width-only dispatch had two bad cases — a runtime divisor ran the unfolded magic setup at every call (6-17x slower than a plain division), and a non-constant argument kept the expression from being an integer constant expression ("initializer element is not constant"). Now a non-constant divisor takes the plain division directly, and a constant dividend with a constant divisor also takes the plain division so the whole expression stays an ICE; only a runtime dividend with a compile-time constant divisor keeps the magic path, gated to 32-bit targets where a plain division would become a__udivdi3libgcc call. On 64-bit targets the compiler's own division-by-constant sequence is smaller and faster than the portable magic (aarch64 GCC 14 -O2: 8 instructions with oneumulhversus 26 with fourumaddl; rv64gc 30 bytes versus 108 bytes), so the compiler sequence is kept there per review feedback. The family takes non-negative arguments only and the in-tree call sites were audited against that contract (direct callers passuint64_t/clkcnt_tvalues; the*2TICK()conversions see constants, unsigned ioctl arguments, and timespec values within their POSIX domain).is_constexpr(x)is now__builtin_constant_p(x)for IAR and TASKING (vendor-documented intrinsic/builtin), joining the GCC/Clang definition; the Linux kernelsizeof(void)trick was empirically verified on SDCC 4.0.0 (z80 at all scopes, mcs51 at expression/array/static-init scope) but SDCC keeps(0)because the trick fails inside mcs51 enum constant initializers (error 174) and its payoff on 8/16-bit targets is unproven; TCC/Zilog/MSVC/generic keep(0)as well. Compilers whoseis_constexpr()is(0)always take the plain division: correct, just without the optimization.Extract
invdiv_umulh64()as theup_umulh64()arch hook: the high half of a 64x64 product is exactly the UMULH primitive some architectures implement in a single instruction (or best provide via inline assembly when the compiler lacks a 128-bit type). The helper is renamed to the generalumulh64()and architectures may provideup_umulh64(), following theup_umul64_const()precedent; the C implementation stays as the fallback and passes edge cases plus 1M randomized differential tests against the native 128-bit computation on both the 128-bit and software-decomposition paths. On 32-bit ARM the arch hook is fourumullplusadds/adcwith the two high words added on top (52 bytes on Cortex-M3; compiled out on Thumb-1, which falls back to the C version), and on 64-bit targets with__int128it is the compiler's singlemulhu.Add reserved-name 128-bit base types and build
math32.hon them:_int128_t/_uint128_tand__INT128_DEFINEDare defined in the per-architecturetypes.hwhen the compiler provides__int128(__SIZEOF_INT128__), andmath32.huses the arch_uint128_tinstead of the compiler-specific__uint128_twith availability gated on__INT128_DEFINED, so the software fallback is used whenever the architecture lacks the type. Per review feedback no public typedefs are added toinclude/stdint.h:uint128_tis not a standard name and would clash with third-party code that defines its own (e.g. vendored HACL/KrML code in apps).Toolchain optimization wiring and call-site fix
Wire the optimization level into toolchain files that silently ignored it:
arch/avr/src/avr32/Toolchain.defsnever set any-Olevel and never consumedCONFIG_DEBUG_OPTLEVEL, so avr32 compiled at the GCC default-O0even withCONFIG_DEBUG_FULLOPT=y; combined with thealways_inlinemath32 helpers this unfolded the magic-number setup at every 64-bit clock conversion call site (avr32-gcc 4.4.7: about 18KB per site) and grewavr32dev1:nshby +90,444 bytes of.text, overflowing the flash region by 20,312 bytes in CI. The same toolchain folds the setup to 224 bytes per site at-O2/-Os, so the root cause is the silent-O0build, not a compiler limitation. Both the avr32 file and nine more toolchain files (arch/x86/src/common/Toolchain.defsplus the board-local hc/m9s12 and renesas m16c/rx65n/sh1 blocks, which translated only theCONFIG_DEBUG_NOOPThalf of the "Optimization Level" choice) now use the standard three-level chain:CONFIG_DEBUG_NOOPT->-O0,CONFIG_DEBUG_CUSTOMOPT->CONFIG_DEBUG_OPTLEVEL,CONFIG_DEBUG_FULLOPT->-Os(x86 keeps-O2), each keeping the file's existing flags. The FULLOPT output is unchanged; NOOPT builds now spell-O0explicitly. This is a latent defect class for every arch in this group until it selectsARCH_HAVE_CUSTOMOPT;[skip-cmake-parity]because none of the affected targets has a CMake counterpart.Print ESP tick conversions at their full width:
div_const()results areuint64_t(the?:composite type withdiv64_const()), but thewlerr()calls in the ESP BLE adapters loggedMSEC2TICK()results with%" PRIu32 "/%lu— a format/type mismatch on esp32c3/esp32/esp32s3. The fourwlerr()call sites (esp32c3-legacy included) now print with%" PRIu64 ";clock_tisint64_t, so the tick domain is genuinely 64-bit wide — no cast, no truncation, and identical output for values below 2^32.Invariant-division rework
Replace the software division loop with the Knuth-D two-digit expansion: the 128/64 quotient was computed one 32-bit digit at a time;
invdiv_udiv128()now uses the two-digit Knuth Algorithm D expansion with aKD2_CORRcorrection step, which assumes the normalizationhi < dthat the initializer guarantees vias = clz(d)(s == 0is a no-op rather than a 64-bit shift). It is only used when the compiler has no 128-bit type; the_uint128_tpath remains a single 128/64 division.Unify the two initializers behind
invdiv_init_param():invdiv_init_param32()andinvdiv_init_param64()no longer carry separate magic-number arithmetic; both build aninvdiv_param64_tthrough oneinvdiv_init_param()that picks the 128/64 division when__INT128_DEFINEDand the softwareinvdiv_udiv128()otherwise, so the 32-bit and 64-bit multipliers can no longer drift apart.div64_const32()is now a thininvdiv_init_param()+invdiv_u64()wrapper (it previously computed the multiplier inline).Give the initializer's integer constants an unsigned type: MISRA C Rule 7.2 asks for a
usuffix on constants represented in an unsigned type and Rule 10.4 for operands of one essential type category; the initializer was mixing plainintliterals withuint64_toperands. Thirteen literals now carry the suffix:(uint64_t)1u << l,(d - 1u) & d) == 0u,d > 1u,b > 1u,base > 0u, the two biases+ 1u,one128 = 1uandsh1 = 1u. Shift counts keep their plain type (a shift does not perform the usual arithmetic conversions, so Rule 10.4 does not apply), and theFLS()/LOG2_*()/IS_POWER_OF_2()macros keep plain literals on purpose: their argument may be signed (OPEN_MAX,CONFIG_PID_INITIAL_COUNTareint), where a suffix would break Rule 10.4 for those callers instead of fixing it.Express
log2ceil()without a zero undefined operation:log2ceil(n)/LOG2_CEIL(n)computedflsx((n) - 1), which evaluates__builtin_clz(0)atn == 1. It is nowflsx(((n) - 1) | 1) - ((n) == 1), son == 1is defined (0) andn == 0yields the bit width instead of an undefined scan; every in-tree caller passesn >= 1.Impact
div_const*()and theMSEC2TICK()/TICK2MSEC()-style time conversions can be used in static initializers again; a runtime divisor now takes a plain division instead of the unfolded magic setup (6-17x slower); result values are unchanged for every non-negative input (1804-case differential test, 0 mismatches); the family's non-negative contract is unchanged and documented, and negative inputs are outside it.log2ceil(0)/LOG2_CEIL(0)now return the bit width (32/64) instead of evaluating__builtin_clz(0), whose result the GCC manual leaves undefined — that is what made the old form undefined atn == 1as well; every in-tree caller passesn >= 1. On 32-bit targets the constant-divisor path still replaces a__udivdi3libgcc call with a folded multiply-shift; on 64-bit targets it is the compiler's own division-by-constant sequence.FLS()/LOG2_FLOOR()/LOG2_CEIL()now give correct results for 64-bit arguments on all hosts.include/nuttx/compiler.hdefinesis_constexpr(x)as__builtin_constant_p(x)for IAR and TASKING (GCC/Clang already did; SDCC/TCC/Zilog/MSVC/generic keep(0)). New base types_int128_t/_uint128_tand__INT128_DEFINEDin thetypes.hof arm64, risc-v, sim, tricore, x86_64 and xtensa. The avr32, x86, hc/m9s12 and renesas toolchain files now honorCONFIG_DEBUG_NOOPT/CONFIG_DEBUG_CUSTOMOPT+CONFIG_DEBUG_OPTLEVEL/CONFIG_DEBUG_FULLOPTwhere they previously ignored them; CMake is intentionally untouched ([skip-cmake-parity]): none of the affected targets is configurable with CMake.-OsunderCONFIG_DEBUG_FULLOPTinstead of a silent-O0— generated code for avr32 changes (that is the fix; it recovers the flash overflow). hc/m9s12, renesas m16c/rx65n/sh1 and x86/i486 keep their previous FULLOPT output (-Os/-O2); only their NOOPT builds change, spelling-O0explicitly instead of relying on the compiler default. No other architecture is affected.div_const*()family and thesizeof()bit-field caveat are documented in the comments ofinclude/nuttx/lib/math32.h.div64_const32(), division by zero from the truncated 64-bit divisor) and the silent wrong-results class ofFLS()for 64-bit values on 32-bit hosts. No new attack surface.div64_const()'s base parameter widensuint32_t->uint64_t(source compatible).umul64_const()returns its result instead of using an output parameter anddiv64_const32()returns the quotient instead of assigning through its first argument: both are internal helpers with no in-tree callers outsidemath32.h, but out-of-tree code calling these names must adapt. No publicint128_t/uint128_ttypedefs are introduced, so third-party code defining its ownuint128_t(e.g. vendored HACL/KrML) keeps building. TheCONFIG_HAVE_EXPRESSION_STATEMENTfallback inmath32.his removed; the configuration was never defined in tree.Testing
Build Host: Linux x86_64, host compilers gcc 13.1.0 / clang 14.0.0 / TCC 0.9.27; probe toolchains SDCC 4.0.0 (z80, mcs51), avr-gcc 5.4, msp430-gcc 4.6.3; target toolchains riscv-none-elf-gcc 14.3.0 (xPack, same version as the CI Dockerfile) and avr32-gcc 4.4.7 (same toolchain as the CI image).
Build / Board-Configuration matrix:
qemu-intel64:nsh,qemu-armv7a:nsh,esp32c3-devkit:nshandesp32c3-devkit:ble(riscv-none-elf-gcc 14.3.0).tools/ci/testlist/risc-v-01..07.datexpansion (381 unique board/configs): 376 PASS/PASS, 5 symmetric failures, 0 single-side regressions, 0 flash overflows. The 5 double failures are pre-existing/environmental and identical on both trees:arty_a7:pwm,arty_a7:sdmmc,bl602evb:elf(pre-existing code issues, all excluded from the CI lists) andrv-virt:leds64_rust,rv-virt:leds64_zig(local toolchains unavailable).sis unchanged for everydin [2, 5000000] and on the2^63 boundaries (0 differences),
s == clz(d)still holds on the same set, andrv-virt:smp64withCONFIG_ONESHOT_FAST_DIVISION(which instantiatesinvdiv_init_param64()) plusnucleo-f072rb:nshbuildwith no new warnings.
tools/checkpatch.sh -g upstream/master..HEAD: all checks pass for the full range and per commit.Differential tests and probes (host unit tests, gcc and clang at -m64/-m32, -O0/-Os where relevant):
div_const*()family against snapshots of the pre-change macro expansions (12 constant bases x 4 dividend/divisor width combos x edge and pseudo-random dividends): 0 mismatches on gcc -m64, gcc -m32 and clang -m64, each with and withoutCONFIG_DEBUG_NOOPT.umulh64()fallback: edge cases plus 1M randomized differential tests against the native 128-bit computation on both the_uint128_tpath and the software decomposition path; theup_umulh64()override dispatch.div_const()dispatch probes: static initializers with constant arguments compile and fold to hand-computed values on gcc -m64/-m32, clang and TCC (run output) and on SDCC 4.0.0 z80/mcs51 (assembly constants100/142/143/143/6); with gcc -O2 a runtime divisor disassembles to a singledivinstruction with no magic setup, while the constant-divisor path disassembles to the folded multiply-shift sequence with zerodivinstructions.is_constexpr()cross-compiler matrix (literal/enum/global/local/volatile at expression scope plus the nested-ternary static-initializer probes) on gcc/clang/TCC and SDCC 4.0.0 z80/mcs51, with assembly-level evidence on SDCC; TASKING and IAR rest on the vendor documentation cited in the commit messages (no local toolchains available — stated limitation).Performance (method: compiler output instruction counts and disassembly on the stated toolchains):
div_const(n, 1000), runtimenumaddl)umulh)div_const(n, 1000), runtimen-O0buildavr32dev1:nsh__avr32_udiv64, 3x__avr32_umod64)-O2/-Os)On 32-bit targets the magic path is kept because a plain 64-bit division there becomes a
__udivdi3libgcc call; the folded multiply-shift replaces it. On 64-bit targets the compiler's own sequence is used, as recommended in review.avr32 overflow reproduction (local build with the CI toolchain, base/merge dual trees): the merge tree overflows
flashby 20,312 bytes exactly as in CI;.textgrows +90,444 bytes (183,820 -> 274,264) across 5 clock-conversion call sites. The wiring fix is verified at the flag level withmake -n V=1:avr32dev1:nshgains-fno-strict-aliasing -Oswhere it previously had no-Ooption at all,rx65n:nshFULLOPT keeps-fno-strict-aliasing -fomit-frame-pointer -Osandqemu-i486:nshFULLOPT keeps-O2(both unchanged), and NOOPT builds spell-O0explicitly; the CIavr32dev1:nshbuild is the final confirmation.Note: qemu-intel64
.rodatagrows 49KB from this series (reproduced byte-for-byte: +49,056B). Root cause: theDEBUGASSERT(nodesize >= MM_MIN_CHUNK)string inmm/mm_heap/mm.hstringifies the fully expanded macro text, and the width-genericFLS()/dispatch changes grew that single string from 17,941 to 66,909 bytes; every configuration withCONFIG_DEBUG_ASSERTIONS=yis affected (all 10 such risc-v configs in the sweep showed +47.5~48.5KB). This is unrelated to the optimization wiring and is a pre-existing assert-stringification weakness; a separate fix will make the assertion reference named constants instead of expanded macro text.