move round to function
[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, Const
6 from nmigen.cli import main, verilog
7
8
9 class FPNum:
10 """ Floating-point Number Class, variable-width TODO (currently 32-bit)
11
12 Contains signals for an incoming copy of the value, decoded into
13 sign / exponent / mantissa.
14 Also contains encoding functions, creation and recognition of
15 zero, NaN and inf (all signed)
16
17 Four extra bits are included in the mantissa: the top bit
18 (m[-1]) is effectively a carry-overflow. The other three are
19 guard (m[2]), round (m[1]), and sticky (m[0])
20 """
21 def __init__(self, width, m_width=None):
22 self.width = width
23 if m_width is None:
24 m_width = width - 5 # mantissa extra bits (top,guard,round)
25 self.v = Signal(width) # Latched copy of value
26 self.m = Signal(m_width) # Mantissa
27 self.e = Signal((10, True)) # Exponent: 10 bits, signed
28 self.s = Signal() # Sign bit
29
30 self.mzero = Const(0, (m_width, False))
31 self.m1s = Const(-1, (m_width, False))
32 self.P128 = Const(128, (10, True))
33 self.P127 = Const(127, (10, True))
34 self.N127 = Const(-127, (10, True))
35 self.N126 = Const(-126, (10, True))
36
37 def decode(self):
38 """ decodes a latched value into sign / exponent / mantissa
39
40 bias is subtracted here, from the exponent. exponent
41 is extended to 10 bits so that subtract 127 is done on
42 a 10-bit number
43 """
44 v = self.v
45 return [self.m.eq(Cat(0, 0, 0, v[0:23])), # mantissa
46 self.e.eq(v[23:31] - self.P127), # exp (minus bias)
47 self.s.eq(v[31]), # sign
48 ]
49
50 def create(self, s, e, m):
51 """ creates a value from sign / exponent / mantissa
52
53 bias is added here, to the exponent
54 """
55 return [
56 self.v[31].eq(s), # sign
57 self.v[23:31].eq(e + self.P127), # exp (add on bias)
58 self.v[0:23].eq(m) # mantissa
59 ]
60
61 def shift_down(self):
62 """ shifts a mantissa down by one. exponent is increased to compensate
63
64 accuracy is lost as a result in the mantissa however there are 3
65 guard bits (the latter of which is the "sticky" bit)
66 """
67 return [self.e.eq(self.e + 1),
68 self.m.eq(Cat(self.m[0] | self.m[1], self.m[2:], 0))
69 ]
70
71 def nan(self, s):
72 return self.create(s, self.P128, 1<<22)
73
74 def inf(self, s):
75 return self.create(s, self.P128, 0)
76
77 def zero(self, s):
78 return self.create(s, self.N127, 0)
79
80 def is_nan(self):
81 return (self.e == self.P128) & (self.m != 0)
82
83 def is_inf(self):
84 return (self.e == self.P128) & (self.m == 0)
85
86 def is_zero(self):
87 return (self.e == self.N127) & (self.m == self.mzero)
88
89 def is_overflowed(self):
90 return (self.e > self.P127)
91
92 def is_denormalised(self):
93 return (self.e == self.N126) & (self.m[23] == 0)
94
95 class FPOp:
96 def __init__(self, width):
97 self.width = width
98
99 self.v = Signal(width)
100 self.stb = Signal()
101 self.ack = Signal()
102
103 def ports(self):
104 return [self.v, self.stb, self.ack]
105
106
107 class Overflow:
108 def __init__(self):
109 self.guard = Signal() # tot[2]
110 self.round_bit = Signal() # tot[1]
111 self.sticky = Signal() # tot[0]
112
113
114 class FPADD:
115 def __init__(self, width):
116 self.width = width
117
118 self.in_a = FPOp(width)
119 self.in_b = FPOp(width)
120 self.out_z = FPOp(width)
121
122 def get_op(self, m, op, v, next_state):
123 with m.If((op.ack) & (op.stb)):
124 m.next = next_state
125 m.d.sync += [
126 v.eq(op.v),
127 op.ack.eq(0)
128 ]
129 with m.Else():
130 m.d.sync += op.ack.eq(1)
131
132 def normalise_1(self, m, z, of, next_state):
133 with m.If((z.m[-1] == 0) & (z.e > z.N126)):
134 m.d.sync +=[
135 z.e.eq(z.e - 1), # DECREASE exponent
136 z.m.eq(z.m << 1), # shift mantissa UP
137 z.m[0].eq(of.guard), # steal guard bit (was tot[2])
138 of.guard.eq(of.round_bit), # steal round_bit (was tot[1])
139 of.round_bit.eq(0), # reset round bit
140 ]
141 with m.Else():
142 m.next = next_state
143
144 def normalise_2(self, m, z, of, next_state):
145 with m.If(z.e < z.N126):
146 m.d.sync +=[
147 z.e.eq(z.e + 1), # INCREASE exponent
148 z.m.eq(z.m >> 1), # shift mantissa DOWN
149 of.guard.eq(z.m[0]),
150 of.round_bit.eq(of.guard),
151 of.sticky.eq(of.sticky | of.round_bit)
152 ]
153 with m.Else():
154 m.next = next_state
155
156 def round(self, m, z, of, next_state):
157 m.next = next_state
158 with m.If(of.guard & (of.round_bit | of.sticky | z.m[0])):
159 m.d.sync += z.m.eq(z.m + 1) # mantissa rounds up
160 with m.If(z.m == z.m1s): # all 1s
161 m.d.sync += z.e.eq(z.e + 1) # exponent rounds up
162
163 def get_fragment(self, platform=None):
164 m = Module()
165
166 # Latches
167 a = FPNum(self.width)
168 b = FPNum(self.width)
169 z = FPNum(self.width, 24)
170
171 tot = Signal(28) # sticky/round/guard bits, 23 result, 1 overflow
172
173 of = Overflow()
174
175 with m.FSM() as fsm:
176
177 # ******
178 # gets operand a
179
180 with m.State("get_a"):
181 self.get_op(m, self.in_a, a.v, "get_b")
182
183 # ******
184 # gets operand b
185
186 with m.State("get_b"):
187 self.get_op(m, self.in_b, b.v, "unpack")
188
189 # ******
190 # unpacks operands into sign, mantissa and exponent
191
192 with m.State("unpack"):
193 m.next = "special_cases"
194 m.d.sync += a.decode()
195 m.d.sync += b.decode()
196
197 # ******
198 # special cases: NaNs, infs, zeros, denormalised
199
200 with m.State("special_cases"):
201
202 # if a is NaN or b is NaN return NaN
203 with m.If(a.is_nan() | b.is_nan()):
204 m.next = "put_z"
205 m.d.sync += z.nan(1)
206
207 # if a is inf return inf (or NaN)
208 with m.Elif(a.is_inf()):
209 m.next = "put_z"
210 m.d.sync += z.inf(a.s)
211 # if a is inf and signs don't match return NaN
212 with m.If((b.e == b.P128) & (a.s != b.s)):
213 m.d.sync += z.nan(b.s)
214
215 # if b is inf return inf
216 with m.Elif(b.is_inf()):
217 m.next = "put_z"
218 m.d.sync += z.inf(b.s)
219
220 # if a is zero and b zero return signed-a/b
221 with m.Elif(a.is_zero() & b.is_zero()):
222 m.next = "put_z"
223 m.d.sync += z.create(a.s & b.s, b.e[0:8], b.m[3:-1])
224
225 # if a is zero return b
226 with m.Elif(a.is_zero()):
227 m.next = "put_z"
228 m.d.sync += z.create(b.s, b.e[0:8], b.m[3:-1])
229
230 # if b is zero return a
231 with m.Elif(b.is_zero()):
232 m.next = "put_z"
233 m.d.sync += z.create(a.s, a.e[0:8], a.m[3:-1])
234
235 # Denormalised Number checks
236 with m.Else():
237 m.next = "align"
238 # denormalise a check
239 with m.If(a.e == a.N127):
240 m.d.sync += a.e.eq(-126) # limit a exponent
241 with m.Else():
242 m.d.sync += a.m[-1].eq(1) # set top mantissa bit
243 # denormalise b check
244 with m.If(b.e == a.N127):
245 m.d.sync += b.e.eq(-126) # limit b exponent
246 with m.Else():
247 m.d.sync += b.m[-1].eq(1) # set top mantissa bit
248
249 # ******
250 # align. NOTE: this does *not* do single-cycle multi-shifting,
251 # it *STAYS* in the align state until the exponents match
252
253 with m.State("align"):
254 # exponent of a greater than b: increment b exp, shift b mant
255 with m.If(a.e > b.e):
256 m.d.sync += b.shift_down()
257 # exponent of b greater than a: increment a exp, shift a mant
258 with m.Elif(a.e < b.e):
259 m.d.sync += a.shift_down()
260 # exponents equal: move to next stage.
261 with m.Else():
262 m.next = "add_0"
263
264 # ******
265 # First stage of add. covers same-sign (add) and subtract
266 # special-casing when mantissas are greater or equal, to
267 # give greatest accuracy.
268
269 with m.State("add_0"):
270 m.next = "add_1"
271 m.d.sync += z.e.eq(a.e)
272 # same-sign (both negative or both positive) add mantissas
273 with m.If(a.s == b.s):
274 m.d.sync += [
275 tot.eq(a.m + b.m),
276 z.s.eq(a.s)
277 ]
278 # a mantissa greater than b, use a
279 with m.Elif(a.m >= b.m):
280 m.d.sync += [
281 tot.eq(a.m - b.m),
282 z.s.eq(a.s)
283 ]
284 # b mantissa greater than a, use b
285 with m.Else():
286 m.d.sync += [
287 tot.eq(b.m - a.m),
288 z.s.eq(b.s)
289 ]
290
291 # ******
292 # Second stage of add: preparation for normalisation.
293 # detects when tot sum is too big (tot[27] is kinda a carry bit)
294
295 with m.State("add_1"):
296 m.next = "normalise_1"
297 # tot[27] gets set when the sum overflows. shift result down
298 with m.If(tot[27]):
299 m.d.sync += [
300 z.m.eq(tot[4:28]),
301 of.guard.eq(tot[3]),
302 of.round_bit.eq(tot[2]),
303 of.sticky.eq(tot[1] | tot[0]),
304 z.e.eq(z.e + 1)
305 ]
306 # tot[27] zero case
307 with m.Else():
308 m.d.sync += [
309 z.m.eq(tot[3:27]),
310 of.guard.eq(tot[2]),
311 of.round_bit.eq(tot[1]),
312 of.sticky.eq(tot[0])
313 ]
314
315 # ******
316 # First stage of normalisation.
317 # NOTE: just like "align", this one keeps going round every clock
318 # until the result's exponent is within acceptable "range"
319 # NOTE: the weirdness of reassigning guard and round is due to
320 # the extra mantissa bits coming from tot[0..2]
321
322 with m.State("normalise_1"):
323 self.normalise_1(m, z, of, "normalise_2")
324
325 # ******
326 # Second stage of normalisation.
327 # NOTE: just like "align", this one keeps going round every clock
328 # until the result's exponent is within acceptable "range"
329 # NOTE: the weirdness of reassigning guard and round is due to
330 # the extra mantissa bits coming from tot[0..2]
331
332 with m.State("normalise_2"):
333 self.normalise_2(m, z, of, "round")
334
335 # ******
336 # rounding stage
337
338 with m.State("round"):
339 self.round(m, z, of, "corrections")
340
341 # ******
342 # correction stage
343
344 with m.State("corrections"):
345 m.next = "pack"
346 # denormalised, correct exponent to zero
347 with m.If(z.is_denormalised()):
348 m.d.sync += z.m.eq(-127)
349 # FIX SIGN BUG: -a + a = +0.
350 with m.If((z.e == z.N126) & (z.m[0:] == 0)):
351 m.d.sync += z.s.eq(0)
352
353 # ******
354 # pack stage
355
356 with m.State("pack"):
357 m.next = "put_z"
358 # if overflow occurs, return inf
359 with m.If(z.is_overflowed()):
360 m.d.sync += z.inf(0)
361 with m.Else():
362 m.d.sync += z.create(z.s, z.e, z.m)
363
364 # ******
365 # put_z stage
366
367 with m.State("put_z"):
368 m.d.sync += [
369 self.out_z.stb.eq(1),
370 self.out_z.v.eq(z.v)
371 ]
372 with m.If(self.out_z.stb & self.out_z.ack):
373 m.d.sync += self.out_z.stb.eq(0)
374 m.next = "get_a"
375
376 return m
377
378
379 if __name__ == "__main__":
380 alu = FPADD(width=32)
381 main(alu, ports=alu.in_a.ports() + alu.in_b.ports() + alu.out_z.ports())
382
383
384 # works... but don't use, just do "python fname.py convert -t v"
385 #print (verilog.convert(alu, ports=[
386 # ports=alu.in_a.ports() + \
387 # alu.in_b.ports() + \
388 # alu.out_z.ports())