src/main/scala/chipsldpc/Arithmetic.scala
Source from the repository checkout used to build these docs. Line numbers link to individual source lines.
1package chipsldpc
2
3import chisel3._
4import chisel3.util.MuxLookup
5
6object Arithmetic {
7 def canonicalSign(sign: Bool, magnitude: UInt): Bool = sign && magnitude.orR
8 def hardDecision(value: SInt): Bool = value < 0.S
9 def hardDecision(value: SignMag): Bool = canonicalSign(value.sign, value.magnitude)
10
11 def fromSignMag(message: SignMag, width: Int): SInt = {
12 val magnitude = message.magnitude.pad(width).asSInt
13 Mux(canonicalSign(message.sign, message.magnitude), 0.S(width.W) -% magnitude, magnitude)
14 }
15
16 def clipSigned(value: SInt, width: Int): SInt = {
17 val inWidth = value.getWidth
18 require(inWidth >= width)
19 val maximum = (BigInt(1) << (width - 1)) - 1
20 val minimum = -(BigInt(1) << (width - 1))
21 Mux(
22 value > maximum.S(inWidth.W),
23 maximum.S(width.W),
24 Mux(value < minimum.S(inWidth.W), minimum.S(width.W), value(width - 1, 0).asSInt),
25 )
26 }
27
28 def toSignMag(value: SInt, bits: Int): (Bool, UInt) = {
29 val width = value.getWidth
30 val negative = value < 0.S
31 val absolute = Mux(negative, (0.S(width.W) -% value).asUInt, value.asUInt)
32 val maximum = (BigInt(1) << bits) - 1
33 val magnitude = Mux(absolute > maximum.U(width.W), maximum.U(bits.W), absolute(bits - 1, 0))
34 (negative && magnitude.orR, magnitude)
35 }
36
37 def sum(values: Seq[SInt], width: Int): SInt = {
38 require(values.nonEmpty)
39 def reduce(level: Seq[SInt]): SInt =
40 if (level.size == 1) level.head
41 else reduce(level.grouped(2).map {
42 case Seq(a, b) => a +% b
43 case Seq(a) => a
44 }.toSeq)
45 reduce(values.map(_.pad(width)))
46 }
47
48 def sumUnsigned(values: Seq[UInt], width: Int): UInt = {
49 require(values.nonEmpty)
50 def reduce(level: Seq[UInt]): UInt =
51 if (level.size == 1) level.head
52 else reduce(level.grouped(2).map {
53 case Seq(a, b) => a +% b
54 case Seq(a) => a
55 }.toSeq)
56 reduce(values.map(_.pad(width)))
57 }
58
59 private def clipUnsigned(value: UInt, bits: Int): UInt = {
60 val width = value.getWidth
61 val maximum = (BigInt(1) << bits) - 1
62 if (width <= bits) value.pad(bits)
63 else Mux(value > maximum.U(width.W), maximum.U(bits.W), value(bits - 1, 0))
64 }
65
66 def scale(value: UInt, control: UInt, policy: CheckScale, bits: Int): UInt = policy match {
67 case NoScale => value
68 case VallsScale(a, b) => clipUnsigned((value >> a) +& (value >> b), bits)
69 case RampScale(maxShift) =>
70 MuxLookup(control, value)((0 to maxShift).map(i => i.U -> (value -% (value >> i))))
71 }
72}