split out add0 stage into separate class
[ieee754fpu.git] / src / add / nmigen_add_experiment.py
1 # IEEE Floating Point Adder (Single Precision)
2 # Copyright (C) Jonathan P Dawson 2013
3 # 2013-12-12
4
5 from nmigen import Module, Signal, Cat
6 from nmigen.cli import main, verilog
7
8 from fpbase import FPNumIn, FPNumOut, FPOp, Overflow, FPBase
9
10
11 class FPState(FPBase):
12 def __init__(self, state_from):
13 self.state_from = state_from
14
15 def set_inputs(self, inputs):
16 self.inputs = inputs
17 for k,v in inputs.items():
18 setattr(self, k, v)
19
20 def set_outputs(self, outputs):
21 self.outputs = outputs
22 for k,v in outputs.items():
23 setattr(self, k, v)
24
25
26 class FPGetOpA(FPState):
27
28 def action(self, m):
29 self.get_op(m, self.in_a, self.a, "get_b")
30
31
32 class FPGetOpB(FPState):
33
34 def action(self, m):
35 self.get_op(m, self.in_b, self.b, "special_cases")
36
37
38 class FPAddSpecialCases(FPState):
39
40 def action(self, m):
41 s_nomatch = Signal()
42 m.d.comb += s_nomatch.eq(self.a.s != self.b.s)
43
44 m_match = Signal()
45 m.d.comb += m_match.eq(self.a.m == self.b.m)
46
47 # if a is NaN or b is NaN return NaN
48 with m.If(self.a.is_nan | self.b.is_nan):
49 m.next = "put_z"
50 m.d.sync += self.z.nan(1)
51
52 # XXX WEIRDNESS for FP16 non-canonical NaN handling
53 # under review
54
55 ## if a is zero and b is NaN return -b
56 #with m.If(a.is_zero & (a.s==0) & b.is_nan):
57 # m.next = "put_z"
58 # m.d.sync += z.create(b.s, b.e, Cat(b.m[3:-2], ~b.m[0]))
59
60 ## if b is zero and a is NaN return -a
61 #with m.Elif(b.is_zero & (b.s==0) & a.is_nan):
62 # m.next = "put_z"
63 # m.d.sync += z.create(a.s, a.e, Cat(a.m[3:-2], ~a.m[0]))
64
65 ## if a is -zero and b is NaN return -b
66 #with m.Elif(a.is_zero & (a.s==1) & b.is_nan):
67 # m.next = "put_z"
68 # m.d.sync += z.create(a.s & b.s, b.e, Cat(b.m[3:-2], 1))
69
70 ## if b is -zero and a is NaN return -a
71 #with m.Elif(b.is_zero & (b.s==1) & a.is_nan):
72 # m.next = "put_z"
73 # m.d.sync += z.create(a.s & b.s, a.e, Cat(a.m[3:-2], 1))
74
75 # if a is inf return inf (or NaN)
76 with m.Elif(self.a.is_inf):
77 m.next = "put_z"
78 m.d.sync += self.z.inf(self.a.s)
79 # if a is inf and signs don't match return NaN
80 with m.If(self.b.exp_128 & s_nomatch):
81 m.d.sync += self.z.nan(1)
82
83 # if b is inf return inf
84 with m.Elif(self.b.is_inf):
85 m.next = "put_z"
86 m.d.sync += self.z.inf(self.b.s)
87
88 # if a is zero and b zero return signed-a/b
89 with m.Elif(self.a.is_zero & self.b.is_zero):
90 m.next = "put_z"
91 m.d.sync += self.z.create(self.a.s & self.b.s, self.b.e,
92 self.b.m[3:-1])
93
94 # if a is zero return b
95 with m.Elif(self.a.is_zero):
96 m.next = "put_z"
97 m.d.sync += self.z.create(self.b.s, self.b.e, self.b.m[3:-1])
98
99 # if b is zero return a
100 with m.Elif(self.b.is_zero):
101 m.next = "put_z"
102 m.d.sync += self.z.create(self.a.s, self.a.e, self.a.m[3:-1])
103
104 # if a equal to -b return zero (+ve zero)
105 with m.Elif(s_nomatch & m_match & (self.a.e == self.b.e)):
106 m.next = "put_z"
107 m.d.sync += self.z.zero(0)
108
109 # Denormalised Number checks
110 with m.Else():
111 m.next = "denormalise"
112
113
114 class FPAddDeNorm(FPState):
115
116 def action(self, m):
117 # Denormalised Number checks
118 m.next = "align"
119 self.denormalise(m, self.a)
120 self.denormalise(m, self.b)
121
122
123 class FPAddAlignMulti(FPState):
124
125 def action(self, m):
126 # NOTE: this does *not* do single-cycle multi-shifting,
127 # it *STAYS* in the align state until exponents match
128
129 # exponent of a greater than b: shift b down
130 with m.If(self.a.e > self.b.e):
131 m.d.sync += self.b.shift_down()
132 # exponent of b greater than a: shift a down
133 with m.Elif(self.a.e < self.b.e):
134 m.d.sync += self.a.shift_down()
135 # exponents equal: move to next stage.
136 with m.Else():
137 m.next = "add_0"
138
139
140 class FPAddAlignSingle(FPState):
141
142 def action(self, m):
143 # This one however (single-cycle) will do the shift
144 # in one go.
145
146 # XXX TODO: the shifter used here is quite expensive
147 # having only one would be better
148
149 ediff = Signal((len(self.a.e), True), reset_less=True)
150 ediffr = Signal((len(self.a.e), True), reset_less=True)
151 m.d.comb += ediff.eq(self.a.e - self.b.e)
152 m.d.comb += ediffr.eq(self.b.e - self.a.e)
153 with m.If(ediff > 0):
154 m.d.sync += self.b.shift_down_multi(ediff)
155 # exponent of b greater than a: shift a down
156 with m.Elif(ediff < 0):
157 m.d.sync += self.a.shift_down_multi(ediffr)
158
159 m.next = "add_0"
160
161
162 class FPAddStage0(FPState):
163
164 def action(self, m):
165 """ First stage of add. covers same-sign (add) and subtract
166 special-casing when mantissas are greater or equal, to
167 give greatest accuracy.
168 """
169 m.next = "add_1"
170 m.d.sync += self.z.e.eq(self.a.e)
171 # same-sign (both negative or both positive) add mantissas
172 with m.If(self.a.s == self.b.s):
173 m.d.sync += [
174 self.tot.eq(Cat(self.a.m, 0) + Cat(self.b.m, 0)),
175 self.z.s.eq(self.a.s)
176 ]
177 # a mantissa greater than b, use a
178 with m.Elif(self.a.m >= self.b.m):
179 m.d.sync += [
180 self.tot.eq(Cat(self.a.m, 0) - Cat(self.b.m, 0)),
181 self.z.s.eq(self.a.s)
182 ]
183 # b mantissa greater than a, use b
184 with m.Else():
185 m.d.sync += [
186 self.tot.eq(Cat(self.b.m, 0) - Cat(self.a.m, 0)),
187 self.z.s.eq(self.b.s)
188 ]
189
190
191 class FPADD(FPBase):
192
193 def __init__(self, width, single_cycle=False):
194 FPBase.__init__(self)
195 self.width = width
196 self.single_cycle = single_cycle
197
198 self.in_a = FPOp(width)
199 self.in_b = FPOp(width)
200 self.out_z = FPOp(width)
201
202 def get_fragment(self, platform=None):
203 """ creates the HDL code-fragment for FPAdd
204 """
205 m = Module()
206
207 # Latches
208 a = FPNumIn(self.in_a, self.width)
209 b = FPNumIn(self.in_b, self.width)
210 z = FPNumOut(self.width, False)
211
212 m.submodules.fpnum_a = a
213 m.submodules.fpnum_b = b
214 m.submodules.fpnum_z = z
215
216 w = z.m_width + 4
217 tot = Signal(w, reset_less=True) # sticky/round/guard, {mantissa} result, 1 overflow
218
219 of = Overflow()
220 m.submodules.overflow = of
221
222 geta = FPGetOpA("get_a")
223 geta.set_inputs({"in_a": self.in_a})
224 geta.set_outputs({"a": a})
225 m.d.comb += a.v.eq(self.in_a.v) # links in_a to a
226
227 getb = FPGetOpB("get_b")
228 getb.set_inputs({"in_b": self.in_b})
229 getb.set_outputs({"b": b})
230 m.d.comb += b.v.eq(self.in_b.v) # links in_b to b
231
232 sc = FPAddSpecialCases("special_cases")
233 sc.set_inputs({"a": a, "b": b})
234 sc.set_outputs({"z": z})
235
236 dn = FPAddDeNorm("denormalise")
237 dn.set_inputs({"a": a, "b": b})
238 dn.set_outputs({"a": a, "b": b}) # XXX outputs same as inputs
239
240 if self.single_cycle:
241 alm = FPAddAlignSingle("align")
242 else:
243 alm = FPAddAlignMulti("align")
244 alm.set_inputs({"a": a, "b": b})
245 alm.set_outputs({"a": a, "b": b}) # XXX outputs same as inputs
246
247 add0 = FPAddStage0("add_0")
248 add0.set_inputs({"a": a, "b": b})
249 add0.set_outputs({"z": z, "tot": tot})
250
251 with m.FSM() as fsm:
252
253 # ******
254 # gets operand a
255
256 with m.State("get_a"):
257 geta.action(m)
258
259 # ******
260 # gets operand b
261
262 with m.State("get_b"):
263 #self.get_op(m, self.in_b, b, "special_cases")
264 getb.action(m)
265
266 # ******
267 # special cases: NaNs, infs, zeros, denormalised
268 # NOTE: some of these are unique to add. see "Special Operations"
269 # https://steve.hollasch.net/cgindex/coding/ieeefloat.html
270
271 with m.State("special_cases"):
272 sc.action(m)
273
274 # ******
275 # denormalise.
276
277 with m.State("denormalise"):
278 dn.action(m)
279
280 # ******
281 # align.
282
283 with m.State("align"):
284 alm.action(m)
285
286 # ******
287 # First stage of add. covers same-sign (add) and subtract
288 # special-casing when mantissas are greater or equal, to
289 # give greatest accuracy.
290
291 with m.State("add_0"):
292 add0.action(m)
293
294 # ******
295 # Second stage of add: preparation for normalisation.
296 # detects when tot sum is too big (tot[27] is kinda a carry bit)
297
298 with m.State("add_1"):
299 m.next = "normalise_1"
300 # tot[27] gets set when the sum overflows. shift result down
301 with m.If(tot[-1]):
302 m.d.sync += [
303 z.m.eq(tot[4:]),
304 of.m0.eq(tot[4]),
305 of.guard.eq(tot[3]),
306 of.round_bit.eq(tot[2]),
307 of.sticky.eq(tot[1] | tot[0]),
308 z.e.eq(z.e + 1)
309 ]
310 # tot[27] zero case
311 with m.Else():
312 m.d.sync += [
313 z.m.eq(tot[3:]),
314 of.m0.eq(tot[3]),
315 of.guard.eq(tot[2]),
316 of.round_bit.eq(tot[1]),
317 of.sticky.eq(tot[0])
318 ]
319
320 # ******
321 # First stage of normalisation.
322
323 with m.State("normalise_1"):
324 self.normalise_1(m, z, of, "normalise_2")
325
326 # ******
327 # Second stage of normalisation.
328
329 with m.State("normalise_2"):
330 self.normalise_2(m, z, of, "round")
331
332 # ******
333 # rounding stage
334
335 with m.State("round"):
336 self.roundz(m, z, of, "corrections")
337
338 # ******
339 # correction stage
340
341 with m.State("corrections"):
342 self.corrections(m, z, "pack")
343
344 # ******
345 # pack stage
346
347 with m.State("pack"):
348 self.pack(m, z, "put_z")
349
350 # ******
351 # put_z stage
352
353 with m.State("put_z"):
354 self.put_z(m, z, self.out_z, "get_a")
355
356 return m
357
358
359 if __name__ == "__main__":
360 alu = FPADD(width=32)
361 main(alu, ports=alu.in_a.ports() + alu.in_b.ports() + alu.out_z.ports())
362
363
364 # works... but don't use, just do "python fname.py convert -t v"
365 #print (verilog.convert(alu, ports=[
366 # ports=alu.in_a.ports() + \
367 # alu.in_b.ports() + \
368 # alu.out_z.ports())