move round, guard and sticky to separate clas
[ieee754fpu.git] / src / add / nmigen_add_experiment.py
index bbadfc0e0417d01ea77e593b956ce131187fb8b2..dd778d8a2e715815068c83cf906496f4f794ccaf 100644 (file)
@@ -2,11 +2,22 @@
 # Copyright (C) Jonathan P Dawson 2013
 # 2013-12-12
 
-from nmigen import Module, Signal, Cat
-from nmigen.cli import main
+from nmigen import Module, Signal, Cat, Const
+from nmigen.cli import main, verilog
 
 
 class FPNum:
+    """ Floating-point Number Class, variable-width TODO (currently 32-bit)
+
+        Contains signals for an incoming copy of the value, decoded into
+        sign / exponent / mantissa.
+        Also contains encoding functions, creation and recognition of
+        zero, NaN and inf (all signed)
+
+        Four extra bits are included in the mantissa: the top bit
+        (m[-1]) is effectively a carry-overflow.  The other three are
+        guard (m[2]), round (m[1]), and sticky (m[0])
+    """
     def __init__(self, width, m_width=None):
         self.width = width
         if m_width is None:
@@ -16,58 +27,121 @@ class FPNum:
         self.e = Signal((10, True)) # Exponent: 10 bits, signed
         self.s = Signal()           # Sign bit
 
+        self.mzero = Const(0, (m_width, False))
+        self.m1s = Const(-1, (m_width, False))
+        self.P128 = Const(128, (10, True))
+        self.P127 = Const(127, (10, True))
+        self.N127 = Const(-127, (10, True))
+        self.N126 = Const(-126, (10, True))
+
     def decode(self):
+        """ decodes a latched value into sign / exponent / mantissa
+
+            bias is subtracted here, from the exponent.  exponent
+            is extended to 10 bits so that subtract 127 is done on
+            a 10-bit number
+        """
         v = self.v
         return [self.m.eq(Cat(0, 0, 0, v[0:23])), # mantissa
-                self.e.eq(Cat(v[23:31]) - 127),   # exponent (take off bias)
-                self.s.eq(Cat(v[31])),            # sign
+                self.e.eq(v[23:31] - self.P127), # exp (minus bias)
+                self.s.eq(v[31]),                 # sign
                 ]
 
     def create(self, s, e, m):
+        """ creates a value from sign / exponent / mantissa
+
+            bias is added here, to the exponent
+        """
         return [
           self.v[31].eq(s),          # sign
-          self.v[23:31].eq(e + 127), # exp
+          self.v[23:31].eq(e + self.P127), # exp (add on bias)
           self.v[0:23].eq(m)         # mantissa
         ]
 
     def shift_down(self):
-        return self.create(self.s,
-                           self.e + 1,
-                           Cat(self.m[0] | self.m[1], self.m[1:-5], 0))
+        """ shifts a mantissa down by one. exponent is increased to compensate
+
+            accuracy is lost as a result in the mantissa however there are 3
+            guard bits (the latter of which is the "sticky" bit)
+        """
+        return [self.e.eq(self.e + 1),
+                self.m.eq(Cat(self.m[0] | self.m[1], self.m[2:], 0))
+               ]
 
     def nan(self, s):
-        return self.create(s, 0xff, 1<<22)
+        return self.create(s, self.P128, 1<<22)
 
     def inf(self, s):
-        return self.create(s, 0xff, 0)
+        return self.create(s, self.P128, 0)
+
+    def zero(self, s):
+        return self.create(s, self.N127, 0)
 
     def is_nan(self):
-        return (self.e == 128) & (self.m != 0)
+        return (self.e == self.P128) & (self.m != 0)
 
     def is_inf(self):
-        return (self.e == 128) & (self.m == 0)
+        return (self.e == self.P128) & (self.m == 0)
 
     def is_zero(self):
-        return (self.e == -127) & (self.m == 0)
+        return (self.e == self.N127) & (self.m == self.mzero)
 
+    def is_overflowed(self):
+        return (self.e > self.P127)
 
-class FPADD:
+    def is_denormalised(self):
+        return (self.e == self.N126) & (self.m[23] == 0)
+
+class FPOp:
     def __init__(self, width):
         self.width = width
 
