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