add in TODO notes tying in SimdScope/SimdMode
[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 SimdSignal 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, SimdSignal):
39 op1 = op1.sig
40 return op1
41
42
43 def applyop(op1, op2, op):
44 if isinstance(op1, SimdSignal):
45 result = SimdSignal.like(op1)
46 else:
47 result = SimdSignal.like(op2)
48 result.m.d.comb += result.sig.eq(op(getsig(op1), getsig(op2)))
49 return result
50
51
52 global modnames
53 modnames = {}
54 # for sub-modules to be created on-demand. Mux is done slightly
55 # differently (has its own global)
56 for name in ['add', 'eq', 'gt', 'ge', 'ls', 'xor', 'bool', 'all']:
57 modnames[name] = 0
58
59
60 # Prototype https://bugs.libre-soc.org/show_bug.cgi?id=713#c53
61 # this provides a "compatibility" layer with existing SimdSignal
62 # behaviour. the idea is that this interface defines which "combinations"
63 # of partition selections are relevant, and as an added bonus it says
64 # which partition lanes are completely irrelevant (padding, blank).
65 class PartType: # TODO decide name
66 def __init__(self, psig):
67 self.psig = psig
68
69 def get_mask(self):
70 return list(self.psig.partpoints.values())
71
72 def get_switch(self):
73 return Cat(self.get_mask())
74
75 def get_cases(self):
76 return range(1 << len(self.get_mask()))
77
78 @property
79 def blanklanes(self):
80 return 0
81
82 # this one would be an elwidth version
83 # see https://bugs.libre-soc.org/show_bug.cgi?id=713#c34
84 # it requires an "adapter" which is the layout() function
85 # where the PartitionPoints was *created* by the layout()
86 # function and this class then "understands" the relationship
87 # between elwidth and the PartitionPoints that were created
88 # by layout()
89
90
91 class ElWidthPartType: # TODO decide name
92 def __init__(self, psig):
93 self.psig = psig
94
95 def get_mask(self):
96 ppoints, pbits = layout()
97 return ppoints.values() # i think
98
99 def get_switch(self):
100 return self.psig.elwidth
101
102 def get_cases(self):
103 ppoints, pbits = layout()
104 return pbits
105
106 @property
107 def blanklanes(self):
108 return 0 # TODO
109
110
111 class SimdSignal(UserValue):
112 # XXX ################################################### XXX
113 # XXX Keep these functions in the same order as ast.Value XXX
114 # XXX ################################################### XXX
115 def __init__(self, mask, *args, src_loc_at=0, **kwargs):
116 super().__init__(src_loc_at=src_loc_at)
117 self.sig = Signal(*args, **kwargs)
118 width = len(self.sig) # get signal width
119 # create partition points
120 if False: # isinstance(mask, SimdMode):
121 self.ptype = ElwidPartType(self)
122 # parse the args, get elwid from SimdMode,
123 # get module as well, call self.set_module(mask.module)
124 self.partpoints = ptype.make_layout_get_stuff(mask, *args, **kwargs)
125 if isinstance(mask, PartitionPoints):
126 self.partpoints = mask
127 else:
128 self.partpoints = make_partition2(mask, width)
129 self.ptype = PartType(self)
130
131 def set_module(self, m):
132 self.m = m
133
134 def get_modname(self, category):
135 modnames[category] += 1
136 return "%s_%d" % (category, modnames[category])
137
138 @staticmethod
139 def like(other, *args, **kwargs):
140 """Builds a new SimdSignal with the same PartitionPoints and
141 Signal properties as the other"""
142 result = SimdSignal(PartitionPoints(other.partpoints))
143 result.sig = Signal.like(other.sig, *args, **kwargs)
144 result.m = other.m
145 return result
146
147 def lower(self):
148 return self.sig
149
150 # nmigen-redirected constructs (Mux, Cat, Switch, Assign)
151
152 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
153 #def __Part__(self, offset, width, stride=1, *, src_loc_at=0):
154 raise NotImplementedError("TODO: implement as "
155 "(self>>(offset*stride)[:width]")
156 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
157 def __Slice__(self, start, stop, *, src_loc_at=0):
158 # NO. Swizzled shall NOT be deployed, it violates
159 # Project Development Practices
160 raise NotImplementedError("TODO: need PartitionedSlice")
161
162 def __Repl__(self, count, *, src_loc_at=0):
163 return PRepl(self.m, self, count, self.ptype)
164
165 def __Cat__(self, *args, src_loc_at=0):
166 print ("partsig cat", self, args)
167 # TODO: need SwizzledSimdValue-aware Cat
168 args = [self] + list(args)
169 for sig in args:
170 assert isinstance(sig, SimdSignal), \
171 "All SimdSignal.__Cat__ arguments must be " \
172 "a SimdSignal. %s is not." % repr(sig)
173 return PCat(self.m, args, self.ptype)
174
175 def __Mux__(self, val1, val2):
176 # print ("partsig mux", self, val1, val2)
177 assert len(val1) == len(val2), \
178 "SimdSignal width sources must be the same " \
179 "val1 == %d, val2 == %d" % (len(val1), len(val2))
180 return PMux(self.m, self.partpoints, self, val1, val2, self.ptype)
181
182 def __Assign__(self, val, *, src_loc_at=0):
183 print ("partsig assign", self, val)
184 # this is a truly awful hack, outlined here:
185 # https://bugs.libre-soc.org/show_bug.cgi?id=731#c13
186 # during the period between constructing Simd-aware sub-modules
187 # and the elaborate() being called on them there is a window of
188 # opportunity to indicate which of those submodules is LHS and
189 # which is RHS. manic laughter is permitted. *gibber*.
190 if hasattr(self, "_hack_submodule"):
191 self._hack_submodule.set_lhs_mode(True)
192 if hasattr(val, "_hack_submodule"):
193 val._hack_submodule.set_lhs_mode(False)
194 return PAssign(self.m, self, val, self.ptype)
195
196 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
197 # def __Switch__(self, cases, *, src_loc=None, src_loc_at=0,
198 # case_src_locs={}):
199
200 # no override needed, Value.__bool__ sufficient
201 # def __bool__(self):
202
203 # unary ops that do not require partitioning
204
205 def __invert__(self):
206 result = SimdSignal.like(self)
207 self.m.d.comb += result.sig.eq(~self.sig)
208 return result
209
210 # unary ops that require partitioning
211
212 def __neg__(self):
213 z = Const(0, len(self.sig))
214 result, _ = self.sub_op(z, self)
215 return result
216
217 # binary ops that need partitioning
218
219 def add_op(self, op1, op2, carry):
220 op1 = getsig(op1)
221 op2 = getsig(op2)
222 pa = PartitionedAdder(len(op1), self.partpoints)
223 setattr(self.m.submodules, self.get_modname('add'), pa)
224 comb = self.m.d.comb
225 comb += pa.a.eq(op1)
226 comb += pa.b.eq(op2)
227 comb += pa.carry_in.eq(carry)
228 result = SimdSignal.like(self)
229 comb += result.sig.eq(pa.output)
230 return result, pa.carry_out
231
232 def sub_op(self, op1, op2, carry=~0):
233 op1 = getsig(op1)
234 op2 = getsig(op2)
235 pa = PartitionedAdder(len(op1), self.partpoints)
236 setattr(self.m.submodules, self.get_modname('add'), pa)
237 comb = self.m.d.comb
238 comb += pa.a.eq(op1)
239 comb += pa.b.eq(~op2)
240 comb += pa.carry_in.eq(carry)
241 result = SimdSignal.like(self)
242 comb += result.sig.eq(pa.output)
243 return result, pa.carry_out
244
245 def __add__(self, other):
246 result, _ = self.add_op(self, other, carry=0)
247 return result
248
249 def __radd__(self, other):
250 # https://bugs.libre-soc.org/show_bug.cgi?id=718
251 result, _ = self.add_op(other, self)
252 return result
253
254 def __sub__(self, other):
255 result, _ = self.sub_op(self, other)
256 return result
257
258 def __rsub__(self, other):
259 # https://bugs.libre-soc.org/show_bug.cgi?id=718
260 result, _ = self.sub_op(other, self)
261 return result
262
263 def __mul__(self, other):
264 raise NotImplementedError # too complicated at the moment
265 return Operator("*", [self, other])
266
267 def __rmul__(self, other):
268 raise NotImplementedError # too complicated at the moment
269 return Operator("*", [other, self])
270
271 # not needed: same as Value.__check_divisor
272 # def __check_divisor(self):
273
274 def __mod__(self, other):
275 raise NotImplementedError
276 other = Value.cast(other)
277 other.__check_divisor()
278 return Operator("%", [self, other])
279
280 def __rmod__(self, other):
281 raise NotImplementedError
282 self.__check_divisor()
283 return Operator("%", [other, self])
284
285 def __floordiv__(self, other):
286 raise NotImplementedError
287 other = Value.cast(other)
288 other.__check_divisor()
289 return Operator("//", [self, other])
290
291 def __rfloordiv__(self, other):
292 raise NotImplementedError
293 self.__check_divisor()
294 return Operator("//", [other, self])
295
296 # not needed: same as Value.__check_shamt
297 # def __check_shamt(self):
298
299 # TODO: detect if the 2nd operand is a Const, a Signal or a
300 # SimdSignal. if it's a Const or a Signal, a global shift
301 # can occur. if it's a SimdSignal, that's much more interesting.
302 def ls_op(self, op1, op2, carry, shr_flag=0):
303 op1 = getsig(op1)
304 if isinstance(op2, Const) or isinstance(op2, Signal):
305 scalar = True
306 pa = PartitionedScalarShift(len(op1), self.partpoints)
307 else:
308 scalar = False
309 op2 = getsig(op2)
310 pa = PartitionedDynamicShift(len(op1), self.partpoints)
311 # else:
312 # TODO: case where the *shifter* is a SimdSignal but
313 # the thing *being* Shifted is a scalar (Signal, expression)
314 # https://bugs.libre-soc.org/show_bug.cgi?id=718
315 setattr(self.m.submodules, self.get_modname('ls'), pa)
316 comb = self.m.d.comb
317 if scalar:
318 comb += pa.data.eq(op1)
319 comb += pa.shifter.eq(op2)
320 comb += pa.shift_right.eq(shr_flag)
321 else:
322 comb += pa.a.eq(op1)
323 comb += pa.b.eq(op2)
324 comb += pa.shift_right.eq(shr_flag)
325 # XXX TODO: carry-in, carry-out (for arithmetic shift)
326 #comb += pa.carry_in.eq(carry)
327 return (pa.output, 0)
328
329 def __lshift__(self, other):
330 z = Const(0, len(self.partpoints)+1)
331 result, _ = self.ls_op(self, other, carry=z) # TODO, carry
332 return result
333
334 def __rlshift__(self, other):
335 # https://bugs.libre-soc.org/show_bug.cgi?id=718
336 raise NotImplementedError
337 return Operator("<<", [other, self])
338
339 def __rshift__(self, other):
340 z = Const(0, len(self.partpoints)+1)
341 result, _ = self.ls_op(self, other, carry=z, shr_flag=1) # TODO, carry
342 return result
343
344 def __rrshift__(self, other):
345 # https://bugs.libre-soc.org/show_bug.cgi?id=718
346 raise NotImplementedError
347 return Operator(">>", [other, self])
348
349 # binary ops that don't require partitioning
350
351 def __and__(self, other):
352 return applyop(self, other, and_)
353
354 def __rand__(self, other):
355 return applyop(other, self, and_)
356
357 def __or__(self, other):
358 return applyop(self, other, or_)
359
360 def __ror__(self, other):
361 return applyop(other, self, or_)
362
363 def __xor__(self, other):
364 return applyop(self, other, xor)
365
366 def __rxor__(self, other):
367 return applyop(other, self, xor)
368
369 # binary comparison ops that need partitioning
370
371 def _compare(self, width, op1, op2, opname, optype):
372 # print (opname, op1, op2)
373 pa = PartitionedEqGtGe(width, self.partpoints)
374 setattr(self.m.submodules, self.get_modname(opname), pa)
375 comb = self.m.d.comb
376 comb += pa.opcode.eq(optype) # set opcode
377 if isinstance(op1, SimdSignal):
378 comb += pa.a.eq(op1.sig)
379 else:
380 comb += pa.a.eq(op1)
381 if isinstance(op2, SimdSignal):
382 comb += pa.b.eq(op2.sig)
383 else:
384 comb += pa.b.eq(op2)
385 return pa.output
386
387 def __eq__(self, other):
388 width = len(self.sig)
389 return self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
390
391 def __ne__(self, other):
392 width = len(self.sig)
393 eq = self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
394 ne = Signal(eq.width)
395 self.m.d.comb += ne.eq(~eq)
396 return ne
397
398 def __lt__(self, other):
399 width = len(self.sig)
400 # swap operands, use gt to do lt
401 return self._compare(width, other, self, "gt", PartitionedEqGtGe.GT)
402
403 def __le__(self, other):
404 width = len(self.sig)
405 # swap operands, use ge to do le
406 return self._compare(width, other, self, "ge", PartitionedEqGtGe.GE)
407
408 def __gt__(self, other):
409 width = len(self.sig)
410 return self._compare(width, self, other, "gt", PartitionedEqGtGe.GT)
411
412 def __ge__(self, other):
413 width = len(self.sig)
414 return self._compare(width, self, other, "ge", PartitionedEqGtGe.GE)
415
416 # no override needed: Value.__abs__ is general enough it does the job
417 # def __abs__(self):
418
419 def __len__(self):
420 return len(self.sig)
421
422 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
423 # def __getitem__(self, key):
424
425 def __new_sign(self, signed):
426 shape = Shape(len(self), signed=signed)
427 result = SimdSignal.like(self, shape=shape)
428 self.m.d.comb += result.sig.eq(self.sig)
429 return result
430
431 # http://bugs.libre-riscv.org/show_bug.cgi?id=719
432 def as_unsigned(self):
433 return self.__new_sign(False)
434
435 def as_signed(self):
436 return self.__new_sign(True)
437
438 # useful operators
439
440 def bool(self):
441 """Conversion to boolean.
442
443 Returns
444 -------
445 Value, out
446 ``1`` if any bits are set, ``0`` otherwise.
447 """
448 width = len(self.sig)
449 pa = PartitionedBool(width, self.partpoints)
450 setattr(self.m.submodules, self.get_modname("bool"), pa)
451 self.m.d.comb += pa.a.eq(self.sig)
452 return pa.output
453
454 def any(self):
455 """Check if any bits are ``1``.
456
457 Returns
458 -------
459 Value, out
460 ``1`` if any bits are set, ``0`` otherwise.
461 """
462 return self != Const(0) # leverage the __ne__ operator here
463 return Operator("r|", [self])
464
465 def all(self):
466 """Check if all bits are ``1``.
467
468 Returns
469 -------
470 Value, out
471 ``1`` if all bits are set, ``0`` otherwise.
472 """
473 # something wrong with PartitionedAll, but self == Const(-1)"
474 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=176#c17
475 #width = len(self.sig)
476 #pa = PartitionedAll(width, self.partpoints)
477 #setattr(self.m.submodules, self.get_modname("all"), pa)
478 #self.m.d.comb += pa.a.eq(self.sig)
479 # return pa.output
480 return self == Const(-1) # leverage the __eq__ operator here
481
482 def xor(self):
483 """Compute pairwise exclusive-or of every bit.
484
485 Returns
486 -------
487 Value, out
488 ``1`` if an odd number of bits are set, ``0`` if an
489 even number of bits are set.
490 """
491 width = len(self.sig)
492 pa = PartitionedXOR(width, self.partpoints)
493 setattr(self.m.submodules, self.get_modname("xor"), pa)
494 self.m.d.comb += pa.a.eq(self.sig)
495 return pa.output
496
497 # not needed: Value.implies does the job
498 # def implies(premise, conclusion):
499
500 # TODO. contains a Value.cast which means an override is needed (on both)
501 # def bit_select(self, offset, width):
502 # def word_select(self, offset, width):
503
504 # not needed: Value.matches, amazingly, should do the job
505 # def matches(self, *patterns):
506
507 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=713
508 def shape(self):
509 return self.sig.shape()