9efcf1c93c6ad12419d39bdb9fcd40088e89bc6e
[openpower-isa.git] / src / openpower / sv / trans / svp64.py
1 # SPDX-License-Identifier: LGPLv3+
2 # Copyright (C) 2021 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
3 # Funded by NLnet http://nlnet.nl
4
5 """SVP64 OpenPOWER v3.0B assembly translator
6
7 This class takes raw svp64 assembly mnemonics (aliases excluded) and creates
8 an EXT001-encoded "svp64 prefix" (as a .long) followed by a v3.0B opcode.
9
10 It is very simple and straightforward, the only weirdness being the
11 extraction of the register information and conversion to v3.0B numbering.
12
13 Encoding format of svp64: https://libre-soc.org/openpower/sv/svp64/
14 Encoding format of arithmetic: https://libre-soc.org/openpower/sv/normal/
15 Encoding format of LDST: https://libre-soc.org/openpower/sv/ldst/
16 **TODO format of branches: https://libre-soc.org/openpower/sv/branches/**
17 **TODO format of CRs: https://libre-soc.org/openpower/sv/cr_ops/**
18 Bugtracker: https://bugs.libre-soc.org/show_bug.cgi?id=578
19 """
20
21 import functools
22 import os
23 import sys
24 from collections import OrderedDict
25
26 from openpower.decoder.isa.caller import (SVP64PrefixFields, SV64P_MAJOR_SIZE,
27 SV64P_PID_SIZE, SVP64RMFields,
28 SVP64RM_EXTRA2_SPEC_SIZE,
29 SVP64RM_EXTRA3_SPEC_SIZE,
30 SVP64RM_MODE_SIZE,
31 SVP64RM_SMASK_SIZE,
32 SVP64RM_MMODE_SIZE,
33 SVP64RM_MASK_SIZE,
34 SVP64RM_SUBVL_SIZE,
35 SVP64RM_EWSRC_SIZE,
36 SVP64RM_ELWIDTH_SIZE)
37 from openpower.decoder.pseudo.pagereader import ISA
38 from openpower.decoder.power_svp64 import SVP64RM, get_regtype, decode_extra
39 from openpower.decoder.selectable_int import SelectableInt
40 from openpower.consts import SVP64MODE
41
42 # for debug logging
43 from openpower.util import log
44
45
46 def instruction(*fields):
47 def instruction(insn, desc):
48 (value, start, end) = desc
49 bits = ((1,) * ((end + 1) - start))
50 mask = 0
51 for bit in bits:
52 mask = ((mask << 1) | bit)
53 return (insn | ((value & mask) << (31 - end)))
54
55 return functools.reduce(instruction, fields, 0)
56
57
58 def setvl(fields, Rc):
59 """
60 setvl is a *32-bit-only* instruction. It controls SVSTATE.
61 It is *not* a 64-bit-prefixed Vector instruction (no sv.setvl, yet),
62 it is a Vector *control* instruction.
63
64 * setvl RT,RA,SVi,vf,vs,ms
65
66 1.6.28 SVL-FORM - from fields.txt
67 |0 |6 |11 |16 |23 |24 |25 |26 |31 |
68 | PO | RT | RA | SVi |ms |vs |vf | XO |Rc |
69 """
70 PO = 22
71 XO = 0b11011
72 # ARRRGH these are in a non-obvious order in openpower/isa/simplev.mdwn
73 # compared to the SVL-Form above. sigh
74 # setvl RT,RA,SVi,vf,vs,ms
75 (RT, RA, SVi, vf, vs, ms) = fields
76 SVi -= 1
77 return instruction(
78 (PO , 0 , 5),
79 (RT , 6 , 10),
80 (RA , 11, 15),
81 (SVi, 16, 22),
82 (ms , 23, 23),
83 (vs , 24, 24),
84 (vf , 25, 25),
85 (XO , 26, 30),
86 (Rc , 31, 31),
87 )
88
89
90 def svstep(fields, Rc):
91 """
92 svstep is a 32-bit instruction. It updates SVSTATE.
93 It *can* be SVP64-prefixed, to indicate that its registers
94 are Vectorised.
95
96 * svstep RT,SVi,vf
97
98 # 1.6.28 SVL-FORM - from fields.txt
99 # |0 |6 |11 |16 |23 |24 |25 |26 |31 |
100 # | PO | RT | / | SVi |/ |/ |vf | XO |Rc |
101
102 """
103 PO = 22
104 XO = 0b10011
105 (RT, SVi, vf) = fields
106 SVi -= 1
107 return instruction(
108 (PO , 0 , 5),
109 (RT , 6 , 10),
110 (0 , 11, 15),
111 (SVi, 16, 22),
112 (0 , 23, 23),
113 (0 , 24, 24),
114 (vf , 25, 25),
115 (XO , 26, 30),
116 (Rc , 31, 31),
117 )
118
119
120 def svshape(fields):
121 """
122 svshape is a *32-bit-only* instruction. It updates SVSHAPE and SVSTATE.
123 It is *not* a 64-bit-prefixed Vector instruction (no sv.svshape, yet),
124 it is a Vector *control* instruction.
125
126 * svshape SVxd,SVyd,SVzd,SVrm,vf
127
128 # 1.6.33 SVM-FORM from fields.txt
129 # |0 |6 |11 |16 |21 |25 |26 |31 |
130 # | PO | SVxd | SVyd | SVzd | SVrm |vf | XO |
131
132 """
133 PO = 22
134 XO = 0b011001
135 (SVxd, SVyd, SVzd, SVrm, vf) = fields
136 SVxd -= 1
137 SVyd -= 1
138 SVzd -= 1
139 return instruction(
140 (PO , 0 , 5),
141 (SVxd, 6 , 10),
142 (SVyd, 11, 15),
143 (SVzd, 16, 20),
144 (SVrm, 21, 24),
145 (vf , 25, 25),
146 (XO , 26, 31),
147 )
148
149
150 def svindex(fields):
151 """
152 svindex is a *32-bit-only* instruction. It is a convenience
153 instruction that reduces instruction count for Indexed REMAP
154 Mode.
155 It is *not* a 64-bit-prefixed Vector instruction (no sv.svindex, yet),
156 it is a Vector *control* instruction.
157
158 1.6.28 SVI-FORM
159 |0 |6 |11 |16 |21 |23|24|25|26 31|
160 | PO | RS |rmm | SVd |ew |yx|mm|sk| XO |
161 """
162 # note that the dimension field one subtracted
163 PO = 22
164 XO = 0b101001
165 (RS, rmm, SVd, ew, yx, mm, sk) = fields
166 SVd -= 1
167 return instruction(
168 (PO , 0 , 5),
169 (RS , 6 , 10),
170 (rmm, 11 , 15),
171 (SVd, 16 , 20),
172 (ew , 21 , 22),
173 (yx , 23 , 23),
174 (mm , 24 , 24),
175 (sk , 25 , 25),
176 (XO , 26 , 31),
177 )
178
179
180 def svremap(fields):
181 """
182 this is a *32-bit-only* instruction. It updates the SVSHAPE SPR
183 it is *not* a 64-bit-prefixed Vector instruction (no sv.svremap),
184 it is a Vector *control* instruction.
185
186 * svremap SVme,mi0,mi1,mi2,mo0,mo1,pst
187
188 # 1.6.34 SVRM-FORM
189 |0 |6 |11 |13 |15 |17 |19 |21 |22 |26 |31 |
190 | PO | SVme |mi0 | mi1 | mi2 | mo0 | mo1 |pst |/// | XO |
191
192 """
193 PO = 22
194 XO = 0b111001
195 (SVme, mi0, mi1, mi2, mo0, mo1, pst) = fields
196 return instruction(
197 (PO , 0 , 5),
198 (SVme, 6 , 10),
199 (mi0 , 11, 12),
200 (mi1 , 13, 14),
201 (mi2 , 15, 16),
202 (mo0 , 17, 18),
203 (mo1 , 19, 20),
204 (pst , 21, 21),
205 (0 , 22, 25),
206 (XO , 26, 31),
207 )
208
209
210 # ok from here-on down these are added as 32-bit instructions
211 # and are here only because binutils (at present) doesn't have
212 # them (that's being fixed!)
213 # they can - if implementations then choose - be Vectorised
214 # because they are general-purpose scalar instructions
215 def bmask(fields):
216 """
217 1.6.2.2 BM2-FORM
218 |0 |6 |11 |16 |21 |26 |27 31|
219 | PO | RT | RA | RB |bm |L | XO |
220 """
221 PO = 22
222 XO = 0b010001
223 (RT, RA, RB, bm, L) = fields
224 return instruction(
225 (PO, 0 , 5),
226 (RT, 6 , 10),
227 (RA, 11, 15),
228 (RB, 16, 20),
229 (bm, 21, 25),
230 (L , 26, 26),
231 (XO, 27, 31),
232 )
233
234
235 def fsins(fields, Rc):
236 # XXX WARNING THESE ARE NOT APPROVED BY OPF ISA WG
237 # however we are out of space with opcode 22
238 # 1.6.7 X-FORM
239 # |0 |6 |7|8|9 |10 |11|12|13 |15|16|17 |20|21 |31 |
240 # | PO | FRT | /// | FRB | XO |Rc |
241 PO = 59
242 XO = 0b1000001110
243 (FRT, FRB) = fields
244 return instruction(
245 (PO , 0 , 5),
246 (FRT, 6 , 10),
247 (0 , 11, 15),
248 (FRB, 16, 20),
249 (XO , 21, 30),
250 (Rc , 31, 31),
251 )
252
253
254 def fcoss(fields, Rc):
255 # XXX WARNING THESE ARE NOT APPROVED BY OPF ISA WG
256 # however we are out of space with opcode 22
257 # 1.6.7 X-FORM
258 # |0 |6 |7|8|9 |10 |11|12|13 |15|16|17 |20|21 |31 |
259 # | PO | FRT | /// | FRB | XO |Rc |
260 PO = 59
261 XO = 0b1000101110
262 (FRT, FRB) = fields
263 return instruction(
264 (PO , 0 , 5),
265 (FRT, 6 , 10),
266 (0 , 11, 15),
267 (FRB, 16, 20),
268 (XO , 21, 30),
269 (Rc , 31, 31),
270 )
271
272
273 def ternlogi(fields, Rc):
274 # XXX WARNING THESE ARE NOT APPROVED BY OPF ISA WG
275 # however we are out of space with opcode 22
276 # 1.6.34 TLI-FORM
277 # |0 |6 |11 |16 |21 |29 |31 |
278 # | PO | RT | RA | RB | TLI | XO |Rc |
279 PO = 5
280 XO = 0
281 (RT, RA, RB, TLI) = fields
282 return instruction(
283 (PO , 0 , 5),
284 (RT , 6 , 10),
285 (RA , 11, 15),
286 (RB , 16, 20),
287 (TLI, 21, 28),
288 (XO , 29, 30),
289 (Rc , 31, 31),
290 )
291
292
293 def grev(fields, Rc, imm, wide):
294 # XXX WARNING THESE ARE NOT APPROVED BY OPF ISA WG
295 # however we are out of space with opcode 22
296 PO = 5
297 # _ matches fields in table at:
298 # https://libre-soc.org/openPOwer/sv/bitmanip/
299 XO = 0b1_0010_110
300 if wide:
301 XO |= 0b100_000
302 if imm:
303 XO |= 0b1000_000
304 (RT, RA, XBI) = fields
305 insn = (insn << 5) | RT
306 insn = (insn << 5) | RA
307 if imm and not wide:
308 assert 0 <= XBI < 64
309 insn = (insn << 6) | XBI
310 insn = (insn << 9) | XO
311 else:
312 assert 0 <= XBI < 32
313 insn = (insn << 5) | XBI
314 insn = (insn << 10) | XO
315 insn = (insn << 1) | Rc
316 return insn
317
318
319 def av(fields, XO, Rc):
320 # 1.6.7 X-FORM
321 # |0 |6 |7|8|9 |10 |11|12|13 |15|16|17 |20|21 |31 |
322 # | PO | RT | RA | RB | XO |Rc |
323 PO = 22
324 (RT, RA, RB) = fields
325 return instruction(
326 (PO, 0 , 5),
327 (RT, 6 , 10),
328 (RA, 11, 15),
329 (RB, 16, 20),
330 (XO, 21, 30),
331 (Rc, 31, 31),
332 )
333
334
335 CUSTOM_INSNS = {}
336 for (name, hook) in (
337 ("setvl", setvl),
338 ("svstep", svstep),
339 ("fsins", fsins),
340 ("fcoss", fcoss),
341 ("ternlogi", ternlogi),
342 ):
343 CUSTOM_INSNS[name] = functools.partial(hook, Rc=False)
344 CUSTOM_INSNS[f"{name}."] = functools.partial(hook, Rc=True)
345 CUSTOM_INSNS["bmask"] = bmask
346 CUSTOM_INSNS["svshape"] = svshape
347 CUSTOM_INSNS["svindex"] = svindex
348 CUSTOM_INSNS["svremap"] = svremap
349
350 for (name, imm, wide) in (
351 ("grev", False, False),
352 ("grevi", True, False),
353 ("grevw", False, True),
354 ("grevwi", True, True),
355 ):
356 CUSTOM_INSNS[name] = functools.partial(grev,
357 imm=("i" in name), wide=("w" in name), Rc=False)
358 CUSTOM_INSNS[f"{name}."] = functools.partial(grev,
359 imm=("i" in name), wide=("w" in name), Rc=True)
360
361 for (name, XO) in (
362 ("maxs" , 0b0111001110),
363 ("maxu" , 0b0011001110),
364 ("minu" , 0b0001001110),
365 ("mins" , 0b0101001110),
366 ("absdu" , 0b1011110110),
367 ("absds" , 0b1001110110),
368 ("avgadd" , 0b1101001110),
369 ("absdacu", 0b1111110110),
370 ("absdacs", 0b0111110110),
371 ("cprop" , 0b0110001110),
372 ):
373 CUSTOM_INSNS[name] = functools.partial(av, XO=XO, Rc=False)
374 CUSTOM_INSNS[f"{name}."] = functools.partial(av, XO=XO, Rc=True)
375
376
377 # decode GPR into sv extra
378 def get_extra_gpr(etype, regmode, field):
379 if regmode == 'scalar':
380 # cut into 2-bits 5-bits SS FFFFF
381 sv_extra = field >> 5
382 field = field & 0b11111
383 else:
384 # cut into 5-bits 2-bits FFFFF SS
385 sv_extra = field & 0b11
386 field = field >> 2
387 return sv_extra, field
388
389
390 # decode 3-bit CR into sv extra
391 def get_extra_cr_3bit(etype, regmode, field):
392 if regmode == 'scalar':
393 # cut into 2-bits 3-bits SS FFF
394 sv_extra = field >> 3
395 field = field & 0b111
396 else:
397 # cut into 3-bits 4-bits FFF SSSS but will cut 2 zeros off later
398 sv_extra = field & 0b1111
399 field = field >> 4
400 return sv_extra, field
401
402
403 # decodes SUBVL
404 def decode_subvl(encoding):
405 pmap = {'2': 0b01, '3': 0b10, '4': 0b11}
406 assert encoding in pmap, \
407 "encoding %s for SUBVL not recognised" % encoding
408 return pmap[encoding]
409
410
411 # decodes elwidth
412 def decode_elwidth(encoding):
413 pmap = {'8': 0b11, '16': 0b10, '32': 0b01}
414 assert encoding in pmap, \
415 "encoding %s for elwidth not recognised" % encoding
416 return pmap[encoding]
417
418
419 # decodes predicate register encoding
420 def decode_predicate(encoding):
421 pmap = { # integer
422 '1<<r3': (0, 0b001),
423 'r3': (0, 0b010),
424 '~r3': (0, 0b011),
425 'r10': (0, 0b100),
426 '~r10': (0, 0b101),
427 'r30': (0, 0b110),
428 '~r30': (0, 0b111),
429 # CR
430 'lt': (1, 0b000),
431 'nl': (1, 0b001), 'ge': (1, 0b001), # same value
432 'gt': (1, 0b010),
433 'ng': (1, 0b011), 'le': (1, 0b011), # same value
434 'eq': (1, 0b100),
435 'ne': (1, 0b101),
436 'so': (1, 0b110), 'un': (1, 0b110), # same value
437 'ns': (1, 0b111), 'nu': (1, 0b111), # same value
438 }
439 assert encoding in pmap, \
440 "encoding %s for predicate not recognised" % encoding
441 return pmap[encoding]
442
443
444 # decodes "Mode" in similar way to BO field (supposed to, anyway)
445 def decode_bo(encoding):
446 pmap = { # TODO: double-check that these are the same as Branch BO
447 'lt': 0b000,
448 'nl': 0b001, 'ge': 0b001, # same value
449 'gt': 0b010,
450 'ng': 0b011, 'le': 0b011, # same value
451 'eq': 0b100,
452 'ne': 0b101,
453 'so': 0b110, 'un': 0b110, # same value
454 'ns': 0b111, 'nu': 0b111, # same value
455 }
456 assert encoding in pmap, \
457 "encoding %s for BO Mode not recognised" % encoding
458 return pmap[encoding]
459
460 # partial-decode fail-first mode
461
462
463 def decode_ffirst(encoding):
464 if encoding in ['RC1', '~RC1']:
465 return encoding
466 return decode_bo(encoding)
467
468
469 def decode_reg(field):
470 # decode the field number. "5.v" or "3.s" or "9"
471 # and now also "*0", and "*%0". note: *NOT* to add "*%rNNN" etc.
472 # https://bugs.libre-soc.org/show_bug.cgi?id=884#c0
473 field = field.split(".")
474 regmode = 'scalar' # default
475 if len(field) == 2:
476 if field[1] == 's':
477 regmode = 'scalar'
478 elif field[1] == 'v':
479 regmode = 'vector'
480 field = int(field[0]) # actual register number
481 return field, regmode
482
483
484 def decode_imm(field):
485 ldst_imm = "(" in field and field[-1] == ')'
486 if ldst_imm:
487 return field[:-1].split("(")
488 else:
489 return None, field
490
491
492 def crf_extra(etype, regmode, field, extras):
493 """takes a CR Field number (CR0-CR127), splits into EXTRA2/3 and v3.0
494 the scalar/vector mode (crNN.v or crNN.s) changes both the format
495 of the EXTRA2/3 encoding as well as what range of registers is possible.
496 this function can be used for both BF/BFA and BA/BB/BT by first removing
497 the bottom 2 bits of BA/BB/BT then re-instating them after encoding.
498 see https://libre-soc.org/openpower/sv/svp64/appendix/#cr_extra
499 for specification
500 """
501 sv_extra, field = get_extra_cr_3bit(etype, regmode, field)
502 # now sanity-check (and shrink afterwards)
503 if etype == 'EXTRA2':
504 # 3-bit CR Field (BF, BFA) EXTRA2 encoding
505 if regmode == 'scalar':
506 # range is CR0-CR15 in increments of 1
507 assert (sv_extra >> 1) == 0, \
508 "scalar CR %s cannot fit into EXTRA2 %s" % \
509 (rname, str(extras[extra_idx]))
510 # all good: encode as scalar
511 sv_extra = sv_extra & 0b01
512 else: # vector
513 # range is CR0-CR127 in increments of 16
514 assert sv_extra & 0b111 == 0, \
515 "vector CR %s cannot fit into EXTRA2 %s" % \
516 (rname, str(extras[extra_idx]))
517 # all good: encode as vector (bit 2 set)
518 sv_extra = 0b10 | (sv_extra >> 3)
519 else:
520 # 3-bit CR Field (BF, BFA) EXTRA3 encoding
521 if regmode == 'scalar':
522 # range is CR0-CR31 in increments of 1
523 assert (sv_extra >> 2) == 0, \
524 "scalar CR %s cannot fit into EXTRA3 %s" % \
525 (rname, str(extras[extra_idx]))
526 # all good: encode as scalar
527 sv_extra = sv_extra & 0b11
528 else: # vector
529 # range is CR0-CR127 in increments of 8
530 assert sv_extra & 0b11 == 0, \
531 "vector CR %s cannot fit into EXTRA3 %s" % \
532 (rname, str(extras[extra_idx]))
533 # all good: encode as vector (bit 3 set)
534 sv_extra = 0b100 | (sv_extra >> 2)
535 return sv_extra, field
536
537
538 # decodes svp64 assembly listings and creates EXT001 svp64 prefixes
539 class SVP64Asm:
540 def __init__(self, lst, bigendian=False, macros=None):
541 if macros is None:
542 macros = {}
543 self.macros = macros
544 self.lst = lst
545 self.trans = self.translate(lst)
546 self.isa = ISA() # reads the v3.0B pseudo-code markdown files
547 self.svp64 = SVP64RM() # reads the svp64 Remap entries for registers
548 assert bigendian == False, "error, bigendian not supported yet"
549
550 def __iter__(self):
551 yield from self.trans
552
553 def translate_one(self, insn, macros=None):
554 if macros is None:
555 macros = {}
556 macros.update(self.macros)
557 isa = self.isa
558 svp64 = self.svp64
559 # find first space, to get opcode
560 ls = insn.split(' ')
561 opcode = ls[0]
562 # now find opcode fields
563 fields = ''.join(ls[1:]).split(',')
564 mfields = list(map(str.strip, fields))
565 log("opcode, fields", ls, opcode, mfields)
566 fields = []
567 # macro substitution
568 for field in mfields:
569 fields.append(macro_subst(macros, field))
570 log("opcode, fields substed", ls, opcode, fields)
571
572 # identify if it is a special instruction
573 custom_insn_hook = CUSTOM_INSNS.get(opcode)
574 if custom_insn_hook is not None:
575 fields = tuple(map(int, fields))
576 insn = custom_insn_hook(fields)
577 log(opcode, bin(insn))
578 yield ".long 0x%x" % insn
579 return
580
581 # identify if is a svp64 mnemonic
582 if not opcode.startswith('sv.'):
583 yield insn # unaltered
584 return
585 opcode = opcode[3:] # strip leading "sv"
586
587 # start working on decoding the svp64 op: sv.basev30Bop/vec2/mode
588 opmodes = opcode.split("/") # split at "/"
589 v30b_op = opmodes.pop(0) # first is the v3.0B
590 # check instruction ends with dot
591 rc_mode = v30b_op.endswith('.')
592 if rc_mode:
593 v30b_op = v30b_op[:-1]
594
595 # sigh again, have to recognised LD/ST bit-reverse instructions
596 # this has to be "processed" to fit into a v3.0B without the "sh"
597 # e.g. ldsh is actually ld
598 ldst_shift = v30b_op.startswith("l") and v30b_op.endswith("sh")
599
600 if v30b_op not in isa.instr:
601 raise Exception("opcode %s of '%s' not supported" %
602 (v30b_op, insn))
603
604 if ldst_shift:
605 # okaay we need to process the fields and make this:
606 # ldsh RT, SVD(RA), RC - 11 bits for SVD, 5 for RC
607 # into this:
608 # ld RT, D(RA) - 16 bits
609 # likewise same for SVDS (9 bits for SVDS, 5 for RC, 14 bits for DS)
610 form = isa.instr[v30b_op].form # get form (SVD-Form, SVDS-Form)
611
612 newfields = []
613 for field in fields:
614 # identify if this is a ld/st immediate(reg) thing
615 ldst_imm = "(" in field and field[-1] == ')'
616 if ldst_imm:
617 newfields.append(field[:-1].split("("))
618 else:
619 newfields.append(field)
620
621 immed, RA = newfields[1]
622 immed = int(immed)
623 RC = int(newfields.pop(2)) # better be an integer number!
624 if form == 'SVD': # 16 bit: immed 11 bits, RC shift up 11
625 immed = (immed & 0b11111111111) | (RC << 11)
626 if immed & (1 << 15): # should be negative
627 immed -= 1 << 16
628 if form == 'SVDS': # 14 bit: immed 9 bits, RC shift up 9
629 immed = (immed & 0b111111111) | (RC << 9)
630 if immed & (1 << 13): # should be negative
631 immed -= 1 << 14
632 newfields[1] = "%d(%s)" % (immed, RA)
633 fields = newfields
634
635 # and strip off "sh" from end, and add "sh" to opmodes, instead
636 v30b_op = v30b_op[:-2]
637 opmodes.append("sh")
638 log("rewritten", v30b_op, opmodes, fields)
639
640 if v30b_op not in svp64.instrs:
641 raise Exception("opcode %s of '%s' not an svp64 instruction" %
642 (v30b_op, insn))
643 v30b_regs = isa.instr[v30b_op].regs[0] # get regs info "RT, RA, RB"
644 rm = svp64.instrs[v30b_op] # one row of the svp64 RM CSV
645 log("v3.0B op", v30b_op, "Rc=1" if rc_mode else '')
646 log("v3.0B regs", opcode, v30b_regs)
647 log("RM", rm)
648
649 # right. the first thing to do is identify the ordering of
650 # the registers, by name. the EXTRA2/3 ordering is in
651 # rm['0']..rm['3'] but those fields contain the names RA, BB
652 # etc. we have to read the pseudocode to understand which
653 # reg is which in our instruction. sigh.
654
655 # first turn the svp64 rm into a "by name" dict, recording
656 # which position in the RM EXTRA it goes into
657 # also: record if the src or dest was a CR, for sanity-checking
658 # (elwidth overrides on CRs are banned)
659 decode = decode_extra(rm)
660 dest_reg_cr, src_reg_cr, svp64_src, svp64_dest = decode
661
662 log("EXTRA field index, src", svp64_src)
663 log("EXTRA field index, dest", svp64_dest)
664
665 # okaaay now we identify the field value (opcode N,N,N) with
666 # the pseudo-code info (opcode RT, RA, RB)
667 assert len(fields) == len(v30b_regs), \
668 "length of fields %s must match insn `%s` fields %s" % \
669 (str(v30b_regs), insn, str(fields))
670 opregfields = zip(fields, v30b_regs) # err that was easy
671
672 # now for each of those find its place in the EXTRA encoding
673 # note there is the possibility (for LD/ST-with-update) of
674 # RA occurring **TWICE**. to avoid it getting added to the
675 # v3.0B suffix twice, we spot it as a duplicate, here
676 extras = OrderedDict()
677 for idx, (field, regname) in enumerate(opregfields):
678 imm, regname = decode_imm(regname)
679 rtype = get_regtype(regname)
680 log(" idx find", rtype, idx, field, regname, imm)
681 if rtype is None:
682 # probably an immediate field, append it straight
683 extras[('imm', idx, False)] = (idx, field, None, None, None)
684 continue
685 extra = svp64_src.get(regname, None)
686 if extra is not None:
687 extra = ('s', extra, False) # not a duplicate
688 extras[extra] = (idx, field, regname, rtype, imm)
689 log(" idx src", idx, extra, extras[extra])
690 dextra = svp64_dest.get(regname, None)
691 log("regname in", regname, dextra)
692 if dextra is not None:
693 is_a_duplicate = extra is not None # duplicate spotted
694 dextra = ('d', dextra, is_a_duplicate)
695 extras[dextra] = (idx, field, regname, rtype, imm)
696 log(" idx dst", idx, extra, extras[dextra])
697
698 # great! got the extra fields in their associated positions:
699 # also we know the register type. now to create the EXTRA encodings
700 etype = rm['Etype'] # Extra type: EXTRA3/EXTRA2
701 ptype = rm['Ptype'] # Predication type: Twin / Single
702 extra_bits = 0
703 v30b_newfields = []
704 for extra_idx, (idx, field, rname, rtype, iname) in extras.items():
705 # is it a field we don't alter/examine? if so just put it
706 # into newfields
707 if rtype is None:
708 v30b_newfields.append(field)
709 continue
710
711 # identify if this is a ld/st immediate(reg) thing
712 ldst_imm = "(" in field and field[-1] == ')'
713 if ldst_imm:
714 immed, field = field[:-1].split("(")
715
716 field, regmode = decode_reg(field)
717 log(" ", extra_idx, rname, rtype,
718 regmode, iname, field, end=" ")
719
720 # see Mode field https://libre-soc.org/openpower/sv/svp64/
721 # XXX TODO: the following is a bit of a laborious repeated
722 # mess, which could (and should) easily be parameterised.
723 # XXX also TODO: the LD/ST modes which are different
724 # https://libre-soc.org/openpower/sv/ldst/
725
726 # rright. SVP64 register numbering is from 0 to 127
727 # for GPRs, FPRs *and* CR Fields, where for v3.0 the GPRs and RPFs
728 # are 0-31 and CR Fields are only 0-7. the SVP64 RM "Extra"
729 # area is used to extend the numbering from the 32-bit
730 # instruction, and also to record whether the register
731 # is scalar or vector. on a per-operand basis. this
732 # results in a slightly finnicky encoding: here we go...
733
734 # encode SV-GPR and SV-FPR field into extra, v3.0field
735 if rtype in ['GPR', 'FPR']:
736 sv_extra, field = get_extra_gpr(etype, regmode, field)
737 # now sanity-check. EXTRA3 is ok, EXTRA2 has limits
738 # (and shrink to a single bit if ok)
739 if etype == 'EXTRA2':
740 if regmode == 'scalar':
741 # range is r0-r63 in increments of 1
742 assert (sv_extra >> 1) == 0, \
743 "scalar GPR %s cannot fit into EXTRA2 %s" % \
744 (rname, str(extras[extra_idx]))
745 # all good: encode as scalar
746 sv_extra = sv_extra & 0b01
747 else:
748 # range is r0-r127 in increments of 2 (r0 r2 ... r126)
749 assert sv_extra & 0b01 == 0, \
750 "%s: vector field %s cannot fit " \
751 "into EXTRA2 %s" % \
752 (insn, rname, str(extras[extra_idx]))
753 # all good: encode as vector (bit 2 set)
754 sv_extra = 0b10 | (sv_extra >> 1)
755 elif regmode == 'vector':
756 # EXTRA3 vector bit needs marking
757 sv_extra |= 0b100
758
759 # encode SV-CR 3-bit field into extra, v3.0field.
760 # 3-bit is for things like BF and BFA
761 elif rtype == 'CR_3bit':
762 sv_extra, field = crf_extra(etype, regmode, field, extras)
763
764 # encode SV-CR 5-bit field into extra, v3.0field
765 # 5-bit is for things like BA BB BC BT etc.
766 # *sigh* this is the same as 3-bit except the 2 LSBs of the
767 # 5-bit field are passed through unaltered.
768 elif rtype == 'CR_5bit':
769 cr_subfield = field & 0b11 # record bottom 2 bits for later
770 field = field >> 2 # strip bottom 2 bits
771 # use the exact same 3-bit function for the top 3 bits
772 sv_extra, field = crf_extra(etype, regmode, field, extras)
773 # reconstruct the actual 5-bit CR field (preserving the
774 # bottom 2 bits, unaltered)
775 field = (field << 2) | cr_subfield
776
777 else:
778 raise Exception("no type match: %s" % rtype)
779
780 # capture the extra field info
781 log("=>", "%5s" % bin(sv_extra), field)
782 extras[extra_idx] = sv_extra
783
784 # append altered field value to v3.0b, differs for LDST
785 # note that duplicates are skipped e.g. EXTRA2 contains
786 # *BOTH* s:RA *AND* d:RA which happens on LD/ST-with-update
787 srcdest, idx, duplicate = extra_idx
788 if duplicate: # skip adding to v3.0b fields, already added
789 continue
790 if ldst_imm:
791 v30b_newfields.append(("%s(%s)" % (immed, str(field))))
792 else:
793 v30b_newfields.append(str(field))
794
795 log("new v3.0B fields", v30b_op, v30b_newfields)
796 log("extras", extras)
797
798 # rright. now we have all the info. start creating SVP64 RM
799 svp64_rm = SVP64RMFields()
800
801 # begin with EXTRA fields
802 for idx, sv_extra in extras.items():
803 log(idx)
804 if idx is None:
805 continue
806 if idx[0] == 'imm':
807 continue
808 srcdest, idx, duplicate = idx
809 if etype == 'EXTRA2':
810 svp64_rm.extra2[idx].eq(
811 SelectableInt(sv_extra, SVP64RM_EXTRA2_SPEC_SIZE))
812 else:
813 svp64_rm.extra3[idx].eq(
814 SelectableInt(sv_extra, SVP64RM_EXTRA3_SPEC_SIZE))
815
816 # identify if the op is a LD/ST. the "blegh" way. copied
817 # from power_enums. TODO, split the list _insns down.
818 is_ld = v30b_op in [
819 "lbarx", "lbz", "lbzu", "lbzux", "lbzx", # load byte
820 "ld", "ldarx", "ldbrx", "ldu", "ldux", "ldx", # load double
821 "lfs", "lfsx", "lfsu", "lfsux", # FP load single
822 "lfd", "lfdx", "lfdu", "lfdux", "lfiwzx", "lfiwax", # FP load dbl
823 "lha", "lharx", "lhau", "lhaux", "lhax", # load half
824 "lhbrx", "lhz", "lhzu", "lhzux", "lhzx", # more load half
825 "lwa", "lwarx", "lwaux", "lwax", "lwbrx", # load word
826 "lwz", "lwzcix", "lwzu", "lwzux", "lwzx", # more load word
827 ]
828 is_st = v30b_op in [
829 "stb", "stbcix", "stbcx", "stbu", "stbux", "stbx",
830 "std", "stdbrx", "stdcx", "stdu", "stdux", "stdx",
831 "stfs", "stfsx", "stfsu", "stfux", # FP store sgl
832 "stfd", "stfdx", "stfdu", "stfdux", "stfiwx", # FP store dbl
833 "sth", "sthbrx", "sthcx", "sthu", "sthux", "sthx",
834 "stw", "stwbrx", "stwcx", "stwu", "stwux", "stwx",
835 ]
836 # use this to determine if the SVP64 RM format is different.
837 # see https://libre-soc.org/openpower/sv/ldst/
838 is_ldst = is_ld or is_st
839
840 # branch-conditional detection
841 is_bc = v30b_op in [
842 "bc", "bclr",
843 ]
844
845 # parts of svp64_rm
846 mmode = 0 # bit 0
847 pmask = 0 # bits 1-3
848 destwid = 0 # bits 4-5
849 srcwid = 0 # bits 6-7
850 subvl = 0 # bits 8-9
851 smask = 0 # bits 16-18 but only for twin-predication
852 mode = 0 # bits 19-23
853
854 mask_m_specified = False
855 has_pmask = False
856 has_smask = False
857
858 saturation = None
859 src_zero = 0
860 dst_zero = 0
861 sv_mode = None
862
863 mapreduce = False
864 reverse_gear = False
865 mapreduce_crm = False
866 mapreduce_svm = False
867
868 predresult = False
869 failfirst = False
870 ldst_elstride = 0
871
872 # branch-conditional bits
873 bc_all = 0
874 bc_lru = 0
875 bc_brc = 0
876 bc_svstep = 0
877 bc_vsb = 0
878 bc_vlset = 0
879 bc_vli = 0
880 bc_snz = 0
881
882 # ok let's start identifying opcode augmentation fields
883 for encmode in opmodes:
884 # predicate mask (src and dest)
885 if encmode.startswith("m="):
886 pme = encmode
887 pmmode, pmask = decode_predicate(encmode[2:])
888 smmode, smask = pmmode, pmask
889 mmode = pmmode
890 mask_m_specified = True
891 # predicate mask (dest)
892 elif encmode.startswith("dm="):
893 pme = encmode
894 pmmode, pmask = decode_predicate(encmode[3:])
895 mmode = pmmode
896 has_pmask = True
897 # predicate mask (src, twin-pred)
898 elif encmode.startswith("sm="):
899 sme = encmode
900 smmode, smask = decode_predicate(encmode[3:])
901 mmode = smmode
902 has_smask = True
903 # shifted LD/ST
904 elif encmode.startswith("sh"):
905 ldst_shift = True
906 # vec2/3/4
907 elif encmode.startswith("vec"):
908 subvl = decode_subvl(encmode[3:])
909 # elwidth
910 elif encmode.startswith("ew="):
911 destwid = decode_elwidth(encmode[3:])
912 elif encmode.startswith("sw="):
913 srcwid = decode_elwidth(encmode[3:])
914 # element-strided LD/ST
915 elif encmode == 'els':
916 ldst_elstride = 1
917 # saturation
918 elif encmode == 'sats':
919 assert sv_mode is None
920 saturation = 1
921 sv_mode = 0b10
922 elif encmode == 'satu':
923 assert sv_mode is None
924 sv_mode = 0b10
925 saturation = 0
926 # predicate zeroing
927 elif encmode == 'sz':
928 src_zero = 1
929 elif encmode == 'dz':
930 dst_zero = 1
931 # failfirst
932 elif encmode.startswith("ff="):
933 assert sv_mode is None
934 sv_mode = 0b01
935 failfirst = decode_ffirst(encmode[3:])
936 # predicate-result, interestingly same as fail-first
937 elif encmode.startswith("pr="):
938 assert sv_mode is None
939 sv_mode = 0b11
940 predresult = decode_ffirst(encmode[3:])
941 # map-reduce mode, reverse-gear
942 elif encmode == 'mrr':
943 assert sv_mode is None
944 sv_mode = 0b00
945 mapreduce = True
946 reverse_gear = True
947 # map-reduce mode
948 elif encmode == 'mr':
949 assert sv_mode is None
950 sv_mode = 0b00
951 mapreduce = True
952 elif encmode == 'crm': # CR on map-reduce
953 assert sv_mode is None
954 sv_mode = 0b00
955 mapreduce_crm = True
956 elif encmode == 'svm': # sub-vector mode
957 mapreduce_svm = True
958 elif is_bc:
959 if encmode == 'all':
960 bc_all = 1
961 elif encmode == 'st': # svstep mode
962 bc_step = 1
963 elif encmode == 'sr': # svstep BRc mode
964 bc_step = 1
965 bc_brc = 1
966 elif encmode == 'vs': # VLSET mode
967 bc_vlset = 1
968 elif encmode == 'vsi': # VLSET mode with VLI (VL inclusives)
969 bc_vlset = 1
970 bc_vli = 1
971 elif encmode == 'vsb': # VLSET mode with VSb
972 bc_vlset = 1
973 bc_vsb = 1
974 elif encmode == 'vsbi': # VLSET mode with VLI and VSb
975 bc_vlset = 1
976 bc_vli = 1
977 bc_vsb = 1
978 elif encmode == 'snz': # sz (only) already set above
979 src_zero = 1
980 bc_snz = 1
981 elif encmode == 'lu': # LR update mode
982 bc_lru = 1
983 else:
984 raise AssertionError("unknown encmode %s" % encmode)
985 else:
986 raise AssertionError("unknown encmode %s" % encmode)
987
988 if ptype == '2P':
989 # since m=xx takes precedence (overrides) sm=xx and dm=xx,
990 # treat them as mutually exclusive
991 if mask_m_specified:
992 assert not has_smask,\
993 "cannot have both source-mask and predicate mask"
994 assert not has_pmask,\
995 "cannot have both dest-mask and predicate mask"
996 # since the default is INT predication (ALWAYS), if you
997 # specify one CR mask, you must specify both, to avoid
998 # mixing INT and CR reg types
999 if has_pmask and pmmode == 1:
1000 assert has_smask, \
1001 "need explicit source-mask in CR twin predication"
1002 if has_smask and smmode == 1:
1003 assert has_pmask, \
1004 "need explicit dest-mask in CR twin predication"
1005 # sanity-check that 2Pred mask is same mode
1006 if has_pmask and has_smask:
1007 assert smmode == pmmode, \
1008 "predicate masks %s and %s must be same reg type" % \
1009 (pme, sme)
1010
1011 # sanity-check that twin-predication mask only specified in 2P mode
1012 if ptype == '1P':
1013 assert not has_smask, \
1014 "source-mask can only be specified on Twin-predicate ops"
1015 assert not has_pmask, \
1016 "dest-mask can only be specified on Twin-predicate ops"
1017
1018 # construct the mode field, doing sanity-checking along the way
1019 if mapreduce_svm:
1020 assert sv_mode == 0b00, "sub-vector mode in mapreduce only"
1021 assert subvl != 0, "sub-vector mode not possible on SUBVL=1"
1022
1023 if src_zero:
1024 assert has_smask or mask_m_specified, \
1025 "src zeroing requires a source predicate"
1026 if dst_zero:
1027 assert has_pmask or mask_m_specified, \
1028 "dest zeroing requires a dest predicate"
1029
1030 # check LDST shifted, only available in "normal" mode
1031 if is_ldst and ldst_shift:
1032 assert sv_mode is None, \
1033 "LD shift cannot have modes (%s) applied" % sv_mode
1034
1035 # okaaay, so there are 4 different modes, here, which will be
1036 # partly-merged-in: is_ldst is merged in with "normal", but
1037 # is_bc is so different it's done separately. likewise is_cr
1038 # (when it is done). here are the maps:
1039
1040 # for "normal" arithmetic: https://libre-soc.org/openpower/sv/normal/
1041 """
1042 | 0-1 | 2 | 3 4 | description |
1043 | --- | --- |---------|-------------------------- |
1044 | 00 | 0 | dz sz | normal mode |
1045 | 00 | 1 | 0 RG | scalar reduce mode (mapreduce), SUBVL=1 |
1046 | 00 | 1 | 1 / | parallel reduce mode (mapreduce), SUBVL=1 |
1047 | 00 | 1 | SVM RG | subvector reduce mode, SUBVL>1 |
1048 | 01 | inv | CR-bit | Rc=1: ffirst CR sel |
1049 | 01 | inv | VLi RC1 | Rc=0: ffirst z/nonz |
1050 | 10 | N | dz sz | sat mode: N=0/1 u/s |
1051 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
1052 | 11 | inv | dz RC1 | Rc=0: pred-result z/nonz |
1053 """
1054
1055 # https://libre-soc.org/openpower/sv/ldst/
1056 # for LD/ST-immediate:
1057 """
1058 | 0-1 | 2 | 3 4 | description |
1059 | --- | --- |---------|--------------------------- |
1060 | 00 | 0 | dz els | normal mode |
1061 | 00 | 1 | dz shf | shift mode |
1062 | 01 | inv | CR-bit | Rc=1: ffirst CR sel |
1063 | 01 | inv | els RC1 | Rc=0: ffirst z/nonz |
1064 | 10 | N | dz els | sat mode: N=0/1 u/s |
1065 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
1066 | 11 | inv | els RC1 | Rc=0: pred-result z/nonz |
1067 """
1068
1069 # for LD/ST-indexed (RA+RB):
1070 """
1071 | 0-1 | 2 | 3 4 | description |
1072 | --- | --- |---------|-------------------------- |
1073 | 00 | SEA | dz sz | normal mode |
1074 | 01 | SEA | dz sz | Strided (scalar only source) |
1075 | 10 | N | dz sz | sat mode: N=0/1 u/s |
1076 | 11 | inv | CR-bit | Rc=1: pred-result CR sel |
1077 | 11 | inv | dz RC1 | Rc=0: pred-result z/nonz |
1078 """
1079
1080 # and leaving out branches and cr_ops for now because they're
1081 # under development
1082 """ TODO branches and cr_ops
1083 """
1084
1085 # now create mode and (overridden) src/dst widths
1086 # XXX TODO: sanity-check bc modes
1087 if is_bc:
1088 sv_mode = ((bc_svstep << SVP64MODE.MOD2_MSB) |
1089 (bc_vlset << SVP64MODE.MOD2_LSB) |
1090 (bc_snz << SVP64MODE.BC_SNZ))
1091 srcwid = (bc_vsb << 1) | bc_lru
1092 destwid = (bc_lru << 1) | bc_all
1093
1094 else:
1095
1096 ######################################
1097 # "normal" mode
1098 if sv_mode is None:
1099 mode |= src_zero << SVP64MODE.SZ # predicate zeroing
1100 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
1101 if is_ldst:
1102 # TODO: for now, LD/ST-indexed is ignored.
1103 mode |= ldst_elstride << SVP64MODE.ELS_NORMAL # el-strided
1104 # shifted mode
1105 if ldst_shift:
1106 mode |= 1 << SVP64MODE.LDST_SHIFT
1107 else:
1108 # TODO, reduce and subvector mode
1109 # 00 1 dz CRM reduce mode (mapreduce), SUBVL=1
1110 # 00 1 SVM CRM subvector reduce mode, SUBVL>1
1111 pass
1112 sv_mode = 0b00
1113
1114 ######################################
1115 # "mapreduce" modes
1116 elif sv_mode == 0b00:
1117 mode |= (0b1 << SVP64MODE.REDUCE) # sets mapreduce
1118 assert dst_zero == 0, "dest-zero not allowed in mapreduce mode"
1119 if reverse_gear:
1120 mode |= (0b1 << SVP64MODE.RG) # sets Reverse-gear mode
1121 if mapreduce_crm:
1122 mode |= (0b1 << SVP64MODE.CRM) # sets CRM mode
1123 assert rc_mode, "CRM only allowed when Rc=1"
1124 # bit of weird encoding to jam zero-pred or SVM mode in.
1125 # SVM mode can be enabled only when SUBVL=2/3/4 (vec2/3/4)
1126 if subvl == 0:
1127 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
1128 elif mapreduce_svm:
1129 mode |= (0b1 << SVP64MODE.SVM) # sets SVM mode
1130
1131 ######################################
1132 # "failfirst" modes
1133 elif sv_mode == 0b01:
1134 assert src_zero == 0, "dest-zero not allowed in failfirst mode"
1135 if failfirst == 'RC1':
1136 mode |= (0b1 << SVP64MODE.RC1) # sets RC1 mode
1137 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
1138 assert rc_mode == False, "ffirst RC1 only ok when Rc=0"
1139 elif failfirst == '~RC1':
1140 mode |= (0b1 << SVP64MODE.RC1) # sets RC1 mode
1141 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
1142 mode |= (0b1 << SVP64MODE.INV) # ... with inversion
1143 assert rc_mode == False, "ffirst RC1 only ok when Rc=0"
1144 else:
1145 assert dst_zero == 0, "dst-zero not allowed in ffirst BO"
1146 assert rc_mode, "ffirst BO only possible when Rc=1"
1147 mode |= (failfirst << SVP64MODE.BO_LSB) # set BO
1148
1149 ######################################
1150 # "saturation" modes
1151 elif sv_mode == 0b10:
1152 mode |= src_zero << SVP64MODE.SZ # predicate zeroing
1153 mode |= dst_zero << SVP64MODE.DZ # predicate zeroing
1154 mode |= (saturation << SVP64MODE.N) # signed/us saturation
1155
1156 ######################################
1157 # "predicate-result" modes. err... code-duplication from ffirst
1158 elif sv_mode == 0b11:
1159 assert src_zero == 0, "dest-zero not allowed in predresult mode"
1160 if predresult == 'RC1':
1161 mode |= (0b1 << SVP64MODE.RC1) # sets RC1 mode
1162 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
1163 assert rc_mode == False, "pr-mode RC1 only ok when Rc=0"
1164 elif predresult == '~RC1':
1165 mode |= (0b1 << SVP64MODE.RC1) # sets RC1 mode
1166 mode |= (dst_zero << SVP64MODE.DZ) # predicate dst-zeroing
1167 mode |= (0b1 << SVP64MODE.INV) # ... with inversion
1168 assert rc_mode == False, "pr-mode RC1 only ok when Rc=0"
1169 else:
1170 assert dst_zero == 0, "dst-zero not allowed in pr-mode BO"
1171 assert rc_mode, "pr-mode BO only possible when Rc=1"
1172 mode |= (predresult << SVP64MODE.BO_LSB) # set BO
1173
1174 # whewww.... modes all done :)
1175 # now put into svp64_rm
1176 mode |= sv_mode
1177 # mode: bits 19-23
1178 svp64_rm.mode.eq(SelectableInt(mode, SVP64RM_MODE_SIZE))
1179
1180 # put in predicate masks into svp64_rm
1181 if ptype == '2P':
1182 # source pred: bits 16-18
1183 svp64_rm.smask.eq(SelectableInt(smask, SVP64RM_SMASK_SIZE))
1184 # mask mode: bit 0
1185 svp64_rm.mmode.eq(SelectableInt(mmode, SVP64RM_MMODE_SIZE))
1186 # 1-pred: bits 1-3
1187 svp64_rm.mask.eq(SelectableInt(pmask, SVP64RM_MASK_SIZE))
1188
1189 # and subvl: bits 8-9
1190 svp64_rm.subvl.eq(SelectableInt(subvl, SVP64RM_SUBVL_SIZE))
1191
1192 # put in elwidths
1193 # srcwid: bits 6-7
1194 svp64_rm.ewsrc.eq(SelectableInt(srcwid, SVP64RM_EWSRC_SIZE))
1195 # destwid: bits 4-5
1196 svp64_rm.elwidth.eq(SelectableInt(destwid, SVP64RM_ELWIDTH_SIZE))
1197
1198 # nice debug printout. (and now for something completely different)
1199 # https://youtu.be/u0WOIwlXE9g?t=146
1200 svp64_rm_value = svp64_rm.spr.value
1201 log("svp64_rm", hex(svp64_rm_value), bin(svp64_rm_value))
1202 log(" mmode 0 :", bin(mmode))
1203 log(" pmask 1-3 :", bin(pmask))
1204 log(" dstwid 4-5 :", bin(destwid))
1205 log(" srcwid 6-7 :", bin(srcwid))
1206 log(" subvl 8-9 :", bin(subvl))
1207 log(" mode 19-23:", bin(mode))
1208 offs = 2 if etype == 'EXTRA2' else 3 # 2 or 3 bits
1209 for idx, sv_extra in extras.items():
1210 if idx is None:
1211 continue
1212 if idx[0] == 'imm':
1213 continue
1214 srcdest, idx, duplicate = idx
1215 start = (10+idx*offs)
1216 end = start + offs-1
1217 log(" extra%d %2d-%2d:" % (idx, start, end),
1218 bin(sv_extra))
1219 if ptype == '2P':
1220 log(" smask 16-17:", bin(smask))
1221 log()
1222
1223 # first, construct the prefix from its subfields
1224 svp64_prefix = SVP64PrefixFields()
1225 svp64_prefix.major.eq(SelectableInt(0x1, SV64P_MAJOR_SIZE))
1226 svp64_prefix.pid.eq(SelectableInt(0b11, SV64P_PID_SIZE))
1227 svp64_prefix.rm.eq(svp64_rm.spr)
1228
1229 # fiinally yield the svp64 prefix and the thingy. v3.0b opcode
1230 rc = '.' if rc_mode else ''
1231 yield ".long 0x%08x" % svp64_prefix.insn.value
1232 log(v30b_op, v30b_newfields)
1233 # argh, sv.fmadds etc. need to be done manually
1234 if v30b_op == 'ffmadds':
1235 opcode = 59 << (32-6) # bits 0..6 (MSB0)
1236 opcode |= int(v30b_newfields[0]) << (32-11) # FRT
1237 opcode |= int(v30b_newfields[1]) << (32-16) # FRA
1238 opcode |= int(v30b_newfields[2]) << (32-21) # FRB
1239 opcode |= int(v30b_newfields[3]) << (32-26) # FRC
1240 opcode |= 0b00101 << (32-31) # bits 26-30
1241 if rc:
1242 opcode |= 1 # Rc, bit 31.
1243 yield ".long 0x%x" % opcode
1244 # argh, sv.fdmadds need to be done manually
1245 elif v30b_op == 'fdmadds':
1246 opcode = 59 << (32-6) # bits 0..6 (MSB0)
1247 opcode |= int(v30b_newfields[0]) << (32-11) # FRT
1248 opcode |= int(v30b_newfields[1]) << (32-16) # FRA
1249 opcode |= int(v30b_newfields[2]) << (32-21) # FRB
1250 opcode |= int(v30b_newfields[3]) << (32-26) # FRC
1251 opcode |= 0b01111 << (32-31) # bits 26-30
1252 if rc:
1253 opcode |= 1 # Rc, bit 31.
1254 yield ".long 0x%x" % opcode
1255 # argh, sv.ffadds etc. need to be done manually
1256 elif v30b_op == 'ffadds':
1257 opcode = 59 << (32-6) # bits 0..6 (MSB0)
1258 opcode |= int(v30b_newfields[0]) << (32-11) # FRT
1259 opcode |= int(v30b_newfields[1]) << (32-16) # FRA
1260 opcode |= int(v30b_newfields[2]) << (32-21) # FRB
1261 opcode |= 0b01101 << (32-31) # bits 26-30
1262 if rc:
1263 opcode |= 1 # Rc, bit 31.
1264 yield ".long 0x%x" % opcode
1265 # sigh have to do svstep here manually for now...
1266 elif v30b_op in ["svstep", "svstep."]:
1267 insn = 22 << (31-5) # opcode 22, bits 0-5
1268 insn |= int(v30b_newfields[0]) << (31-10) # RT , bits 6-10
1269 insn |= int(v30b_newfields[1]) << (31-22) # SVi , bits 16-22
1270 insn |= int(v30b_newfields[2]) << (31-25) # vf , bit 25
1271 insn |= 0b10011 << (31-30) # XO , bits 26..30
1272 if opcode == 'svstep.':
1273 insn |= 1 << (31-31) # Rc=1 , bit 31
1274 log("svstep", bin(insn))
1275 yield ".long 0x%x" % insn
1276 # argh, sv.fcoss etc. need to be done manually
1277 elif v30b_op in ["fcoss", "fcoss."]:
1278 insn = 59 << (31-5) # opcode 59, bits 0-5
1279 insn |= int(v30b_newfields[0]) << (31-10) # RT , bits 6-10
1280 insn |= int(v30b_newfields[1]) << (31-20) # RB , bits 16-20
1281 insn |= 0b1000101110 << (31-30) # XO , bits 21..30
1282 if opcode == 'fcoss.':
1283 insn |= 1 << (31-31) # Rc=1 , bit 31
1284 log("fcoss", bin(insn))
1285 yield ".long 0x%x" % insn
1286
1287 else:
1288 yield "%s %s" % (v30b_op+rc, ", ".join(v30b_newfields))
1289 log("new v3.0B fields", v30b_op, v30b_newfields)
1290
1291 def translate(self, lst):
1292 for insn in lst:
1293 yield from self.translate_one(insn)
1294
1295
1296 def macro_subst(macros, txt):
1297 again = True
1298 log("subst", txt, macros)
1299 while again:
1300 again = False
1301 for macro, value in macros.items():
1302 if macro == txt:
1303 again = True
1304 replaced = txt.replace(macro, value)
1305 log("macro", txt, "replaced", replaced, macro, value)
1306 txt = replaced
1307 continue
1308 toreplace = '%s.s' % macro
1309 if toreplace == txt:
1310 again = True
1311 replaced = txt.replace(toreplace, "%s.s" % value)
1312 log("macro", txt, "replaced", replaced, toreplace, value)
1313 txt = replaced
1314 continue
1315 toreplace = '%s.v' % macro
1316 if toreplace == txt:
1317 again = True
1318 replaced = txt.replace(toreplace, "%s.v" % value)
1319 log("macro", txt, "replaced", replaced, toreplace, value)
1320 txt = replaced
1321 continue
1322 toreplace = '(%s)' % macro
1323 if toreplace in txt:
1324 again = True
1325 replaced = txt.replace(toreplace, '(%s)' % value)
1326 log("macro", txt, "replaced", replaced, toreplace, value)
1327 txt = replaced
1328 continue
1329 log(" processed", txt)
1330 return txt
1331
1332
1333 def get_ws(line):
1334 # find whitespace
1335 ws = ''
1336 while line:
1337 if not line[0].isspace():
1338 break
1339 ws += line[0]
1340 line = line[1:]
1341 return ws, line
1342
1343
1344 def asm_process():
1345 # get an input file and an output file
1346 args = sys.argv[1:]
1347 if len(args) == 0:
1348 infile = sys.stdin
1349 outfile = sys.stdout
1350 # read the whole lot in advance in case of in-place
1351 lines = list(infile.readlines())
1352 elif len(args) != 2:
1353 print("pysvp64asm [infile | -] [outfile | -]", file=sys.stderr)
1354 exit(0)
1355 else:
1356 if args[0] == '--':
1357 infile = sys.stdin
1358 else:
1359 infile = open(args[0], "r")
1360 # read the whole lot in advance in case of in-place overwrite
1361 lines = list(infile.readlines())
1362
1363 if args[1] == '--':
1364 outfile = sys.stdout
1365 else:
1366 outfile = open(args[1], "w")
1367
1368 # read the line, look for custom insn, process it
1369 macros = {} # macros which start ".set"
1370 isa = SVP64Asm([])
1371 for line in lines:
1372 op = line.split("#")[0].strip()
1373 # identify macros
1374 if op.startswith(".set"):
1375 macro = op[4:].split(",")
1376 (macro, value) = map(str.strip, macro)
1377 macros[macro] = value
1378 if not op.startswith('sv.') and not op.startswith(tuple(CUSTOM_INSNS)):
1379 outfile.write(line)
1380 continue
1381
1382 (ws, line) = get_ws(line)
1383 lst = isa.translate_one(op, macros)
1384 lst = '; '.join(lst)
1385 outfile.write("%s%s # %s\n" % (ws, lst, op))
1386
1387
1388 if __name__ == '__main__':
1389 lst = ['slw 3, 1, 4',
1390 'extsw 5, 3',
1391 'sv.extsw 5, 3',
1392 'sv.cmpi 5, 1, 3, 2',
1393 'sv.setb 5, 31',
1394 'sv.isel 64.v, 3, 2, 65.v',
1395 'sv.setb/dm=r3/sm=1<<r3 5, 31',
1396 'sv.setb/m=r3 5, 31',
1397 'sv.setb/vec2 5, 31',
1398 'sv.setb/sw=8/ew=16 5, 31',
1399 'sv.extsw./ff=eq 5, 31',
1400 'sv.extsw./satu/sz/dz/sm=r3/dm=r3 5, 31',
1401 'sv.extsw./pr=eq 5.v, 31',
1402 'sv.add. 5.v, 2.v, 1.v',
1403 'sv.add./m=r3 5.v, 2.v, 1.v',
1404 ]
1405 lst += [
1406 'sv.stw 5.v, 4(1.v)',
1407 'sv.ld 5.v, 4(1.v)',
1408 'setvl. 2, 3, 4, 0, 1, 1',
1409 'sv.setvl. 2, 3, 4, 0, 1, 1',
1410 ]
1411 lst = [
1412 "sv.stfsu 0.v, 16(4.v)",
1413 ]
1414 lst = [
1415 "sv.stfsu/els 0.v, 16(4)",
1416 ]
1417 lst = [
1418 'sv.add./mr 5.v, 2.v, 1.v',
1419 ]
1420 macros = {'win2': '50', 'win': '60'}
1421 lst = [
1422 'sv.addi win2.v, win.v, -1',
1423 'sv.add./mrr 5.v, 2.v, 1.v',
1424 #'sv.lhzsh 5.v, 11(9.v), 15',
1425 #'sv.lwzsh 5.v, 11(9.v), 15',
1426 'sv.ffmadds 6.v, 2.v, 4.v, 6.v',
1427 ]
1428 lst = [
1429 #'sv.fmadds 0.v, 8.v, 16.v, 4.v',
1430 #'sv.ffadds 0.v, 8.v, 4.v',
1431 'svremap 11, 0, 1, 2, 3, 2, 1',
1432 'svshape 8, 1, 1, 1, 0',
1433 'svshape 8, 1, 1, 1, 1',
1434 ]
1435 lst = [
1436 #'sv.lfssh 4.v, 11(8.v), 15',
1437 #'sv.lwzsh 4.v, 11(8.v), 15',
1438 #'sv.svstep. 2.v, 4, 0',
1439 #'sv.fcfids. 48.v, 64.v',
1440 'sv.fcoss. 80.v, 0.v',
1441 'sv.fcoss. 20.v, 0.v',
1442 ]
1443 lst = [
1444 'sv.bc/all 3,12,192',
1445 'sv.bclr/vsbi 3,81.v,192',
1446 'sv.ld 5.v, 4(1.v)',
1447 'sv.svstep. 2.v, 4, 0',
1448 ]
1449 lst = [
1450 'maxs 3,12,5',
1451 'maxs. 3,12,5',
1452 'avgadd 3,12,5',
1453 'absdu 3,12,5',
1454 'absds 3,12,5',
1455 'absdacu 3,12,5',
1456 'absdacs 3,12,5',
1457 'cprop 3,12,5',
1458 'svindex 0,0,1,0,0,0,0',
1459 ]
1460 lst = [
1461 'sv.svstep./m=r3 2.v, 4, 0',
1462 ]
1463 isa = SVP64Asm(lst, macros=macros)
1464 log("list", list(isa))
1465 asm_process()