1 # SPDX-License-Identifier: LGPL-3-or-later
2 from nmigen
import Module
, Signal
, Elaboratable
, Cat
, Repl
4 """ This module is much more efficient than PriorityEncoder
5 although it is functionally identical.
6 see https://bugs.libre-soc.org/show_bug.cgi?id=326
8 This work is funded through NLnet under Grant 2019-02-012
15 class CLZ(Elaboratable
):
16 def __init__(self
, width
):
18 self
.sig_in
= Signal(width
, reset_less
=True)
19 out_width
= math
.ceil(math
.log2(width
+1))
20 self
.lz
= Signal(out_width
)
22 def generate_pairs(self
, m
):
25 for i
in range(0, self
.width
, 2):
27 pair
= Signal(1, name
="cnt_1_%d" % (i
/2))
28 comb
+= pair
.eq(~self
.sig_in
[i
])
29 pairs
.append((pair
, 1))
31 pair
= Signal(2, name
="pair%d" % i
)
32 comb
+= pair
.eq(self
.sig_in
[i
:i
+2])
34 pair_cnt
= Signal(2, name
="cnt_1_%d" % (i
/2))
37 comb
+= pair_cnt
.eq(2)
39 comb
+= pair_cnt
.eq(1)
41 comb
+= pair_cnt
.eq(0)
42 pairs
.append((pair_cnt
, 2)) # append pair, max_value
45 def combine_pairs(self
, m
, iteration
, pairs
):
49 for i
in range(0, length
, 2):
53 new_pair
= Signal(width
, name
="cnt_%d_%d" % (iteration
, i
))
54 comb
+= new_pair
.eq(Cat(right
, 0))
55 ret
.append((new_pair
, mv
))
59 width
= right
.width
+ 1
60 new_pair
= Signal(width
, name
="cnt_%d_%d" % (iteration
, i
))
62 with m
.If(left
[-1] == 1):
63 with m
.If(right
[-1] == 1):
64 comb
+= new_pair
.eq(Cat(Repl(0, width
-1), 1))
66 comb
+= new_pair
.eq(Cat(right
[0:-1], 0b01))
68 comb
+= new_pair
.eq(Cat(left
, 0))
70 with m
.If(left
== lv
):
71 comb
+= new_pair
.eq(right
+ left
)
73 comb
+= new_pair
.eq(left
)
75 ret
.append((new_pair
, lv
+rv
))
78 def elaborate(self
, platform
):
82 pairs
= self
.generate_pairs(m
)
85 pairs
= self
.combine_pairs(m
, i
, pairs
)
88 comb
+= self
.lz
.eq(pairs
[0][0])