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

Jay Foad via llvm-commits llvm-commits at lists.llvm.org
Sat Jun 15 01:05:36 PDT 2024


================
@@ -461,9 +467,13 @@ 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. Guaranteed to
+/// never overflow.
 inline uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator) {
-  return (Numerator + (Denominator / 2)) / Denominator;
+  uint64_t Mod = Numerator % Denominator;
----------------
jayfoad wrote:

Assert Denominator is non-zero, like the other methods do?

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


More information about the llvm-commits mailing list