26e526aca2a6a695f91256d860f9ed18f178e7e9
1 # SPDX-License-Identifier: LGPL-2.1-or-later
2 # See Notices.txt for copyright information
5 Copyright (C) 2020 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
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*.
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.
16 * http://bugs.libre-riscv.org/show_bug.cgi?id=132
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_
35 from nmigen
import (Signal
, Const
, Cat
)
36 from nmigen
.hdl
.ast
import UserValue
, Shape
40 if isinstance(op1
, SimdSignal
):
45 def applyop(op1
, op2
, op
):
46 if isinstance(op1
, SimdSignal
):
47 result
= SimdSignal
.like(op1
)
49 result
= SimdSignal
.like(op2
)
50 result
.m
.d
.comb
+= result
.sig
.eq(op(getsig(op1
), getsig(op2
)))
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']:
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
):
72 return list(self
.psig
.partpoints
.values())
75 return Cat(self
.get_mask())
78 return range(1 << len(self
.get_mask()))
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
92 class ElwidPartType
: # TODO decide name
93 def __init__(self
, psig
):
97 return list(self
.psig
._shape
.partpoints
.values()) # i think
100 return self
.psig
.scope
.elwid
# switch on elwid: match get_cases()
103 return self
.psig
._shape
.bitp
.keys() # all possible values of elwid
106 def blanklanes(self
):
107 return self
.psig
.shape
.blankmask
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
116 naming is preserved to be compatible with Shape().
118 def __init__(self
, scope
, width
=None, # this is actually widths_at_elwid
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
) = \
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
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
)
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
153 self
.ptype
= ElwidPartType(self
)
154 # adapt shape to a SimdShape
155 if not isinstance(shape
, SimdShape
):
156 shape
= SimdShape(self
.scope
, shape
)
158 self
.sig
= Signal(shape
, *args
, **kwargs
)
159 # get partpoints from SimdShape
160 self
.partpoints
= shape
.partpoints
162 self
.sig
= Signal(shape
, *args
, **kwargs
)
163 width
= len(self
.sig
) # get signal width
164 if isinstance(mask
, PartitionPoints
):
165 self
.partpoints
= mask
167 self
.partpoints
= make_partition2(mask
, width
)
168 self
.ptype
= PartType(self
)
170 def set_module(self
, m
):
173 def get_modname(self
, category
):
174 modnames
[category
] += 1
175 return "%s_%d" % (category
, modnames
[category
])
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
)
189 # nmigen-redirected constructs (Mux, Cat, Switch, Assign)
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")
201 def __Repl__(self
, count
, *, src_loc_at
=0):
202 return PRepl(self
.m
, self
, count
, self
.ptype
)
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
)
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
)
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
)
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
)
235 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
236 # def __Switch__(self, cases, *, src_loc=None, src_loc_at=0,
239 # no override needed, Value.__bool__ sufficient
240 # def __bool__(self):
242 # unary ops that do not require partitioning
244 def __invert__(self
):
245 result
= SimdSignal
.like(self
)
246 self
.m
.d
.comb
+= result
.sig
.eq(~self
.sig
)
249 # unary ops that require partitioning
252 z
= Const(0, len(self
.sig
))
253 result
, _
= self
.sub_op(z
, self
)
256 # binary ops that need partitioning
258 def add_op(self
, op1
, op2
, carry
):
261 pa
= PartitionedAdder(len(op1
), self
.partpoints
)
262 setattr(self
.m
.submodules
, self
.get_modname('add'), pa
)
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
271 def sub_op(self
, op1
, op2
, carry
=~
0):
274 pa
= PartitionedAdder(len(op1
), self
.partpoints
)
275 setattr(self
.m
.submodules
, self
.get_modname('add'), pa
)
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
284 def __add__(self
, other
):
285 result
, _
= self
.add_op(self
, other
, carry
=0)
288 def __radd__(self
, other
):
289 # https://bugs.libre-soc.org/show_bug.cgi?id=718
290 result
, _
= self
.add_op(other
, self
)
293 def __sub__(self
, other
):
294 result
, _
= self
.sub_op(self
, other
)
297 def __rsub__(self
, other
):
298 # https://bugs.libre-soc.org/show_bug.cgi?id=718
299 result
, _
= self
.sub_op(other
, self
)
302 def __mul__(self
, other
):
303 raise NotImplementedError # too complicated at the moment
304 return Operator("*", [self
, other
])
306 def __rmul__(self
, other
):
307 raise NotImplementedError # too complicated at the moment
308 return Operator("*", [other
, self
])
310 # not needed: same as Value.__check_divisor
311 # def __check_divisor(self):
313 def __mod__(self
, other
):
314 raise NotImplementedError
315 other
= Value
.cast(other
)
316 other
.__check
_divisor
()
317 return Operator("%", [self
, other
])
319 def __rmod__(self
, other
):
320 raise NotImplementedError
321 self
.__check
_divisor
()
322 return Operator("%", [other
, self
])
324 def __floordiv__(self
, other
):
325 raise NotImplementedError
326 other
= Value
.cast(other
)
327 other
.__check
_divisor
()
328 return Operator("//", [self
, other
])
330 def __rfloordiv__(self
, other
):
331 raise NotImplementedError
332 self
.__check
_divisor
()
333 return Operator("//", [other
, self
])
335 # not needed: same as Value.__check_shamt
336 # def __check_shamt(self):
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):
343 if isinstance(op2
, Const
) or isinstance(op2
, Signal
):
345 pa
= PartitionedScalarShift(len(op1
), self
.partpoints
)
349 pa
= PartitionedDynamicShift(len(op1
), self
.partpoints
)
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
)
357 comb
+= pa
.data
.eq(op1
)
358 comb
+= pa
.shifter
.eq(op2
)
359 comb
+= pa
.shift_right
.eq(shr_flag
)
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)
368 def __lshift__(self
, other
):
369 z
= Const(0, len(self
.partpoints
)+1)
370 result
, _
= self
.ls_op(self
, other
, carry
=z
) # TODO, carry
373 def __rlshift__(self
, other
):
374 # https://bugs.libre-soc.org/show_bug.cgi?id=718
375 raise NotImplementedError
376 return Operator("<<", [other
, self
])
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
383 def __rrshift__(self
, other
):
384 # https://bugs.libre-soc.org/show_bug.cgi?id=718
385 raise NotImplementedError
386 return Operator(">>", [other
, self
])
388 # binary ops that don't require partitioning
390 def __and__(self
, other
):
391 return applyop(self
, other
, and_
)
393 def __rand__(self
, other
):
394 return applyop(other
, self
, and_
)
396 def __or__(self
, other
):
397 return applyop(self
, other
, or_
)
399 def __ror__(self
, other
):
400 return applyop(other
, self
, or_
)
402 def __xor__(self
, other
):
403 return applyop(self
, other
, xor
)
405 def __rxor__(self
, other
):
406 return applyop(other
, self
, xor
)
408 # binary comparison ops that need partitioning
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
)
415 comb
+= pa
.opcode
.eq(optype
) # set opcode
416 if isinstance(op1
, SimdSignal
):
417 comb
+= pa
.a
.eq(op1
.sig
)
420 if isinstance(op2
, SimdSignal
):
421 comb
+= pa
.b
.eq(op2
.sig
)
426 def __eq__(self
, other
):
427 width
= len(self
.sig
)
428 return self
._compare
(width
, self
, other
, "eq", PartitionedEqGtGe
.EQ
)
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
)
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
)
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
)
447 def __gt__(self
, other
):
448 width
= len(self
.sig
)
449 return self
._compare
(width
, self
, other
, "gt", PartitionedEqGtGe
.GT
)
451 def __ge__(self
, other
):
452 width
= len(self
.sig
)
453 return self
._compare
(width
, self
, other
, "ge", PartitionedEqGtGe
.GE
)
455 # no override needed: Value.__abs__ is general enough it does the job
461 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
462 # def __getitem__(self, key):
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
)
472 # http://bugs.libre-riscv.org/show_bug.cgi?id=719
473 def as_unsigned(self
):
474 return self
.__new
_sign
(False)
477 return self
.__new
_sign
(True)
482 """Conversion to boolean.
487 ``1`` if any bits are set, ``0`` otherwise.
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
)
496 """Check if any bits are ``1``.
501 ``1`` if any bits are set, ``0`` otherwise.
503 return self
!= Const(0) # leverage the __ne__ operator here
504 return Operator("r|", [self
])
507 """Check if all bits are ``1``.
512 ``1`` if all bits are set, ``0`` otherwise.
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)
521 return self
== Const(-1) # leverage the __eq__ operator here
524 """Compute pairwise exclusive-or of every bit.
529 ``1`` if an odd number of bits are set, ``0`` if an
530 even number of bits are set.
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
)
538 # not needed: Value.implies does the job
539 # def implies(premise, conclusion):
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):
545 # not needed: Value.matches, amazingly, should do the job
546 # def matches(self, *patterns):
548 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=713
550 return self
.sig
.shape()