fix bug in nan/inf, exp-bias needed subtracting
[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
7
8
9 class FPNum:
10 """ Floating-point Number Class, variable-width TODO (currently 32-bit)
11 Contains signals for an incoming copy of the value, decoded into
12 sign / exponent / mantissa.
13 Also contains encoding functions, creation and recognition of
14 zero, NaN and inf (all signed)
15 """
16 def __init__(self, width, m_width=None):
17 self.width = width
18 if m_width is None:
19 m_width = width - 5 # mantissa extra bits (top,guard,round)
20 self.v = Signal(width) # Latched copy of value
21 self.m = Signal(m_width) # Mantissa
22 self.e = Signal((10, True)) # Exponent: 10 bits, signed
23 self.s = Signal() # Sign bit
24
25 def decode(self):
26 v = self.v
27 return [self.m.eq(Cat(0, 0, 0, v[0:23])), # mantissa
28 self.e.eq(Cat(v[23:31]) - 127), # exponent (take off bias)
29 self.s.eq(Cat(v[31])), # sign
30 ]
31
32 def create(self, s, e, m):
33 return [
34 self.v[31].eq(s), # sign
35 self.v[23:31].eq(e + 127), # exp
36 self.v[0:23].eq(m) # mantissa
37 ]
38
39 def shift_down(self):
40 return self.create(self.s,
41 self.e + 1,
42 Cat(self.m[0] | self.m[1], self.m[1:-5], 0))
43
44 def nan(self, s):
45 return self.create(s, 0x80, 1<<22)
46
47 def inf(self, s):
48 return self.create(s, 0x80, 0)
49
50 def is_nan(self):
51 return (self.e == 128) & (self.m != 0)
52
53 def is_inf(self):
54 return (self.e == 128) & (self.m == 0)
55
56 def is_zero(self):
57 return (self.e == -127) & (self.m == 0)
58
59
60 class FPADD:
61 def __init__(self, width):
62 self.width = width
63
64 self.in_a = Signal(width)
65 self.in_a_stb = Signal()
66 self.in_a_ack = Signal()
67
68 self.in_b = Signal(width)
69 self.in_b_stb = Signal()
70 self.in_b_ack = Signal()
71
72 self.out_z = Signal(width)
73 self.out_z_stb = Signal()
74 self.out_z_ack = Signal()
75
76 def get_fragment(self, platform):
77 m = Module()
78
79 # Latches
80 a = FPNum(self.width)
81 b = FPNum(self.width)
82 z = FPNum(self.width, 24)
83
84 guard = Signal()
85 round_bit = Signal()
86 sticky = Signal()
87
88 tot = Signal(28)
89
90 with m.FSM() as fsm:
91
92 # ******
93 # gets operand a
94
95 with m.State("get_a"):
96 with m.If((self.in_a_ack) & (self.in_a_stb)):
97 m.next = "get_b"
98 m.d.sync += [
99 a.v.eq(self.in_a),
100 self.in_a_ack.eq(0)
101 ]
102 with m.Else():
103 m.d.sync += self.in_a_ack.eq(1)
104
105 # ******
106 # gets operand b
107
108 with m.State("get_b"):
109 with m.If((self.in_b_ack) & (self.in_b_stb)):
110 m.next = "get_a"
111 m.d.sync += [
112 b.v.eq(self.in_b),
113 self.in_b_ack.eq(0)
114 ]
115 with m.Else():
116 m.d.sync += self.in_b_ack.eq(1)
117
118 # ******
119 # unpacks operands into sign, mantissa and exponent
120
121 with m.State("unpack"):
122 m.next = "special_cases"
123 m.d.sync += a.decode()
124 m.d.sync += b.decode()
125
126 # ******
127 # special cases: NaNs, infs, zeros, denormalised
128
129 with m.State("special_cases"):
130
131 # if a is NaN or b is NaN return NaN
132 with m.If(a.is_nan() | b.is_nan()):
133 m.next = "put_z"
134 m.d.sync += z.nan(1)
135
136 # if a is inf return inf (or NaN)
137 with m.Elif(a.is_inf()):
138 m.next = "put_z"
139 m.d.sync += z.inf(a.s)
140 # if a is inf and signs don't match return NaN
141 with m.If((b.e == 128) & (a.s != b.s)):
142 m.d.sync += z.nan(b.s)
143
144 # if b is inf return inf
145 with m.Elif(b.is_inf()):
146 m.next = "put_z"
147 m.d.sync += z.inf(b.s)
148
149 # if a is zero and b zero return signed-a/b
150 with m.Elif(a.is_zero() & b.is_zero()):
151 m.next = "put_z"
152 m.d.sync += z.create(a.s & b.s, b.e[0:8], b.m[3:26])
153
154 # if a is zero return b
155 with m.Elif(a.is_zero()):
156 m.next = "put_z"
157 m.d.sync += z.create(b.s, b.e[0:8], b.m[3:26])
158
159 # if b is zero return a
160 with m.Elif(b.is_zero()):
161 m.next = "put_z"
162 m.d.sync += z.create(a.s, a.e[0:8], a.m[3:26])
163
164 # Denormalised Number checks
165 with m.Else():
166 m.next = "align"
167 # denormalise a check
168 with m.If(a.e == -127):
169 m.d.sync += a.e.eq(-126) # limit a exponent
170 with m.Else():
171 m.d.sync += a.m[26].eq(1) # set highest mantissa bit
172 # denormalise b check
173 with m.If(b.e == -127):
174 m.d.sync += b.e.eq(-126) # limit b exponent
175 with m.Else():
176 m.d.sync += b.m[26].eq(1) # set highest mantissa bit
177
178 # ******
179 # align. NOTE: this does *not* do single-cycle multi-shifting,
180 # it *STAYS* in the align state until the exponents match
181
182 with m.State("align"):
183 # exponent of a greater than b: increment b exp, shift b mant
184 with m.If(a.e > b.e):
185 m.d.sync += b.shift_down()
186 # exponent of b greater than a: increment a exp, shift a mant
187 with m.Elif(a.e < b.e):
188 m.d.sync += a.shift_down()
189 # exponents equal: move to next stage.
190 with m.Else():
191 m.next = "add_0"
192
193 # ******
194 # First stage of add. covers same-sign (add) and subtract
195 # special-casing when mantissas are greater or equal, to
196 # give greatest accuracy.
197
198 with m.State("add_0"):
199 m.next = "add_1"
200 m.d.sync += z.e.eq(a.e)
201 # same-sign (both negative or both positive) add mantissas
202 with m.If(a.s == b.s):
203 m.d.sync += [
204 tot.eq(a.m + b.m),
205 z.s.eq(a.s)
206 ]
207 # a mantissa greater than b, use a
208 with m.Elif(a.m >= b.m):
209 m.d.sync += [
210 tot.eq(a.m - b.m),
211 z.s.eq(a.s)
212 ]
213 # b mantissa greater than a, use b
214 with m.Else():
215 m.d.sync += [
216 tot.eq(b.m - a.m),
217 z.s.eq(b.s)
218 ]
219
220 # ******
221 # Second stage of add: preparation for normalisation.
222 # detects when tot sum is too big (tot[27] is kinda a carry bit)
223
224 with m.State("add_1"):
225 m.next = "normalise_1"
226 # tot[27] gets set when the sum overflows. shift result down
227 with m.If(tot[27]):
228 m.d.sync += [
229 z.m.eq(tot[4:28]),
230 guard.eq(tot[3]),
231 round_bit.eq(tot[2]),
232 sticky.eq(tot[1] | tot[0]),
233 z.e.eq(z.e + 1)
234 ]
235 # tot[27] zero case
236 with m.Else():
237 m.d.sync += [
238 z.m.eq(tot[3:27]),
239 guard.eq(tot[2]),
240 round_bit.eq(tot[1]),
241 sticky.eq(tot[0])
242 ]
243
244 # ******
245 # First stage of normalisation.
246 # NOTE: just like "align", this one keeps going round every clock
247 # until the result's exponent is within acceptable "range"
248 # NOTE: the weirdness of reassigning guard and round is due to
249 # the extra mantissa bits coming from tot[0..2]
250
251 with m.State("normalise_1"):
252 with m.If((z.m[23] == 0) & (z.e > -126)):
253 m.d.sync +=[
254 z.e.eq(z.e - 1), # DECREASE exponent
255 z.m.eq(z.m << 1), # shift mantissa UP
256 z.m[0].eq(guard), # steal guard bit (was tot[2])
257 guard.eq(round_bit), # steal round_bit (was tot[1])
258 ]
259 with m.Else():
260 m.next = "normalize_2"
261
262 # ******
263 # Second stage of normalisation.
264 # NOTE: just like "align", this one keeps going round every clock
265 # until the result's exponent is within acceptable "range"
266 # NOTE: the weirdness of reassigning guard and round is due to
267 # the extra mantissa bits coming from tot[0..2]
268
269 with m.State("normalise_2"):
270 with m.If(z.e < -126):
271 m.d.sync +=[
272 z.e.eq(z.e + 1), # INCREASE exponent
273 z.m.eq(z.m >> 1), # shift mantissa DOWN
274 guard.eq(z.m[0]),
275 round_bit.eq(guard),
276 sticky.eq(sticky | round_bit)
277 ]
278 with m.Else():
279 m.next = "round"
280
281 # ******
282 # rounding stage
283
284 with m.State("round"):
285 m.next = "pack"
286 with m.If(guard & (round_bit | sticky | z.m[0])):
287 m.d.sync += z.m.eq(z.m + 1) # mantissa rounds up
288 with m.If(z.m == 0xffffff): # all 1s
289 m.d.sync += z.e.eq(z.e + 1) # exponent rounds up
290
291 # ******
292 # pack stage
293
294 """ TODO: see if z.create can be used *later*. convert
295 verilog first (and commit), *second* phase, convert nmigen
296 code to use FPNum.create() (as a separate commit)
297
298 pack:
299 begin
300 z[22 : 0] <= z_m[22:0];
301 z[30 : 23] <= z_e[7:0] + 127;
302 z[31] <= z_s;
303 if ($signed(z_e) == -126 && z_m[23] == 0) begin
304 z[30 : 23] <= 0;
305 end
306 if ($signed(z_e) == -126 && z_m[23:0] == 24'h0) begin
307 z[31] <= 1'b0; // FIX SIGN BUG: -a + a = +0.
308 end
309 //if overflow occurs, return inf
310 if ($signed(z_e) > 127) begin
311 z[22 : 0] <= 0;
312 z[30 : 23] <= 255;
313 z[31] <= z_s;
314 end
315 state <= put_z;
316 end
317 """
318
319 # ******
320 # put_z stage
321
322 """
323 put_z:
324 begin
325 s_out_z_stb <= 1;
326 s_out_z <= z;
327 if (s_out_z_stb && out_z_ack) begin
328 s_out_z_stb <= 0;
329 state <= get_a;
330 end
331 end
332 """
333
334 return m
335
336 """
337 always @(posedge clk)
338 begin
339
340 case(state)
341
342 get_a:
343 begin
344 s_in_a_ack <= 1;
345 if (s_in_a_ack && in_a_stb) begin
346 a <= in_a;
347 s_in_a_ack <= 0;
348 state <= get_b;
349 end
350 end
351
352 get_b:
353 begin
354 s_in_b_ack <= 1;
355 if (s_in_b_ack && in_b_stb) begin
356 b <= in_b;
357 s_in_b_ack <= 0;
358 state <= unpack;
359 end
360 end
361
362 unpack:
363 begin
364 a_m <= {a[22 : 0], 3'd0};
365 b_m <= {b[22 : 0], 3'd0};
366 a_e <= a[30 : 23] - 127;
367 b_e <= b[30 : 23] - 127;
368 a_s <= a[31];
369 b_s <= b[31];
370 state <= special_cases;
371 end
372
373 special_cases:
374 begin
375 //if a is NaN or b is NaN return NaN
376 if ((a_e == 128 && a_m != 0) || (b_e == 128 && b_m != 0)) begin
377 z[31] <= 1;
378 z[30:23] <= 255;
379 z[22] <= 1;
380 z[21:0] <= 0;
381 state <= put_z;
382 //if a is inf return inf
383 end else if (a_e == 128) begin
384 z[31] <= a_s;
385 z[30:23] <= 255;
386 z[22:0] <= 0;
387 //if a is inf and signs don't match return nan
388 if ((b_e == 128) && (a_s != b_s)) begin
389 z[31] <= b_s;
390 z[30:23] <= 255;
391 z[22] <= 1;
392 z[21:0] <= 0;
393 end
394 state <= put_z;
395 //if b is inf return inf
396 end else if (b_e == 128) begin
397 z[31] <= b_s;
398 z[30:23] <= 255;
399 z[22:0] <= 0;
400 state <= put_z;
401 //if a is zero return b
402 end else if ((($signed(a_e) == -127) && (a_m == 0)) && (($signed(b_e) == -127) && (b_m == 0))) begin
403 z[31] <= a_s & b_s;
404 z[30:23] <= b_e[7:0] + 127;
405 z[22:0] <= b_m[26:3];
406 state <= put_z;
407 //if a is zero return b
408 end else if (($signed(a_e) == -127) && (a_m == 0)) begin
409 z[31] <= b_s;
410 z[30:23] <= b_e[7:0] + 127;
411 z[22:0] <= b_m[26:3];
412 state <= put_z;
413 //if b is zero return a
414 end else if (($signed(b_e) == -127) && (b_m == 0)) begin
415 z[31] <= a_s;
416 z[30:23] <= a_e[7:0] + 127;
417 z[22:0] <= a_m[26:3];
418 state <= put_z;
419 end else begin
420 //Denormalised Number
421 if ($signed(a_e) == -127) begin
422 a_e <= -126;
423 end else begin
424 a_m[26] <= 1;
425 end
426 //Denormalised Number
427 if ($signed(b_e) == -127) begin
428 b_e <= -126;
429 end else begin
430 b_m[26] <= 1;
431 end
432 state <= align;
433 end
434 end
435
436 align:
437 begin
438 if ($signed(a_e) > $signed(b_e)) begin
439 b_e <= b_e + 1;
440 b_m <= b_m >> 1;
441 b_m[0] <= b_m[0] | b_m[1];
442 end else if ($signed(a_e) < $signed(b_e)) begin
443 a_e <= a_e + 1;
444 a_m <= a_m >> 1;
445 a_m[0] <= a_m[0] | a_m[1];
446 end else begin
447 state <= add_0;
448 end
449 end
450
451 add_0:
452 begin
453 z_e <= a_e;
454 if (a_s == b_s) begin
455 tot <= a_m + b_m;
456 z_s <= a_s;
457 end else begin
458 if (a_m >= b_m) begin
459 tot <= a_m - b_m;
460 z_s <= a_s;
461 end else begin
462 tot <= b_m - a_m;
463 z_s <= b_s;
464 end
465 end
466 state <= add_1;
467 end
468
469 add_1:
470 begin
471 if (tot[27]) begin
472 z_m <= tot[27:4];
473 guard <= tot[3];
474 round_bit <= tot[2];
475 sticky <= tot[1] | tot[0];
476 z_e <= z_e + 1;
477 end else begin
478 z_m <= tot[26:3];
479 guard <= tot[2];
480 round_bit <= tot[1];
481 sticky <= tot[0];
482 end
483 state <= normalise_1;
484 end
485
486 normalise_1:
487 begin
488 if (z_m[23] == 0 && $signed(z_e) > -126) begin
489 z_e <= z_e - 1;
490 z_m <= z_m << 1;
491 z_m[0] <= guard;
492 guard <= round_bit;
493 round_bit <= 0;
494 end else begin
495 state <= normalise_2;
496 end
497 end
498
499 normalise_2:
500 begin
501 if ($signed(z_e) < -126) begin
502 z_e <= z_e + 1;
503 z_m <= z_m >> 1;
504 guard <= z_m[0];
505 round_bit <= guard;
506 sticky <= sticky | round_bit;
507 end else begin
508 state <= round;
509 end
510 end
511
512 round:
513 begin
514 if (guard && (round_bit | sticky | z_m[0])) begin
515 z_m <= z_m + 1;
516 if (z_m == 24'hffffff) begin
517 z_e <=z_e + 1;
518 end
519 end
520 state <= pack;
521 end
522
523 pack:
524 begin
525 z[22 : 0] <= z_m[22:0];
526 z[30 : 23] <= z_e[7:0] + 127;
527 z[31] <= z_s;
528 if ($signed(z_e) == -126 && z_m[23] == 0) begin
529 z[30 : 23] <= 0;
530 end
531 if ($signed(z_e) == -126 && z_m[23:0] == 24'h0) begin
532 z[31] <= 1'b0; // FIX SIGN BUG: -a + a = +0.
533 end
534 //if overflow occurs, return inf
535 if ($signed(z_e) > 127) begin
536 z[22 : 0] <= 0;
537 z[30 : 23] <= 255;
538 z[31] <= z_s;
539 end
540 state <= put_z;
541 end
542
543 put_z:
544 begin
545 s_out_z_stb <= 1;
546 s_out_z <= z;
547 if (s_out_z_stb && out_z_ack) begin
548 s_out_z_stb <= 0;
549 state <= get_a;
550 end
551 end
552
553 endcase
554
555 if (rst == 1) begin
556 state <= get_a;
557 s_in_a_ack <= 0;
558 s_in_b_ack <= 0;
559 s_out_z_stb <= 0;
560 end
561
562 end
563 assign in_a_ack = s_in_a_ack;
564 assign in_b_ack = s_in_b_ack;
565 assign out_z_stb = s_out_z_stb;
566 assign out_z = s_out_z;
567
568 endmodule
569 """
570
571 if __name__ == "__main__":
572 alu = FPADD(width=32)
573 main(alu, ports=[
574 alu.in_a, alu.in_a_stb, alu.in_a_ack,
575 alu.in_b, alu.in_b_stb, alu.in_b_ack,
576 alu.out_z, alu.out_z_stb, alu.out_z_ack,
577 ])