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