move get_a and get_b to their own classes
[ieee754fpu.git] / src / add / nmigen_add_experiment.py
index 1a1189a7bee2b5bd15fe27545b0ffd36954dc0f0..8c691868142d2d856cb9ae40d3d7f45d6d0f0855 100644 (file)
@@ -3,58 +3,78 @@
 # 2013-12-12
 
 from nmigen import Module, Signal, Cat
-from nmigen.cli import main
+from nmigen.cli import main, verilog
 
+from fpbase import FPNumIn, FPNumOut, FPOp, Overflow, FPBase
 
-class FPADD:
-    def __init__(self, width):
-        self.width = width
+class FPState(FPBase):
+    def __init__(self, state_from, state_to):
+        self.state_from = state_from
+        self.state_to = state_to
+
+    def set_inputs(self, inputs):
+        self.inputs = inputs
+        for k,v in inputs.items():
+            setattr(self, k, v)
+
+    def set_outputs(self, outputs):
+        self.outputs = outputs
+        for k,v in outputs.items():
+            setattr(self, k, v)
+
+
+class FPGetOpA(FPState):
+
+    def action(self, m):
+        self.get_op(m, self.in_a, self.a, self.state_to)
 
-        self.in_a     = Signal(width)
-        self.in_a_stb = Signal()
-        self.in_a_ack = Signal()
 
-        self.in_b     = Signal(width)
-        self.in_b_stb = Signal()
-        self.in_b_ack = Signal()
+class FPGetOpB(FPState):
 
-        self.out_z     = Signal(width)
-        self.out_z_stb = Signal()
-        self.out_z_ack = Signal()
+    def action(self, m):
+        self.get_op(m, self.in_b, self.b, self.state_to)
 
-        s_out_z_stb  = Signal()
-        s_out_z      = Signal(width)
-        s_in_a_ack   = Signal()
-        s_in_b_ack   = Signal()
 
-    def get_fragment(self, platform):
+class FPADD(FPBase):
+
+    def __init__(self, width, single_cycle=False):
+        FPBase.__init__(self)
+        self.width = width
+        self.single_cycle = single_cycle
+
+        self.in_a  = FPOp(width)
+        self.in_b  = FPOp(width)
+        self.out_z = FPOp(width)
+
+    def get_fragment(self, platform=None):
+        """ creates the HDL code-fragment for FPAdd
+        """
         m = Module()
 
         # Latches
-        a = Signal(self.width)
-        b = Signal(self.width)
-        z = Signal(self.width)
+        a = FPNumIn(self.in_a, self.width)
+        b = FPNumIn(self.in_b, self.width)
+        z = FPNumOut(self.width, False)
 
-        # Mantissa
-        a_m = Signal(27)
-        b_m = Signal(27)
-        z_m = Signal(23)
+        m.submodules.fpnum_a = a
+        m.submodules.fpnum_b = b
+        m.submodules.fpnum_z = z
 
-        # Exponent
-        a_e = Signal(10)
-        b_e = Signal(10)
-        z_e = Signal(10)
+        w = z.m_width + 4
+        tot = Signal(w, reset_less=True) # sticky/round/guard, {mantissa} result, 1 overflow
 
-        # Sign
-        a_s = Signal()
-        b_s = Signal()
-        z_s = Signal()
+        of = Overflow()
+        m.submodules.overflow = of
 
-        guard = Signal()
-        round_bit = Signal()
-        sticky = Signal()
+        geta = FPGetOpA("get_a", "get_b")
+        geta.set_inputs({"in_a": self.in_a})
+        geta.set_outputs({"a": a})
+        m.d.comb += a.v.eq(self.in_a.v) # links in_a to a
 
-        tot = Signal(28)
+        getb = FPGetOpB("get_b", "special_cases")
+        getb.set_inputs({"in_b": self.in_b})
+        getb.set_outputs({"b": b})
+        m.d.comb += b.v.eq(self.in_b.v) # links in_b to b
 
         with m.FSM() as fsm:
 
@@ -62,318 +82,237 @@ class FPADD:
             # gets operand a
 
             with m.State("get_a"):
-                with m.If((self.in_a_ack) & (self.in_a_stb)):
-                    m.next = "get_b"
-                    m.d.sync += [
-                        a.eq(self.in_a),
-                        self.in_a_ack.eq(0)
-                    ]
-                with m.Else():
-                    m.d.sync += self.in_a_ack.eq(1)
+                geta.action(m)
 
             # ******
             # gets operand b
 
             with m.State("get_b"):
