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