move core hazard set/clear to separate function, for clarity
[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 from nmigen.cli import rtlil
24
25 from openpower.decoder.power_decoder2 import PowerDecodeSubset
26 from openpower.decoder.power_regspec_map import regspec_decode_read
27 from openpower.decoder.power_regspec_map import regspec_decode_write
28 from openpower.sv.svp64 import SVP64Rec
29
30 from nmutil.picker import PriorityPicker
31 from nmutil.util import treereduce
32 from nmutil.singlepipe import ControlBase
33
34 from soc.fu.compunits.compunits import AllFunctionUnits
35 from soc.regfile.regfiles import RegFiles
36 from openpower.decoder.power_decoder2 import get_rdflags
37 from soc.experiment.l0_cache import TstL0CacheBuffer # test only
38 from soc.config.test.test_loadstore import TestMemPspec
39 from openpower.decoder.power_enums import MicrOp, Function
40 from soc.simple.core_data import CoreInput, CoreOutput
41
42 from collections import defaultdict
43 import operator
44
45 from nmutil.util import rising_edge
46
47
48 # helper function for reducing a list of signals down to a parallel
49 # ORed single signal.
50 def ortreereduce(tree, attr="o_data"):
51 return treereduce(tree, operator.or_, lambda x: getattr(x, attr))
52
53
54 def ortreereduce_sig(tree):
55 return treereduce(tree, operator.or_, lambda x: x)
56
57
58 # helper function to place full regs declarations first
59 def sort_fuspecs(fuspecs):
60 res = []
61 for (regname, fspec) in fuspecs.items():
62 if regname.startswith("full"):
63 res.append((regname, fspec))
64 for (regname, fspec) in fuspecs.items():
65 if not regname.startswith("full"):
66 res.append((regname, fspec))
67 return res # enumerate(res)
68
69
70 # derive from ControlBase rather than have a separate Stage instance,
71 # this is simpler to do
72 class NonProductionCore(ControlBase):
73 def __init__(self, pspec):
74 self.pspec = pspec
75
76 # test is SVP64 is to be enabled
77 self.svp64_en = hasattr(pspec, "svp64") and (pspec.svp64 == True)
78
79 # test to see if regfile ports should be reduced
80 self.regreduce_en = (hasattr(pspec, "regreduce") and
81 (pspec.regreduce == True))
82
83 # test core type
84 self.make_hazard_vecs = True
85 self.core_type = "fsm"
86 if hasattr(pspec, "core_type"):
87 self.core_type = pspec.core_type
88
89 super().__init__(stage=self)
90
91 # single LD/ST funnel for memory access
92 self.l0 = l0 = TstL0CacheBuffer(pspec, n_units=1)
93 pi = l0.l0.dports[0]
94
95 # function units (only one each)
96 # only include mmu if enabled in pspec
97 self.fus = AllFunctionUnits(pspec, pilist=[pi])
98
99 # link LoadStore1 into MMU
100 mmu = self.fus.get_fu('mmu0')
101 print ("core pspec", pspec.ldst_ifacetype)
102 print ("core mmu", mmu)
103 if mmu is not None:
104 print ("core lsmem.lsi", l0.cmpi.lsmem.lsi)
105 mmu.alu.set_ldst_interface(l0.cmpi.lsmem.lsi)
106
107 # register files (yes plural)
108 self.regs = RegFiles(pspec, make_hazard_vecs=self.make_hazard_vecs)
109
110 # set up input and output: unusual requirement to set data directly
111 # (due to the way that the core is set up in a different domain,
112 # see TestIssuer.setup_peripherals
113 self.i, self.o = self.new_specs(None)
114 self.i, self.o = self.p.i_data, self.n.o_data
115
116 # create per-FU instruction decoders (subsetted). these "satellite"
117 # decoders reduce wire fan-out from the one (main) PowerDecoder2
118 # (used directly by the trap unit) to the *twelve* (or more)
119 # Function Units. we can either have 32 wires (the instruction)
120 # to each, or we can have well over a 200 wire fan-out (to 12
121 # ALUs). it's an easy choice to make.
122 self.decoders = {}
123 self.des = {}
124
125 for funame, fu in self.fus.fus.items():
126 f_name = fu.fnunit.name
127 fnunit = fu.fnunit.value
128 opkls = fu.opsubsetkls
129 if f_name == 'TRAP':
130 # TRAP decoder is the *main* decoder
131 self.trapunit = funame
132 continue
133 self.decoders[funame] = PowerDecodeSubset(None, opkls, f_name,
134 final=True,
135 state=self.i.state,
136 svp64_en=self.svp64_en,
137 regreduce_en=self.regreduce_en)
138 self.des[funame] = self.decoders[funame].do
139
140 # share the SPR decoder with the MMU if it exists
141 if "mmu0" in self.decoders:
142 self.decoders["mmu0"].mmu0_spr_dec = self.decoders["spr0"]
143
144 # next 3 functions are Stage API Compliance
145 def setup(self, m, i):
146 pass
147
148 def ispec(self):
149 return CoreInput(self.pspec, self.svp64_en, self.regreduce_en)
150
151 def ospec(self):
152 return CoreOutput()
153
154 # elaborate function to create HDL
155 def elaborate(self, platform):
156 m = super().elaborate(platform)
157
158 # for testing purposes, to cut down on build time in coriolis2
159 if hasattr(self.pspec, "nocore") and self.pspec.nocore == True:
160 x = Signal() # dummy signal
161 m.d.sync += x.eq(~x)
162 return m
163 comb = m.d.comb
164
165 m.submodules.fus = self.fus
166 m.submodules.l0 = l0 = self.l0
167 self.regs.elaborate_into(m, platform)
168 regs = self.regs
169 fus = self.fus.fus
170
171 # connect decoders
172 self.connect_satellite_decoders(m)
173
174 # ssh, cheat: trap uses the main decoder because of the rewriting
175 self.des[self.trapunit] = self.i.e.do
176
177 # connect up Function Units, then read/write ports
178 fu_bitdict, fu_selected = self.connect_instruction(m)
179 self.connect_rdports(m, fu_selected)
180 self.connect_wrports(m, fu_selected)
181
182 # note if an exception happened. in a pipelined or OoO design
183 # this needs to be accompanied by "shadowing" (or stalling)
184 el = []
185 for exc in self.fus.excs.values():
186 el.append(exc.happened)
187 if len(el) > 0: # at least one exception
188 comb += self.o.exc_happened.eq(Cat(*el).bool())
189
190 return m
191
192 def connect_satellite_decoders(self, m):
193 comb = m.d.comb
194 for k, v in self.decoders.items():
195 # connect each satellite decoder and give it the instruction.
196 # as subset decoders this massively reduces wire fanout given
197 # the large number of ALUs
198 setattr(m.submodules, "dec_%s" % v.fn_name, v)
199 comb += v.dec.raw_opcode_in.eq(self.i.raw_insn_i)
200 comb += v.dec.bigendian.eq(self.i.bigendian_i)
201 # sigh due to SVP64 RA_OR_ZERO detection connect these too
202 comb += v.sv_a_nz.eq(self.i.sv_a_nz)
203 if self.svp64_en:
204 comb += v.pred_sm.eq(self.i.sv_pred_sm)
205 comb += v.pred_dm.eq(self.i.sv_pred_dm)
206 if k != self.trapunit:
207 comb += v.sv_rm.eq(self.i.sv_rm) # pass through SVP64 ReMap
208 comb += v.is_svp64_mode.eq(self.i.is_svp64_mode)
209 # only the LDST PowerDecodeSubset *actually* needs to
210 # know to use the alternative decoder. this is all
211 # a terrible hack
212 if k.lower().startswith("ldst"):
213 comb += v.use_svp64_ldst_dec.eq(
214 self.i.use_svp64_ldst_dec)
215
216 def connect_instruction(self, m):
217 """connect_instruction
218
219 uses decoded (from PowerOp) function unit information from CSV files
220 to ascertain which Function Unit should deal with the current
221 instruction.
222
223 some (such as OP_ATTN, OP_NOP) are dealt with here, including
224 ignoring it and halting the processor. OP_NOP is a bit annoying
225 because the issuer expects busy flag still to be raised then lowered.
226 (this requires a fake counter to be set).
227 """
228 comb, sync = m.d.comb, m.d.sync
229 fus = self.fus.fus
230
231 # indicate if core is busy
232 busy_o = self.o.busy_o
233
234 # enable/busy-signals for each FU, get one bit for each FU (by name)
235 fu_enable = Signal(len(fus), reset_less=True)
236 fu_busy = Signal(len(fus), reset_less=True)
237 fu_bitdict = {}
238 fu_selected = {}
239 for i, funame in enumerate(fus.keys()):
240 fu_bitdict[funame] = fu_enable[i]
241 fu_selected[funame] = fu_busy[i]
242
243 # identify function units and create a list by fnunit so that
244 # PriorityPickers can be created for selecting one of them that
245 # isn't busy at the time the incoming instruction needs passing on
246 by_fnunit = defaultdict(list)
247 for fname, member in Function.__members__.items():
248 for funame, fu in fus.items():
249 fnunit = fu.fnunit.value
250 if member.value & fnunit: # this FU handles this type of op
251 by_fnunit[fname].append((funame, fu)) # add by Function
252
253 # ok now just print out the list of FUs by Function, because we can
254 for fname, fu_list in by_fnunit.items():
255 print ("FUs by type", fname, fu_list)
256
257 # now create a PriorityPicker per FU-type such that only one
258 # non-busy FU will be picked
259 issue_pps = {}
260 fu_found = Signal() # take a note if no Function Unit was available
261 for fname, fu_list in by_fnunit.items():
262 i_pp = PriorityPicker(len(fu_list))
263 m.submodules['i_pp_%s' % fname] = i_pp
264 i_l = []
265 for i, (funame, fu) in enumerate(fu_list):
266 # match the decoded instruction (e.do.fn_unit) against the
267 # "capability" of this FU, gate that by whether that FU is
268 # busy, and drop that into the PriorityPicker.
269 # this will give us an output of the first available *non-busy*
270 # Function Unit (Reservation Statio) capable of handling this
271 # instruction.
272 fnunit = fu.fnunit.value
273 en_req = Signal(name="issue_en_%s" % funame, reset_less=True)
274 fnmatch = (self.i.e.do.fn_unit & fnunit).bool()
275 comb += en_req.eq(fnmatch & ~fu.busy_o & self.p.i_valid)
276 i_l.append(en_req) # store in list for doing the Cat-trick
277 # picker output, gated by enable: store in fu_bitdict
278 po = Signal(name="o_issue_pick_"+funame) # picker output
279 comb += po.eq(i_pp.o[i] & i_pp.en_o)
280 comb += fu_bitdict[funame].eq(po)
281 comb += fu_selected[funame].eq(fu.busy_o | po)
282 # if we don't do this, then when there are no FUs available,
283 # the "p.o_ready" signal will go back "ok we accepted this
284 # instruction" which of course isn't true.
285 comb += fu_found.eq(~fnmatch | i_pp.en_o)
286 # for each input, Cat them together and drop them into the picker
287 comb += i_pp.i.eq(Cat(*i_l))
288
289 # sigh - need a NOP counter
290 counter = Signal(2)
291 with m.If(counter != 0):
292 sync += counter.eq(counter - 1)
293 comb += busy_o.eq(1)
294
295 with m.If(self.p.i_valid): # run only when valid
296 with m.Switch(self.i.e.do.insn_type):
297 # check for ATTN: halt if true
298 with m.Case(MicrOp.OP_ATTN):
299 m.d.sync += self.o.core_terminate_o.eq(1)
300
301 # fake NOP - this isn't really used (Issuer detects NOP)
302 with m.Case(MicrOp.OP_NOP):
303 sync += counter.eq(2)
304 comb += busy_o.eq(1)
305
306 with m.Default():
307 # connect up instructions. only one enabled at a time
308 for funame, fu in fus.items():
309 do = self.des[funame]
310 enable = fu_bitdict[funame]
311
312 # run this FunctionUnit if enabled
313 # route op, issue, busy, read flags and mask to FU
314 with m.If(enable):
315 # operand comes from the *local* decoder
316 comb += fu.oper_i.eq_from(do)
317 comb += fu.issue_i.eq(1) # issue when input valid
318 # rdmask, which is for registers, needs to come
319 # from the *main* decoder
320 rdmask = get_rdflags(self.i.e, fu)
321 comb += fu.rdmaskn.eq(~rdmask)
322
323 # if instruction is busy, set busy output for core.
324 busys = map(lambda fu: fu.busy_o, fus.values())
325 comb += busy_o.eq(Cat(*busys).bool())
326
327 # ready/valid signalling. if busy, means refuse incoming issue.
328 # (this is a global signal, TODO, change to one which allows
329 # overlapping instructions)
330 # also, if there was no fu found we must not send back a valid
331 # indicator. BUT, of course, when there is no instruction
332 # we must ignore the fu_found flag, otherwise o_ready will never
333 # be set when everything is idle
334 comb += self.p.o_ready.eq(fu_found | ~self.p.i_valid)
335
336 # return both the function unit "enable" dict as well as the "busy".
337 # the "busy-or-issued" can be passed in to the Read/Write port
338 # connecters to give them permission to request access to regfiles
339 return fu_bitdict, fu_selected
340
341 def connect_rdport(self, m, fu_bitdict, rdpickers, regfile, regname, fspec):
342 comb, sync = m.d.comb, m.d.sync
343 fus = self.fus.fus
344 regs = self.regs
345
346 rpidx = regname
347
348 # select the required read port. these are pre-defined sizes
349 rfile = regs.rf[regfile.lower()]
350 rport = rfile.r_ports[rpidx]
351 print("read regfile", rpidx, regfile, regs.rf.keys(),
352 rfile, rfile.unary)
353
354 fspecs = fspec
355 if not isinstance(fspecs, list):
356 fspecs = [fspecs]
357
358 rdflags = []
359 pplen = 0
360 reads = []
361 ppoffs = []
362 for i, fspec in enumerate(fspecs):
363 # get the regfile specs for this regfile port
364 (rf, wf, read, write, wid, fuspec) = fspec
365 print ("fpsec", i, fspec, len(fuspec))
366 ppoffs.append(pplen) # record offset for picker
367 pplen += len(fuspec)
368 name = "rdflag_%s_%s_%d" % (regfile, regname, i)
369 rdflag = Signal(name=name, reset_less=True)
370 comb += rdflag.eq(rf)
371 rdflags.append(rdflag)
372 reads.append(read)
373
374 print ("pplen", pplen)
375
376 # create a priority picker to manage this port
377 rdpickers[regfile][rpidx] = rdpick = PriorityPicker(pplen)
378 setattr(m.submodules, "rdpick_%s_%s" % (regfile, rpidx), rdpick)
379
380 rens = []
381 addrs = []
382 wvens = []
383
384 for i, fspec in enumerate(fspecs):
385 (rf, wf, read, write, wid, fuspec) = fspec
386 # connect up the FU req/go signals, and the reg-read to the FU
387 # and create a Read Broadcast Bus
388 for pi, (funame, fu, idx) in enumerate(fuspec):
389 pi += ppoffs[i]
390
391 # connect request-read to picker input, and output to go-rd
392 fu_active = fu_bitdict[funame]
393 name = "%s_%s_%s_%i" % (regfile, rpidx, funame, pi)
394 addr_en = Signal.like(reads[i], name="addr_en_"+name)
395 pick = Signal(name="pick_"+name) # picker input
396 rp = Signal(name="rp_"+name) # picker output
397 delay_pick = Signal(name="dp_"+name) # read-enable "underway"
398
399 # exclude any currently-enabled read-request (mask out active)
400 comb += pick.eq(fu.rd_rel_o[idx] & fu_active & rdflags[i] &
401 ~delay_pick)
402 comb += rdpick.i[pi].eq(pick)
403 comb += fu.go_rd_i[idx].eq(delay_pick) # pass in *delayed* pick
404
405 # if picked, select read-port "reg select" number to port
406 comb += rp.eq(rdpick.o[pi] & rdpick.en_o)
407 sync += delay_pick.eq(rp) # delayed "pick"
408 comb += addr_en.eq(Mux(rp, reads[i], 0))
409
410 # the read-enable happens combinatorially (see mux-bus below)
411 # but it results in the data coming out on a one-cycle delay.
412 if rfile.unary:
413 rens.append(addr_en)
414 else:
415 addrs.append(addr_en)
416 rens.append(rp)
417
418 # use the *delayed* pick signal to put requested data onto bus
419 with m.If(delay_pick):
420 # connect regfile port to input, creating fan-out Bus
421 src = fu.src_i[idx]
422 print("reg connect widths",
423 regfile, regname, pi, funame,
424 src.shape(), rport.o_data.shape())
425 # all FUs connect to same port
426 comb += src.eq(rport.o_data)
427
428 # or-reduce the muxed read signals
429 if rfile.unary:
430 # for unary-addressed
431 comb += rport.ren.eq(ortreereduce_sig(rens))
432 else:
433 # for binary-addressed
434 comb += rport.addr.eq(ortreereduce_sig(addrs))
435 comb += rport.ren.eq(Cat(*rens).bool())
436 print ("binary", regfile, rpidx, rport, rport.ren, rens, addrs)
437
438 def connect_rdports(self, m, fu_bitdict):
439 """connect read ports
440
441 orders the read regspecs into a dict-of-dicts, by regfile, by
442 regport name, then connects all FUs that want that regport by
443 way of a PriorityPicker.
444 """
445 comb, sync = m.d.comb, m.d.sync
446 fus = self.fus.fus
447 regs = self.regs
448
449 # dictionary of lists of regfile read ports
450 byregfiles_rd, byregfiles_rdspec = self.get_byregfiles(True)
451
452 # okaay, now we need a PriorityPicker per regfile per regfile port
453 # loootta pickers... peter piper picked a pack of pickled peppers...
454 rdpickers = {}
455 for regfile, spec in byregfiles_rd.items():
456 fuspecs = byregfiles_rdspec[regfile]
457 rdpickers[regfile] = {}
458
459 # argh. an experiment to merge RA and RB in the INT regfile
460 # (we have too many read/write ports)
461 if self.regreduce_en:
462 if regfile == 'INT':
463 fuspecs['rabc'] = [fuspecs.pop('rb')]
464 fuspecs['rabc'].append(fuspecs.pop('rc'))
465 fuspecs['rabc'].append(fuspecs.pop('ra'))
466 if regfile == 'FAST':
467 fuspecs['fast1'] = [fuspecs.pop('fast1')]
468 if 'fast2' in fuspecs:
469 fuspecs['fast1'].append(fuspecs.pop('fast2'))
470 if 'fast3' in fuspecs:
471 fuspecs['fast1'].append(fuspecs.pop('fast3'))
472
473 # for each named regfile port, connect up all FUs to that port
474 for (regname, fspec) in sort_fuspecs(fuspecs):
475 print("connect rd", regname, fspec)
476 self.connect_rdport(m, fu_bitdict, rdpickers, regfile,
477 regname, fspec)
478
479 def make_hazards(self, m, regfile, rfile, wvclr, wvset,
480 funame, regname, idx,
481 addr_en, wp, fu, fu_active, wrflag, write):
482 """make_hazards: a setter and a clearer for the regfile write ports
483
484 setter is at issue time (using PowerDecoder2 regfile write numbers)
485 clearer is at regfile write time (when FU has said what to write to)
486
487 there is *one* unusual case here which has to be dealt with:
488 when the Function Unit does *NOT* request a write to the regfile
489 (has its data.ok bit CLEARED). this is perfectly legitimate.
490 and a royal pain.
491 """
492 comb = m.d.comb
493 name = "%s_%s_%d" % (funame, regname, idx)
494
495 # deal with write vector clear: this kicks in when the regfile
496 # is written to, and clears the corresponding bitvector entry
497 print ("write vector", regfile, wvclr)
498 wvaddr_en = Signal(len(wvclr.wen), name="wvaddr_en_"+name)
499 if rfile.unary:
500 comb += wvaddr_en.eq(addr_en)
501 else:
502 with m.If(wp):
503 comb += wvaddr_en.eq(1<<addr_en)
504
505 # now connect up the bitvector write hazard. unlike the
506 # regfile writeports, a ONE must be written to the corresponding
507 # bit of the hazard bitvector (to indicate the existence of
508 # the hazard)
509
510 # the detection of what shall be written to is based
511 # on *issue*
512 print ("write vector (for regread)", regfile, wvset)
513 wviaddr_en = Signal(len(wvset.wen), name="wv_issue_addr_en_"+name)
514 issue_active = Signal(name="iactive_"+name)
515 comb += issue_active.eq(fu.issue_i & fu_active & wrflag)
516 with m.If(issue_active):
517 if rfile.unary:
518 comb += wviaddr_en.eq(write)
519 else:
520 comb += wviaddr_en.eq(1<<write)
521
522 return wvaddr_en, wviaddr_en
523
524 def connect_wrport(self, m, fu_bitdict, wrpickers, regfile, regname, fspec):
525 comb, sync = m.d.comb, m.d.sync
526 fus = self.fus.fus
527 regs = self.regs
528
529 rpidx = regname
530
531 # select the required write port. these are pre-defined sizes
532 rfile = regs.rf[regfile.lower()]
533 wport = rfile.w_ports[rpidx]
534
535 print("connect wr", regname, "unary", rfile.unary, fspec)
536 print(regfile, regs.rf.keys())
537
538 # select the write-protection hazard vector. note that this still
539 # requires to WRITE to the hazard bitvector! read-requests need
540 # to RAISE the bitvector (set it to 1), which, duh, requires a WRITE
541 if self.make_hazard_vecs:
542 wv = regs.wv[regfile.lower()]
543 wvset = wv.w_ports["set"] # write-vec bit-level hazard ctrl
544 wvclr = wv.w_ports["clr"] # write-vec bit-level hazard ctrl
545
546 fspecs = fspec
547 if not isinstance(fspecs, list):
548 fspecs = [fspecs]
549
550 pplen = 0
551 writes = []
552 ppoffs = []
553 rdflags = []
554 wrflags = []
555 for i, fspec in enumerate(fspecs):
556 # get the regfile specs for this regfile port
557 (rf, wf, read, write, wid, fuspec) = fspec
558 print ("fpsec", i, "wrflag", wf, fspec, len(fuspec))
559 ppoffs.append(pplen) # record offset for picker
560 pplen += len(fuspec)
561
562 name = "%s_%s_%d" % (regfile, regname, i)
563 rdflag = Signal(name="rd_flag_"+name)
564 wrflag = Signal(name="wr_flag_"+name)
565 if rf is not None:
566 comb += rdflag.eq(rf)
567 else:
568 comb += rdflag.eq(0)
569 if wf is not None:
570 comb += wrflag.eq(wf)
571 else:
572 comb += wrflag.eq(0)
573 rdflags.append(rdflag)
574 wrflags.append(wrflag)
575
576 # create a priority picker to manage this port
577 wrpickers[regfile][rpidx] = wrpick = PriorityPicker(pplen)
578 setattr(m.submodules, "wrpick_%s_%s" % (regfile, rpidx), wrpick)
579
580 wsigs = []
581 wens = []
582 wvsets = []
583 wvseten = []
584 wvclren = []
585 addrs = []
586 for i, fspec in enumerate(fspecs):
587 # connect up the FU req/go signals and the reg-read to the FU
588 # these are arbitrated by Data.ok signals
589 (rf, wf, read, _write, wid, fuspec) = fspec
590 wrname = "write_%s_%s_%d" % (regfile, regname, i)
591 write = Signal.like(_write, name=wrname)
592 comb += write.eq(_write)
593 for pi, (funame, fu, idx) in enumerate(fuspec):
594 pi += ppoffs[i]
595
596 # write-request comes from dest.ok
597 dest = fu.get_out(idx)
598 fu_dest_latch = fu.get_fu_out(idx) # latched output
599 name = "wrflag_%s_%s_%d" % (funame, regname, idx)
600 wrflag = Signal(name=name, reset_less=True)
601 comb += wrflag.eq(dest.ok & fu.busy_o)
602
603 # connect request-write to picker input, and output to go-wr
604 fu_active = fu_bitdict[funame]
605 pick = fu.wr.rel_o[idx] & fu_active # & wrflag
606 comb += wrpick.i[pi].eq(pick)
607 # create a single-pulse go write from the picker output
608 wr_pick = Signal(name="wpick_%s_%s_%d" % (funame, regname, idx))
609 comb += wr_pick.eq(wrpick.o[pi] & wrpick.en_o)
610 comb += fu.go_wr_i[idx].eq(rising_edge(m, wr_pick))
611
612 # connect the regspec write "reg select" number to this port
613 # only if one FU actually requests (and is granted) the port
614 # will the write-enable be activated
615 wname = "waddr_en_%s_%s_%d" % (funame, regname, idx)
616 addr_en = Signal.like(write, name=wname)
617 wp = Signal()
618 comb += wp.eq(wr_pick & wrpick.en_o)
619 comb += addr_en.eq(Mux(wp, write, 0))
620 if rfile.unary:
621 wens.append(addr_en)
622 else:
623 addrs.append(addr_en)
624 wens.append(wp)
625
626 # connect regfile port to input
627 print("reg connect widths",
628 regfile, regname, pi, funame,
629 dest.shape(), wport.i_data.shape())
630 wsigs.append(fu_dest_latch)
631
632 # now connect up the bitvector write hazard
633 if not self.make_hazard_vecs:
634 continue
635 res = self.make_hazards(m, regfile, rfile, wvclr, wvset,
636 funame, regname, idx,
637 addr_en, wp, fu, fu_active,
638 wrflags[i], write)
639 wvaddr_en, wv_issue_en = res
640 wvclren.append(wvaddr_en) # set only: no data => clear bit
641 wvseten.append(wv_issue_en) # set data same as enable
642 wvsets.append(wv_issue_en) # because enable needs a 1
643
644 # here is where we create the Write Broadcast Bus. simple, eh?
645 comb += wport.i_data.eq(ortreereduce_sig(wsigs))
646 if rfile.unary:
647 # for unary-addressed
648 comb += wport.wen.eq(ortreereduce_sig(wens))
649 else:
650 # for binary-addressed
651 comb += wport.addr.eq(ortreereduce_sig(addrs))
652 comb += wport.wen.eq(ortreereduce_sig(wens))
653
654 # for write-vectors
655 comb += wvclr.wen.eq(ortreereduce_sig(wvclren)) # clear (regfile write)
656 comb += wvset.wen.eq(ortreereduce_sig(wvseten)) # set (issue time)
657 comb += wvset.i_data.eq(ortreereduce_sig(wvsets))
658
659 def connect_wrports(self, m, fu_bitdict):
660 """connect write ports
661
662 orders the write regspecs into a dict-of-dicts, by regfile,
663 by regport name, then connects all FUs that want that regport
664 by way of a PriorityPicker.
665
666 note that the write-port wen, write-port data, and go_wr_i all need to
667 be on the exact same clock cycle. as there is a combinatorial loop bug
668 at the moment, these all use sync.
669 """
670 comb, sync = m.d.comb, m.d.sync
671 fus = self.fus.fus
672 regs = self.regs
673 # dictionary of lists of regfile write ports
674 byregfiles_wr, byregfiles_wrspec = self.get_byregfiles(False)
675
676 # same for write ports.
677 # BLECH! complex code-duplication! BLECH!
678 wrpickers = {}
679 for regfile, spec in byregfiles_wr.items():
680 fuspecs = byregfiles_wrspec[regfile]
681 wrpickers[regfile] = {}
682
683 if self.regreduce_en:
684 # argh, more port-merging
685 if regfile == 'INT':
686 fuspecs['o'] = [fuspecs.pop('o')]
687 fuspecs['o'].append(fuspecs.pop('o1'))
688 if regfile == 'FAST':
689 fuspecs['fast1'] = [fuspecs.pop('fast1')]
690 if 'fast2' in fuspecs:
691 fuspecs['fast1'].append(fuspecs.pop('fast2'))
692 if 'fast3' in fuspecs:
693 fuspecs['fast1'].append(fuspecs.pop('fast3'))
694
695 for (regname, fspec) in sort_fuspecs(fuspecs):
696 self.connect_wrport(m, fu_bitdict, wrpickers,
697 regfile, regname, fspec)
698
699 def get_byregfiles(self, readmode):
700
701 mode = "read" if readmode else "write"
702 regs = self.regs
703 fus = self.fus.fus
704 e = self.i.e # decoded instruction to execute
705
706 # dictionary of lists of regfile ports
707 byregfiles = {}
708 byregfiles_spec = {}
709 for (funame, fu) in fus.items():
710 print("%s ports for %s" % (mode, funame))
711 for idx in range(fu.n_src if readmode else fu.n_dst):
712 if readmode:
713 (regfile, regname, wid) = fu.get_in_spec(idx)
714 else:
715 (regfile, regname, wid) = fu.get_out_spec(idx)
716 print(" %d %s %s %s" % (idx, regfile, regname, str(wid)))
717 if readmode:
718 rdflag, read = regspec_decode_read(e, regfile, regname)
719 wrport, write = None, None
720 else:
721 rdflag, read = None, None
722 wrport, write = regspec_decode_write(e, regfile, regname)
723 if regfile not in byregfiles:
724 byregfiles[regfile] = {}
725 byregfiles_spec[regfile] = {}
726 if regname not in byregfiles_spec[regfile]:
727 byregfiles_spec[regfile][regname] = \
728 (rdflag, wrport, read, write, wid, [])
729 # here we start to create "lanes"
730 if idx not in byregfiles[regfile]:
731 byregfiles[regfile][idx] = []
732 fuspec = (funame, fu, idx)
733 byregfiles[regfile][idx].append(fuspec)
734 byregfiles_spec[regfile][regname][5].append(fuspec)
735
736 # ok just print that out, for convenience
737 for regfile, spec in byregfiles.items():
738 print("regfile %s ports:" % mode, regfile)
739 fuspecs = byregfiles_spec[regfile]
740 for regname, fspec in fuspecs.items():
741 [rdflag, wrflag, read, write, wid, fuspec] = fspec
742 print(" rf %s port %s lane: %s" % (mode, regfile, regname))
743 print(" %s" % regname, wid, read, write, rdflag, wrflag)
744 for (funame, fu, idx) in fuspec:
745 fusig = fu.src_i[idx] if readmode else fu.dest[idx]
746 print(" ", funame, fu.__class__.__name__, idx, fusig)
747 print()
748
749 return byregfiles, byregfiles_spec
750
751 def __iter__(self):
752 yield from self.fus.ports()
753 yield from self.i.e.ports()
754 yield from self.l0.ports()
755 # TODO: regs
756
757 def ports(self):
758 return list(self)
759
760
761 if __name__ == '__main__':
762 pspec = TestMemPspec(ldst_ifacetype='testpi',
763 imem_ifacetype='',
764 addr_wid=48,
765 mask_wid=8,
766 reg_wid=64)
767 dut = NonProductionCore(pspec)
768 vl = rtlil.convert(dut, ports=dut.ports())
769 with open("test_core.il", "w") as f:
770 f.write(vl)