1 from nmigen
import Module
, Signal
, Elaboratable
, Cat
, Repl
3 """ This module is much more efficient than PriorityEncoder
4 although it is functionally identical.
5 see https://bugs.libre-soc.org/show_bug.cgi?id=326
7 This work is funded through NLnet under Grant 2019-02-012
13 class CLZ(Elaboratable
):
14 def __init__(self
, width
):
16 self
.sig_in
= Signal(width
, reset_less
=True)
17 out_width
= math
.ceil(math
.log2(width
+1))
18 self
.lz
= Signal(out_width
)
20 def generate_pairs(self
, m
):
23 for i
in range(0, self
.width
, 2):
25 pair
= Signal(1, name
="cnt_1_%d" % (i
/2))
26 comb
+= pair
.eq(~self
.sig_in
[i
])
27 pairs
.append((pair
, 1))
29 pair
= Signal(2, name
="pair%d" % i
)
30 comb
+= pair
.eq(self
.sig_in
[i
:i
+2])
32 pair_cnt
= Signal(2, name
="cnt_1_%d" % (i
/2))
35 comb
+= pair_cnt
.eq(2)
37 comb
+= pair_cnt
.eq(1)
39 comb
+= pair_cnt
.eq(0)
40 pairs
.append((pair_cnt
, 2)) # append pair, max_value
43 def combine_pairs(self
, m
, iteration
, pairs
):
47 for i
in range(0, length
, 2):
51 new_pair
= Signal(width
, name
="cnt_%d_%d" % (iteration
, i
))
52 comb
+= new_pair
.eq(Cat(right
, 0))
53 ret
.append((new_pair
, mv
))
57 width
= right
.width
+ 1
58 new_pair
= Signal(width
, name
="cnt_%d_%d" % (iteration
, i
))
60 with m
.If(left
[-1] == 1):
61 with m
.If(right
[-1] == 1):
62 comb
+= new_pair
.eq(Cat(Repl(0, width
-1), 1))
64 comb
+= new_pair
.eq(Cat(right
[0:-1], 0b01))
66 comb
+= new_pair
.eq(Cat(left
, 0))
68 with m
.If(left
== lv
):
69 comb
+= new_pair
.eq(right
+ left
)
71 comb
+= new_pair
.eq(left
)
73 ret
.append((new_pair
, lv
+rv
))
76 def elaborate(self
, platform
):
80 pairs
= self
.generate_pairs(m
)
83 pairs
= self
.combine_pairs(m
, i
, pairs
)
86 comb
+= self
.lz
.eq(pairs
[0][0])