-                with m.If((self.in_b_ack) & (self.in_b_stb)):
-                    m.next = "get_a"
-                    m.d.sync += [
-                        b.eq(self.in_b),
-                        self.in_b_ack.eq(0)
-                    ]
-                with m.Else():
-                    m.d.sync += self.in_b_ack.eq(1)
-
-            # ******
-            # unpacks operands into sign, mantissa and exponent
-
-            with m.State("unpack"):
-                m.next = "special_cases"
-                m.d.sync += [
-                    # mantissa
-                    a_m.eq(Cat(0, 0, 0, a[0:23])),
-                    b_m.eq(Cat(0, 0, 0, b[0:23])),
-                    # exponent (take off exponent bias, here)
-                    a_e.eq(Cat(a[23:31]) - 127),
-                    b_e.eq(Cat(b[23:31]) - 127),
-                    # sign
-                    a_s.eq(Cat(a[31])),
-                    b_s.eq(Cat(b[31]))
-                ]
+                #self.get_op(m, self.in_b, b, "special_cases")
+                getb.action(m)
 
             # ******
             # special cases: NaNs, infs, zeros, denormalised
+            # NOTE: some of these are unique to add.  see "Special Operations"
+            # https://steve.hollasch.net/cgindex/coding/ieeefloat.html
 
             with m.State("special_cases"):
 
+                s_nomatch = Signal()
+                m.d.comb += s_nomatch.eq(a.s != b.s)
+
+                m_match = Signal()
+                m.d.comb += m_match.eq(a.m == b.m)
+
                 # if a is NaN or b is NaN return NaN
-                with m.If(((a_e == 128) & (a_m != 0)) | \
-                          ((b_e == 128) & (b_m != 0))):
+                with m.If(a.is_nan | b.is_nan):
                     m.next = "put_z"
-                    m.d.sync += [
-                          z[31].eq(1),      # sign: 1
-                          z[23:31].eq(255), # exp: 0b11111...
-                          z[22].eq(1),      # mantissa top bit: 1
-                          z[0:22].eq(0)     # mantissa rest: 0b0000...
-                    ]
+                    m.d.sync += z.nan(1)
+
+                # XXX WEIRDNESS for FP16 non-canonical NaN handling
+                # under review
+
+                ## if a is zero and b is NaN return -b
+                #with m.If(a.is_zero & (a.s==0) & b.is_nan):
+                #    m.next = "put_z"
+                #    m.d.sync += z.create(b.s, b.e, Cat(b.m[3:-2], ~b.m[0]))
+
+                ## if b is zero and a is NaN return -a
+                #with m.Elif(b.is_zero & (b.s==0) & a.is_nan):
+                #    m.next = "put_z"
+                #    m.d.sync += z.create(a.s, a.e, Cat(a.m[3:-2], ~a.m[0]))
+
+                ## if a is -zero and b is NaN return -b
+                #with m.Elif(a.is_zero & (a.s==1) & b.is_nan):
+                #    m.next = "put_z"
+                #    m.d.sync += z.create(a.s & b.s, b.e, Cat(b.m[3:-2], 1))
+
+                ## if b is -zero and a is NaN return -a
+                #with m.Elif(b.is_zero & (b.s==1) & a.is_nan):
+                #    m.next = "put_z"
+                #    m.d.sync += z.create(a.s & b.s, a.e, Cat(a.m[3:-2], 1))
 
                 # if a is inf return inf (or NaN)
-                with m.Elif(a_e == 128):
+                with m.Elif(a.is_inf):
                     m.next = "put_z"
