move align down-shift to separate 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
6 from nmigen.cli import main
7
8
9 class FPNum:
10 def __init__(self, width, m_width=None):
11 self.width = width
12 self.mw = 23 # TODO
13 if m_width is None:
14 m_width = width + 3 # extra accuracy bits
15 self.v = Signal(width) # Latched copy of value
16 self.m = Signal(m_width) # Mantissa
17 self.e = Signal((10, True)) # Exponent: 10 bits, signed
18 self.s = Signal() # Sign bit
19
20 def decode(self):
21 v = self.v
22 return [self.m.eq(Cat(0, 0, 0, v[0:23])), # mantissa
23 self.e.eq(Cat(v[23:31]) - 127), # exponent (take off bias)
24 self.s.eq(Cat(v[31])), # sign
25 ]
26
27 def create(self, s, e, m):
28 return [
29 self.v[31].eq(s), # sign
30 self.v[23:31].eq(e + 127), # exp
31 self.v[0:23].eq(m) # mantissa
32 ]
33
34 def shift_down(self):
35 return self.create(self.s,
36 self.e + 1,
37 Cat(self.m[0] | self.m[1], self.m[1:self.mw-1], 0))
38
39 def nan(self, s):
40 return self.create(s, 0xff, 1<<22)
41
42 def inf(self, s):
43 return self.create(s, 0xff, 0)
44
45 def is_nan(self):
46 return (self.e == 128) & (self.m != 0)
47
48 def is_inf(self):
49 return (self.e == 128) & (self.m == 0)
50
51 def is_zero(self):
52 return (self.e == -127) & (self.m == 0)
53
54
55 class FPADD:
56 def __init__(self, width):
57 self.width = width
58
59 self.in_a = Signal(width)
60 self.in_a_stb = Signal()
61 self.in_a_ack = Signal()
62
63 self.in_b = Signal(width)
64 self.in_b_stb = Signal()
65 self.in_b_ack = Signal()
66
67 self.out_z = Signal(width)
68 self.out_z_stb = Signal()
69 self.out_z_ack = Signal()
70
71 def get_fragment(self, platform):
72 m = Module()
73
74 # Latches
75 a = FPNum(self.width)
76 b = FPNum(self.width)
77 z = FPNum(self.width, 24)
78
79 # Sign
80 a_s = Signal()
81 b_s = Signal()
82 z_s = Signal()
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 return m
292
293 """
294 always @(posedge clk)
295 begin
296
297 case(state)
298
299 get_a:
300 begin
301 s_in_a_ack <= 1;
302 if (s_in_a_ack && in_a_stb) begin
303 a <= in_a;
304 s_in_a_ack <= 0;
305 state <= get_b;
306 end
307 end
308
309 get_b:
310 begin
311 s_in_b_ack <= 1;
312 if (s_in_b_ack && in_b_stb) begin
313 b <= in_b;
314 s_in_b_ack <= 0;
315 state <= unpack;
316 end
317 end
318
319 unpack:
320 begin
321 a_m <= {a[22 : 0], 3'd0};
322 b_m <= {b[22 : 0], 3'd0};
323 a_e <= a[30 : 23] - 127;
324 b_e <= b[30 : 23] - 127;
325 a_s <= a[31];
326 b_s <= b[31];
327 state <= special_cases;
328 end
329
330 special_cases:
331 begin
332 //if a is NaN or b is NaN return NaN
333 if ((a_e == 128 && a_m != 0) || (b_e == 128 && b_m != 0)) begin
334 z[31] <= 1;
335 z[30:23] <= 255;
336 z[22] <= 1;
337 z[21:0] <= 0;
338 state <= put_z;
339 //if a is inf return inf
340 end else if (a_e == 128) begin
341 z[31] <= a_s;
342 z[30:23] <= 255;
343 z[22:0] <= 0;
344 //if a is inf and signs don't match return nan
345 if ((b_e == 128) && (a_s != b_s)) begin
346 z[31] <= b_s;
347 z[30:23] <= 255;
348 z[22] <= 1;
349 z[21:0] <= 0;
350 end
351 state <= put_z;
352 //if b is inf return inf
353 end else if (b_e == 128) begin
354 z[31] <= b_s;
355 z[30:23] <= 255;
356 z[22:0] <= 0;
357 state <= put_z;
358 //if a is zero return b
359 end else if ((($signed(a_e) == -127) && (a_m == 0)) && (($signed(b_e) == -127) && (b_m == 0))) begin
360 z[31] <= a_s & b_s;
361 z[30:23] <= b_e[7:0] + 127;
362 z[22:0] <= b_m[26:3];
363 state <= put_z;
364 //if a is zero return b
365 end else if (($signed(a_e) == -127) && (a_m == 0)) begin
366 z[31] <= b_s;
367 z[30:23] <= b_e[7:0] + 127;
368 z[22:0] <= b_m[26:3];
369 state <= put_z;
370 //if b is zero return a
371 end else if (($signed(b_e) == -127) && (b_m == 0)) begin
372 z[31] <= a_s;
373 z[30:23] <= a_e[7:0] + 127;
374 z[22:0] <= a_m[26:3];
375 state <= put_z;
376 end else begin
377 //Denormalised Number
378 if ($signed(a_e) == -127) begin
379 a_e <= -126;
380 end else begin
381 a_m[26] <= 1;
382 end
383 //Denormalised Number
384 if ($signed(b_e) == -127) begin
385 b_e <= -126;
386 end else begin
387 b_m[26] <= 1;
388 end
389 state <= align;
390 end
391 end
392
393 align:
394 begin
395 if ($signed(a_e) > $signed(b_e)) begin
396 b_e <= b_e + 1;
397 b_m <= b_m >> 1;
398 b_m[0] <= b_m[0] | b_m[1];
399 end else if ($signed(a_e) < $signed(b_e)) begin
400 a_e <= a_e + 1;
401 a_m <= a_m >> 1;
402 a_m[0] <= a_m[0] | a_m[1];
403 end else begin
404 state <= add_0;
405 end
406 end
407
408 add_0:
409 begin
410 z_e <= a_e;
411 if (a_s == b_s) begin
412 tot <= a_m + b_m;
413 z_s <= a_s;
414 end else begin
415 if (a_m >= b_m) begin
416 tot <= a_m - b_m;
417 z_s <= a_s;
418 end else begin
419 tot <= b_m - a_m;
420 z_s <= b_s;
421 end
422 end
423 state <= add_1;
424 end
425
426 add_1:
427 begin
428 if (tot[27]) begin
429 z_m <= tot[27:4];
430 guard <= tot[3];
431 round_bit <= tot[2];
432 sticky <= tot[1] | tot[0];
433 z_e <= z_e + 1;
434 end else begin
435 z_m <= tot[26:3];
436 guard <= tot[2];
437 round_bit <= tot[1];
438 sticky <= tot[0];
439 end
440 state <= normalise_1;
441 end
442
443 normalise_1:
444 begin
445 if (z_m[23] == 0 && $signed(z_e) > -126) begin
446 z_e <= z_e - 1;
447 z_m <= z_m << 1;
448 z_m[0] <= guard;
449 guard <= round_bit;
450 round_bit <= 0;
451 end else begin
452 state <= normalise_2;
453 end
454 end
455
456 normalise_2:
457 begin
458 if ($signed(z_e) < -126) begin
459 z_e <= z_e + 1;
460 z_m <= z_m >> 1;
461 guard <= z_m[0];
462 round_bit <= guard;
463 sticky <= sticky | round_bit;
464 end else begin
465 state <= round;
466 end
467 end
468
469 round:
470 begin
471 if (guard && (round_bit | sticky | z_m[0])) begin
472 z_m <= z_m + 1;
473 if (z_m == 24'hffffff) begin
474 z_e <=z_e + 1;
475 end
476 end
477 state <= pack;
478 end
479
480 pack:
481 begin
482 z[22 : 0] <= z_m[22:0];
483 z[30 : 23] <= z_e[7:0] + 127;
484 z[31] <= z_s;
485 if ($signed(z_e) == -126 && z_m[23] == 0) begin
486 z[30 : 23] <= 0;
487 end
488 if ($signed(z_e) == -126 && z_m[23:0] == 24'h0) begin
489 z[31] <= 1'b0; // FIX SIGN BUG: -a + a = +0.
490 end
491 //if overflow occurs, return inf
492 if ($signed(z_e) > 127) begin
493 z[22 : 0] <= 0;
494 z[30 : 23] <= 255;
495 z[31] <= z_s;
496 end
497 state <= put_z;
498 end
499
500 put_z:
501 begin
502 s_out_z_stb <= 1;
503 s_out_z <= z;
504 if (s_out_z_stb && out_z_ack) begin
505 s_out_z_stb <= 0;
506 state <= get_a;
507 end
508 end
509
510 endcase
511
512 if (rst == 1) begin
513 state <= get_a;
514 s_in_a_ack <= 0;
515 s_in_b_ack <= 0;
516 s_out_z_stb <= 0;
517 end
518
519 end
520 assign in_a_ack = s_in_a_ack;
521 assign in_b_ack = s_in_b_ack;
522 assign out_z_stb = s_out_z_stb;
523 assign out_z = s_out_z;
524
525 endmodule
526 """
527
528 if __name__ == "__main__":
529 alu = FPADD(width=32)
530 main(alu, ports=[
531 alu.in_a, alu.in_a_stb, alu.in_a_ack,
532 alu.in_b, alu.in_b_stb, alu.in_b_ack,
533 alu.out_z, alu.out_z_stb, alu.out_z_ack,
534 ])