add default argument fn=None to treereduce (identity operation)
[nmutil.git] / src / nmutil / util.py
1 """
2 This work is funded through NLnet under Grant 2019-02-012
3
4 License: LGPLv3+
5
6 """
7
8 from collections.abc import Iterable
9 from nmigen import Mux, Signal, Cat
10
11
12 # XXX this already exists in nmigen._utils
13 # see https://bugs.libre-soc.org/show_bug.cgi?id=297
14 def flatten(v):
15 if isinstance(v, Iterable):
16 for i in v:
17 yield from flatten(i)
18 else:
19 yield v
20
21
22 # tree reduction function. operates recursively.
23 def treereduce(tree, op, fn=None):
24 """treereduce: apply a map-reduce to a list, reducing to a single item
25
26 this is *not* the same as "x = Signal(64) reduce(x, operator.add)",
27 which is a bit-wise reduction down to a single bit
28
29 it is "l = [Signal(w), ..., Signal(w)] reduce(l, operator.add)"
30 i.e. l[0] + l[1] ...
31
32 examples: OR-reduction of one member of a list of Records down to a
33 single value:
34 treereduce(tree, operator.or_, lambda x: getattr(x, "o_data"))
35 """
36 if fn is None:
37 fn = lambda x: x
38 if not isinstance(tree, list):
39 return tree
40 if len(tree) == 1:
41 return fn(tree[0])
42 if len(tree) == 2:
43 return op(fn(tree[0]), fn(tree[1]))
44 s = len(tree) // 2 # splitpoint
45 return op(treereduce(tree[:s], op, fn),
46 treereduce(tree[s:], op, fn))
47
48 # chooses assignment of 32 bit or full 64 bit depending on is_32bit
49 def eq32(is_32bit, dest, src):
50 return [dest[0:32].eq(src[0:32]),
51 dest[32:64].eq(Mux(is_32bit, 0, src[32:64]))]
52
53
54 # a wrapper function formerly in run_simulation that is still useful.
55 # Simulation.add_sync_process now only takes functions, it does not
56 # take generators. so passing in arguments is no longer possible.
57 # with this wrapper, the following is possible:
58 # sim.add_sync_process(wrap.dut(parallel_sender_number=0))
59 # sim.add_sync_process(wrap.dut(parallel_sender_number=1))
60
61 def wrap(process):
62 def wrapper():
63 yield from process
64 return wrapper
65
66
67 # a "rising edge" generator. can take signals of greater than width 1
68
69 def rising_edge(m, sig):
70 delay = Signal.like(sig)
71 rising = Signal.like(sig)
72 delay.name = "%s_dly" % sig.name
73 rising.name = "%s_rise" % sig.name
74 m.d.sync += delay.eq(sig) # 1 clock delay
75 m.d.comb += rising.eq(sig & ~delay) # sig is hi but delay-sig is lo
76 return rising
77
78
79 # Display function (dummy if non-existent)
80 # added as a patch from jeanthom
81 # https://gist.githubusercontent.com/jeanthom/
82 # f97f5b928720d4adda9d295e8a5bc078/
83 # raw/694274e0aceec993c0fc127e296b1a85b93c1b89/nmigen-display.diff
84 try:
85 from nmigen.hdl.ast import Display
86 except ImportError:
87 def Display(*args):
88 return []
89
90
91 def sel(m, r, sel_bits, field_width=None, name=None, src_loc_at=0):
92 """Forms a subfield from a selection of bits of the signal `r`
93 ("register").
94
95 :param m: nMigen Module for adding the wires
96 :param r: signal containing the field from which to select the subfield
97 :param sel_bits: bit indices of the subfield, in "MSB 0" convention,
98 from most significant to least significant. Note that
99 the indices are allowed to be non-contiguous and/or
100 out-of-order.
101 :param field_width: field width. If absent, use the signal `r` own width.
102 :param name: name of the generated Signal
103 :param src_loc_at: in the absence of `name`, stack level in which
104 to find it
105
106 :returns: a new Signal which gets assigned to the subfield
107 """
108 # find the MSB index in LSB0 numbering
109 if field_width is None:
110 msb = len(r) - 1
111 else:
112 msb = field_width - 1
113 # extract the selected bits
114 sig_list = []
115 for idx in sel_bits:
116 sig_list.append(r[msb - idx])
117 # place the LSB at the front of the list,
118 # since, in nMigen, Cat starts from the LSB
119 sig_list.reverse()
120 sel_ret = Signal(len(sig_list), name=name, src_loc_at=src_loc_at+1)
121 m.d.comb += sel_ret.eq(Cat(*sig_list))
122 return sel_ret