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