+                    m.d.sync += z.inf(a.s)
+                    # if a is inf and signs don't match return NaN
+                    with m.If(b.exp_128 & s_nomatch):
+                        m.d.sync += z.nan(1)
+
+                # if b is inf return inf
+                with m.Elif(b.is_inf):
+                    m.next = "put_z"
+                    m.d.sync += z.inf(b.s)
+
+                # if a is zero and b zero return signed-a/b
+                with m.Elif(a.is_zero & b.is_zero):
+                    m.next = "put_z"
+                    m.d.sync += z.create(a.s & b.s, b.e, b.m[3:-1])
+
+                # if a is zero return b
+                with m.Elif(a.is_zero):
+                    m.next = "put_z"
+                    m.d.sync += z.create(b.s, b.e, b.m[3:-1])
+
+                # if b is zero return a
+                with m.Elif(b.is_zero):
+                    m.next = "put_z"
+                    m.d.sync += z.create(a.s, a.e, a.m[3:-1])
+
+                # if a equal to -b return zero (+ve zero)
+                with m.Elif(s_nomatch & m_match & (a.e == b.e)):
+                    m.next = "put_z"
+                    m.d.sync += z.zero(0)
+
+                # Denormalised Number checks
+                with m.Else():
+                    m.next = "denormalise"
+
+            # ******
+            # denormalise.
+
+            with m.State("denormalise"):
+                # Denormalised Number checks
+                m.next = "align"
+                self.denormalise(m, a)
+                self.denormalise(m, b)
+
+            # ******
+            # align.
+
+            with m.State("align"):
+                if not self.single_cycle:
+                    # NOTE: this does *not* do single-cycle multi-shifting,
+                    #       it *STAYS* in the align state until exponents match
+
+                    # exponent of a greater than b: shift b down
+                    with m.If(a.e > b.e):
+                        m.d.sync += b.shift_down()
+                    # exponent of b greater than a: shift a down
+                    with m.Elif(a.e < b.e):
+                        m.d.sync += a.shift_down()
+                    # exponents equal: move to next stage.
+                    with m.Else():
+                        m.next = "add_0"
+                else:
+                    # This one however (single-cycle) will do the shift
+                    # in one go.
+
+                    # XXX TODO: the shifter used here is quite expensive
+                    # having only one would be better
+
+                    ediff = Signal((len(a.e), True), reset_less=True)
+                    ediffr = Signal((len(a.e), True), reset_less=True)
+                    m.d.comb += ediff.eq(a.e - b.e)
+                    m.d.comb += ediffr.eq(b.e - a.e)
+                    with m.If(ediff > 0):
+                        m.d.sync += b.shift_down_multi(ediff)
+                    # exponent of b greater than a: shift a down
+                    with m.Elif(ediff < 0):
+                        m.d.sync += a.shift_down_multi(ediffr)
+
+                    m.next = "add_0"
+
+            # ******
+            # First stage of add.  covers same-sign (add) and subtract
+            # special-casing when mantissas are greater or equal, to
+            # give greatest accuracy.
+
+            with m.State("add_0"):
+                m.next = "add_1"
+                m.d.sync += z.e.eq(a.e)
+                # same-sign (both negative or both positive) add mantissas
+                with m.If(a.s == b.s):
                     m.d.sync += [
-                        z[31].eq(a_s),    # sign: a_s
-                        z[23:31].eq(255), # exp: 0b11111...
-                        z[0:23].eq(0)     # mantissa rest: 0b0000...
+                        tot.eq(Cat(a.m, 0) + Cat(b.m, 0)),
+                        z.s.eq(a.s)
                     ]
-                    # if a is inf and signs don't match return NaN
-                    with m.If((b_e == 128) & (a_s != b_s)):
-                        m.d.sync += [
-                          z[31].eq(b_s),    # sign: b_s
-                          z[23:31].eq(255), # exp: 0b11111...
-                          z[22].eq(1),      # mantissa top bit: 1
-                          z[0:22].eq(0)     # mantissa rest: 0b0000...
-                        ]
+                # a mantissa greater than b, use a
+                with m.Elif(a.m >= b.m):
+                    m.d.sync += [
+                        tot.eq(Cat(a.m, 0) - Cat(b.m, 0)),
+                        z.s.eq(a.s)
+                    ]
+                # b mantissa greater than a, use b
+                with m.Else():
+                    m.d.sync += [
+                        tot.eq(Cat(b.m, 0) - Cat(a.m, 0)),
+                        z.s.eq(b.s)
+                ]
+
+            # ******
+            # Second stage of add: preparation for normalisation.
+            # detects when tot sum is too big (tot[27] is kinda a carry bit)
+
+            with m.State("add_1"):
+                m.next = "normalise_1"
+                # tot[27] gets set when the sum overflows. shift result down
+                with m.If(tot[-1]):
+                    m.d.sync += [
+                        z.m.eq(tot[4:]),
+                        of.m0.eq(tot[4]),
+                        of.guard.eq(tot[3]),
+                        of.round_bit.eq(tot[2]),
+                        of.sticky.eq(tot[1] | tot[0]),
+                        z.e.eq(z.e + 1)
+                ]
+                # tot[27] zero case
+                with m.Else():
+                    m.d.sync += [
+                        z.m.eq(tot[3:]),
+                        of.m0.eq(tot[3]),
+                        of.guard.eq(tot[2]),
+                        of.round_bit.eq(tot[1]),
+                        of.sticky.eq(tot[0])
+                ]
+
+            # ******
+            # First stage of normalisation.
+
+            with m.State("normalise_1"):
+                self.normalise_1(m, z, of, "normalise_2")
+
+            # ******
+            # Second stage of normalisation.
+
+            with m.State("normalise_2"):
+                self.normalise_2(m, z, of, "round")
+
+            # ******
+            # rounding stage
+
+            with m.State("round"):
+                self.roundz(m, z, of, "corrections")
+
+            # ******
+            # correction stage
+
+            with m.State("corrections"):
+                self.corrections(m, z, "pack")
+
+            # ******
+            # pack stage
+
+            with m.State("pack"):
+                self.pack(m, z, "put_z")
+
+            # ******
+            # put_z stage
+
+            with m.State("put_z"):
+                self.put_z(m, z, self.out_z, "get_a")
+
         return m
 
