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}"
620 for operand
in record
.dynamic_operands
:
621 operand
= int(self
[record
.fields
[operand
.name
]])
622 operands
.append(operand
)
624 operands
= ",".join(map(str, operands
))
625 operands
= f
" {operands}"
629 yield f
"{record.name}{operands}"
631 class PrefixedInstruction(Instruction
):
632 class Prefix(WordInstruction
.remap(range(0, 32))):
635 class Suffix(WordInstruction
.remap(range(32, 64))):
638 _
: _Field
= range(64)
644 def integer(cls
, value
, byteorder
="little"):
645 return super().integer(bits
=64, value
=value
, byteorder
=byteorder
)
648 def pair(cls
, prefix
=0, suffix
=0, byteorder
="little"):
649 def transform(value
):
650 return WordInstruction
.integer(value
=value
,
651 byteorder
=byteorder
)[0:32]
653 (prefix
, suffix
) = map(transform
, (prefix
, suffix
))
654 value
= _selectconcat(prefix
, suffix
)
656 return super().integer(value
=value
)
658 def disassemble(self
, db
):
659 record
= db
[self
.suffix
]
661 yield f
".llong 0x{int(self):016x}"
663 yield f
".llong 0x{int(self):016x} # {record.name}"
666 class SVP64Instruction(PrefixedInstruction
):
667 """SVP64 instruction: https://libre-soc.org/openpower/sv/svp64/"""
668 class Prefix(PrefixedInstruction
.Prefix
):
670 _
: _Field
= range(24)
672 mask
: _Field
= range(1, 4)
673 elwidth
: _Field
= range(4, 6)
674 ewsrc
: _Field
= range(6, 8)
675 subvl
: _Field
= range(8, 10)
676 extra
: _Field
= range(10, 19)
677 mode
: _Field
= range(19, 24)
678 extra2
: _Field
[4] = (
684 smask
: _Field
= range(16, 19)
685 extra3
: _Field
[3] = (
692 rm
: RM
= ((6, 8) + tuple(range(10, 32)))
696 def disassemble(self
, db
):
697 record
= db
[self
.suffix
]
699 yield f
".llong 0x{int(self):016x}"
701 yield f
".llong 0x{int(self):016x} # sv.{record.name}"
704 def parse(stream
, factory
):
705 lines
= filter(lambda line
: not line
.strip().startswith("#"), stream
)
706 entries
= _csv
.DictReader(lines
)
707 entries
= filter(lambda entry
: "TODO" not in frozenset(entry
.values()), entries
)
708 return tuple(map(factory
, entries
))
712 def __init__(self
, root
):
713 db
= _collections
.defaultdict(set)
714 path
= (root
/ "insndb.csv")
715 with
open(path
, "r", encoding
="UTF-8") as stream
:
716 for section
in parse(stream
, Section
.CSV
):
717 path
= (root
/ section
.path
)
719 section
.Mode
.INTEGER
: IntegerOpcode
,
720 section
.Mode
.PATTERN
: PatternOpcode
,
722 factory
= _functools
.partial(PPCRecord
.CSV
, opcode_cls
=opcode_cls
)
723 with
open(path
, "r", encoding
="UTF-8") as stream
:
724 db
[section
].update(parse(stream
, factory
))
726 return super().__init
__()
728 def __getitem__(self
, key
):
729 for (section
, records
) in self
.__db
.items():
730 for record
in records
:
731 for name
in record
.names
:
733 ((record
.rc
is _RC
.RC
) and
734 key
.endswith(".") and
736 return (section
, record
)
741 def __init__(self
, root
):
743 pattern
= _re
.compile(r
"^(?:LDST)?RM-(1P|2P)-.*?\.csv$")
744 for (prefix
, _
, names
) in _os
.walk(root
):
745 prefix
= _pathlib
.Path(prefix
)
746 for name
in filter(lambda name
: pattern
.match(name
), names
):
747 path
= (prefix
/ _pathlib
.Path(name
))
748 with
open(path
, "r", encoding
="UTF-8") as stream
:
749 db
.update(parse(stream
, SVP64Record
.CSV
))
750 self
.__db
= {record
.name
:record
for record
in db
}
751 return super().__init
__()
753 def __getitem__(self
, key
):
755 record
= self
.__db
.get(name
, None)
756 if record
is not None:
761 class FieldsDatabase
:
766 for (form
, fields
) in df
.instrs
.items():
767 if form
in {"DQE", "TX"}:
771 db
[_Form
[form
]] = Fields(fields
)
773 return super().__init
__()
775 def __getitem__(self
, key
):
776 return self
.__db
.__getitem
__(key
)
779 class MarkdownDatabase
:
782 for (name
, desc
) in _ISA():
785 (dynamic
, *static
) = desc
.regs
786 operands
.extend(dynamic
)
787 operands
.extend(static
)
788 db
[name
] = Operands(operands
)
790 return super().__init
__()
793 yield from self
.__db
.items()
795 def __getitem__(self
, key
):
796 return self
.__db
.__getitem
__(key
)
800 def __init__(self
, root
):
801 root
= _pathlib
.Path(root
)
803 mdwndb
= MarkdownDatabase()
804 fieldsdb
= FieldsDatabase()
805 svp64db
= SVP64Database(root
)
806 ppcdb
= PPCDatabase(root
)
809 for (name
, operands
) in mdwndb
:
810 (section
, ppc
) = ppcdb
[name
]
813 svp64
= svp64db
[ppc
.names
]
814 fields
= fieldsdb
[ppc
.form
]
815 record
= Record(name
=name
,
816 section
=section
, ppc
=ppc
, svp64
=svp64
,
817 operands
=operands
, fields
=fields
)
820 self
.__db
= tuple(sorted(db
))
822 return super().__init
__()
825 return repr(self
.__db
)
830 @_functools.lru_cache(maxsize
=None)
831 def __contains__(self
, key
):
832 return self
.__getitem
__(key
) is not None
834 @_functools.lru_cache(maxsize
=None)
835 def __getitem__(self
, key
):
836 if isinstance(key
, (int, Instruction
)):
839 opcode
= record
.opcode
840 if ((opcode
.value
& opcode
.mask
) ==
841 (key
& opcode
.mask
)):
844 elif isinstance(key
, Opcode
):
846 if record
.opcode
== key
:
848 elif isinstance(key
, str):
850 if record
.name
== key
: