1 import collections
as _collections
3 import dataclasses
as _dataclasses
5 import functools
as _functools
7 import operator
as _operator
8 import pathlib
as _pathlib
12 from functools
import cached_property
14 from cached_property
import cached_property
16 from openpower
.decoder
.power_enums
import (
17 Function
as _Function
,
24 CROutSel
as _CROutSel
,
26 LDSTMode
as _LDSTMode
,
34 SVExtraRegType
as _SVExtraRegType
,
35 SVExtraReg
as _SVExtraReg
,
37 from openpower
.decoder
.selectable_int
import (
38 SelectableInt
as _SelectableInt
,
39 selectconcat
as _selectconcat
,
41 from openpower
.decoder
.power_fields
import (
44 DecodeFields
as _DecodeFields
,
46 from openpower
.decoder
.pseudo
.pagereader
import ISA
as _ISA
49 def dataclass(cls
, record
, keymap
=None, typemap
=None):
53 typemap
= {field
.name
:field
.type for field
in _dataclasses
.fields(cls
)}
55 def transform(key_value
):
56 (key
, value
) = key_value
57 key
= keymap
.get(key
, key
)
58 hook
= typemap
.get(key
, lambda value
: value
)
59 if hook
is bool and value
in ("", "0"):
65 record
= dict(map(transform
, record
.items()))
66 for key
in frozenset(record
.keys()):
73 @_functools.total_ordering
74 @_dataclasses.dataclass(eq
=True, frozen
=True)
78 if self
.bit_length() <= 32:
79 return f
"0x{self:08x}"
81 return f
"0x{self:016x}"
85 if self
.bit_length() <= 32:
86 return f
"0x{self:08x}"
88 return f
"0x{self:016x}"
93 def __lt__(self
, other
):
94 if not isinstance(other
, Opcode
):
96 return ((self
.value
, self
.mask
) < (other
.value
, other
.mask
))
98 def __post_init__(self
):
99 (value
, mask
) = (self
.value
, self
.mask
)
101 if isinstance(value
, Opcode
):
103 raise ValueError(mask
)
104 (value
, mask
) = (value
.value
, value
.mask
)
105 elif isinstance(value
, str):
107 raise ValueError(mask
)
108 value
= int(value
, 0)
110 if not isinstance(value
, int):
111 raise ValueError(value
)
114 if not isinstance(mask
, int):
115 raise ValueError(mask
)
117 object.__setattr
__(self
, "value", self
.__class
__.Value(value
))
118 object.__setattr
__(self
, "mask", self
.__class
__.Mask(mask
))
121 class IntegerOpcode(Opcode
):
122 def __init__(self
, value
):
123 if isinstance(value
, str):
124 value
= int(value
, 0)
125 return super().__init
__(value
=value
, mask
=None)
128 class PatternOpcode(Opcode
):
129 def __init__(self
, value
):
130 (pattern
, value
, mask
) = (value
, 0, 0)
132 for symbol
in pattern
:
133 if symbol
not in {"0", "1", "-"}:
134 raise ValueError(pattern
)
135 value |
= (symbol
== "1")
136 mask |
= (symbol
!= "-")
142 return super().__init
__(value
=value
, mask
=mask
)
145 class FieldsOpcode(Opcode
):
146 def __init__(self
, fields
):
147 def field(opcode
, field
):
148 (value
, mask
) = opcode
149 (field
, bits
) = field
150 shifts
= map(lambda bit
: (31 - bit
), reversed(tuple(bits
)))
151 for (index
, shift
) in enumerate(shifts
):
152 bit
= ((field
& (1 << index
)) != 0)
153 value |
= (bit
<< shift
)
157 (value
, mask
) = _functools
.reduce(field
, fields
, (0, 0))
159 return super().__init
__(value
=value
, mask
=mask
)
162 @_dataclasses.dataclass(eq
=True, frozen
=True)
164 class FlagsMeta(type):
179 class Flags(frozenset, metaclass
=FlagsMeta
):
180 def __new__(cls
, flags
=frozenset()):
181 flags
= frozenset(flags
)
182 diff
= (flags
- frozenset(cls
))
184 raise ValueError(flags
)
185 return super().__new
__(cls
, flags
)
189 flags
: Flags
= Flags()
191 function
: _Function
= _Function
.NONE
192 intop
: _MicrOp
= _MicrOp
.OP_ILLEGAL
193 in1
: _In1Sel
= _In1Sel
.RA
194 in2
: _In2Sel
= _In2Sel
.NONE
195 in3
: _In3Sel
= _In3Sel
.NONE
196 out
: _OutSel
= _OutSel
.NONE
197 cr_in
: _CRInSel
= _CRInSel
.NONE
198 cr_out
: _CROutSel
= _CROutSel
.NONE
199 cry_in
: _CryIn
= _CryIn
.ZERO
200 ldst_len
: _LDSTLen
= _LDSTLen
.NONE
201 upd
: _LDSTMode
= _LDSTMode
.NONE
202 rc
: _RCOE
= _RCOE
.NONE
203 form
: _Form
= _Form
.NONE
205 unofficial
: bool = False
209 "internal op": "intop",
213 "ldst len": "ldst_len",
214 "CONDITIONS": "conditions",
218 def CSV(cls
, record
, opcode_cls
=Opcode
):
219 typemap
= {field
.name
:field
.type for field
in _dataclasses
.fields(cls
)}
220 typemap
["opcode"] = opcode_cls
223 for flag
in frozenset(PPCRecord
.Flags
):
224 if bool(record
.pop(flag
, "")):
226 record
["flags"] = PPCRecord
.Flags(flags
)
228 return dataclass(cls
, record
, keymap
=PPCRecord
.__KEYMAP
, typemap
=typemap
)
232 return frozenset(self
.comment
.split("=")[-1].split("/"))
235 @_dataclasses.dataclass(eq
=True, frozen
=True)
237 class ExtraMap(tuple):
239 @_dataclasses.dataclass(eq
=True, frozen
=True)
241 regtype
: _SVExtraRegType
= _SVExtraRegType
.NONE
242 reg
: _SVExtraReg
= _SVExtraReg
.NONE
245 return f
"{self.regtype.value}:{self.reg.name}"
247 def __new__(cls
, value
="0"):
248 if isinstance(value
, str):
249 def transform(value
):
250 (regtype
, reg
) = value
.split(":")
251 regtype
= _SVExtraRegType(regtype
)
252 reg
= _SVExtraReg(reg
)
253 return cls
.Entry(regtype
=regtype
, reg
=reg
)
258 value
= map(transform
, value
.split(";"))
260 return super().__new
__(cls
, value
)
263 return repr(list(self
))
265 def __new__(cls
, value
=tuple()):
269 return super().__new
__(cls
, map(cls
.Extra
, value
))
272 return repr({index
:self
[index
] for index
in range(0, 4)})
275 ptype
: _SVPtype
= _SVPtype
.NONE
276 etype
: _SVEtype
= _SVEtype
.NONE
277 in1
: _In1Sel
= _In1Sel
.NONE
278 in2
: _In2Sel
= _In2Sel
.NONE
279 in3
: _In3Sel
= _In3Sel
.NONE
280 out
: _OutSel
= _OutSel
.NONE
281 out2
: _OutSel
= _OutSel
.NONE
282 cr_in
: _CRInSel
= _CRInSel
.NONE
283 cr_out
: _CROutSel
= _CROutSel
.NONE
284 extra
: ExtraMap
= ExtraMap()
287 mode
: _SVMode
= _SVMode
.NORMAL
291 "CONDITIONS": "conditions",
300 def CSV(cls
, record
):
301 for key
in ("in1", "in2", "in3", "out", "out2", "CR in", "CR out"):
306 record
["extra"] = cls
.ExtraMap(record
.pop(f
"{index}") for index
in range(0, 4))
308 return dataclass(cls
, record
, keymap
=cls
.__KEYMAP
)
312 def __init__(self
, value
=(0, 32)):
313 if isinstance(value
, str):
314 (start
, end
) = map(int, value
.split(":"))
317 if start
< 0 or end
< 0 or start
>= end
:
318 raise ValueError(value
)
323 return super().__init
__()
326 return f
"[{self.__start}:{self.__end}]"
329 yield from range(self
.start
, (self
.end
+ 1))
340 @_dataclasses.dataclass(eq
=True, frozen
=True)
342 class Mode(_enum
.Enum
):
343 INTEGER
= _enum
.auto()
344 PATTERN
= _enum
.auto()
347 def _missing_(cls
, value
):
348 if isinstance(value
, str):
349 return cls
[value
.upper()]
350 return super()._missing
_(value
)
353 def __new__(cls
, value
=None):
354 if isinstance(value
, str):
355 if value
.upper() == "NONE":
358 value
= int(value
, 0)
362 return super().__new
__(cls
, value
)
368 return (bin(self
) if self
else "None")
377 def CSV(cls
, record
):
378 return dataclass(cls
, record
)
382 def __init__(self
, items
):
383 if isinstance(items
, dict):
384 items
= items
.items()
387 (name
, bitrange
) = item
388 return (name
, tuple(bitrange
.values()))
390 self
.__mapping
= dict(map(transform
, items
))
392 return super().__init
__()
395 return repr(self
.__mapping
)
398 yield from self
.__mapping
.items()
400 def __contains__(self
, key
):
401 return self
.__mapping
.__contains
__(key
)
403 def __getitem__(self
, key
):
404 return self
.__mapping
.get(key
, None)
407 @_dataclasses.dataclass(eq
=True, frozen
=True)
412 @_dataclasses.dataclass(eq
=True, frozen
=True)
413 class DynamicOperand(Operand
):
417 @_dataclasses.dataclass(eq
=True, frozen
=True)
418 class StaticOperand(Operand
):
423 class Operands(tuple):
424 def __new__(cls
, iterable
):
426 for operand
in iterable
:
428 (name
, value
) = operand
.split("=")
430 operand
= StaticOperand(name
=name
, value
=value
)
432 operand
= DynamicOperand(name
=operand
)
433 operands
.append(operand
)
434 return super().__new
__(cls
, operands
)
437 @_functools.total_ordering
438 @_dataclasses.dataclass(eq
=True, frozen
=True)
445 svp64
: SVP64Record
= None
454 def __lt__(self
, other
):
455 if not isinstance(other
, Record
):
456 return NotImplemented
457 return (self
.opcode
< other
.opcode
)
460 return f
"{self.__class__.__name__}(name={self.name!r}, opcode={self.opcode})"
465 if self
.section
.opcode
:
466 fields
+= [(self
.section
.opcode
.value
, BitSel((0, 5)))]
467 fields
+= [(self
.ppc
.opcode
.value
, self
.section
.bitsel
)]
469 fields
+= [(self
.ppc
.opcode
.value
, self
.section
.bitsel
)]
471 for operand
in self
.static_operands
:
472 fields
+= [(operand
.value
, self
.fields
[operand
.name
])]
474 return FieldsOpcode(fields
)
478 return self
.ppc
.function
498 if self
.svp64
is None:
504 return self
.ppc
.cr_in
508 return self
.ppc
.cr_out
510 def sv_extra(self
, key
):
511 if key
not in frozenset({
512 "in1", "in2", "in3", "cr_in",
513 "out", "out2", "cr_out",
517 sel
= getattr(self
.svp64
, key
)
518 if sel
is _CRInSel
.BA_BB
:
519 return _SVExtra
.Idx_1_2
520 reg
= _SVExtraReg(sel
)
521 if reg
is _SVExtraReg
.NONE
:
525 _SVExtraRegType
.SRC
: {},
526 _SVExtraRegType
.DST
: {},
528 for index
in range(0, 4):
529 for entry
in self
.svp64
.extra
[index
]:
530 extra_map
[entry
.regtype
][entry
.reg
] = Record
.__EXTRA
[index
]
532 for regtype
in (_SVExtraRegType
.SRC
, _SVExtraRegType
.DST
):
533 extra
= extra_map
[regtype
].get(reg
, _SVExtra
.NONE
)
534 if extra
is not _SVExtra
.NONE
:
539 sv_in1
= property(_functools
.partial(sv_extra
, key
="in1"))
540 sv_in2
= property(_functools
.partial(sv_extra
, key
="in2"))
541 sv_in3
= property(_functools
.partial(sv_extra
, key
="in3"))
542 sv_out
= property(_functools
.partial(sv_extra
, key
="out"))
543 sv_out2
= property(_functools
.partial(sv_extra
, key
="out2"))
544 sv_cr_in
= property(_functools
.partial(sv_extra
, key
="cr_in"))
545 sv_cr_out
= property(_functools
.partial(sv_extra
, key
="cr_out"))
549 if self
.svp64
is None:
551 return self
.svp64
.ptype
555 if self
.svp64
is None:
557 return self
.svp64
.etype
560 def dynamic_operands(self
):
561 for operand
in self
.operands
:
562 if isinstance(operand
, DynamicOperand
):
566 def static_operands(self
):
567 for operand
in self
.operands
:
568 if isinstance(operand
, StaticOperand
):
572 class Instruction(_Mapping
):
574 def integer(cls
, value
=0, bits
=None, byteorder
="little"):
575 if isinstance(value
, (int, bytes
)) and not isinstance(bits
, int):
576 raise ValueError(bits
)
578 if isinstance(value
, bytes
):
579 if ((len(value
) * 8) != bits
):
580 raise ValueError(f
"bit length mismatch")
581 value
= int.from_bytes(value
, byteorder
=byteorder
)
583 if isinstance(value
, int):
584 value
= _SelectableInt(value
=value
, bits
=bits
)
585 elif isinstance(value
, Instruction
):
586 value
= value
.storage
588 if not isinstance(value
, _SelectableInt
):
589 raise ValueError(value
)
592 if len(value
) != bits
:
593 raise ValueError(value
)
595 value
= _SelectableInt(value
=value
, bits
=bits
)
597 return cls(storage
=value
)
600 return hash(int(self
))
602 def disassemble(self
, db
):
603 raise NotImplementedError
606 class WordInstruction(Instruction
):
607 _
: _Field
= range(0, 32)
608 po
: _Field
= range(0, 6)
611 def integer(cls
, value
, byteorder
="little"):
612 return super().integer(bits
=32, value
=value
, byteorder
=byteorder
)
614 def disassemble(self
, db
):
617 yield f
".long 0x{int(self):08x}"
619 yield f
".long 0x{int(self):08x} # {record.name}"
622 class PrefixedInstruction(Instruction
):
623 class Prefix(WordInstruction
.remap(range(0, 32))):
626 class Suffix(WordInstruction
.remap(range(32, 64))):
629 _
: _Field
= range(64)
635 def integer(cls
, value
, byteorder
="little"):
636 return super().integer(bits
=64, value
=value
, byteorder
=byteorder
)
639 def pair(cls
, prefix
=0, suffix
=0, byteorder
="little"):
640 def transform(value
):
641 return WordInstruction
.integer(value
=value
,
642 byteorder
=byteorder
)[0:32]
644 (prefix
, suffix
) = map(transform
, (prefix
, suffix
))
645 value
= _selectconcat(prefix
, suffix
)
647 return super().integer(value
=value
)
649 def disassemble(self
, db
):
650 record
= db
[self
.suffix
]
652 yield f
".llong 0x{int(self):016x}"
654 yield f
".llong 0x{int(self):016x} # {record.name}"
657 class SVP64Instruction(PrefixedInstruction
):
658 """SVP64 instruction: https://libre-soc.org/openpower/sv/svp64/"""
659 class Prefix(PrefixedInstruction
.Prefix
):
661 _
: _Field
= range(24)
663 mask
: _Field
= range(1, 4)
664 elwidth
: _Field
= range(4, 6)
665 ewsrc
: _Field
= range(6, 8)
666 subvl
: _Field
= range(8, 10)
667 extra
: _Field
= range(10, 19)
668 mode
: _Field
= range(19, 24)
669 extra2
: _Field
[4] = (
675 smask
: _Field
= range(16, 19)
676 extra3
: _Field
[3] = (
683 rm
: RM
= ((6, 8) + tuple(range(10, 32)))
687 def disassemble(self
, db
):
688 record
= db
[self
.suffix
]
690 yield f
".llong 0x{int(self):016x}"
692 yield f
".llong 0x{int(self):016x} # sv.{record.name}"
695 def parse(stream
, factory
):
696 lines
= filter(lambda line
: not line
.strip().startswith("#"), stream
)
697 entries
= _csv
.DictReader(lines
)
698 entries
= filter(lambda entry
: "TODO" not in frozenset(entry
.values()), entries
)
699 return tuple(map(factory
, entries
))
703 class KeyError(KeyError):
706 def __init__(self
, root
):
707 db
= _collections
.defaultdict(set)
708 path
= (root
/ "insndb.csv")
709 with
open(path
, "r", encoding
="UTF-8") as stream
:
710 for section
in parse(stream
, Section
.CSV
):
711 path
= (root
/ section
.path
)
713 section
.Mode
.INTEGER
: IntegerOpcode
,
714 section
.Mode
.PATTERN
: PatternOpcode
,
716 factory
= _functools
.partial(PPCRecord
.CSV
, opcode_cls
=opcode_cls
)
717 with
open(path
, "r", encoding
="UTF-8") as stream
:
718 db
[section
].update(parse(stream
, factory
))
720 return super().__init
__()
722 def __getitem__(self
, key
):
723 for (section
, records
) in self
.__db
.items():
724 for record
in records
:
725 for name
in record
.names
:
727 ((record
.rc
is _RC
.RC
) and
728 key
.endswith(".") and
730 return (section
, record
)
731 raise self
.__class
__.KeyError(key
)
735 class KeyError(KeyError):
738 def __init__(self
, root
, ppcdb
):
740 pattern
= _re
.compile(r
"^(?:LDST)?RM-(1P|2P)-.*?\.csv$")
741 for (prefix
, _
, names
) in _os
.walk(root
):
742 prefix
= _pathlib
.Path(prefix
)
743 for name
in filter(lambda name
: pattern
.match(name
), names
):
744 path
= (prefix
/ _pathlib
.Path(name
))
745 with
open(path
, "r", encoding
="UTF-8") as stream
:
746 db
.update(parse(stream
, SVP64Record
.CSV
))
747 self
.__db
= {record
.name
:record
for record
in db
}
748 return super().__init
__()
750 def __getitem__(self
, key
):
752 record
= self
.__db
.get(name
, None)
753 if record
is not None:
755 raise self
.__class
__.KeyError(key
)
758 class FieldsDatabase
:
763 for (form
, fields
) in df
.instrs
.items():
764 if form
in {"DQE", "TX"}:
768 db
[_Form
[form
]] = Fields(fields
)
770 return super().__init
__()
772 def __getitem__(self
, key
):
773 return self
.__db
.__getitem
__(key
)
776 class MarkdownDatabase
:
779 for (name
, desc
) in _ISA():
782 (dynamic
, *static
) = desc
.regs
783 operands
.extend(dynamic
)
784 operands
.extend(static
)
785 db
[name
] = Operands(operands
)
787 return super().__init
__()
790 yield from self
.__db
.items()
792 def __getitem__(self
, key
):
793 return self
.__db
.__getitem
__(key
)
797 def __init__(self
, root
):
798 root
= _pathlib
.Path(root
)
800 mdwndb
= MarkdownDatabase()
801 fieldsdb
= FieldsDatabase()
802 ppcdb
= PPCDatabase(root
)
803 svp64db
= SVP64Database(root
, ppcdb
)
806 unknown_ppcdb
= set()
807 unknown_svp64
= set()
808 for (name
, operands
) in mdwndb
:
810 (section
, ppc
) = ppcdb
[name
]
811 svp64
= svp64db
[ppc
.names
]
812 fields
= fieldsdb
[ppc
.form
]
813 record
= Record(name
=name
,
814 section
=section
, ppc
=ppc
, svp64
=svp64
,
815 operands
=operands
, fields
=fields
)
817 except PPCDatabase
.KeyError:
818 unknown_ppcdb
.add(name
)
819 except SVP64Database
.KeyError:
820 unknown_svp64
.add(name
)
822 self
.__db
= tuple(sorted(db
))
824 return super().__init
__()
827 return repr(self
.__db
)
832 @_functools.lru_cache(maxsize
=None)
833 def __contains__(self
, key
):
834 return self
.__getitem
__(key
) is not None
836 @_functools.lru_cache(maxsize
=None)
837 def __getitem__(self
, key
):
838 if isinstance(key
, (int, Instruction
)):
841 opcode
= record
.opcode
842 if ((opcode
.value
& opcode
.mask
) ==
843 (key
& opcode
.mask
)):
846 elif isinstance(key
, Opcode
):
848 if record
.opcode
== key
:
850 elif isinstance(key
, str):
852 if record
.name
== key
: