[llvm] [MathExtras][NFC] Optimize NextPowerOf2 similar to PowerOf2Ceil (PR #189160)

via llvm-commits llvm-commits at lists.llvm.org
Sat Mar 28 05:36:52 PDT 2026


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-support

Author: Max Graey (MaxGraey)

<details>
<summary>Changes</summary>

Original `NextPowerOf2` was added [18 years ago](https://github.com/llvm/llvm-project/commit/05546f67cbcb85228ab17b7e52f4a960ce680466) and before the necessary intrinsics and `Log2_64_Ceil` were available. I think it's time to rewrite this using a more efficient method that leverages `Log2_64_Ceil`, similar to `PowerOf2Ceil` with the slight difference that we don't need to check if `A == 0`.

---
Full diff: https://github.com/llvm/llvm-project/pull/189160.diff


1 Files Affected:

- (modified) llvm/include/llvm/Support/MathExtras.h (+4-8) 


``````````diff
diff --git a/llvm/include/llvm/Support/MathExtras.h b/llvm/include/llvm/Support/MathExtras.h
index de2813094a950..59e7e40b742aa 100644
--- a/llvm/include/llvm/Support/MathExtras.h
+++ b/llvm/include/llvm/Support/MathExtras.h
@@ -370,14 +370,10 @@ constexpr uint64_t MinAlign(uint64_t A, uint64_t B) {
 
 /// Returns the next power of two (in 64-bits) that is strictly greater than A.
 /// Returns zero on overflow.
-constexpr uint64_t NextPowerOf2(uint64_t A) {
-  A |= (A >> 1);
-  A |= (A >> 2);
-  A |= (A >> 4);
-  A |= (A >> 8);
-  A |= (A >> 16);
-  A |= (A >> 32);
-  return A + 1;
+inline uint64_t NextPowerOf2(uint64_t A) {
+  if (A > UINT64_MAX / 2)
+    return 0;
+  return UINT64_C(1) << Log2_64_Ceil(A + 1);
 }
 
 /// Returns the power of two which is greater than or equal to the given value.

``````````

</details>


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


More information about the llvm-commits mailing list