Merge branch 'master' of ssh://git.libre-riscv.org:922/soc
[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, LDSTFunctionUnit
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, and hazard conflict
178 issue_conflict = Signal()
179 fu_bitdict, fu_selected = self.connect_instruction(m, issue_conflict)
180 raw_hazard = self.connect_rdports(m, fu_selected)
181 self.connect_wrports(m, fu_selected)
182 comb += issue_conflict.eq(raw_hazard)
183
184 # note if an exception happened. in a pipelined or OoO design
185 # this needs to be accompanied by "shadowing" (or stalling)
186 el = []
187 for exc in self.fus.excs.values():
188 el.append(exc.happened)
189 if len(el) > 0: # at least one exception
190 comb += self.o.exc_happened.eq(Cat(*el).bool())
191
192 return m
193
194 def connect_satellite_decoders(self, m):
195 comb = m.d.comb
196 for k, v in self.decoders.items():
197 # connect each satellite decoder and give it the instruction.
198 # as subset decoders this massively reduces wire fanout given
199 # the large number of ALUs
200 setattr(m.submodules, "dec_%s" % v.fn_name, v)
201 comb += v.dec.raw_opcode_in.eq(self.i.raw_insn_i)
202 comb += v.dec.bigendian.eq(self.i.bigendian_i)
203 # sigh due to SVP64 RA_OR_ZERO detection connect these too
204 comb += v.sv_a_nz.eq(self.i.sv_a_nz)
205 if self.svp64_en:
206 comb += v.pred_sm.eq(self.i.sv_pred_sm)
207 comb += v.pred_dm.eq(self.i.sv_pred_dm)
208 if k != self.trapunit:
209 comb += v.sv_rm.eq(self.i.sv_rm) # pass through SVP64 ReMap
210 comb += v.is_svp64_mode.eq(self.i.is_svp64_mode)
211 # only the LDST PowerDecodeSubset *actually* needs to
212 # know to use the alternative decoder. this is all
213 # a terrible hack
214 if k.lower().startswith("ldst"):
215 comb += v.use_svp64_ldst_dec.eq(
216 self.i.use_svp64_ldst_dec)
217
218 def connect_instruction(self, m, issue_conflict):
219 """connect_instruction
220
221 uses decoded (from PowerOp) function unit information from CSV files
222 to ascertain which Function Unit should deal with the current
223 instruction.
224
225 some (such as OP_ATTN, OP_NOP) are dealt with here, including
226 ignoring it and halting the processor. OP_NOP is a bit annoying
227 because the issuer expects busy flag still to be raised then lowered.
228 (this requires a fake counter to be set).
229 """
230 comb, sync = m.d.comb, m.d.sync
231 fus = self.fus.fus
232
233 # indicate if core is busy
234 busy_o = self.o.busy_o
235
236 # enable/busy-signals for each FU, get one bit for each FU (by name)
237 fu_enable = Signal(len(fus), reset_less=True)
238 fu_busy = Signal(len(fus), reset_less=True)
239 fu_bitdict = {}
240 fu_selected = {}
241 for i, funame in enumerate(fus.keys()):
242 fu_bitdict[funame] = fu_enable[i]
243 fu_selected[funame] = fu_busy[i]
244
245 # identify function units and create a list by fnunit so that
246 # PriorityPickers can be created for selecting one of them that
247 # isn't busy at the time the incoming instruction needs passing on
248 by_fnunit = defaultdict(list)
249 for fname, member in Function.__members__.items():
250 for funame, fu in fus.items():
251 fnunit = fu.fnunit.value
252 if member.value & fnunit: # this FU handles this type of op
253 by_fnunit[fname].append((funame, fu)) # add by Function
254
255 # ok now just print out the list of FUs by Function, because we can
256 for fname, fu_list in by_fnunit.items():
257 print ("FUs by type", fname, fu_list)
258
259 # now create a PriorityPicker per FU-type such that only one
260 # non-busy FU will be picked
261 issue_pps = {}
262 fu_found = Signal() # take a note if no Function Unit was available
263 for fname, fu_list in by_fnunit.items():
264 i_pp = PriorityPicker(len(fu_list))
265 m.submodules['i_pp_%s' % fname] = i_pp
266 i_l = []
267 for i, (funame, fu) in enumerate(fu_list):
268 # match the decoded instruction (e.do.fn_unit) against the
269 # "capability" of this FU, gate that by whether that FU is
270 # busy, and drop that into the PriorityPicker.
271 # this will give us an output of the first available *non-busy*
272 # Function Unit (Reservation Statio) capable of handling this
273 # instruction.
274 fnunit = fu.fnunit.value
275 en_req = Signal(name="issue_en_%s" % funame, reset_less=True)
276 fnmatch = (self.i.e.do.fn_unit & fnunit).bool()
277 comb += en_req.eq(fnmatch & ~fu.busy_o & self.p.i_valid)
278 i_l.append(en_req) # store in list for doing the Cat-trick
279 # picker output, gated by enable: store in fu_bitdict
280 po = Signal(name="o_issue_pick_"+funame) # picker output
281 comb += po.eq(i_pp.o[i] & i_pp.en_o)
282 comb += fu_bitdict[funame].eq(po)
283 comb += fu_selected[funame].eq(fu.busy_o | po)
284 # if we don't do this, then when there are no FUs available,
285 # the "p.o_ready" signal will go back "ok we accepted this
286 # instruction" which of course isn't true.
287 comb += fu_found.eq(~fnmatch | i_pp.en_o)
288 # for each input, Cat them together and drop them into the picker
289 comb += i_pp.i.eq(Cat(*i_l))
290
291 # sigh - need a NOP counter
292 counter = Signal(2)
293 with m.If(counter != 0):
294 sync += counter.eq(counter - 1)
295 comb += busy_o.eq(1)
296
297 with m.If(self.p.i_valid): # run only when valid
298 with m.Switch(self.i.e.do.insn_type):
299 # check for ATTN: halt if true
300 with m.Case(MicrOp.OP_ATTN):
301 m.d.sync += self.o.core_terminate_o.eq(1)
302
303 # fake NOP - this isn't really used (Issuer detects NOP)
304 with m.Case(MicrOp.OP_NOP):
305 sync += counter.eq(2)
306 comb += busy_o.eq(1)
307
308 with m.Default():
309 # connect up instructions. only one enabled at a time
310 for funame, fu in fus.items():
311 do = self.des[funame]
312 enable = fu_bitdict[funame]
313
314 # run this FunctionUnit if enabled
315 # route op, issue, busy, read flags and mask to FU
316 with m.If(enable):
317 # operand comes from the *local* decoder
318 comb += fu.oper_i.eq_from(do)
319 comb += fu.issue_i.eq(1) # issue when input valid
320 # rdmask, which is for registers, needs to come
321 # from the *main* decoder
322 rdmask = get_rdflags(self.i.e, fu)
323 comb += fu.rdmaskn.eq(~rdmask)
324
325 # if instruction is busy, set busy output for core.
326 busys = map(lambda fu: fu.busy_o, fus.values())
327 comb += busy_o.eq(Cat(*busys).bool())
328
329 # ready/valid signalling. if busy, means refuse incoming issue.
330 # (this is a global signal, TODO, change to one which allows
331 # overlapping instructions)
332 # also, if there was no fu found we must not send back a valid
333 # indicator. BUT, of course, when there is no instruction
334 # we must ignore the fu_found flag, otherwise o_ready will never
335 # be set when everything is idle
336 comb += self.p.o_ready.eq(fu_found | ~self.p.i_valid)
337
338 # return both the function unit "enable" dict as well as the "busy".
339 # the "busy-or-issued" can be passed in to the Read/Write port
340 # connecters to give them permission to request access to regfiles
341 return fu_bitdict, fu_selected
342
343 def connect_rdport(self, m, fu_bitdict, rdpickers, regfile, regname, fspec):
344 comb, sync = m.d.comb, m.d.sync
345 fus = self.fus.fus
346 regs = self.regs
347
348 rpidx = regname
349
350 # select the required read port. these are pre-defined sizes
351 rfile = regs.rf[regfile.lower()]
352 rport = rfile.r_ports[rpidx]
353 print("read regfile", rpidx, regfile, regs.rf.keys(),
354 rfile, rfile.unary)
355
356 # for checking if the read port has an outstanding write
357 if self.make_hazard_vecs:
358 wv = regs.wv[regfile.lower()]
359 wvchk = wv.r_ports["issue"] # write-vec bit-level hazard check
360
361 fspecs = fspec
362 if not isinstance(fspecs, list):
363 fspecs = [fspecs]
364
365 rdflags = []
366 pplen = 0
367 reads = []
368 ppoffs = []
369 for i, fspec in enumerate(fspecs):
370 # get the regfile specs for this regfile port
371 (rf, wf, read, write, wid, fuspec) = fspec
372 print ("fpsec", i, fspec, len(fuspec))
373 ppoffs.append(pplen) # record offset for picker
374 pplen += len(fuspec)
375 name = "rdflag_%s_%s_%d" % (regfile, regname, i)
376 rdflag = Signal(name=name, reset_less=True)
377 comb += rdflag.eq(rf)
378 rdflags.append(rdflag)
379 reads.append(read)
380
381 print ("pplen", pplen)
382
383 # create a priority picker to manage this port
384 rdpickers[regfile][rpidx] = rdpick = PriorityPicker(pplen)
385 setattr(m.submodules, "rdpick_%s_%s" % (regfile, rpidx), rdpick)
386
387 rens = []
388 addrs = []
389 wvens = []
390
391 for i, fspec in enumerate(fspecs):
392 (rf, wf, read, write, wid, fuspec) = fspec
393 # connect up the FU req/go signals, and the reg-read to the FU
394 # and create a Read Broadcast Bus
395 for pi, (funame, fu, idx) in enumerate(fuspec):
396 pi += ppoffs[i]
397
398 # connect request-read to picker input, and output to go-rd
399 fu_active = fu_bitdict[funame]
400 name = "%s_%s_%s_%i" % (regfile, rpidx, funame, pi)
401 addr_en = Signal.like(reads[i], name="addr_en_"+name)
402 pick = Signal(name="pick_"+name) # picker input
403 rp = Signal(name="rp_"+name) # picker output
404 delay_pick = Signal(name="dp_"+name) # read-enable "underway"
405
406 # exclude any currently-enabled read-request (mask out active)
407 comb += pick.eq(fu.rd_rel_o[idx] & fu_active & rdflags[i] &
408 ~delay_pick)
409 comb += rdpick.i[pi].eq(pick)
410 comb += fu.go_rd_i[idx].eq(delay_pick) # pass in *delayed* pick
411
412 # if picked, select read-port "reg select" number to port
413 comb += rp.eq(rdpick.o[pi] & rdpick.en_o)
414 sync += delay_pick.eq(rp) # delayed "pick"
415 comb += addr_en.eq(Mux(rp, reads[i], 0))
416
417 # the read-enable happens combinatorially (see mux-bus below)
418 # but it results in the data coming out on a one-cycle delay.
419 if rfile.unary:
420 rens.append(addr_en)
421 else:
422 addrs.append(addr_en)
423 rens.append(rp)
424
425 # use the *delayed* pick signal to put requested data onto bus
426 with m.If(delay_pick):
427 # connect regfile port to input, creating fan-out Bus
428 src = fu.src_i[idx]
429 print("reg connect widths",
430 regfile, regname, pi, funame,
431 src.shape(), rport.o_data.shape())
432 # all FUs connect to same port
433 comb += src.eq(rport.o_data)
434
435 if not self.make_hazard_vecs:
436 continue
437
438 # read the write-hazard bitvector (wv) for any bit that is
439 wvchk_en = Signal(len(wvchk.ren), name="wv_chk_addr_en_"+name)
440 issue_active = Signal(name="rd_iactive_"+name)
441 comb += issue_active.eq(fu.issue_i & rdflags[i])
442 with m.If(issue_active):
443 if rfile.unary:
444 comb += wvchk_en.eq(reads[i])
445 else:
446 comb += wvchk_en.eq(1<<reads[i])
447 wvens.append(wvchk_en)
448
449 # or-reduce the muxed read signals
450 if rfile.unary:
451 # for unary-addressed
452 comb += rport.ren.eq(ortreereduce_sig(rens))
453 else:
454 # for binary-addressed
455 comb += rport.addr.eq(ortreereduce_sig(addrs))
456 comb += rport.ren.eq(Cat(*rens).bool())
457 print ("binary", regfile, rpidx, rport, rport.ren, rens, addrs)
458
459 if not self.make_hazard_vecs:
460 return Const(0) # declare "no hazards"
461
462 # enable the read bitvectors for this issued instruction
463 # and return whether any write-hazard bit is set
464 comb += wvchk.ren.eq(ortreereduce_sig(wvens))
465 hazard_detected = Signal(name="raw_%s_%s" % (regfile, rpidx))
466 comb += hazard_detected.eq(wvchk.o_data.bool())
467 return hazard_detected
468
469 def connect_rdports(self, m, fu_bitdict):
470 """connect read ports
471
472 orders the read regspecs into a dict-of-dicts, by regfile, by
473 regport name, then connects all FUs that want that regport by
474 way of a PriorityPicker.
475 """
476 comb, sync = m.d.comb, m.d.sync
477 fus = self.fus.fus
478 regs = self.regs
479 rd_hazard = []
480
481 # dictionary of lists of regfile read ports
482 byregfiles_rd, byregfiles_rdspec = self.get_byregfiles(True)
483
484 # okaay, now we need a PriorityPicker per regfile per regfile port
485 # loootta pickers... peter piper picked a pack of pickled peppers...
486 rdpickers = {}
487 for regfile, spec in byregfiles_rd.items():
488 fuspecs = byregfiles_rdspec[regfile]
489 rdpickers[regfile] = {}
490
491 # argh. an experiment to merge RA and RB in the INT regfile
492 # (we have too many read/write ports)
493 if self.regreduce_en:
494 if regfile == 'INT':
495 fuspecs['rabc'] = [fuspecs.pop('rb')]
496 fuspecs['rabc'].append(fuspecs.pop('rc'))
497 fuspecs['rabc'].append(fuspecs.pop('ra'))
498 if regfile == 'FAST':
499 fuspecs['fast1'] = [fuspecs.pop('fast1')]
500 if 'fast2' in fuspecs:
501 fuspecs['fast1'].append(fuspecs.pop('fast2'))
502 if 'fast3' in fuspecs:
503 fuspecs['fast1'].append(fuspecs.pop('fast3'))
504
505 # for each named regfile port, connect up all FUs to that port
506 for (regname, fspec) in sort_fuspecs(fuspecs):
507 print("connect rd", regname, fspec)
508 rh = self.connect_rdport(m, fu_bitdict, rdpickers, regfile,
509 regname, fspec)
510 #rd_hazard.append(rh)
511
512 return Cat(*rd_hazard).bool()
513
514 def make_hazards(self, m, regfile, rfile, wvclr, wvset,
515 funame, regname, idx,
516 addr_en, wp, fu, fu_active, wrflag, write,
517 fu_wrok):
518 """make_hazards: a setter and a clearer for the regfile write ports
519
520 setter is at issue time (using PowerDecoder2 regfile write numbers)
521 clearer is at regfile write time (when FU has said what to write to)
522
523 there is *one* unusual case here which has to be dealt with:
524 when the Function Unit does *NOT* request a write to the regfile
525 (has its data.ok bit CLEARED). this is perfectly legitimate.
526 and a royal pain.
527 """
528 comb, sync = m.d.comb, m.d.sync
529 name = "%s_%s_%d" % (funame, regname, idx)
530
531 # connect up the bitvector write hazard. unlike the
532 # regfile writeports, a ONE must be written to the corresponding
533 # bit of the hazard bitvector (to indicate the existence of
534 # the hazard)
535
536 # the detection of what shall be written to is based
537 # on *issue*
538 print ("write vector (for regread)", regfile, wvset)
539 wviaddr_en = Signal(len(wvset.wen), name="wv_issue_addr_en_"+name)
540 issue_active = Signal(name="iactive_"+name)
541 comb += issue_active.eq(fu.issue_i & fu_active & wrflag)
542 with m.If(issue_active):
543 if rfile.unary:
544 comb += wviaddr_en.eq(write)
545 else:
546 comb += wviaddr_en.eq(1<<write)
547
548 # deal with write vector clear: this kicks in when the regfile
549 # is written to, and clears the corresponding bitvector entry
550 print ("write vector", regfile, wvclr)
551 wvaddr_en = Signal(len(wvclr.wen), name="wvaddr_en_"+name)
552 if rfile.unary:
553 comb += wvaddr_en.eq(addr_en)
554 else:
555 with m.If(wp):
556 comb += wvaddr_en.eq(1<<addr_en)
557
558 # XXX ASSUME that LDSTFunctionUnit always sets the data it intends to
559 # this may NOT be the case when an exception occurs
560 if isinstance(fu, LDSTFunctionUnit):
561 return wvaddr_en, wviaddr_en
562
563 # okaaay, this is preparation for the awkward case.
564 # * latch a copy of wrflag when issue goes high.
565 # * when the fu_wrok (data.ok) flag is NOT set,
566 # but the FU is done, the FU is NEVER going to write
567 # so the bitvector has to be cleared.
568 latch_wrflag = Signal(name="latch_wrflag_"+name)
569 with m.If(~fu.busy_o):
570 sync += latch_wrflag.eq(0)
571 with m.If(fu.issue_i & fu_active):
572 sync += latch_wrflag.eq(wrflag)
573 with m.If(fu.alu_done_o & latch_wrflag & ~fu_wrok):
574 if rfile.unary:
575 comb += wvaddr_en.eq(write) # addr_en gated with wp, don't use
576 else:
577 comb += wvaddr_en.eq(1<<addr_en) # binary addr_en not gated
578
579 return wvaddr_en, wviaddr_en
580
581 def connect_wrport(self, m, fu_bitdict, wrpickers, regfile, regname, fspec):
582 comb, sync = m.d.comb, m.d.sync
583 fus = self.fus.fus
584 regs = self.regs
585
586 rpidx = regname
587
588 # select the required write port. these are pre-defined sizes
589 rfile = regs.rf[regfile.lower()]
590 wport = rfile.w_ports[rpidx]
591
592 print("connect wr", regname, "unary", rfile.unary, fspec)
593 print(regfile, regs.rf.keys())
594
595 # select the write-protection hazard vector. note that this still
596 # requires to WRITE to the hazard bitvector! read-requests need
597 # to RAISE the bitvector (set it to 1), which, duh, requires a WRITE
598 if self.make_hazard_vecs:
599 wv = regs.wv[regfile.lower()]
600 wvset = wv.w_ports["set"] # write-vec bit-level hazard ctrl
601 wvclr = wv.w_ports["clr"] # write-vec bit-level hazard ctrl
602
603 fspecs = fspec
604 if not isinstance(fspecs, list):
605 fspecs = [fspecs]
606
607 pplen = 0
608 writes = []
609 ppoffs = []
610 rdflags = []
611 wrflags = []
612 for i, fspec in enumerate(fspecs):
613 # get the regfile specs for this regfile port
614 (rf, wf, read, write, wid, fuspec) = fspec
615 print ("fpsec", i, "wrflag", wf, fspec, len(fuspec))
616 ppoffs.append(pplen) # record offset for picker
617 pplen += len(fuspec)
618
619 name = "%s_%s_%d" % (regfile, regname, i)
620 rdflag = Signal(name="rd_flag_"+name)
621 wrflag = Signal(name="wr_flag_"+name)
622 if rf is not None:
623 comb += rdflag.eq(rf)
624 else:
625 comb += rdflag.eq(0)
626 if wf is not None:
627 comb += wrflag.eq(wf)
628 else:
629 comb += wrflag.eq(0)
630 rdflags.append(rdflag)
631 wrflags.append(wrflag)
632
633 # create a priority picker to manage this port
634 wrpickers[regfile][rpidx] = wrpick = PriorityPicker(pplen)
635 setattr(m.submodules, "wrpick_%s_%s" % (regfile, rpidx), wrpick)
636
637 wsigs = []
638 wens = []
639 wvsets = []
640 wvseten = []
641 wvclren = []
642 addrs = []
643 for i, fspec in enumerate(fspecs):
644 # connect up the FU req/go signals and the reg-read to the FU
645 # these are arbitrated by Data.ok signals
646 (rf, wf, read, _write, wid, fuspec) = fspec
647 wrname = "write_%s_%s_%d" % (regfile, regname, i)
648 write = Signal.like(_write, name=wrname)
649 comb += write.eq(_write)
650 for pi, (funame, fu, idx) in enumerate(fuspec):
651 pi += ppoffs[i]
652
653 # write-request comes from dest.ok
654 dest = fu.get_out(idx)
655 fu_dest_latch = fu.get_fu_out(idx) # latched output
656 name = "fu_wrok_%s_%s_%d" % (funame, regname, idx)
657 fu_wrok = Signal(name=name, reset_less=True)
658 comb += fu_wrok.eq(dest.ok & fu.busy_o)
659
660 # connect request-write to picker input, and output to go-wr
661 fu_active = fu_bitdict[funame]
662 pick = fu.wr.rel_o[idx] & fu_active
663 comb += wrpick.i[pi].eq(pick)
664 # create a single-pulse go write from the picker output
665 wr_pick = Signal(name="wpick_%s_%s_%d" % (funame, regname, idx))
666 comb += wr_pick.eq(wrpick.o[pi] & wrpick.en_o)
667 comb += fu.go_wr_i[idx].eq(rising_edge(m, wr_pick))
668
669 # connect the regspec write "reg select" number to this port
670 # only if one FU actually requests (and is granted) the port
671 # will the write-enable be activated
672 wname = "waddr_en_%s_%s_%d" % (funame, regname, idx)
673 addr_en = Signal.like(write, name=wname)
674 wp = Signal()
675 comb += wp.eq(wr_pick & wrpick.en_o)
676 comb += addr_en.eq(Mux(wp, write, 0))
677 if rfile.unary:
678 wens.append(addr_en)
679 else:
680 addrs.append(addr_en)
681 wens.append(wp)
682
683 # connect regfile port to input
684 print("reg connect widths",
685 regfile, regname, pi, funame,
686 dest.shape(), wport.i_data.shape())
687 wsigs.append(fu_dest_latch)
688
689 # now connect up the bitvector write hazard
690 if not self.make_hazard_vecs:
691 continue
692 res = self.make_hazards(m, regfile, rfile, wvclr, wvset,
693 funame, regname, idx,
694 addr_en, wp, fu, fu_active,
695 wrflags[i], write, fu_wrok)
696 wvaddr_en, wv_issue_en = res
697 wvclren.append(wvaddr_en) # set only: no data => clear bit
698 wvseten.append(wv_issue_en) # set data same as enable
699 wvsets.append(wv_issue_en) # because enable needs a 1
700
701 # here is where we create the Write Broadcast Bus. simple, eh?
702 comb += wport.i_data.eq(ortreereduce_sig(wsigs))
703 if rfile.unary:
704 # for unary-addressed
705 comb += wport.wen.eq(ortreereduce_sig(wens))
706 else:
707 # for binary-addressed
708 comb += wport.addr.eq(ortreereduce_sig(addrs))
709 comb += wport.wen.eq(ortreereduce_sig(wens))
710
711 if not self.make_hazard_vecs:
712 return
713
714 # for write-vectors
715 comb += wvclr.wen.eq(ortreereduce_sig(wvclren)) # clear (regfile write)
716 comb += wvset.wen.eq(ortreereduce_sig(wvseten)) # set (issue time)
717 comb += wvset.i_data.eq(ortreereduce_sig(wvsets))
718
719 def connect_wrports(self, m, fu_bitdict):
720 """connect write ports
721
722 orders the write regspecs into a dict-of-dicts, by regfile,
723 by regport name, then connects all FUs that want that regport
724 by way of a PriorityPicker.
725
726 note that the write-port wen, write-port data, and go_wr_i all need to
727 be on the exact same clock cycle. as there is a combinatorial loop bug
728 at the moment, these all use sync.
729 """
730 comb, sync = m.d.comb, m.d.sync
731 fus = self.fus.fus
732 regs = self.regs
733 # dictionary of lists of regfile write ports
734 byregfiles_wr, byregfiles_wrspec = self.get_byregfiles(False)
735
736 # same for write ports.
737 # BLECH! complex code-duplication! BLECH!
738 wrpickers = {}
739 for regfile, spec in byregfiles_wr.items():
740 fuspecs = byregfiles_wrspec[regfile]
741 wrpickers[regfile] = {}
742
743 if self.regreduce_en:
744 # argh, more port-merging
745 if regfile == 'INT':
746 fuspecs['o'] = [fuspecs.pop('o')]
747 fuspecs['o'].append(fuspecs.pop('o1'))
748 if regfile == 'FAST':
749 fuspecs['fast1'] = [fuspecs.pop('fast1')]
750 if 'fast2' in fuspecs:
751 fuspecs['fast1'].append(fuspecs.pop('fast2'))
752 if 'fast3' in fuspecs:
753 fuspecs['fast1'].append(fuspecs.pop('fast3'))
754
755 for (regname, fspec) in sort_fuspecs(fuspecs):
756 self.connect_wrport(m, fu_bitdict, wrpickers,
757 regfile, regname, fspec)
758
759 def get_byregfiles(self, readmode):
760
761 mode = "read" if readmode else "write"
762 regs = self.regs
763 fus = self.fus.fus
764 e = self.i.e # decoded instruction to execute
765
766 # dictionary of lists of regfile ports
767 byregfiles = {}
768 byregfiles_spec = {}
769 for (funame, fu) in fus.items():
770 print("%s ports for %s" % (mode, funame))
771 for idx in range(fu.n_src if readmode else fu.n_dst):
772 if readmode:
773 (regfile, regname, wid) = fu.get_in_spec(idx)
774 else:
775 (regfile, regname, wid) = fu.get_out_spec(idx)
776 print(" %d %s %s %s" % (idx, regfile, regname, str(wid)))
777 if readmode:
778 rdflag, read = regspec_decode_read(e, regfile, regname)
779 wrport, write = None, None
780 else:
781 rdflag, read = None, None
782 wrport, write = regspec_decode_write(e, regfile, regname)
783 if regfile not in byregfiles:
784 byregfiles[regfile] = {}
785 byregfiles_spec[regfile] = {}
786 if regname not in byregfiles_spec[regfile]:
787 byregfiles_spec[regfile][regname] = \
788 (rdflag, wrport, read, write, wid, [])
789 # here we start to create "lanes"
790 if idx not in byregfiles[regfile]:
791 byregfiles[regfile][idx] = []
792 fuspec = (funame, fu, idx)
793 byregfiles[regfile][idx].append(fuspec)
794 byregfiles_spec[regfile][regname][5].append(fuspec)
795
796 # ok just print that out, for convenience
797 for regfile, spec in byregfiles.items():
798 print("regfile %s ports:" % mode, regfile)
799 fuspecs = byregfiles_spec[regfile]
800 for regname, fspec in fuspecs.items():
801 [rdflag, wrflag, read, write, wid, fuspec] = fspec
802 print(" rf %s port %s lane: %s" % (mode, regfile, regname))
803 print(" %s" % regname, wid, read, write, rdflag, wrflag)
804 for (funame, fu, idx) in fuspec:
805 fusig = fu.src_i[idx] if readmode else fu.dest[idx]
806 print(" ", funame, fu.__class__.__name__, idx, fusig)
807 print()
808
809 return byregfiles, byregfiles_spec
810
811 def __iter__(self):
812 yield from self.fus.ports()
813 yield from self.i.e.ports()
814 yield from self.l0.ports()
815 # TODO: regs
816
817 def ports(self):
818 return list(self)
819
820
821 if __name__ == '__main__':
822 pspec = TestMemPspec(ldst_ifacetype='testpi',
823 imem_ifacetype='',
824 addr_wid=48,
825 mask_wid=8,
826 reg_wid=64)
827 dut = NonProductionCore(pspec)
828 vl = rtlil.convert(dut, ports=dut.ports())
829 with open("test_core.il", "w") as f:
830 f.write(vl)