From bcf5e923896eb84d9d342246a5c2dfd5c3b61c92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Povi=C5=A1er?= Date: Mon, 11 Dec 2023 22:10:51 +0100 Subject: [PATCH] cxxrtl: Fix `ctlz` implementation --- backends/cxxrtl/runtime/cxxrtl/cxxrtl.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/backends/cxxrtl/runtime/cxxrtl/cxxrtl.h b/backends/cxxrtl/runtime/cxxrtl/cxxrtl.h index bd4affc30..0be7ab2b2 100644 --- a/backends/cxxrtl/runtime/cxxrtl/cxxrtl.h +++ b/backends/cxxrtl/runtime/cxxrtl/cxxrtl.h @@ -508,12 +508,13 @@ struct value : public expr_base> { size_t count = 0; for (size_t n = 0; n < chunks; n++) { chunk::type x = data[chunks - 1 - n]; - if (x == 0) { - count += (n == 0 ? Bits % chunk::bits : chunk::bits); - } else { - // This loop implements the find first set idiom as recognized by LLVM. - for (; x != 0; count++) + // First add to `count` as if the chunk is zero + count += (n == 0 ? Bits % chunk::bits : chunk::bits); + // If the chunk isn't zero, correct the `count` value and return + if (x != 0) { + for (; x != 0; count--) x >>= 1; + break; } } return count;