Skip to content

Commit ea61c8c

Browse files
keith-packardjhedberg
authored andcommitted
sys/time_units.h: Work around clang div-by-zero warning
clang emits a warning for this code: foo.c:1:25: warning: division by zero is undefined [-Wdivision-by-zero] int i = (10 > 100 ? (20 / (10 / 100)) : (20 * (100 / 10))); ^ ~~~~~~~~~~ The warning is generated for code whose value does not affect the expression result, but technically it is still 'undefined behavior'. Work around this warning by checking for a zero divisor and substituting one to make the compiler happy. Signed-off-by: Keith Packard <[email protected]>
1 parent f2af4a7 commit ea61c8c

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

include/zephyr/sys/time_units.h

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,16 @@ static TIME_CONSTEXPR inline int sys_clock_hw_cycles_per_sec(void)
138138
(__round_up) ? ((__from_hz) / (__to_hz)) - 1 : \
139139
0)
140140

141+
/* Clang emits a divide-by-zero warning even though the int_div macro
142+
* results are only used when the divisor will not be zero. Work
143+
* around this by substituting 1 to make the compiler happy.
144+
*/
145+
#ifdef __clang__
146+
#define z_tmcvt_divisor(a, b) ((a) / (b) ?: 1)
147+
#else
148+
#define z_tmcvt_divisor(a, b) ((a) / (b))
149+
#endif
150+
141151
/*
142152
* Compute the offset needed to round the result correctly when
143153
* the conversion requires a full mul/div
@@ -154,12 +164,12 @@ static TIME_CONSTEXPR inline int sys_clock_hw_cycles_per_sec(void)
154164
((uint32_t)((__t) + \
155165
z_tmcvt_off_div(__from_hz, __to_hz, \
156166
__round_up, __round_off)) / \
157-
((__from_hz) / (__to_hz))) \
167+
z_tmcvt_divisor(__from_hz, __to_hz)) \
158168
: \
159169
(uint32_t) (((uint64_t) (__t) + \
160170
z_tmcvt_off_div(__from_hz, __to_hz, \
161171
__round_up, __round_off)) / \
162-
((__from_hz) / (__to_hz))) \
172+
z_tmcvt_divisor(__from_hz, __to_hz)) \
163173
)
164174

165175
/* Integer multiplication 32-bit conversion */
@@ -173,9 +183,9 @@ static TIME_CONSTEXPR inline int sys_clock_hw_cycles_per_sec(void)
173183

174184
/* Integer division 64-bit conversion */
175185
#define z_tmcvt_int_div_64(__t, __from_hz, __to_hz, __round_up, __round_off) \
176-
((uint64_t) (__t) + z_tmcvt_off_div(__from_hz, __to_hz, \
177-
__round_up, __round_off)) / \
178-
((__from_hz) / (__to_hz))
186+
(((uint64_t) (__t) + z_tmcvt_off_div(__from_hz, __to_hz, \
187+
__round_up, __round_off)) / \
188+
z_tmcvt_divisor(__from_hz, __to_hz))
179189

180190
/* Integer multiplcation 64-bit conversion */
181191
#define z_tmcvt_int_mul_64(__t, __from_hz, __to_hz) \

0 commit comments

Comments
 (0)