use slice magic constants
[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
96 class FPADD:
97 def __init__(self, width):
98 self.width = width
99
100 self.in_a = Signal(width)
101 self.in_a_stb = Signal()
102 self.in_a_ack = Signal()
103
104 self.in_b = Signal(width)
105 self.in_b_stb = Signal()
106 self.in_b_ack = Signal()
107
108 self.out_z = Signal(width)
109 self.out_z_stb = Signal()
110 self.out_z_ack = Signal()
111
112 def get_fragment(self, platform=None):
113 m = Module()
114
115 # Latches
116 a = FPNum(self.width)
117 b = FPNum(self.width)
118 z = FPNum(self.width, 24)
119
120 tot = Signal(28) # sticky/round/guard bits, 23 result, 1 overflow
121
122 guard = Signal() # tot[2]
123 round_bit = Signal() # tot[1]
124 sticky = Signal() # tot[0]
125
126 with m.FSM() as fsm:
127
128 # ******
129 # gets operand a
130
131 with m.State("get_a"):
132 with m.If((self.in_a_ack) & (self.in_a_stb)):
133 m.next = "get_b"
134 m.d.sync += [
135 a.v.eq(self.in_a),
136 self.in_a_ack.eq(0)
137 ]
138 with m.Else():
139 m.d.sync += self.in_a_ack.eq(1)
140
141 # ******
142 # gets operand b
143
144 with m.State("get_b"):
145 with m.If((self.in_b_ack) & (self.in_b_stb)):
146 m.next = "unpack"
147 m.d.sync += [
148 b.v.eq(self.in_b),
149 self.in_b_ack.eq(0)
150 ]
151 with m.Else():
152 m.d.sync += self.in_b_ack.eq(1)
153
154 # ******
155 # unpacks operands into sign, mantissa and exponent
156
157 with m.State("unpack"):
158 m.next = "special_cases"
159 m.d.sync += a.decode()
160 m.d.sync += b.decode()
161
162 # ******
163 # special cases: NaNs, infs, zeros, denormalised
164
165 with m.State("special_cases"):
166
167 # if a is NaN or b is NaN return NaN
168 with m.If(a.is_nan() | b.is_nan()):
169 m.next = "put_z"
170 m.d.sync += z.nan(1)
171
172 # if a is inf return inf (or NaN)
173 with m.Elif(a.is_inf()):
174 m.next = "put_z"
175 m.d.sync += z.inf(a.s)
176 # if a is inf and signs don't match return NaN
177 with m.If((b.e == b.P128) & (a.s != b.s)):
178 m.d.sync += z.nan(b.s)
179
180 # if b is inf return inf
181 with m.Elif(b.is_inf()):
182 m.next = "put_z"
183 m.d.sync += z.inf(b.s)
184
185 # if a is zero and b zero return signed-a/b
186 with m.Elif(a.is_zero() & b.is_zero()):
187 m.next = "put_z"
188 m.d.sync += z.create(a.s & b.s, b.e[0:8], b.m[3:-1])
189
190 # if a is zero return b
191 with m.Elif(a.is_zero()):
192 m.next = "put_z"
193 m.d.sync += z.create(b.s, b.e[0:8], b.m[3:-1])
194
195 # if b is zero return a
196 with m.Elif(b.is_zero()):
197 m.next = "put_z"
198 m.d.sync += z.create(a.s, a.e[0:8], a.m[3:-1])
199
200 # Denormalised Number checks
201 with m.Else():
202 m.next = "align"
203 # denormalise a check
204 with m.If(a.e == a.N127):
205 m.d.sync += a.e.eq(-126) # limit a exponent
206 with m.Else():
207 m.d.sync += a.m[-1].eq(1) # set top mantissa bit
208 # denormalise b check
209 with m.If(b.e == a.N127):
210 m.d.sync += b.e.eq(-126) # limit b exponent
211 with m.Else():
212 m.d.sync += b.m[-1].eq(1) # set top mantissa bit
213
214 # ******
215 # align. NOTE: this does *not* do single-cycle multi-shifting,
216 # it *STAYS* in the align state until the exponents match
217
218 with m.State("align"):
219 # exponent of a greater than b: increment b exp, shift b mant
220 with m.If(a.e > b.e):
221 m.d.sync += b.shift_down()
222 # exponent of b greater than a: increment a exp, shift a mant
223 with m.Elif(a.e < b.e):
224 m.d.sync += a.shift_down()
225 # exponents equal: move to next stage.
226 with m.Else():
227 m.next = "add_0"
228
229 # ******
230 # First stage of add. covers same-sign (add) and subtract
231 # special-casing when mantissas are greater or equal, to
232 # give greatest accuracy.
233
234 with m.State("add_0"):
235 m.next = "add_1"
236 m.d.sync += z.e.eq(a.e)
237 # same-sign (both negative or both positive) add mantissas
238 with m.If(a.s == b.s):
239 m.d.sync += [
240 tot.eq(a.m + b.m),
241 z.s.eq(a.s)
242 ]
243 # a mantissa greater than b, use a
244 with m.Elif(a.m >= b.m):
245 m.d.sync += [
246 tot.eq(a.m - b.m),
247 z.s.eq(a.s)
248 ]
249 # b mantissa greater than a, use b
250 with m.Else():
251 m.d.sync += [
252 tot.eq(b.m - a.m),
253 z.s.eq(b.s)
254 ]
255
256 # ******
257 # Second stage of add: preparation for normalisation.
258 # detects when tot sum is too big (tot[27] is kinda a carry bit)
259
260 with m.State("add_1"):
261 m.next = "normalise_1"
262 # tot[27] gets set when the sum overflows. shift result down
263 with m.If(tot[27]):
264 m.d.sync += [
265 z.m.eq(tot[4:28]),
266 guard.eq(tot[3]),
267 round_bit.eq(tot[2]),
268 sticky.eq(tot[1] | tot[0]),
269 z.e.eq(z.e + 1)
270 ]
271 # tot[27] zero case
272 with m.Else():
273 m.d.sync += [
274 z.m.eq(tot[3:27]),
275 guard.eq(tot[2]),
276 round_bit.eq(tot[1]),
277 sticky.eq(tot[0])
278 ]
279
280 # ******
281 # First stage of normalisation.
282 # NOTE: just like "align", this one keeps going round every clock
283 # until the result's exponent is within acceptable "range"
284 # NOTE: the weirdness of reassigning guard and round is due to
285 # the extra mantissa bits coming from tot[0..2]
286
287 with m.State("normalise_1"):
288 with m.If((z.m[-1] == 0) & (z.e > z.N126)):
289 m.d.sync +=[
290 z.e.eq(z.e - 1), # DECREASE exponent
291 z.m.eq(z.m << 1), # shift mantissa UP
292 z.m[0].eq(guard), # steal guard bit (was tot[2])
293 guard.eq(round_bit), # steal round_bit (was tot[1])
294 ]
295 with m.Else():
296 m.next = "normalise_2"
297
298 # ******
299 # Second stage of normalisation.
300 # NOTE: just like "align", this one keeps going round every clock
301 # until the result's exponent is within acceptable "range"
302 # NOTE: the weirdness of reassigning guard and round is due to
303 # the extra mantissa bits coming from tot[0..2]
304
305 with m.State("normalise_2"):
306 with m.If(z.e < z.N126):
307 m.d.sync +=[
308 z.e.eq(z.e + 1), # INCREASE exponent
309 z.m.eq(z.m >> 1), # shift mantissa DOWN
310 guard.eq(z.m[0]),
311 round_bit.eq(guard),
312 sticky.eq(sticky | round_bit)
313 ]
314 with m.Else():
315 m.next = "round"
316
317 # ******
318 # rounding stage
319
320 with m.State("round"):
321 m.next = "corrections"
322 with m.If(guard & (round_bit | sticky | z.m[0])):
323 m.d.sync += z.m.eq(z.m + 1) # mantissa rounds up
324 with m.If(z.m == z.m1s): # all 1s
325 m.d.sync += z.e.eq(z.e + 1) # exponent rounds up
326
327 # ******
328 # correction stage
329
330 with m.State("corrections"):
331 m.next = "pack"
332 # denormalised, correct exponent to zero
333 with m.If(z.is_denormalised()):
334 m.d.sync += z.m.eq(-127)
335 # FIX SIGN BUG: -a + a = +0.
336 with m.If((z.e == z.N126) & (z.m[0:] == 0)):
337 m.d.sync += z.s.eq(0)
338
339 # ******
340 # pack stage
341
342 with m.State("pack"):
343 m.next = "put_z"
344 # if overflow occurs, return inf
345 with m.If(z.is_overflowed()):
346 m.d.sync += z.inf(0)
347 with m.Else():
348 m.d.sync += z.create(z.s, z.e, z.m)
349
350 # ******
351 # put_z stage
352
353 with m.State("put_z"):
354 m.d.sync += [
355 self.out_z_stb.eq(1),
356 self.out_z.eq(z.v)
357 ]
358 with m.If(self.out_z_stb & self.out_z_ack):
359 m.d.sync += self.out_z_stb.eq(0)
360 m.next = "get_a"
361
362 return m
363
364
365 if __name__ == "__main__":
366 alu = FPADD(width=32)
367 main(alu, ports=[
368 alu.in_a, alu.in_a_stb, alu.in_a_ack,
369 alu.in_b, alu.in_b_stb, alu.in_b_ack,
370 alu.out_z, alu.out_z_stb, alu.out_z_ack,
371 ])
372
373
374 # works... but don't use, just do "python fname.py convert -t v"
375 #print (verilog.convert(alu, ports=[
376 # alu.in_a, alu.in_a_stb, alu.in_a_ack,
377 # alu.in_b, alu.in_b_stb, alu.in_b_ack,
378 # alu.out_z, alu.out_z_stb, alu.out_z_ack,
379 # ]))