boolean logic inversion, x = ~a & ~b & ~c ==> ~(a | b | c) then use list
[ieee754fpu.git] / src / ieee754 / part_mul_add / multiply.py
1 # SPDX-License-Identifier: LGPL-2.1-or-later
2 # See Notices.txt for copyright information
3 """Integer Multiplication."""
4
5 from nmigen import Signal, Module, Value, Elaboratable, Cat, C, Mux, Repl
6 from nmigen.hdl.ast import Assign
7 from abc import ABCMeta, abstractmethod
8 from nmigen.cli import main
9
10
11 class PartitionPoints(dict):
12 """Partition points and corresponding ``Value``s.
13
14 The points at where an ALU is partitioned along with ``Value``s that
15 specify if the corresponding partition points are enabled.
16
17 For example: ``{1: True, 5: True, 10: True}`` with
18 ``width == 16`` specifies that the ALU is split into 4 sections:
19 * bits 0 <= ``i`` < 1
20 * bits 1 <= ``i`` < 5
21 * bits 5 <= ``i`` < 10
22 * bits 10 <= ``i`` < 16
23
24 If the partition_points were instead ``{1: True, 5: a, 10: True}``
25 where ``a`` is a 1-bit ``Signal``:
26 * If ``a`` is asserted:
27 * bits 0 <= ``i`` < 1
28 * bits 1 <= ``i`` < 5
29 * bits 5 <= ``i`` < 10
30 * bits 10 <= ``i`` < 16
31 * Otherwise
32 * bits 0 <= ``i`` < 1
33 * bits 1 <= ``i`` < 10
34 * bits 10 <= ``i`` < 16
35 """
36
37 def __init__(self, partition_points=None):
38 """Create a new ``PartitionPoints``.
39
40 :param partition_points: the input partition points to values mapping.
41 """
42 super().__init__()
43 if partition_points is not None:
44 for point, enabled in partition_points.items():
45 if not isinstance(point, int):
46 raise TypeError("point must be a non-negative integer")
47 if point < 0:
48 raise ValueError("point must be a non-negative integer")
49 self[point] = Value.wrap(enabled)
50
51 def like(self, name=None, src_loc_at=0):
52 """Create a new ``PartitionPoints`` with ``Signal``s for all values.
53
54 :param name: the base name for the new ``Signal``s.
55 """
56 if name is None:
57 name = Signal(src_loc_at=1+src_loc_at).name # get variable name
58 retval = PartitionPoints()
59 for point, enabled in self.items():
60 retval[point] = Signal(enabled.shape(), name=f"{name}_{point}")
61 return retval
62
63 def eq(self, rhs):
64 """Assign ``PartitionPoints`` using ``Signal.eq``."""
65 if set(self.keys()) != set(rhs.keys()):
66 raise ValueError("incompatible point set")
67 for point, enabled in self.items():
68 yield enabled.eq(rhs[point])
69
70 def as_mask(self, width):
71 """Create a bit-mask from `self`.
72
73 Each bit in the returned mask is clear only if the partition point at
74 the same bit-index is enabled.
75
76 :param width: the bit width of the resulting mask
77 """
78 bits = []
79 for i in range(width):
80 if i in self:
81 bits.append(~self[i])
82 else:
83 bits.append(True)
84 return Cat(*bits)
85
86 def get_max_partition_count(self, width):
87 """Get the maximum number of partitions.
88
89 Gets the number of partitions when all partition points are enabled.
90 """
91 retval = 1
92 for point in self.keys():
93 if point < width:
94 retval += 1
95 return retval
96
97 def fits_in_width(self, width):
98 """Check if all partition points are smaller than `width`."""
99 for point in self.keys():
100 if point >= width:
101 return False
102 return True
103
104
105 class FullAdder(Elaboratable):
106 """Full Adder.
107
108 :attribute in0: the first input
109 :attribute in1: the second input
110 :attribute in2: the third input
111 :attribute sum: the sum output
112 :attribute carry: the carry output
113 """
114
115 def __init__(self, width):
116 """Create a ``FullAdder``.
117
118 :param width: the bit width of the input and output
119 """
120 self.in0 = Signal(width)
121 self.in1 = Signal(width)
122 self.in2 = Signal(width)
123 self.sum = Signal(width)
124 self.carry = Signal(width)
125
126 def elaborate(self, platform):
127 """Elaborate this module."""
128 m = Module()
129 m.d.comb += self.sum.eq(self.in0 ^ self.in1 ^ self.in2)
130 m.d.comb += self.carry.eq((self.in0 & self.in1)
131 | (self.in1 & self.in2)
132 | (self.in2 & self.in0))
133 return m
134
135
136 class PartitionedAdder(Elaboratable):
137 """Partitioned Adder.
138
139 :attribute width: the bit width of the input and output. Read-only.
140 :attribute a: the first input to the adder
141 :attribute b: the second input to the adder
142 :attribute output: the sum output
143 :attribute partition_points: the input partition points. Modification not
144 supported, except for by ``Signal.eq``.
145 """
146
147 def __init__(self, width, partition_points):
148 """Create a ``PartitionedAdder``.
149
150 :param width: the bit width of the input and output
151 :param partition_points: the input partition points
152 """
153 self.width = width
154 self.a = Signal(width)
155 self.b = Signal(width)
156 self.output = Signal(width)
157 self.partition_points = PartitionPoints(partition_points)
158 if not self.partition_points.fits_in_width(width):
159 raise ValueError("partition_points doesn't fit in width")
160 expanded_width = 0
161 for i in range(self.width):
162 if i in self.partition_points:
163 expanded_width += 1
164 expanded_width += 1
165 self._expanded_width = expanded_width
166 self._expanded_a = Signal(expanded_width)
167 self._expanded_b = Signal(expanded_width)
168 self._expanded_output = Signal(expanded_width)
169
170 def elaborate(self, platform):
171 """Elaborate this module."""
172 m = Module()
173 expanded_index = 0
174 # store bits in a list, use Cat later. graphviz is much cleaner
175 al = []
176 bl = []
177 ol = []
178 ea = []
179 eb = []
180 eo = []
181 # partition points are "breaks" (extra zeros) in what would otherwise
182 # be a massive long add.
183 for i in range(self.width):
184 if i in self.partition_points:
185 # add extra bit set to 0 + 0 for enabled partition points
186 # and 1 + 0 for disabled partition points
187 ea.append(self._expanded_a[expanded_index])
188 al.append(~self.partition_points[i])
189 eb.append(self._expanded_b[expanded_index])
190 bl.append(C(0))
191 expanded_index += 1
192 ea.append(self._expanded_a[expanded_index])
193 al.append(self.a[i])
194 eb.append(self._expanded_b[expanded_index])
195 bl.append(self.b[i])
196 eo.append(self._expanded_output[expanded_index])
197 ol.append(self.output[i])
198 expanded_index += 1
199 # combine above using Cat
200 m.d.comb += Cat(*ea).eq(Cat(*al))
201 m.d.comb += Cat(*eb).eq(Cat(*bl))
202 m.d.comb += Cat(*eo).eq(Cat(*ol))
203 # use only one addition to take advantage of look-ahead carry and
204 # special hardware on FPGAs
205 m.d.comb += self._expanded_output.eq(
206 self._expanded_a + self._expanded_b)
207 return m
208
209
210 FULL_ADDER_INPUT_COUNT = 3
211
212
213 class AddReduce(Elaboratable):
214 """Add list of numbers together.
215
216 :attribute inputs: input ``Signal``s to be summed. Modification not
217 supported, except for by ``Signal.eq``.
218 :attribute register_levels: List of nesting levels that should have
219 pipeline registers.
220 :attribute output: output sum.
221 :attribute partition_points: the input partition points. Modification not
222 supported, except for by ``Signal.eq``.
223 """
224
225 def __init__(self, inputs, output_width, register_levels, partition_points):
226 """Create an ``AddReduce``.
227
228 :param inputs: input ``Signal``s to be summed.
229 :param output_width: bit-width of ``output``.
230 :param register_levels: List of nesting levels that should have
231 pipeline registers.
232 :param partition_points: the input partition points.
233 """
234 self.inputs = list(inputs)
235 self._resized_inputs = [
236 Signal(output_width, name=f"resized_inputs[{i}]")
237 for i in range(len(self.inputs))]
238 self.register_levels = list(register_levels)
239 self.output = Signal(output_width)
240 self.partition_points = PartitionPoints(partition_points)
241 if not self.partition_points.fits_in_width(output_width):
242 raise ValueError("partition_points doesn't fit in output_width")
243 self._reg_partition_points = self.partition_points.like()
244 max_level = AddReduce.get_max_level(len(self.inputs))
245 for level in self.register_levels:
246 if level > max_level:
247 raise ValueError(
248 "not enough adder levels for specified register levels")
249
250 @staticmethod
251 def get_max_level(input_count):
252 """Get the maximum level.
253
254 All ``register_levels`` must be less than or equal to the maximum
255 level.
256 """
257 retval = 0
258 while True:
259 groups = AddReduce.full_adder_groups(input_count)
260 if len(groups) == 0:
261 return retval
262 input_count %= FULL_ADDER_INPUT_COUNT
263 input_count += 2 * len(groups)
264 retval += 1
265
266 def next_register_levels(self):
267 """``Iterable`` of ``register_levels`` for next recursive level."""
268 for level in self.register_levels:
269 if level > 0:
270 yield level - 1
271
272 @staticmethod
273 def full_adder_groups(input_count):
274 """Get ``inputs`` indices for which a full adder should be built."""
275 return range(0,
276 input_count - FULL_ADDER_INPUT_COUNT + 1,
277 FULL_ADDER_INPUT_COUNT)
278
279 def elaborate(self, platform):
280 """Elaborate this module."""
281 m = Module()
282
283 # resize inputs to correct bit-width and optionally add in
284 # pipeline registers
285 resized_input_assignments = [self._resized_inputs[i].eq(self.inputs[i])
286 for i in range(len(self.inputs))]
287 if 0 in self.register_levels:
288 m.d.sync += resized_input_assignments
289 m.d.sync += self._reg_partition_points.eq(self.partition_points)
290 else:
291 m.d.comb += resized_input_assignments
292 m.d.comb += self._reg_partition_points.eq(self.partition_points)
293
294 groups = AddReduce.full_adder_groups(len(self.inputs))
295 # if there are no full adders to create, then we handle the base cases
296 # and return, otherwise we go on to the recursive case
297 if len(groups) == 0:
298 if len(self.inputs) == 0:
299 # use 0 as the default output value
300 m.d.comb += self.output.eq(0)
301 elif len(self.inputs) == 1:
302 # handle single input
303 m.d.comb += self.output.eq(self._resized_inputs[0])
304 else:
305 # base case for adding 2 or more inputs, which get recursively
306 # reduced to 2 inputs
307 assert len(self.inputs) == 2
308 adder = PartitionedAdder(len(self.output),
309 self._reg_partition_points)
310 m.submodules.final_adder = adder
311 m.d.comb += adder.a.eq(self._resized_inputs[0])
312 m.d.comb += adder.b.eq(self._resized_inputs[1])
313 m.d.comb += self.output.eq(adder.output)
314 return m
315 # go on to handle recursive case
316 intermediate_terms = []
317
318 def add_intermediate_term(value):
319 intermediate_term = Signal(
320 len(self.output),
321 name=f"intermediate_terms[{len(intermediate_terms)}]")
322 intermediate_terms.append(intermediate_term)
323 m.d.comb += intermediate_term.eq(value)
324
325 # store mask in intermediary (simplifies graph)
326 part_mask = Signal(len(self.output), reset_less=True)
327 mask = self._reg_partition_points.as_mask(len(self.output))
328 m.d.comb += part_mask.eq(mask)
329
330 # create full adders for this recursive level.
331 # this shrinks N terms to 2 * (N // 3) plus the remainder
332 for i in groups:
333 adder_i = FullAdder(len(self.output))
334 setattr(m.submodules, f"adder_{i}", adder_i)
335 m.d.comb += adder_i.in0.eq(self._resized_inputs[i])
336 m.d.comb += adder_i.in1.eq(self._resized_inputs[i + 1])
337 m.d.comb += adder_i.in2.eq(self._resized_inputs[i + 2])
338 add_intermediate_term(adder_i.sum)
339 shifted_carry = adder_i.carry << 1
340 # mask out carry bits to prevent carries between partitions
341 add_intermediate_term((adder_i.carry << 1) & part_mask)
342 # handle the remaining inputs.
343 if len(self.inputs) % FULL_ADDER_INPUT_COUNT == 1:
344 add_intermediate_term(self._resized_inputs[-1])
345 elif len(self.inputs) % FULL_ADDER_INPUT_COUNT == 2:
346 # Just pass the terms to the next layer, since we wouldn't gain
347 # anything by using a half adder since there would still be 2 terms
348 # and just passing the terms to the next layer saves gates.
349 add_intermediate_term(self._resized_inputs[-2])
350 add_intermediate_term(self._resized_inputs[-1])
351 else:
352 assert len(self.inputs) % FULL_ADDER_INPUT_COUNT == 0
353 # recursive invocation of ``AddReduce``
354 next_level = AddReduce(intermediate_terms,
355 len(self.output),
356 self.next_register_levels(),
357 self._reg_partition_points)
358 m.submodules.next_level = next_level
359 m.d.comb += self.output.eq(next_level.output)
360 return m
361
362
363 OP_MUL_LOW = 0
364 OP_MUL_SIGNED_HIGH = 1
365 OP_MUL_SIGNED_UNSIGNED_HIGH = 2 # a is signed, b is unsigned
366 OP_MUL_UNSIGNED_HIGH = 3
367
368
369 class Mul8_16_32_64(Elaboratable):
370 """Signed/Unsigned 8/16/32/64-bit partitioned integer multiplier.
371
372 Supports partitioning into any combination of 8, 16, 32, and 64-bit
373 partitions on naturally-aligned boundaries. Supports the operation being
374 set for each partition independently.
375
376 :attribute part_pts: the input partition points. Has a partition point at
377 multiples of 8 in 0 < i < 64. Each partition point's associated
378 ``Value`` is a ``Signal``. Modification not supported, except for by
379 ``Signal.eq``.
380 :attribute part_ops: the operation for each byte. The operation for a
381 particular partition is selected by assigning the selected operation
382 code to each byte in the partition. The allowed operation codes are:
383
384 :attribute OP_MUL_LOW: the LSB half of the product. Equivalent to
385 RISC-V's `mul` instruction.
386 :attribute OP_MUL_SIGNED_HIGH: the MSB half of the product where both
387 ``a`` and ``b`` are signed. Equivalent to RISC-V's `mulh`
388 instruction.
389 :attribute OP_MUL_SIGNED_UNSIGNED_HIGH: the MSB half of the product
390 where ``a`` is signed and ``b`` is unsigned. Equivalent to RISC-V's
391 `mulhsu` instruction.
392 :attribute OP_MUL_UNSIGNED_HIGH: the MSB half of the product where both
393 ``a`` and ``b`` are unsigned. Equivalent to RISC-V's `mulhu`
394 instruction.
395 """
396
397 def __init__(self, register_levels= ()):
398 self.part_pts = PartitionPoints()
399 for i in range(8, 64, 8):
400 self.part_pts[i] = Signal(name=f"part_pts_{i}")
401 self.part_ops = [Signal(2, name=f"part_ops_{i}") for i in range(8)]
402 self.a = Signal(64)
403 self.b = Signal(64)
404 self.output = Signal(64)
405 self.register_levels = list(register_levels)
406 self._intermediate_output = Signal(128)
407 self._delayed_part_ops = [
408 [Signal(2, name=f"_delayed_part_ops_{delay}_{i}")
409 for i in range(8)]
410 for delay in range(1 + len(self.register_levels))]
411 self._part_8 = [Signal(name=f"_part_8_{i}") for i in range(8)]
412 self._part_16 = [Signal(name=f"_part_16_{i}") for i in range(4)]
413 self._part_32 = [Signal(name=f"_part_32_{i}") for i in range(2)]
414 self._part_64 = [Signal(name=f"_part_64")]
415 self._delayed_part_8 = [
416 [Signal(name=f"_delayed_part_8_{delay}_{i}")
417 for i in range(8)]
418 for delay in range(1 + len(self.register_levels))]
419 self._delayed_part_16 = [
420 [Signal(name=f"_delayed_part_16_{delay}_{i}")
421 for i in range(4)]
422 for delay in range(1 + len(self.register_levels))]
423 self._delayed_part_32 = [
424 [Signal(name=f"_delayed_part_32_{delay}_{i}")
425 for i in range(2)]
426 for delay in range(1 + len(self.register_levels))]
427 self._delayed_part_64 = [
428 [Signal(name=f"_delayed_part_64_{delay}")]
429 for delay in range(1 + len(self.register_levels))]
430 self._output_64 = Signal(64)
431 self._output_32 = Signal(64)
432 self._output_16 = Signal(64)
433 self._output_8 = Signal(64)
434 self._a_signed = [Signal(name=f"_a_signed_{i}") for i in range(8)]
435 self._b_signed = [Signal(name=f"_b_signed_{i}") for i in range(8)]
436 self._not_a_term_8 = Signal(128)
437 self._neg_lsb_a_term_8 = Signal(128)
438 self._not_b_term_8 = Signal(128)
439 self._neg_lsb_b_term_8 = Signal(128)
440 self._not_a_term_16 = Signal(128)
441 self._neg_lsb_a_term_16 = Signal(128)
442 self._not_b_term_16 = Signal(128)
443 self._neg_lsb_b_term_16 = Signal(128)
444 self._not_a_term_32 = Signal(128)
445 self._neg_lsb_a_term_32 = Signal(128)
446 self._not_b_term_32 = Signal(128)
447 self._neg_lsb_b_term_32 = Signal(128)
448 self._not_a_term_64 = Signal(128)
449 self._neg_lsb_a_term_64 = Signal(128)
450 self._not_b_term_64 = Signal(128)
451 self._neg_lsb_b_term_64 = Signal(128)
452
453 def _part_byte(self, index):
454 if index == -1 or index == 7:
455 return C(True, 1)
456 assert index >= 0 and index < 8
457 return self.part_pts[index * 8 + 8]
458
459 def elaborate(self, platform):
460 m = Module()
461
462 for i in range(len(self.part_ops)):
463 m.d.comb += self._delayed_part_ops[0][i].eq(self.part_ops[i])
464 m.d.sync += [self._delayed_part_ops[j + 1][i]
465 .eq(self._delayed_part_ops[j][i])
466 for j in range(len(self.register_levels))]
467
468 def add_intermediate_value(value):
469 intermediate_value = Signal(len(value), reset_less=True)
470 m.d.comb += intermediate_value.eq(value)
471 return intermediate_value
472
473 for parts, delayed_parts in [(self._part_64, self._delayed_part_64),
474 (self._part_32, self._delayed_part_32),
475 (self._part_16, self._delayed_part_16),
476 (self._part_8, self._delayed_part_8)]:
477 byte_count = 8 // len(parts)
478 for i in range(len(parts)):
479 pb = self._part_byte(i * byte_count - 1)
480 value = add_intermediate_value(pb)
481 for j in range(i * byte_count, (i + 1) * byte_count - 1):
482 pb = add_intermediate_value(~self._part_byte(j))
483 value = add_intermediate_value(value & pb)
484 pb = self._part_byte((i + 1) * byte_count - 1)
485 value = add_intermediate_value(value & pb)
486 m.d.comb += parts[i].eq(value)
487 m.d.comb += delayed_parts[0][i].eq(parts[i])
488 m.d.sync += [delayed_parts[j + 1][i].eq(delayed_parts[j][i])
489 for j in range(len(self.register_levels))]
490
491 products = [[
492 Signal(16, name=f"products_{i}_{j}")
493 for j in range(8)]
494 for i in range(8)]
495
496 for a_index in range(8):
497 for b_index in range(8):
498 a = self.a.part(a_index * 8, 8)
499 b = self.b.part(b_index * 8, 8)
500 m.d.comb += products[a_index][b_index].eq(a * b)
501
502 terms = []
503
504 def add_term(value, shift=0, enabled=None):
505 term = Signal(128)
506 terms.append(term)
507 if enabled is not None:
508 value = Mux(enabled, value, 0)
509 if shift > 0:
510 value = Cat(Repl(C(0, 1), shift), value)
511 else:
512 assert shift == 0
513 m.d.comb += term.eq(value)
514
515 for a_index in range(8):
516 for b_index in range(8):
517 terms = []
518 min_index = min(a_index, b_index)
519 max_index = max(a_index, b_index)
520 for i in range(min_index, max_index):
521 pbs = Signal(reset_less=True)
522 m.d.comb += pbs.eq(self._part_byte(i))
523 terms.append(pbs)
524 name = "te_%d_%d" % (a_index, b_index)
525 term_enabled = Signal(name=name, reset_less=True)
526 m.d.comb += term_enabled.eq(~(Cat(*terms).bool()))
527 add_term(products[a_index][b_index],
528 8 * (a_index + b_index),
529 term_enabled)
530
531 for i in range(8):
532 a_signed = self.part_ops[i] != OP_MUL_UNSIGNED_HIGH
533 b_signed = (self.part_ops[i] == OP_MUL_LOW) \
534 | (self.part_ops[i] == OP_MUL_SIGNED_HIGH)
535 m.d.comb += self._a_signed[i].eq(a_signed)
536 m.d.comb += self._b_signed[i].eq(b_signed)
537
538 # it's fine to bitwise-or these together since they are never enabled
539 # at the same time
540 add_term(self._not_a_term_8 | self._not_a_term_16
541 | self._not_a_term_32 | self._not_a_term_64)
542 add_term(self._neg_lsb_a_term_8 | self._neg_lsb_a_term_16
543 | self._neg_lsb_a_term_32 | self._neg_lsb_a_term_64)
544 add_term(self._not_b_term_8 | self._not_b_term_16
545 | self._not_b_term_32 | self._not_b_term_64)
546 add_term(self._neg_lsb_b_term_8 | self._neg_lsb_b_term_16
547 | self._neg_lsb_b_term_32 | self._neg_lsb_b_term_64)
548
549 for not_a_term, \
550 neg_lsb_a_term, \
551 not_b_term, \
552 neg_lsb_b_term, \
553 parts in [
554 (self._not_a_term_8,
555 self._neg_lsb_a_term_8,
556 self._not_b_term_8,
557 self._neg_lsb_b_term_8,
558 self._part_8),
559 (self._not_a_term_16,
560 self._neg_lsb_a_term_16,
561 self._not_b_term_16,
562 self._neg_lsb_b_term_16,
563 self._part_16),
564 (self._not_a_term_32,
565 self._neg_lsb_a_term_32,
566 self._not_b_term_32,
567 self._neg_lsb_b_term_32,
568 self._part_32),
569 (self._not_a_term_64,
570 self._neg_lsb_a_term_64,
571 self._not_b_term_64,
572 self._neg_lsb_b_term_64,
573 self._part_64),
574 ]:
575 byte_width = 8 // len(parts)
576 bit_width = 8 * byte_width
577 for i in range(len(parts)):
578 ae = parts[i] & self.a[(i + 1) * bit_width - 1] \
579 & self._a_signed[i * byte_width]
580 be = parts[i] & self.b[(i + 1) * bit_width - 1] \
581 & self._b_signed[i * byte_width]
582 a_enabled = Signal(name="a_enabled_%d" % i, reset_less=True)
583 b_enabled = Signal(name="b_enabled_%d" % i, reset_less=True)
584 m.d.comb += a_enabled.eq(ae)
585 m.d.comb += b_enabled.eq(be)
586
587 # for 8-bit values: form a * 0xFF00 by using -a * 0x100, the
588 # negation operation is split into a bitwise not and a +1.
589 # likewise for 16, 32, and 64-bit values.
590 m.d.comb += [
591 not_a_term.part(bit_width * 2 * i, bit_width * 2)
592 .eq(Mux(a_enabled,
593 Cat(Repl(0, bit_width),
594 ~self.a.part(bit_width * i, bit_width)),
595 0)),
596
597 neg_lsb_a_term.part(bit_width * 2 * i, bit_width * 2)
598 .eq(Cat(Repl(0, bit_width), a_enabled)),
599
600 not_b_term.part(bit_width * 2 * i, bit_width * 2)
601 .eq(Mux(b_enabled,
602 Cat(Repl(0, bit_width),
603 ~self.b.part(bit_width * i, bit_width)),
604 0)),
605
606 neg_lsb_b_term.part(bit_width * 2 * i, bit_width * 2)
607 .eq(Cat(Repl(0, bit_width), b_enabled))]
608
609 expanded_part_pts = PartitionPoints()
610 for i, v in self.part_pts.items():
611 signal = Signal(name=f"expanded_part_pts_{i*2}")
612 expanded_part_pts[i * 2] = signal
613 m.d.comb += signal.eq(v)
614
615 add_reduce = AddReduce(terms,
616 128,
617 self.register_levels,
618 expanded_part_pts)
619 m.submodules.add_reduce = add_reduce
620 m.d.comb += self._intermediate_output.eq(add_reduce.output)
621 m.d.comb += self._output_64.eq(
622 Mux(self._delayed_part_ops[-1][0] == OP_MUL_LOW,
623 self._intermediate_output.part(0, 64),
624 self._intermediate_output.part(64, 64)))
625
626 # create _output_32
627 ol = []
628 for i in range(2):
629 ol.append(
630 Mux(self._delayed_part_ops[-1][4 * i] == OP_MUL_LOW,
631 self._intermediate_output.part(i * 64, 32),
632 self._intermediate_output.part(i * 64 + 32, 32)))
633 m.d.comb += self._output_32.eq(Cat(*ol))
634
635 # create _output_16
636 ol = []
637 for i in range(4):
638 ol.append(
639 Mux(self._delayed_part_ops[-1][2 * i] == OP_MUL_LOW,
640 self._intermediate_output.part(i * 32, 16),
641 self._intermediate_output.part(i * 32 + 16, 16)))
642 m.d.comb += self._output_16.eq(Cat(*ol))
643
644 # create _output_8
645 ol = []
646 for i in range(8):
647 ol.append(
648 Mux(self._delayed_part_ops[-1][i] == OP_MUL_LOW,
649 self._intermediate_output.part(i * 16, 8),
650 self._intermediate_output.part(i * 16 + 8, 8)))
651 m.d.comb += self._output_8.eq(Cat(*ol))
652
653 # final output
654 ol = []
655 for i in range(8):
656 ol.append(
657 Mux(self._delayed_part_8[-1][i]
658 | self._delayed_part_16[-1][i // 2],
659 Mux(self._delayed_part_8[-1][i],
660 self._output_8.part(i * 8, 8),
661 self._output_16.part(i * 8, 8)),
662 Mux(self._delayed_part_32[-1][i // 4],
663 self._output_32.part(i * 8, 8),
664 self._output_64.part(i * 8, 8))))
665 m.d.comb += self.output.eq(Cat(*ol))
666 return m
667
668
669 if __name__ == "__main__":
670 m = Mul8_16_32_64()
671 main(m, ports=[m.a,
672 m.b,
673 m._intermediate_output,
674 m.output,
675 *m.part_ops,
676 *m.part_pts.values()])