[llvm] [APint] Add fast path for APInt::urem if RHS is power of 2 (PR #189245)
via llvm-commits
llvm-commits at lists.llvm.org
Sun Mar 29 06:25:32 PDT 2026
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-llvm-support
Author: Max Graey (MaxGraey)
<details>
<summary>Changes</summary>
---
Full diff: https://github.com/llvm/llvm-project/pull/189245.diff
1 Files Affected:
- (modified) llvm/lib/Support/APInt.cpp (+6)
``````````diff
diff --git a/llvm/lib/Support/APInt.cpp b/llvm/lib/Support/APInt.cpp
index 0a9cda5299fc8..55c7e4f004132 100644
--- a/llvm/lib/Support/APInt.cpp
+++ b/llvm/lib/Support/APInt.cpp
@@ -1705,6 +1705,9 @@ APInt APInt::urem(const APInt &RHS) const {
if (lhsWords == 1)
// All high words are zero, just use native remainder
return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]);
+ if (RHS.isPowerOf2())
+ // X % 2^w ===> X & (2^w - 1)
+ return trunc(RHS.logBase2());
// We have to compute it the hard way. Invoke the Knuth divide algorithm.
APInt Remainder(BitWidth, 0);
@@ -1737,6 +1740,9 @@ uint64_t APInt::urem(uint64_t RHS) const {
if (lhsWords == 1)
// All high words are zero, just use native remainder
return U.pVal[0] % RHS;
+ if (llvm::isPowerOf2_64(RHS))
+ // X % 2^w ===> X & (2^w - 1)
+ return getZExtValue() & (RHS - 1);
// We have to compute it the hard way. Invoke the Knuth divide algorithm.
uint64_t Remainder;
``````````
</details>
https://github.com/llvm/llvm-project/pull/189245
More information about the llvm-commits
mailing list