start some use of namedtuples in core.py
[soc.git] / src / soc / simple / core.py
1 """simple core
2
3 not in any way intended for production use. connects up FunctionUnits to
4 Register Files in a brain-dead fashion that only permits one and only one
5 Function Unit to be operational.
6
7 the principle here is to take the Function Units, analyse their regspecs,
8 and turn their requirements for access to register file read/write ports
9 into groupings by Register File and Register File Port name.
10
11 under each grouping - by regfile/port - a list of Function Units that
12 need to connect to that port is created. as these are a contended
13 resource a "Broadcast Bus" per read/write port is then also created,
14 with access to it managed by a PriorityPicker.
15
16 the brain-dead part of this module is that even though there is no
17 conflict of access, regfile read/write hazards are *not* analysed,
18 and consequently it is safer to wait for the Function Unit to complete
19 before allowing a new instruction to proceed.
20 """
21
22 from nmigen import (Elaboratable, Module, Signal, ResetSignal, Cat, Mux,
23 Const)
24 from nmigen.cli import rtlil
25
26 from openpower.decoder.power_decoder2 import PowerDecodeSubset
27 from openpower.decoder.power_regspec_map import regspec_decode_read
28 from openpower.decoder.power_regspec_map import regspec_decode_write
29 from openpower.sv.svp64 import SVP64Rec
30
31 from nmutil.picker import PriorityPicker
32 from nmutil.util import treereduce
33 from nmutil.singlepipe import ControlBase
34
35 from soc.fu.compunits.compunits import AllFunctionUnits, LDSTFunctionUnit
36 from soc.regfile.regfiles import RegFiles
37 from openpower.decoder.power_decoder2 import get_rdflags
38 from soc.experiment.l0_cache import TstL0CacheBuffer # test only
39 from soc.config.test.test_loadstore import TestMemPspec
40 from openpower.decoder.power_enums import MicrOp, Function
41 from soc.simple.core_data import CoreInput, CoreOutput
42
43 from collections import defaultdict, namedtuple
44 import operator
45
46 from nmutil.util import rising_edge
47
48 FUSpec = namedtuple("FUSpec", ["funame", "fu", "idx"])
49 ByRegSpec = namedtuple("ByRegSpec", ["rdport", "wrport", "read",
50 "write", "wid", "specs"])
51
52 # helper function for reducing a list of signals down to a parallel
53 # ORed single signal.
54 def ortreereduce(tree, attr="o_data"):
55 return treereduce(tree, operator.or_, lambda x: getattr(x, attr))
56
57
58 def ortreereduce_sig(tree):
59 return treereduce(tree, operator.or_, lambda x: x)
60
61
62 # helper function to place full regs declarations first
63 def sort_fuspecs(fuspecs):
64 res = []
65 for (regname, fspec) in fuspecs.items():
66 if regname.startswith("full"):
67 res.append((regname, fspec))
68 for (regname, fspec) in fuspecs.items():
69 if not regname.startswith("full"):
70 res.append((regname, fspec))
71 return res # enumerate(res)
72
73
74 # derive from ControlBase rather than have a separate Stage instance,
75 # this is simpler to do
76 class NonProductionCore(ControlBase):
77 def __init__(self, pspec):
78 self.pspec = pspec
79
80 # test is SVP64 is to be enabled
81 self.svp64_en = hasattr(pspec, "svp64") and (pspec.svp64 == True)
82
83 # test to see if regfile ports should be reduced
84 self.regreduce_en = (hasattr(pspec, "regreduce") and
85 (pspec.regreduce == True))
86
87 # test to see if overlapping of instructions is allowed
88 # (not normally enabled for TestIssuer FSM but useful for checking
89 # the bitvector hazard detection, before doing In-Order)
90 self.allow_overlap = (hasattr(pspec, "allow_overlap") and
91 (pspec.allow_overlap == True))
92
93 # test core type
94 self.make_hazard_vecs = True
95 self.core_type = "fsm"
96 if hasattr(pspec, "core_type"):
97 self.core_type = pspec.core_type
98
99 super().__init__(stage=self)
100
101 # single LD/ST funnel for memory access
102 self.l0 = l0 = TstL0CacheBuffer(pspec, n_units=1)
103 pi = l0.l0.dports[0]
104
105 # function units (only one each)
106 # only include mmu if enabled in pspec
107 self.fus = AllFunctionUnits(pspec, pilist=[pi])
108
109 # link LoadStore1 into MMU
110 mmu = self.fus.get_fu('mmu0')
111 print ("core pspec", pspec.ldst_ifacetype)
112 print ("core mmu", mmu)
113 if mmu is not None:
114 print ("core lsmem.lsi", l0.cmpi.lsmem.lsi)
115 mmu.alu.set_ldst_interface(l0.cmpi.lsmem.lsi)
116
117 # register files (yes plural)
118 self.regs = RegFiles(pspec, make_hazard_vecs=self.make_hazard_vecs)
119
120 # set up input and output: unusual requirement to set data directly
121 # (due to the way that the core is set up in a different domain,
122 # see TestIssuer.setup_peripherals
123 self.p.i_data, self.n.o_data = self.new_specs(None)
124 self.i, self.o = self.p.i_data, self.n.o_data
125
126 # actual internal input data used (captured)
127 self.ireg = self.ispec()
128
129 # create per-FU instruction decoders (subsetted). these "satellite"
130 # decoders reduce wire fan-out from the one (main) PowerDecoder2
131 # (used directly by the trap unit) to the *twelve* (or more)
132 # Function Units. we can either have 32 wires (the instruction)
133 # to each, or we can have well over a 200 wire fan-out (to 12
134 # ALUs). it's an easy choice to make.
135 self.decoders = {}
136 self.des = {}
137
138 for funame, fu in self.fus.fus.items():
139 f_name = fu.fnunit.name
140 fnunit = fu.fnunit.value
141 opkls = fu.opsubsetkls
142 if f_name == 'TRAP':
143 # TRAP decoder is the *main* decoder
144 self.trapunit = funame
145 continue
146 self.decoders[funame] = PowerDecodeSubset(None, opkls, f_name,
147 final=True,
148 state=self.ireg.state,
149 svp64_en=self.svp64_en,
150 regreduce_en=self.regreduce_en)
151 self.des[funame] = self.decoders[funame].do
152
153 # share the SPR decoder with the MMU if it exists
154 if "mmu0" in self.decoders:
155 self.decoders["mmu0"].mmu0_spr_dec = self.decoders["spr0"]
156
157 # next 3 functions are Stage API Compliance
158 def setup(self, m, i):
159 pass
160
161 def ispec(self):
162 return CoreInput(self.pspec, self.svp64_en, self.regreduce_en)
163
164 def ospec(self):
165 return CoreOutput()
166
167 # elaborate function to create HDL
168 def elaborate(self, platform):
169 m = super().elaborate(platform)
170
171 # for testing purposes, to cut down on build time in coriolis2
172 if hasattr(self.pspec, "nocore") and self.pspec.nocore == True:
173 x = Signal() # dummy signal
174 m.d.sync += x.eq(~x)
175 return m
176 comb = m.d.comb
177
178 m.submodules.fus = self.fus
179 m.submodules.l0 = l0 = self.l0
180 self.regs.elaborate_into(m, platform)
181 regs = self.regs
182 fus = self.fus.fus
183
184 # connect decoders
185 self.connect_satellite_decoders(m)
186
187 # ssh, cheat: trap uses the main decoder because of the rewriting
188 self.des[self.trapunit] = self.ireg.e.do
189
190 # connect up Function Units, then read/write ports, and hazard conflict
191 self.issue_conflict = Signal()
192 fu_bitdict, fu_selected = self.connect_instruction(m)
193 raw_hazard = self.connect_rdports(m, fu_bitdict, fu_selected)
194 self.connect_wrports(m, fu_bitdict, fu_selected)
195 if self.allow_overlap:
196 comb += self.issue_conflict.eq(raw_hazard)
197
198 # note if an exception happened. in a pipelined or OoO design
199 # this needs to be accompanied by "shadowing" (or stalling)
200 el = []
201 for exc in self.fus.excs.values():
202 el.append(exc.happened)
203 if len(el) > 0: # at least one exception
204 comb += self.o.exc_happened.eq(Cat(*el).bool())
205
206 return m
207
208 def connect_satellite_decoders(self, m):
209 comb = m.d.comb
210 for k, v in self.decoders.items():
211 # connect each satellite decoder and give it the instruction.
212 # as subset decoders this massively reduces wire fanout given
213 # the large number of ALUs
214 setattr(m.submodules, "dec_%s" % v.fn_name, v)
215 comb += v.dec.raw_opcode_in.eq(self.ireg.raw_insn_i)
216 comb += v.dec.bigendian.eq(self.ireg.bigendian_i)
217 # sigh due to SVP64 RA_OR_ZERO detection connect these too
218 comb += v.sv_a_nz.eq(self.ireg.sv_a_nz)
219 if self.svp64_en:
220 comb += v.pred_sm.eq(self.ireg.sv_pred_sm)
221 comb += v.pred_dm.eq(self.ireg.sv_pred_dm)
222 if k != self.trapunit:
223 comb += v.sv_rm.eq(self.ireg.sv_rm) # pass through SVP64 RM
224 comb += v.is_svp64_mode.eq(self.ireg.is_svp64_mode)
225 # only the LDST PowerDecodeSubset *actually* needs to
226 # know to use the alternative decoder. this is all
227 # a terrible hack
228 if k.lower().startswith("ldst"):
229 comb += v.use_svp64_ldst_dec.eq(
230 self.ireg.use_svp64_ldst_dec)
231
232 def connect_instruction(self, m):
233 """connect_instruction
234
235 uses decoded (from PowerOp) function unit information from CSV files
236 to ascertain which Function Unit should deal with the current
237 instruction.
238
239 some (such as OP_ATTN, OP_NOP) are dealt with here, including
240 ignoring it and halting the processor. OP_NOP is a bit annoying
241 because the issuer expects busy flag still to be raised then lowered.
242 (this requires a fake counter to be set).
243 """
244 comb, sync = m.d.comb, m.d.sync
245 fus = self.fus.fus
246
247 # indicate if core is busy
248 busy_o = self.o.busy_o
249 any_busy_o = self.o.any_busy_o
250
251 # connect up temporary copy of incoming instruction. the FSM will
252 # either blat the incoming instruction (if valid) into self.ireg
253 # or if the instruction could not be delivered, keep dropping the
254 # latched copy into ireg
255 ilatch = self.ispec()
256 self.instr_active = Signal()
257
258 # enable/busy-signals for each FU, get one bit for each FU (by name)
259 fu_enable = Signal(len(fus), reset_less=True)
260 fu_busy = Signal(len(fus), reset_less=True)
261 fu_bitdict = {}
262 fu_selected = {}
263 for i, funame in enumerate(fus.keys()):
264 fu_bitdict[funame] = fu_enable[i]
265 fu_selected[funame] = fu_busy[i]
266
267 # identify function units and create a list by fnunit so that
268 # PriorityPickers can be created for selecting one of them that
269 # isn't busy at the time the incoming instruction needs passing on
270 by_fnunit = defaultdict(list)
271 for fname, member in Function.__members__.items():
272 for funame, fu in fus.items():
273 fnunit = fu.fnunit.value
274 if member.value & fnunit: # this FU handles this type of op
275 by_fnunit[fname].append((funame, fu)) # add by Function
276
277 # ok now just print out the list of FUs by Function, because we can
278 for fname, fu_list in by_fnunit.items():
279 print ("FUs by type", fname, fu_list)
280
281 # now create a PriorityPicker per FU-type such that only one
282 # non-busy FU will be picked
283 issue_pps = {}
284 fu_found = Signal() # take a note if no Function Unit was available
285 for fname, fu_list in by_fnunit.items():
286 i_pp = PriorityPicker(len(fu_list))
287 m.submodules['i_pp_%s' % fname] = i_pp
288 i_l = []
289 for i, (funame, fu) in enumerate(fu_list):
290 # match the decoded instruction (e.do.fn_unit) against the
291 # "capability" of this FU, gate that by whether that FU is
292 # busy, and drop that into the PriorityPicker.
293 # this will give us an output of the first available *non-busy*
294 # Function Unit (Reservation Statio) capable of handling this
295 # instruction.
296 fnunit = fu.fnunit.value
297 en_req = Signal(name="issue_en_%s" % funame, reset_less=True)
298 fnmatch = (self.ireg.e.do.fn_unit & fnunit).bool()
299 comb += en_req.eq(fnmatch & ~fu.busy_o &
300 self.instr_active)
301 i_l.append(en_req) # store in list for doing the Cat-trick
302 # picker output, gated by enable: store in fu_bitdict
303 po = Signal(name="o_issue_pick_"+funame) # picker output
304 comb += po.eq(i_pp.o[i] & i_pp.en_o)
305 comb += fu_bitdict[funame].eq(po)
306 comb += fu_selected[funame].eq(fu.busy_o | po)
307 # if we don't do this, then when there are no FUs available,
308 # the "p.o_ready" signal will go back "ok we accepted this
309 # instruction" which of course isn't true.
310 with m.If(i_pp.en_o):
311 comb += fu_found.eq(1)
312 # for each input, Cat them together and drop them into the picker
313 comb += i_pp.i.eq(Cat(*i_l))
314
315 # rdmask, which is for registers needs to come from the *main* decoder
316 for funame, fu in fus.items():
317 rdmask = get_rdflags(self.ireg.e, fu)
318 comb += fu.rdmaskn.eq(~rdmask)
319
320 # sigh - need a NOP counter
321 counter = Signal(2)
322 with m.If(counter != 0):
323 sync += counter.eq(counter - 1)
324 comb += busy_o.eq(1)
325
326 # default to reading from incoming instruction: may be overridden
327 # by copy from latch when "waiting"
328 comb += self.ireg.eq(self.i)
329 # always say "ready" except if overridden
330 comb += self.p.o_ready.eq(1)
331
332 with m.FSM():
333 with m.State("READY"):
334 with m.If(self.p.i_valid): # run only when valid
335 with m.Switch(self.ireg.e.do.insn_type):
336 # check for ATTN: halt if true
337 with m.Case(MicrOp.OP_ATTN):
338 m.d.sync += self.o.core_terminate_o.eq(1)
339
340 # fake NOP - this isn't really used (Issuer detects NOP)
341 with m.Case(MicrOp.OP_NOP):
342 sync += counter.eq(2)
343 comb += busy_o.eq(1)
344
345 with m.Default():
346 comb += self.instr_active.eq(1)
347 comb += self.p.o_ready.eq(0)
348 # connect instructions. only one enabled at a time
349 for funame, fu in fus.items():
350 do = self.des[funame]
351 enable = fu_bitdict[funame]
352
353 # run this FunctionUnit if enabled route op,
354 # issue, busy, read flags and mask to FU
355 with m.If(enable):
356 # operand comes from the *local* decoder
357 comb += fu.oper_i.eq_from(do)
358 comb += fu.issue_i.eq(1) # issue when valid
359 # instruction ok, indicate ready
360 comb += self.p.o_ready.eq(1)
361
362 if self.allow_overlap:
363 with m.If(~fu_found):
364 # latch copy of instruction
365 sync += ilatch.eq(self.i)
366 comb += self.p.o_ready.eq(1) # accept
367 comb += busy_o.eq(1)
368 m.next = "WAITING"
369
370 with m.State("WAITING"):
371 comb += self.instr_active.eq(1)
372 comb += self.p.o_ready.eq(0)
373 comb += busy_o.eq(1)
374 # using copy of instruction, keep waiting until an FU is free
375 comb += self.ireg.eq(ilatch)
376 with m.If(fu_found): # wait for conflict to clear
377 # connect instructions. only one enabled at a time
378 for funame, fu in fus.items():
379 do = self.des[funame]
380 enable = fu_bitdict[funame]
381
382 # run this FunctionUnit if enabled route op,
383 # issue, busy, read flags and mask to FU
384 with m.If(enable):
385 # operand comes from the *local* decoder
386 comb += fu.oper_i.eq_from(do)
387 comb += fu.issue_i.eq(1) # issue when valid
388 comb += self.p.o_ready.eq(1)
389 comb += busy_o.eq(0)
390 m.next = "READY"
391
392 print ("core: overlap allowed", self.allow_overlap)
393 busys = map(lambda fu: fu.busy_o, fus.values())
394 comb += any_busy_o.eq(Cat(*busys).bool())
395 if not self.allow_overlap:
396 # for simple non-overlap, if any instruction is busy, set
397 # busy output for core.
398 comb += busy_o.eq(any_busy_o)
399 else:
400 # sigh deal with a fun situation that needs to be investigated
401 # and resolved
402 with m.If(self.issue_conflict):
403 comb += busy_o.eq(1)
404
405 # return both the function unit "enable" dict as well as the "busy".
406 # the "busy-or-issued" can be passed in to the Read/Write port
407 # connecters to give them permission to request access to regfiles
408 return fu_bitdict, fu_selected
409
410 def connect_rdport(self, m, fu_bitdict, fu_selected,
411 rdpickers, regfile, regname, fspec):
412 comb, sync = m.d.comb, m.d.sync
413 fus = self.fus.fus
414 regs = self.regs
415
416 rpidx = regname
417
418 # select the required read port. these are pre-defined sizes
419 rfile = regs.rf[regfile.lower()]
420 rport = rfile.r_ports[rpidx]
421 print("read regfile", rpidx, regfile, regs.rf.keys(),
422 rfile, rfile.unary)
423
424 # for checking if the read port has an outstanding write
425 if self.make_hazard_vecs:
426 wv = regs.wv[regfile.lower()]
427 wvchk = wv.r_ports["issue"] # write-vec bit-level hazard check
428
429 # if a hazard is detected on this read port, simply blithely block
430 # every FU from reading on it. this is complete overkill but very
431 # simple for now.
432 hazard_detected = Signal(name="raw_%s_%s" % (regfile, rpidx))
433
434 fspecs = fspec
435 if not isinstance(fspecs, list):
436 fspecs = [fspecs]
437
438 rdflags = []
439 pplen = 0
440 ppoffs = []
441 for i, fspec in enumerate(fspecs):
442 # get the regfile specs for this regfile port
443 (rf, wf, read, write, wid, fuspec) = fspec
444 print ("fpsec", i, fspec, len(fuspec))
445 ppoffs.append(pplen) # record offset for picker
446 pplen += len(fspec.specs)
447 name = "rdflag_%s_%s_%d" % (regfile, regname, i)
448 rdflag = Signal(name=name, reset_less=True)
449 comb += rdflag.eq(fspec.rdport)
450 rdflags.append(rdflag)
451
452 print ("pplen", pplen)
453
454 # create a priority picker to manage this port
455 rdpickers[regfile][rpidx] = rdpick = PriorityPicker(pplen)
456 setattr(m.submodules, "rdpick_%s_%s" % (regfile, rpidx), rdpick)
457
458 rens = []
459 addrs = []
460 wvens = []
461
462 for i, fspec in enumerate(fspecs):
463 (rf, wf, _read, _write, wid, fuspecs) = fspec
464 # connect up the FU req/go signals, and the reg-read to the FU
465 # and create a Read Broadcast Bus
466 for pi, fuspec in enumerate(fspec.specs):
467 (funame, fu, idx) = (fuspec.funame, fuspec.fu, fuspec.idx)
468 pi += ppoffs[i]
469 name = "%s_%s_%s_%i" % (regfile, rpidx, funame, pi)
470 fu_active = fu_selected[funame]
471 fu_issued = fu_bitdict[funame]
472
473 # get (or set up) a latched copy of read register number
474 rname = "%s_%s_%s_%d" % (funame, regfile, regname, pi)
475 read = Signal.like(_read, name="read_"+name)
476 if rname not in fu.rd_latches:
477 rdl = Signal.like(_read, name="rdlatch_"+rname)
478 fu.rd_latches[rname] = rdl
479 with m.If(fu.issue_i):
480 sync += rdl.eq(_read)
481 else:
482 rdl = fu.rd_latches[rname]
483 # latch to make the read immediately available on issue cycle
484 # after the read cycle, use the latched copy
485 with m.If(fu.issue_i):
486 comb += read.eq(_read)
487 with m.Else():
488 comb += read.eq(rdl)
489
490 # connect request-read to picker input, and output to go-rd
491 addr_en = Signal.like(read, name="addr_en_"+name)
492 pick = Signal(name="pick_"+name) # picker input
493 rp = Signal(name="rp_"+name) # picker output
494 delay_pick = Signal(name="dp_"+name) # read-enable "underway"
495 rhazard = Signal(name="rhaz_"+name)
496
497 # exclude any currently-enabled read-request (mask out active)
498 # entirely block anything hazarded from being picked
499 comb += pick.eq(fu.rd_rel_o[idx] & fu_active & rdflags[i] &
500 ~delay_pick & ~rhazard)
501 comb += rdpick.i[pi].eq(pick)
502 comb += fu.go_rd_i[idx].eq(delay_pick) # pass in *delayed* pick
503
504 # if picked, select read-port "reg select" number to port
505 comb += rp.eq(rdpick.o[pi] & rdpick.en_o)
506 sync += delay_pick.eq(rp) # delayed "pick"
507 comb += addr_en.eq(Mux(rp, read, 0))
508
509 # the read-enable happens combinatorially (see mux-bus below)
510 # but it results in the data coming out on a one-cycle delay.
511 if rfile.unary:
512 rens.append(addr_en)
513 else:
514 addrs.append(addr_en)
515 rens.append(rp)
516
517 # use the *delayed* pick signal to put requested data onto bus
518 with m.If(delay_pick):
519 # connect regfile port to input, creating fan-out Bus
520 src = fu.src_i[idx]
521 print("reg connect widths",
522 regfile, regname, pi, funame,
523 src.shape(), rport.o_data.shape())
524 # all FUs connect to same port
525 comb += src.eq(rport.o_data)
526
527 if not self.make_hazard_vecs:
528 continue
529
530 # read the write-hazard bitvector (wv) for any bit that is
531 wvchk_en = Signal(len(wvchk.ren), name="wv_chk_addr_en_"+name)
532 issue_active = Signal(name="rd_iactive_"+name)
533 # XXX combinatorial loop here
534 comb += issue_active.eq(fu_active & rf)
535 with m.If(issue_active):
536 if rfile.unary:
537 comb += wvchk_en.eq(read)
538 else:
539 comb += wvchk_en.eq(1<<read)
540 # if FU is busy (which doesn't get set at the same time as
541 # issue) and no hazard was detected, clear wvchk_en (i.e.
542 # stop checking for hazards). there is a loop here, but it's
543 # via a DFF, so is ok. some linters may complain, but hey.
544 with m.If(fu.busy_o & ~rhazard):
545 comb += wvchk_en.eq(0)
546
547 # read-hazard is ANDed with (filtered by) what is actually
548 # being requested.
549 comb += rhazard.eq((wvchk.o_data & wvchk_en).bool())
550
551 wvens.append(wvchk_en)
552
553 # or-reduce the muxed read signals
554 if rfile.unary:
555 # for unary-addressed
556 comb += rport.ren.eq(ortreereduce_sig(rens))
557 else:
558 # for binary-addressed
559 comb += rport.addr.eq(ortreereduce_sig(addrs))
560 comb += rport.ren.eq(Cat(*rens).bool())
561 print ("binary", regfile, rpidx, rport, rport.ren, rens, addrs)
562
563 if not self.make_hazard_vecs:
564 return Const(0) # declare "no hazards"
565
566 # enable the read bitvectors for this issued instruction
567 # and return whether any write-hazard bit is set
568 comb += wvchk.ren.eq(ortreereduce_sig(wvens))
569 comb += hazard_detected.eq(wvchk.o_data.bool())
570 return hazard_detected
571
572 def connect_rdports(self, m, fu_bitdict, fu_selected):
573 """connect read ports
574
575 orders the read regspecs into a dict-of-dicts, by regfile, by
576 regport name, then connects all FUs that want that regport by
577 way of a PriorityPicker.
578 """
579 comb, sync = m.d.comb, m.d.sync
580 fus = self.fus.fus
581 regs = self.regs
582 rd_hazard = []
583
584 # dictionary of lists of regfile read ports
585 byregfiles_rd, byregfiles_rdspec = self.get_byregfiles(True)
586
587 # okaay, now we need a PriorityPicker per regfile per regfile port
588 # loootta pickers... peter piper picked a pack of pickled peppers...
589 rdpickers = {}
590 for regfile, spec in byregfiles_rd.items():
591 fuspecs = byregfiles_rdspec[regfile]
592 rdpickers[regfile] = {}
593
594 # argh. an experiment to merge RA and RB in the INT regfile
595 # (we have too many read/write ports)
596 if self.regreduce_en:
597 if regfile == 'INT':
598 fuspecs['rabc'] = [fuspecs.pop('rb')]
599 fuspecs['rabc'].append(fuspecs.pop('rc'))
600 fuspecs['rabc'].append(fuspecs.pop('ra'))
601 if regfile == 'FAST':
602 fuspecs['fast1'] = [fuspecs.pop('fast1')]
603 if 'fast2' in fuspecs:
604 fuspecs['fast1'].append(fuspecs.pop('fast2'))
605 if 'fast3' in fuspecs:
606 fuspecs['fast1'].append(fuspecs.pop('fast3'))
607
608 # for each named regfile port, connect up all FUs to that port
609 # also return (and collate) hazard detection)
610 for (regname, fspec) in sort_fuspecs(fuspecs):
611 print("connect rd", regname, fspec)
612 rh = self.connect_rdport(m, fu_bitdict, fu_selected,
613 rdpickers, regfile,
614 regname, fspec)
615 rd_hazard.append(rh)
616
617 return Cat(*rd_hazard).bool()
618
619 def make_hazards(self, m, regfile, rfile, wvclr, wvset,
620 funame, regname, idx,
621 addr_en, wp, fu, fu_active, wrflag, write,
622 fu_wrok):
623 """make_hazards: a setter and a clearer for the regfile write ports
624
625 setter is at issue time (using PowerDecoder2 regfile write numbers)
626 clearer is at regfile write time (when FU has said what to write to)
627
628 there is *one* unusual case here which has to be dealt with:
629 when the Function Unit does *NOT* request a write to the regfile
630 (has its data.ok bit CLEARED). this is perfectly legitimate.
631 and a royal pain.
632 """
633 comb, sync = m.d.comb, m.d.sync
634 name = "%s_%s_%d" % (funame, regname, idx)
635
636 # connect up the bitvector write hazard. unlike the
637 # regfile writeports, a ONE must be written to the corresponding
638 # bit of the hazard bitvector (to indicate the existence of
639 # the hazard)
640
641 # the detection of what shall be written to is based
642 # on *issue*
643 print ("write vector (for regread)", regfile, wvset)
644 wviaddr_en = Signal(len(wvset.wen), name="wv_issue_addr_en_"+name)
645 issue_active = Signal(name="iactive_"+name)
646 comb += issue_active.eq(fu.issue_i & fu_active & wrflag)
647 with m.If(issue_active):
648 if rfile.unary:
649 comb += wviaddr_en.eq(write)
650 else:
651 comb += wviaddr_en.eq(1<<write)
652
653 # deal with write vector clear: this kicks in when the regfile
654 # is written to, and clears the corresponding bitvector entry
655 print ("write vector", regfile, wvclr)
656 wvaddr_en = Signal(len(wvclr.wen), name="wvaddr_en_"+name)
657 if rfile.unary:
658 comb += wvaddr_en.eq(addr_en)
659 else:
660 with m.If(wp):
661 comb += wvaddr_en.eq(1<<addr_en)
662
663 # XXX ASSUME that LDSTFunctionUnit always sets the data it intends to
664 # this may NOT be the case when an exception occurs
665 if isinstance(fu, LDSTFunctionUnit):
666 return wvaddr_en, wviaddr_en
667
668 # okaaay, this is preparation for the awkward case.
669 # * latch a copy of wrflag when issue goes high.
670 # * when the fu_wrok (data.ok) flag is NOT set,
671 # but the FU is done, the FU is NEVER going to write
672 # so the bitvector has to be cleared.
673 latch_wrflag = Signal(name="latch_wrflag_"+name)
674 with m.If(~fu.busy_o):
675 sync += latch_wrflag.eq(0)
676 with m.If(fu.issue_i & fu_active):
677 sync += latch_wrflag.eq(wrflag)
678 with m.If(fu.alu_done_o & latch_wrflag & ~fu_wrok):
679 if rfile.unary:
680 comb += wvaddr_en.eq(write) # addr_en gated with wp, don't use
681 else:
682 comb += wvaddr_en.eq(1<<addr_en) # binary addr_en not gated
683
684 return wvaddr_en, wviaddr_en
685
686 def connect_wrport(self, m, fu_bitdict, fu_selected,
687 wrpickers, regfile, regname, fspec):
688 comb, sync = m.d.comb, m.d.sync
689 fus = self.fus.fus
690 regs = self.regs
691
692 rpidx = regname
693
694 # select the required write port. these are pre-defined sizes
695 rfile = regs.rf[regfile.lower()]
696 wport = rfile.w_ports[rpidx]
697
698 print("connect wr", regname, "unary", rfile.unary, fspec)
699 print(regfile, regs.rf.keys())
700
701 # select the write-protection hazard vector. note that this still
702 # requires to WRITE to the hazard bitvector! read-requests need
703 # to RAISE the bitvector (set it to 1), which, duh, requires a WRITE
704 if self.make_hazard_vecs:
705 wv = regs.wv[regfile.lower()]
706 wvset = wv.w_ports["set"] # write-vec bit-level hazard ctrl
707 wvclr = wv.w_ports["clr"] # write-vec bit-level hazard ctrl
708
709 fspecs = fspec
710 if not isinstance(fspecs, list):
711 fspecs = [fspecs]
712
713 pplen = 0
714 writes = []
715 ppoffs = []
716 rdflags = []
717 wrflags = []
718 for i, fspec in enumerate(fspecs):
719 # get the regfile specs for this regfile port
720 (rf, wf, read, write, wid, fuspec) = fspec
721 print ("fpsec", i, "wrflag", wf, fspec, len(fuspec))
722 ppoffs.append(pplen) # record offset for picker
723 pplen += len(fuspec)
724
725 name = "%s_%s_%d" % (regfile, regname, i)
726 rdflag = Signal(name="rd_flag_"+name)
727 wrflag = Signal(name="wr_flag_"+name)
728 if rf is not None:
729 comb += rdflag.eq(rf)
730 else:
731 comb += rdflag.eq(0)
732 if wf is not None:
733 comb += wrflag.eq(wf)
734 else:
735 comb += wrflag.eq(0)
736 rdflags.append(rdflag)
737 wrflags.append(wrflag)
738
739 # create a priority picker to manage this port
740 wrpickers[regfile][rpidx] = wrpick = PriorityPicker(pplen)
741 setattr(m.submodules, "wrpick_%s_%s" % (regfile, rpidx), wrpick)
742
743 wsigs = []
744 wens = []
745 wvsets = []
746 wvseten = []
747 wvclren = []
748 addrs = []
749 for i, fspec in enumerate(fspecs):
750 # connect up the FU req/go signals and the reg-read to the FU
751 # these are arbitrated by Data.ok signals
752 (rf, wf, read, _write, wid, fuspec) = fspec
753 for pi, (funame, fu, idx) in enumerate(fuspec):
754 pi += ppoffs[i]
755 name = "%s_%s_%s_%d" % (funame, regfile, regname, idx)
756 # get (or set up) a write-latched copy of write register number
757 write = Signal.like(_write, name="write_"+name)
758 rname = "%s_%s_%s" % (funame, regfile, regname)
759 if rname not in fu.wr_latches:
760 wrl = Signal.like(_write, name="wrlatch_"+rname)
761 fu.wr_latches[rname] = write
762 with m.If(fu.issue_i):
763 sync += wrl.eq(_write)
764 comb += write.eq(_write)
765 with m.Else():
766 comb += write.eq(wrl)
767 else:
768 write = fu.wr_latches[rname]
769
770 # write-request comes from dest.ok
771 dest = fu.get_out(idx)
772 fu_dest_latch = fu.get_fu_out(idx) # latched output
773 name = "fu_wrok_%s_%s_%d" % (funame, regname, idx)
774 fu_wrok = Signal(name=name, reset_less=True)
775 comb += fu_wrok.eq(dest.ok & fu.busy_o)
776
777 # connect request-write to picker input, and output to go-wr
778 fu_active = fu_selected[funame]
779 pick = fu.wr.rel_o[idx] & fu_active
780 comb += wrpick.i[pi].eq(pick)
781 # create a single-pulse go write from the picker output
782 wr_pick = Signal(name="wpick_%s_%s_%d" % (funame, regname, idx))
783 comb += wr_pick.eq(wrpick.o[pi] & wrpick.en_o)
784 comb += fu.go_wr_i[idx].eq(rising_edge(m, wr_pick))
785
786 # connect the regspec write "reg select" number to this port
787 # only if one FU actually requests (and is granted) the port
788 # will the write-enable be activated
789 wname = "waddr_en_%s_%s_%d" % (funame, regname, idx)
790 addr_en = Signal.like(write, name=wname)
791 wp = Signal()
792 comb += wp.eq(wr_pick & wrpick.en_o)
793 comb += addr_en.eq(Mux(wp, write, 0))
794 if rfile.unary:
795 wens.append(addr_en)
796 else:
797 addrs.append(addr_en)
798 wens.append(wp)
799
800 # connect regfile port to input
801 print("reg connect widths",
802 regfile, regname, pi, funame,
803 dest.shape(), wport.i_data.shape())
804 wsigs.append(fu_dest_latch)
805
806 # now connect up the bitvector write hazard
807 if not self.make_hazard_vecs:
808 continue
809 res = self.make_hazards(m, regfile, rfile, wvclr, wvset,
810 funame, regname, idx,
811 addr_en, wp, fu, fu_active,
812 wrflags[i], write, fu_wrok)
813 wvaddr_en, wv_issue_en = res
814 wvclren.append(wvaddr_en) # set only: no data => clear bit
815 wvseten.append(wv_issue_en) # set data same as enable
816 wvsets.append(wv_issue_en) # because enable needs a 1
817
818 # here is where we create the Write Broadcast Bus. simple, eh?
819 comb += wport.i_data.eq(ortreereduce_sig(wsigs))
820 if rfile.unary:
821 # for unary-addressed
822 comb += wport.wen.eq(ortreereduce_sig(wens))
823 else:
824 # for binary-addressed
825 comb += wport.addr.eq(ortreereduce_sig(addrs))
826 comb += wport.wen.eq(ortreereduce_sig(wens))
827
828 if not self.make_hazard_vecs:
829 return
830
831 # for write-vectors
832 comb += wvclr.wen.eq(ortreereduce_sig(wvclren)) # clear (regfile write)
833 comb += wvset.wen.eq(ortreereduce_sig(wvseten)) # set (issue time)
834 comb += wvset.i_data.eq(ortreereduce_sig(wvsets))
835
836 def connect_wrports(self, m, fu_bitdict, fu_selected):
837 """connect write ports
838
839 orders the write regspecs into a dict-of-dicts, by regfile,
840 by regport name, then connects all FUs that want that regport
841 by way of a PriorityPicker.
842
843 note that the write-port wen, write-port data, and go_wr_i all need to
844 be on the exact same clock cycle. as there is a combinatorial loop bug
845 at the moment, these all use sync.
846 """
847 comb, sync = m.d.comb, m.d.sync
848 fus = self.fus.fus
849 regs = self.regs
850 # dictionary of lists of regfile write ports
851 byregfiles_wr, byregfiles_wrspec = self.get_byregfiles(False)
852
853 # same for write ports.
854 # BLECH! complex code-duplication! BLECH!
855 wrpickers = {}
856 for regfile, spec in byregfiles_wr.items():
857 fuspecs = byregfiles_wrspec[regfile]
858 wrpickers[regfile] = {}
859
860 if self.regreduce_en:
861 # argh, more port-merging
862 if regfile == 'INT':
863 fuspecs['o'] = [fuspecs.pop('o')]
864 fuspecs['o'].append(fuspecs.pop('o1'))
865 if regfile == 'FAST':
866 fuspecs['fast1'] = [fuspecs.pop('fast1')]
867 if 'fast2' in fuspecs:
868 fuspecs['fast1'].append(fuspecs.pop('fast2'))
869 if 'fast3' in fuspecs:
870 fuspecs['fast1'].append(fuspecs.pop('fast3'))
871
872 for (regname, fspec) in sort_fuspecs(fuspecs):
873 self.connect_wrport(m, fu_bitdict, fu_selected, wrpickers,
874 regfile, regname, fspec)
875
876 def get_byregfiles(self, readmode):
877
878 mode = "read" if readmode else "write"
879 regs = self.regs
880 fus = self.fus.fus
881 e = self.ireg.e # decoded instruction to execute
882
883 # dictionary of dictionaries of lists/tuples of regfile ports.
884 # first key: regfile. second key: regfile port name
885 byregfiles = defaultdict(lambda: defaultdict(list))
886 byregfiles_spec = defaultdict(dict)
887
888 for (funame, fu) in fus.items():
889 # create in each FU a receptacle for the read/write register
890 # hazard numbers. to be latched in connect_rd/write_ports
891 # XXX better that this is moved into the actual FUs, but
892 # the issue there is that this function is actually better
893 # suited at the moment
894 if readmode:
895 fu.rd_latches = {}
896 else:
897 fu.wr_latches = {}
898
899 print("%s ports for %s" % (mode, funame))
900 for idx in range(fu.n_src if readmode else fu.n_dst):
901 # construct regfile specs: read uses inspec, write outspec
902 if readmode:
903 (regfile, regname, wid) = fu.get_in_spec(idx)
904 else:
905 (regfile, regname, wid) = fu.get_out_spec(idx)
906 print(" %d %s %s %s" % (idx, regfile, regname, str(wid)))
907
908 # the PowerDecoder2 (main one, not the satellites) contains
909 # the decoded regfile numbers. obtain these now
910 if readmode:
911 rdport, read = regspec_decode_read(e, regfile, regname)
912 wrport, write = None, None
913 else:
914 rdport, read = None, None
915 wrport, write = regspec_decode_write(e, regfile, regname)
916
917 # construct the dictionary of regspec information by regfile
918 if regname not in byregfiles_spec[regfile]:
919 byregfiles_spec[regfile][regname] = \
920 ByRegSpec(rdport, wrport, read, write, wid, [])
921 # here we start to create "lanes"
922 fuspec = FUSpec(funame, fu, idx)
923 byregfiles[regfile][idx].append(fuspec)
924 byregfiles_spec[regfile][regname].specs.append(fuspec)
925
926 continue
927 # append a latch Signal to the FU's list of latches
928 rname = "%s_%s" % (regfile, regname)
929 if readmode:
930 if rname not in fu.rd_latches:
931 rdl = Signal.like(read, name="rdlatch_"+rname)
932 fu.rd_latches[rname] = rdl
933 else:
934 if rname not in fu.wr_latches:
935 wrl = Signal.like(write, name="wrlatch_"+rname)
936 fu.wr_latches[rname] = wrl
937
938 # ok just print that all out, for convenience
939 for regfile, spec in byregfiles.items():
940 print("regfile %s ports:" % mode, regfile)
941 fuspecs = byregfiles_spec[regfile]
942 for regname, fspec in fuspecs.items():
943 [rdport, wrport, read, write, wid, fuspecs] = fspec
944 print(" rf %s port %s lane: %s" % (mode, regfile, regname))
945 print(" %s" % regname, wid, read, write, rdport, wrport)
946 for (funame, fu, idx) in fuspecs:
947 fusig = fu.src_i[idx] if readmode else fu.dest[idx]
948 print(" ", funame, fu.__class__.__name__, idx, fusig)
949 print()
950
951 return byregfiles, byregfiles_spec
952
953 def __iter__(self):
954 yield from self.fus.ports()
955 yield from self.i.e.ports()
956 yield from self.l0.ports()
957 # TODO: regs
958
959 def ports(self):
960 return list(self)
961
962
963 if __name__ == '__main__':
964 pspec = TestMemPspec(ldst_ifacetype='testpi',
965 imem_ifacetype='',
966 addr_wid=48,
967 mask_wid=8,
968 reg_wid=64)
969 dut = NonProductionCore(pspec)
970 vl = rtlil.convert(dut, ports=dut.ports())
971 with open("test_core.il", "w") as f:
972 f.write(vl)