1 from nmigen
import Module
, Signal
, Elaboratable
, Cat
, Repl
4 class CLZ(Elaboratable
):
5 def __init__(self
, width
):
7 self
.sig_in
= Signal(width
, reset_less
=True)
8 out_width
= math
.ceil(math
.log2(width
+1))
9 self
.lz
= Signal(out_width
)
11 def generate_pairs(self
, m
):
13 assert self
.width
% 2 == 0 # TODO handle odd widths
15 for i
in range(0, self
.width
, 2):
16 pair
= Signal(2, name
="pair%d" % i
)
17 comb
+= pair
.eq(self
.sig_in
[i
:i
+2])
19 pair_cnt
= Signal(2, name
="cnt_1_%d" % (i
/2))
22 comb
+= pair_cnt
.eq(2)
24 comb
+= pair_cnt
.eq(1)
26 comb
+= pair_cnt
.eq(0)
27 pairs
.append((pair_cnt
, 2)) # append pair, max_value
30 def combine_pairs(self
, m
, iteration
, pairs
):
34 for i
in range(0, length
, 2):
38 print(f
"single({i}) - cnt_{iteration}_{i}")
39 new_pair
= Signal(width
, name
="cnt_%d_%d" % (iteration
, i
))
40 comb
+= new_pair
.eq(Cat(right
, 0))
41 ret
.append((new_pair
, mv
))
45 width
= right
.width
+ 1
47 print(f
"pair({left}, {right}) - cnt_{iteration}_{i}")
48 new_pair
= Signal(width
, name
="cnt_%d_%d" %
51 with m
.If(left
[-1] == 1):
52 with m
.If(right
[-1] == 1):
53 comb
+= new_pair
.eq(Cat(Repl(0, width
-1), 1))
55 comb
+= new_pair
.eq(Cat(right
[0:-1], 0b01))
57 comb
+= new_pair
.eq(Cat(left
, 0))
59 with m
.If(left
== lv
):
60 comb
+= new_pair
.eq(right
+ left
)
62 comb
+= new_pair
.eq(left
)
65 ret
.append((new_pair
, lv
+rv
))
68 def elaborate(self
, platform
):
72 pairs
= self
.generate_pairs(m
)
75 pairs
= self
.combine_pairs(m
, i
, pairs
)
79 comb
+= self
.lz
.eq(pairs
[0][0])