-        self.in_a     = Signal(width)
-        self.in_a_stb = Signal()
-        self.in_a_ack = Signal()
+        self.v     = Signal(width)
+        self.stb = Signal()
+        self.ack = Signal()
+
+    def ports(self):
+        return [self.v, self.stb, self.ack]
+
+
+class Overflow:
+    def __init__(self):
+        self.guard = Signal()     # tot[2]
+        self.round_bit = Signal() # tot[1]
+        self.sticky = Signal()    # tot[0]
 
-        self.in_b     = Signal(width)
-        self.in_b_stb = Signal()
-        self.in_b_ack = Signal()
 
-        self.out_z     = Signal(width)
-        self.out_z_stb = Signal()
-        self.out_z_ack = Signal()
+class FPADD:
+    def __init__(self, width):
+        self.width = width
 
-    def get_fragment(self, platform):
+        self.in_a     = FPOp(width)
+        self.in_b     = FPOp(width)
+        self.out_z     = FPOp(width)
+
+    def get_op(self, m, op, v, next_state):
+        with m.If((op.ack) & (op.stb)):
+            m.next = next_state
+            m.d.sync += [
+                v.eq(op.v),
+                op.ack.eq(0)
+            ]
+        with m.Else():
+            m.d.sync += op.ack.eq(1)
+
+    def normalise_1(self, m, z, of, next_state):
+        with m.If((z.m[-1] == 0) & (z.e > z.N126)):
+            m.d.sync +=[
+                z.e.eq(z.e - 1),  # DECREASE exponent
+                z.m.eq(z.m << 1), # shift mantissa UP
+                z.m[0].eq(of.guard),       # steal guard bit (was tot[2])
+                of.guard.eq(of.round_bit), # steal round_bit (was tot[1])
+                of.round_bit.eq(0),        # reset round bit
+            ]
+        with m.Else():
+            m.next = next_state
+
+    def get_fragment(self, platform=None):
         m = Module()
 
         # Latches
@@ -75,11 +149,9 @@ class FPADD:
         b = FPNum(self.width)
         z = FPNum(self.width, 24)
 
-        guard = Signal()
-        round_bit = Signal()
-        sticky = Signal()
+        tot = Signal(28)     # sticky/round/guard bits, 23 result, 1 overflow
 
-        tot = Signal(28)
+        of = Overflow()
 
         with m.FSM() as fsm:
 
@@ -87,27 +159,13 @@ 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.v.eq(self.in_a),
-                        self.in_a_ack.eq(0)
-                    ]
-                with m.Else():
-                    m.d.sync += self.in_a_ack.eq(1)
+                self.get_op(m, self.in_a, a.v, "get_b")
 
             # ******
             # 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.v.eq(self.in_b),
-                        self.in_b_ack.eq(0)
-                    ]
-                with m.Else():
-                    m.d.sync += self.in_b_ack.eq(1)
+                self.get_op(m, self.in_b, b.v, "unpack")
 
             # ******
             # unpacks operands into sign, mantissa and exponent
@@ -132,7 +190,7 @@ class FPADD:
                     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.e == 128) & (a.s != b.s)):
+                    with m.If((b.e == b.P128) & (a.s != b.s)):
                         m.d.sync += z.nan(b.s)
 
                 # if b is inf return inf
@@ -143,31 +201,31 @@ class FPADD:
                 # 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[0:8], b.m[3:26])
+                    m.d.sync += z.create(a.s & b.s, b.e[0:8], 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[0:8], b.m[3:26])
+                    m.d.sync += z.create(b.s, b.e[0:8], 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[0:8], a.m[3:26])
+                    m.d.sync += z.create(a.s, a.e[0:8], a.m[3:-1])
 
                 # Denormalised Number checks
                 with m.Else():
                     m.next = "align"
                     # denormalise a check
-                    with m.If(a.e == -127):
+                    with m.If(a.e == a.N127):
                         m.d.sync += a.e.eq(-126) # limit a exponent
                     with m.Else():
-                        m.d.sync += a.m[26].eq(1) # set highest mantissa bit
+                        m.d.sync += a.m[-1].eq(1) # set top mantissa bit
                     # denormalise b check
-                    with m.If(b.e == -127):
+                    with m.If(b.e == a.N127):
                         m.d.sync += b.e.eq(-126) # limit b exponent
                     with m.Else():
-                        m.d.sync += b.m[26].eq(1) # set highest mantissa bit
+                        m.d.sync += b.m[-1].eq(1) # set top mantissa bit
 
             # ******
             # align.  NOTE: this does *not* do single-cycle multi-shifting,
