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
14 class CLZ(Elaboratable
):
15 def __init__(self
, width
):
17 self
.sig_in
= Signal(width
, reset_less
=True)
18 out_width
= math
.ceil(math
.log2(width
+1))
19 self
.lz
= Signal(out_width
)
21 def generate_pairs(self
, m
):
24 for i
in range(0, self
.width
, 2):
26 pair
= Signal(1, name
="cnt_1_%d" % (i
/2))
27 comb
+= pair
.eq(~self
.sig_in
[i
])
28 pairs
.append((pair
, 1))
30 pair
= Signal(2, name
="pair%d" % i
)
31 comb
+= pair
.eq(self
.sig_in
[i
:i
+2])
33 pair_cnt
= Signal(2, name
="cnt_1_%d" % (i
/2))
36 comb
+= pair_cnt
.eq(2)
38 comb
+= pair_cnt
.eq(1)
40 comb
+= pair_cnt
.eq(0)
41 pairs
.append((pair_cnt
, 2)) # append pair, max_value
44 def combine_pairs(self
, m
, iteration
, pairs
):
48 for i
in range(0, length
, 2):
52 new_pair
= Signal(width
, name
="cnt_%d_%d" % (iteration
, i
))
53 comb
+= new_pair
.eq(Cat(right
, 0))
54 ret
.append((new_pair
, mv
))
58 width
= right
.width
+ 1
59 new_pair
= Signal(width
, name
="cnt_%d_%d" % (iteration
, i
))
61 with m
.If(left
[-1] == 1):
62 with m
.If(right
[-1] == 1):
63 comb
+= new_pair
.eq(Cat(Repl(0, width
-1), 1))
65 comb
+= new_pair
.eq(Cat(right
[0:-1], 0b01))
67 comb
+= new_pair
.eq(Cat(left
, 0))
69 with m
.If(left
== lv
):
70 comb
+= new_pair
.eq(right
+ left
)
72 comb
+= new_pair
.eq(left
)
74 ret
.append((new_pair
, lv
+rv
))
77 def elaborate(self
, platform
):
81 pairs
= self
.generate_pairs(m
)
84 pairs
= self
.combine_pairs(m
, i
, pairs
)
87 comb
+= self
.lz
.eq(pairs
[0][0])