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