@@ -221,18 +279,18 @@ class FPADD:
                 with m.If(tot[27]):
                     m.d.sync += [
                         z.m.eq(tot[4:28]),
-                        guard.eq(tot[3]),
-                        round_bit.eq(tot[2]),
-                        sticky.eq(tot[1] | tot[0]),
+                        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:27]),
-                        guard.eq(tot[2]),
-                        round_bit.eq(tot[1]),
-                        sticky.eq(tot[0])
+                        of.guard.eq(tot[2]),
+                        of.round_bit.eq(tot[1]),
+                        of.sticky.eq(tot[0])
                 ]
 
             # ******
@@ -243,15 +301,15 @@ class FPADD:
             #       the extra mantissa bits coming from tot[0..2]
 
             with m.State("normalise_1"):
-                with m.If((z.m[23] == 0) & (z.e > -126)):
+                with m.If((z.m[-1] == 0) & (z.e > z.N126)):
                     m.d.sync +=[
                         z.e.eq(z.e - 1),  # DECREASE exponent
                         z.m.eq(z.m << 1), # shift mantissa UP
-                        z.m[0].eq(guard), # steal guard bit (was tot[2])
-                        guard.eq(round_bit), # steal round_bit (was tot[1])
+                        z.m[0].eq(of.guard), # steal guard bit (was tot[2])
+                        of.guard.eq(of.round_bit), # steal round_bit was tot[1])
                     ]
                 with m.Else():
-                    m.next = "normalize_2"
+                    m.next = "normalise_2"
 
             # ******
             # Second stage of normalisation.
@@ -261,13 +319,13 @@ class FPADD:
             #       the extra mantissa bits coming from tot[0..2]
 
             with m.State("normalise_2"):
-                with m.If(z.e < -126):
+                with m.If(z.e < z.N126):
                     m.d.sync +=[
                         z.e.eq(z.e + 1),  # INCREASE exponent
                         z.m.eq(z.m >> 1), # shift mantissa DOWN
-                        guard.eq(z.m[0]),
-                        round_bit.eq(guard),
-                        sticky.eq(sticky | round_bit)
+                        of.guard.eq(z.m[0]),
+                        of.round_bit.eq(of.guard),
+                        of.sticky.eq(of.sticky | of.round_bit)
                     ]
                 with m.Else():
                     m.next = "round"
@@ -276,296 +334,57 @@ class FPADD:
             # rounding stage
 
             with m.State("round"):
-                m.next = "pack"
-                with m.If(guard & (round_bit | sticky | z.m[0])):
+                m.next = "corrections"
+                with m.If(of.guard & (of.round_bit | of.sticky | z.m[0])):
                     m.d.sync += z.m.eq(z.m + 1) # mantissa rounds up
-                    with m.If(z.m == 0xffffff): # all 1s
+                    with m.If(z.m == z.m1s): # all 1s
                         m.d.sync += z.e.eq(z.e + 1) # exponent rounds up
 
+            # ******
+            # correction stage
+
+            with m.State("corrections"):
+                m.next = "pack"
+                # denormalised, correct exponent to zero
+                with m.If(z.is_denormalised()):
+                    m.d.sync += z.m.eq(-127)
+                # FIX SIGN BUG: -a + a = +0.
+                with m.If((z.e == z.N126) & (z.m[0:] == 0)):
+                    m.d.sync += z.s.eq(0)
+
             # ******
             # pack stage
 
-            """ TODO: see if z.create can be used *later*.  convert
-                verilog first (and commit), *second* phase, convert nmigen
-                code to use FPNum.create() (as a separate commit)
-
-              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
-            """
+            with m.State("pack"):
+                m.next = "put_z"
+                # if overflow occurs, return inf
+                with m.If(z.is_overflowed()):
+                    m.d.sync += z.inf(0)
+                with m.Else():
+                    m.d.sync += z.create(z.s, z.e, z.m)
 
             # ******
             # put_z stage
 
-            """
-              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
-            """
+            with m.State("put_z"):
+              m.d.sync += [
+                  self.out_z.stb.eq(1),
+                  self.out_z.v.eq(z.v)
+              ]
+              with m.If(self.out_z.stb & self.out_z.ack):
+                  m.d.sync += self.out_z.stb.eq(0)
+                  m.next = "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())