Skip to content

Commit ac4f7ef

Browse files
kazutakahiratagithub-actions[bot]
authored andcommitted
Automerge: [ADT] Simplify rotl/rotr implementations (NFC) (#164055)
This patch simplifies rotl and rotr by ANDing the rotate amount with N - 1. This way, we can remove the mutual dependencies and the forward declaration of rotr.
2 parents a4d5f8b + e3609ae commit ac4f7ef

File tree

1 file changed

+12
-17
lines changed
  • llvm/include/llvm/ADT

1 file changed

+12
-17
lines changed

llvm/include/llvm/ADT/bit.h

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -336,33 +336,28 @@ template <typename T> [[nodiscard]] T bit_ceil(T Value) {
336336
return T(1) << llvm::bit_width<T>(Value - 1u);
337337
}
338338

339-
// Forward-declare rotr so that rotl can use it.
340-
template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
341-
[[nodiscard]] constexpr T rotr(T V, int R);
342-
343339
template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
344340
[[nodiscard]] constexpr T rotl(T V, int R) {
345-
unsigned N = std::numeric_limits<T>::digits;
341+
constexpr unsigned N = std::numeric_limits<T>::digits;
346342

347-
R = R % N;
348-
if (!R)
349-
return V;
343+
static_assert(has_single_bit(N), "& (N - 1) is only valid for powers of two");
344+
R = R & (N - 1);
350345

351-
if (R < 0)
352-
return llvm::rotr(V, -R);
346+
if (R == 0)
347+
return V;
353348

354349
return (V << R) | (V >> (N - R));
355350
}
356351

357-
template <typename T, typename> [[nodiscard]] constexpr T rotr(T V, int R) {
358-
unsigned N = std::numeric_limits<T>::digits;
352+
template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
353+
[[nodiscard]] constexpr T rotr(T V, int R) {
354+
constexpr unsigned N = std::numeric_limits<T>::digits;
359355

360-
R = R % N;
361-
if (!R)
362-
return V;
356+
static_assert(has_single_bit(N), "& (N - 1) is only valid for powers of two");
357+
R = R & (N - 1);
363358

364-
if (R < 0)
365-
return llvm::rotl(V, -R);
359+
if (R == 0)
360+
return V;
366361

367362
return (V >> R) | (V << (N - R));
368363
}

0 commit comments

Comments
 (0)