d02dac4a1691b8320eb826ec7539d4648edd0902
[ieee754fpu.git] / src / ieee754 / part / partsig.py
1 # SPDX-License-Identifier: LGPL-2.1-or-later
2 # See Notices.txt for copyright information
3
4 """
5 Copyright (C) 2020 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
6
7 dynamic-partitionable class similar to Signal, which, when the partition
8 is fully open will be identical to Signal. when partitions are closed,
9 the class turns into a SIMD variant of Signal. *this is dynamic*.
10
11 the basic fundamental idea is: write code once, and if you want a SIMD
12 version of it, use PartitionedSignal in place of Signal. job done.
13 this however requires the code to *not* be designed to use nmigen.If,
14 nmigen.Case, or other constructs: only Mux and other logic.
15
16 * http://bugs.libre-riscv.org/show_bug.cgi?id=132
17 """
18
19 from ieee754.part_mul_add.adder import PartitionedAdder
20 from ieee754.part_cmp.eq_gt_ge import PartitionedEqGtGe
21 from ieee754.part_bits.xor import PartitionedXOR
22 from ieee754.part_bits.bool import PartitionedBool
23 from ieee754.part_bits.all import PartitionedAll
24 from ieee754.part_shift.part_shift_dynamic import PartitionedDynamicShift
25 from ieee754.part_shift.part_shift_scalar import PartitionedScalarShift
26 from ieee754.part_mul_add.partpoints import make_partition2, PartitionPoints
27 from ieee754.part_mux.part_mux import PMux
28 from ieee754.part_ass.passign import PAssign
29 from ieee754.part_cat.pcat import PCat
30 from ieee754.part_repl.prepl import PRepl
31 from operator import or_, xor, and_, not_
32
33 from nmigen import (Signal, Const, Cat)
34 from nmigen.hdl.ast import UserValue, Shape
35
36
37 def getsig(op1):
38 if isinstance(op1, PartitionedSignal):
39 op1 = op1.sig
40 return op1
41
42
43 def applyop(op1, op2, op):
44 if isinstance(op1, PartitionedSignal):
45 result = PartitionedSignal.like(op1)
46 else:
47 result = PartitionedSignal.like(op2)
48 result.m.d.comb += result.sig.eq(op(getsig(op1), getsig(op2)))
49 return result
50
51 global modnames
52 modnames = {}
53 # for sub-modules to be created on-demand. Mux is done slightly
54 # differently (has its own global)
55 for name in ['add', 'eq', 'gt', 'ge', 'ls', 'xor', 'bool', 'all']:
56 modnames[name] = 0
57
58
59
60 class PartType: # TODO decide name
61 def __init__(self, psig):
62 self.psig = psig
63 def get_mask(self):
64 return list(self.psig.partpoints.values())
65 def get_switch(self):
66 return Cat(self.get_mask())
67 def get_cases(self):
68 return range(1<<len(self.get_mask()))
69 @property
70 def blanklanes(self):
71 return 0
72
73
74 class PartitionedSignal(UserValue):
75 # XXX ################################################### XXX
76 # XXX Keep these functions in the same order as ast.Value XXX
77 # XXX ################################################### XXX
78 def __init__(self, mask, *args, src_loc_at=0, **kwargs):
79 super().__init__(src_loc_at=src_loc_at)
80 self.sig = Signal(*args, **kwargs)
81 width = len(self.sig) # get signal width
82 # create partition points
83 if isinstance(mask, PartitionPoints):
84 self.partpoints = mask
85 else:
86 self.partpoints = make_partition2(mask, width)
87 self.ptype = PartType(self)
88
89 def set_module(self, m):
90 self.m = m
91
92 def get_modname(self, category):
93 modnames[category] += 1
94 return "%s_%d" % (category, modnames[category])
95
96 @staticmethod
97 def like(other, *args, **kwargs):
98 """Builds a new PartitionedSignal with the same PartitionPoints and
99 Signal properties as the other"""
100 result = PartitionedSignal(PartitionPoints(other.partpoints))
101 result.sig = Signal.like(other.sig, *args, **kwargs)
102 result.m = other.m
103 return result
104
105 def lower(self):
106 return self.sig
107
108 # nmigen-redirected constructs (Mux, Cat, Switch, Assign)
109
110 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
111 #def __Part__(self, offset, width, stride=1, *, src_loc_at=0):
112
113 def __Repl__(self, count, *, src_loc_at=0):
114 return PRepl(self.m, self, count, self.ptype)
115
116 def __Cat__(self, *args, src_loc_at=0):
117 args = [self] + list(args)
118 for sig in args:
119 assert isinstance(sig, PartitionedSignal), \
120 "All PartitionedSignal.__Cat__ arguments must be " \
121 "a PartitionedSignal. %s is not." % repr(sig)
122 return PCat(self.m, args, self.partpoints)
123
124 def __Mux__(self, val1, val2):
125 # print ("partsig mux", self, val1, val2)
126 assert len(val1) == len(val2), \
127 "PartitionedSignal width sources must be the same " \
128 "val1 == %d, val2 == %d" % (len(val1), len(val2))
129 return PMux(self.m, self.partpoints, self, val1, val2)
130
131 def __Assign__(self, val, *, src_loc_at=0):
132 # print ("partsig ass", self, val)
133 return PAssign(self.m, self, val, self.partpoints)
134
135 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
136 #def __Switch__(self, cases, *, src_loc=None, src_loc_at=0,
137 # case_src_locs={}):
138
139 # no override needed, Value.__bool__ sufficient
140 # def __bool__(self):
141
142 # unary ops that do not require partitioning
143
144 def __invert__(self):
145 result = PartitionedSignal.like(self)
146 self.m.d.comb += result.sig.eq(~self.sig)
147 return result
148
149 # unary ops that require partitioning
150
151 def __neg__(self):
152 z = Const(0, len(self.sig))
153 result, _ = self.sub_op(z, self)
154 return result
155
156 # binary ops that need partitioning
157
158 def add_op(self, op1, op2, carry):
159 op1 = getsig(op1)
160 op2 = getsig(op2)
161 pa = PartitionedAdder(len(op1), self.partpoints)
162 setattr(self.m.submodules, self.get_modname('add'), pa)
163 comb = self.m.d.comb
164 comb += pa.a.eq(op1)
165 comb += pa.b.eq(op2)
166 comb += pa.carry_in.eq(carry)
167 result = PartitionedSignal.like(self)
168 comb += result.sig.eq(pa.output)
169 return result, pa.carry_out
170
171 def sub_op(self, op1, op2, carry=~0):
172 op1 = getsig(op1)
173 op2 = getsig(op2)
174 pa = PartitionedAdder(len(op1), self.partpoints)
175 setattr(self.m.submodules, self.get_modname('add'), pa)
176 comb = self.m.d.comb
177 comb += pa.a.eq(op1)
178 comb += pa.b.eq(~op2)
179 comb += pa.carry_in.eq(carry)
180 result = PartitionedSignal.like(self)
181 comb += result.sig.eq(pa.output)
182 return result, pa.carry_out
183
184 def __add__(self, other):
185 result, _ = self.add_op(self, other, carry=0)
186 return result
187
188 def __radd__(self, other):
189 # https://bugs.libre-soc.org/show_bug.cgi?id=718
190 result, _ = self.add_op(other, self)
191 return result
192
193 def __sub__(self, other):
194 result, _ = self.sub_op(self, other)
195 return result
196
197 def __rsub__(self, other):
198 # https://bugs.libre-soc.org/show_bug.cgi?id=718
199 result, _ = self.sub_op(other, self)
200 return result
201
202 def __mul__(self, other):
203 raise NotImplementedError # too complicated at the moment
204 return Operator("*", [self, other])
205
206 def __rmul__(self, other):
207 raise NotImplementedError # too complicated at the moment
208 return Operator("*", [other, self])
209
210 # not needed: same as Value.__check_divisor
211 #def __check_divisor(self):
212
213 def __mod__(self, other):
214 raise NotImplementedError
215 other = Value.cast(other)
216 other.__check_divisor()
217 return Operator("%", [self, other])
218
219 def __rmod__(self, other):
220 raise NotImplementedError
221 self.__check_divisor()
222 return Operator("%", [other, self])
223
224 def __floordiv__(self, other):
225 raise NotImplementedError
226 other = Value.cast(other)
227 other.__check_divisor()
228 return Operator("//", [self, other])
229
230 def __rfloordiv__(self, other):
231 raise NotImplementedError
232 self.__check_divisor()
233 return Operator("//", [other, self])
234
235 # not needed: same as Value.__check_shamt
236 #def __check_shamt(self):
237
238 # TODO: detect if the 2nd operand is a Const, a Signal or a
239 # PartitionedSignal. if it's a Const or a Signal, a global shift
240 # can occur. if it's a PartitionedSignal, that's much more interesting.
241 def ls_op(self, op1, op2, carry, shr_flag=0):
242 op1 = getsig(op1)
243 if isinstance(op2, Const) or isinstance(op2, Signal):
244 scalar = True
245 pa = PartitionedScalarShift(len(op1), self.partpoints)
246 else:
247 scalar = False
248 op2 = getsig(op2)
249 pa = PartitionedDynamicShift(len(op1), self.partpoints)
250 # else:
251 # TODO: case where the *shifter* is a PartitionedSignal but
252 # the thing *being* Shifted is a scalar (Signal, expression)
253 # https://bugs.libre-soc.org/show_bug.cgi?id=718
254 setattr(self.m.submodules, self.get_modname('ls'), pa)
255 comb = self.m.d.comb
256 if scalar:
257 comb += pa.data.eq(op1)
258 comb += pa.shifter.eq(op2)
259 comb += pa.shift_right.eq(shr_flag)
260 else:
261 comb += pa.a.eq(op1)
262 comb += pa.b.eq(op2)
263 comb += pa.shift_right.eq(shr_flag)
264 # XXX TODO: carry-in, carry-out (for arithmetic shift)
265 #comb += pa.carry_in.eq(carry)
266 return (pa.output, 0)
267
268 def __lshift__(self, other):
269 z = Const(0, len(self.partpoints)+1)
270 result, _ = self.ls_op(self, other, carry=z) # TODO, carry
271 return result
272
273 def __rlshift__(self, other):
274 # https://bugs.libre-soc.org/show_bug.cgi?id=718
275 raise NotImplementedError
276 return Operator("<<", [other, self])
277
278 def __rshift__(self, other):
279 z = Const(0, len(self.partpoints)+1)
280 result, _ = self.ls_op(self, other, carry=z, shr_flag=1) # TODO, carry
281 return result
282
283 def __rrshift__(self, other):
284 # https://bugs.libre-soc.org/show_bug.cgi?id=718
285 raise NotImplementedError
286 return Operator(">>", [other, self])
287
288 # binary ops that don't require partitioning
289
290 def __and__(self, other):
291 return applyop(self, other, and_)
292
293 def __rand__(self, other):
294 return applyop(other, self, and_)
295
296 def __or__(self, other):
297 return applyop(self, other, or_)
298
299 def __ror__(self, other):
300 return applyop(other, self, or_)
301
302 def __xor__(self, other):
303 return applyop(self, other, xor)
304
305 def __rxor__(self, other):
306 return applyop(other, self, xor)
307
308 # binary comparison ops that need partitioning
309
310 def _compare(self, width, op1, op2, opname, optype):
311 # print (opname, op1, op2)
312 pa = PartitionedEqGtGe(width, self.partpoints)
313 setattr(self.m.submodules, self.get_modname(opname), pa)
314 comb = self.m.d.comb
315 comb += pa.opcode.eq(optype) # set opcode
316 if isinstance(op1, PartitionedSignal):
317 comb += pa.a.eq(op1.sig)
318 else:
319 comb += pa.a.eq(op1)
320 if isinstance(op2, PartitionedSignal):
321 comb += pa.b.eq(op2.sig)
322 else:
323 comb += pa.b.eq(op2)
324 return pa.output
325
326 def __eq__(self, other):
327 width = len(self.sig)
328 return self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
329
330 def __ne__(self, other):
331 width = len(self.sig)
332 eq = self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
333 ne = Signal(eq.width)
334 self.m.d.comb += ne.eq(~eq)
335 return ne
336
337 def __lt__(self, other):
338 width = len(self.sig)
339 # swap operands, use gt to do lt
340 return self._compare(width, other, self, "gt", PartitionedEqGtGe.GT)
341
342 def __le__(self, other):
343 width = len(self.sig)
344 # swap operands, use ge to do le
345 return self._compare(width, other, self, "ge", PartitionedEqGtGe.GE)
346
347 def __gt__(self, other):
348 width = len(self.sig)
349 return self._compare(width, self, other, "gt", PartitionedEqGtGe.GT)
350
351 def __ge__(self, other):
352 width = len(self.sig)
353 return self._compare(width, self, other, "ge", PartitionedEqGtGe.GE)
354
355 # no override needed: Value.__abs__ is general enough it does the job
356 # def __abs__(self):
357
358 def __len__(self):
359 return len(self.sig)
360
361 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
362 # def __getitem__(self, key):
363
364 def __new_sign(self, signed):
365 shape = Shape(len(self), signed=signed)
366 result = PartitionedSignal.like(self, shape=shape)
367 self.m.d.comb += result.sig.eq(self.sig)
368 return result
369
370 # http://bugs.libre-riscv.org/show_bug.cgi?id=719
371 def as_unsigned(self):
372 return self.__new_sign(False)
373 def as_signed(self):
374 return self.__new_sign(True)
375
376 # useful operators
377
378 def bool(self):
379 """Conversion to boolean.
380
381 Returns
382 -------
383 Value, out
384 ``1`` if any bits are set, ``0`` otherwise.
385 """
386 width = len(self.sig)
387 pa = PartitionedBool(width, self.partpoints)
388 setattr(self.m.submodules, self.get_modname("bool"), pa)
389 self.m.d.comb += pa.a.eq(self.sig)
390 return pa.output
391
392 def any(self):
393 """Check if any bits are ``1``.
394
395 Returns
396 -------
397 Value, out
398 ``1`` if any bits are set, ``0`` otherwise.
399 """
400 return self != Const(0) # leverage the __ne__ operator here
401 return Operator("r|", [self])
402
403 def all(self):
404 """Check if all bits are ``1``.
405
406 Returns
407 -------
408 Value, out
409 ``1`` if all bits are set, ``0`` otherwise.
410 """
411 # something wrong with PartitionedAll, but self == Const(-1)"
412 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=176#c17
413 #width = len(self.sig)
414 #pa = PartitionedAll(width, self.partpoints)
415 #setattr(self.m.submodules, self.get_modname("all"), pa)
416 #self.m.d.comb += pa.a.eq(self.sig)
417 #return pa.output
418 return self == Const(-1) # leverage the __eq__ operator here
419
420 def xor(self):
421 """Compute pairwise exclusive-or of every bit.
422
423 Returns
424 -------
425 Value, out
426 ``1`` if an odd number of bits are set, ``0`` if an
427 even number of bits are set.
428 """
429 width = len(self.sig)
430 pa = PartitionedXOR(width, self.partpoints)
431 setattr(self.m.submodules, self.get_modname("xor"), pa)
432 self.m.d.comb += pa.a.eq(self.sig)
433 return pa.output
434
435 # not needed: Value.implies does the job
436 # def implies(premise, conclusion):
437
438 # TODO. contains a Value.cast which means an override is needed (on both)
439 # def bit_select(self, offset, width):
440 # def word_select(self, offset, width):
441
442 # not needed: Value.matches, amazingly, should do the job
443 # def matches(self, *patterns):
444
445 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=713
446 def shape(self):
447 return self.sig.shape()