[llvm] MathExtras: rewrite two methods to never overflow (PR #95556)
Ramkumar Ramachandra via llvm-commits
llvm-commits at lists.llvm.org
Fri Jun 14 09:19:00 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);
----------------
artagnon wrote:
The issue is that I can't do `2 * (Numerator % Denominator)`, due to possible overflow.
https://github.com/llvm/llvm-project/pull/95556
More information about the llvm-commits
mailing list