[llvm] MathExtras: rewrite two methods to never overflow (PR #95556)

Jay Foad via llvm-commits llvm-commits at lists.llvm.org
Fri Jun 14 08:59:09 PDT 2024


================
@@ -461,9 +467,11 @@ inline int64_t mod(int64_t Numerator, int64_t Denominator) {
   return Mod < 0 ? Mod + Denominator : Mod;
 }
 
-/// Returns the integer nearest(Numerator / Denominator).
+/// Returns (Numerator / Denominator) rounded by round-half-up. Guranteed to
+/// never overflow.
 inline uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator) {
-  return (Numerator + (Denominator / 2)) / Denominator;
+  return (Numerator / Denominator) +
+         (Denominator == 1 ? 0 : Numerator % Denominator >= Denominator / 2);
----------------
jayfoad wrote:

This doesn't look right. It looks like `3 / 7` would round up to `1` with this implementation.

https://github.com/llvm/llvm-project/pull/95556


More information about the llvm-commits mailing list