-"""
-  always @(posedge clk)
-  begin
-
-    case(state)
-
-      get_a:
-      begin
-        s_in_a_ack <= 1;
-        if (s_in_a_ack && in_a_stb) begin
-          a <= in_a;
-          s_in_a_ack <= 0;
-          state <= get_b;
-        end
-      end
-
-      get_b:
-      begin
-        s_in_b_ack <= 1;
-        if (s_in_b_ack && in_b_stb) begin
-          b <= in_b;
-          s_in_b_ack <= 0;
-          state <= unpack;
-        end
-      end
-
-      unpack:
-      begin
-        a_m <= {a[22 : 0], 3'd0};
-        b_m <= {b[22 : 0], 3'd0};
-        a_e <= a[30 : 23] - 127;
-        b_e <= b[30 : 23] - 127;
-        a_s <= a[31];
-        b_s <= b[31];
-        state <= special_cases;
-      end
-
-      special_cases:
-      begin
-        //if a is NaN or b is NaN return NaN
-        if ((a_e == 128 && a_m != 0) || (b_e == 128 && b_m != 0)) begin
-          z[31] <= 1;
-          z[30:23] <= 255;
-          z[22] <= 1;
-          z[21:0] <= 0;
-          state <= put_z;
-        //if a is inf return inf
-        end else if (a_e == 128) begin
-          z[31] <= a_s;
-          z[30:23] <= 255;
-          z[22:0] <= 0;
-          //if a is inf and signs don't match return nan
-          if ((b_e == 128) && (a_s != b_s)) begin
-              z[31] <= b_s;
-              z[30:23] <= 255;
-              z[22] <= 1;
-              z[21:0] <= 0;
-          end
-          state <= put_z;
-        //if b is inf return inf
-        end else if (b_e == 128) begin
-          z[31] <= b_s;
-          z[30:23] <= 255;
-          z[22:0] <= 0;
-          state <= put_z;
-        //if a is zero return b
-        end else if ((($signed(a_e) == -127) && (a_m == 0)) && (($signed(b_e) == -127) && (b_m == 0))) begin
-          z[31] <= a_s & b_s;
-          z[30:23] <= b_e[7:0] + 127;
-          z[22:0] <= b_m[26:3];
-          state <= put_z;
-        //if a is zero return b
-        end else if (($signed(a_e) == -127) && (a_m == 0)) begin
-          z[31] <= b_s;
-          z[30:23] <= b_e[7:0] + 127;
-          z[22:0] <= b_m[26:3];
-          state <= put_z;
-        //if b is zero return a
-        end else if (($signed(b_e) == -127) && (b_m == 0)) begin
-          z[31] <= a_s;
-          z[30:23] <= a_e[7:0] + 127;
-          z[22:0] <= a_m[26:3];
-          state <= put_z;
-        end else begin
-          //Denormalised Number
-          if ($signed(a_e) == -127) begin
-            a_e <= -126;
-          end else begin
-            a_m[26] <= 1;
-          end
-          //Denormalised Number
-          if ($signed(b_e) == -127) begin
-            b_e <= -126;
-          end else begin
-            b_m[26] <= 1;
-          end
-          state <= align;
-        end
-      end
-
-      align:
-      begin
-        if ($signed(a_e) > $signed(b_e)) begin
-          b_e <= b_e + 1;
-          b_m <= b_m >> 1;
-          b_m[0] <= b_m[0] | b_m[1];
-        end else if ($signed(a_e) < $signed(b_e)) begin
-          a_e <= a_e + 1;
-          a_m <= a_m >> 1;
-          a_m[0] <= a_m[0] | a_m[1];
-        end else begin
-          state <= add_0;
-        end
-      end
-
-      add_0:
-      begin
-        z_e <= a_e;
-        if (a_s == b_s) begin
-          tot <= a_m + b_m;
-          z_s <= a_s;
-        end else begin
-          if (a_m >= b_m) begin
-            tot <= a_m - b_m;
-            z_s <= a_s;
-          end else begin
-            tot <= b_m - a_m;
-            z_s <= b_s;
-          end
-        end
-        state <= add_1;
-      end
-
-      add_1:
-      begin
-        if (tot[27]) begin
-          z_m <= tot[27:4];
-          guard <= tot[3];
-          round_bit <= tot[2];
-          sticky <= tot[1] | tot[0];
-          z_e <= z_e + 1;
-        end else begin
-          z_m <= tot[26:3];
-          guard <= tot[2];
-          round_bit <= tot[1];
-          sticky <= tot[0];
-        end
-        state <= normalise_1;
-      end
-
-      normalise_1:
-      begin
-        if (z_m[23] == 0 && $signed(z_e) > -126) begin
-          z_e <= z_e - 1;
-          z_m <= z_m << 1;
-          z_m[0] <= guard;
-          guard <= round_bit;
-          round_bit <= 0;
-        end else begin
-          state <= normalise_2;
-        end
-      end
-
-      normalise_2:
-      begin
-        if ($signed(z_e) < -126) begin
-          z_e <= z_e + 1;
-          z_m <= z_m >> 1;
-          guard <= z_m[0];
-          round_bit <= guard;
-          sticky <= sticky | round_bit;
-        end else begin
-          state <= round;
-        end
-      end
-
-      round:
-      begin
-        if (guard && (round_bit | sticky | z_m[0])) begin
-          z_m <= z_m + 1;
-          if (z_m == 24'hffffff) begin
-            z_e <=z_e + 1;
-          end
-        end
-        state <= pack;
-      end
-
-      pack:
-      begin
-        z[22 : 0] <= z_m[22:0];
-        z[30 : 23] <= z_e[7:0] + 127;
-        z[31] <= z_s;
-        if ($signed(z_e) == -126 && z_m[23] == 0) begin
-          z[30 : 23] <= 0;
-        end
-        if ($signed(z_e) == -126 && z_m[23:0] == 24'h0) begin
-          z[31] <= 1'b0; // FIX SIGN BUG: -a + a = +0.
-        end
-        //if overflow occurs, return inf
-        if ($signed(z_e) > 127) begin
-          z[22 : 0] <= 0;
-          z[30 : 23] <= 255;
-          z[31] <= z_s;
-        end
-        state <= put_z;
-      end
-
-      put_z:
-      begin
-        s_out_z_stb <= 1;
-        s_out_z <= z;
-        if (s_out_z_stb && out_z_ack) begin
-          s_out_z_stb <= 0;
-          state <= get_a;
-        end
-      end
-
-    endcase
-
-    if (rst == 1) begin
-      state <= get_a;
-      s_in_a_ack <= 0;
-      s_in_b_ack <= 0;
-      s_out_z_stb <= 0;
-    end
-
-  end
-  assign in_a_ack = s_in_a_ack;
-  assign in_b_ack = s_in_b_ack;
-  assign out_z_stb = s_out_z_stb;
-  assign out_z = s_out_z;
-
-endmodule
-"""
 
 if __name__ == "__main__":
     alu = FPADD(width=32)
-    main(alu, ports=[
-                    alu.in_a, alu.in_a_stb, alu.in_a_ack,
-                    alu.in_b, alu.in_b_stb, alu.in_b_ack,
-                    alu.out_z, alu.out_z_stb, alu.out_z_ack,
-        ])
+    main(alu, ports=alu.in_a.ports() + alu.in_b.ports() + alu.out_z.ports())
+
+
+    # works... but don't use, just do "python fname.py convert -t v"
+    #print (verilog.convert(alu, ports=[
+    #                        ports=alu.in_a.ports() + \
+    #                              alu.in_b.ports() + \
+    #                              alu.out_z.ports())