Beispiel #1
0
    def __init__(self, yml: object, mnemonic: str,
                 insn_encoding: Optional[Encoding]) -> None:
        # The YAML representation should be a string (a bare operand name) or a
        # dict.
        what = 'operand for {!r} instruction'.format(mnemonic)
        if isinstance(yml, str):
            name = yml.lower()
            abbrev = None
            op_type = None
            doc = None
            pc_rel = False
            op_what = '{!r} {}'.format(name, what)
        elif isinstance(yml, dict):
            yd = check_keys(yml, what, ['name'],
                            ['type', 'pc-rel', 'doc', 'abbrev'])
            name = check_str(yd['name'], 'name of ' + what).lower()

            op_what = '{!r} {}'.format(name, what)
            abbrev = get_optional_str(yd, 'abbrev', op_what)
            if abbrev is not None:
                abbrev = abbrev.lower()
            op_type = get_optional_str(yd, 'type', op_what)
            pc_rel = check_bool(yd.get('pc-rel', False),
                                'pc-rel field of ' + op_what)
            doc = get_optional_str(yd, 'doc', op_what)

        # If there is an encoding, look up the encoding scheme field that
        # corresponds to this operand.
        enc_scheme_field = None
        if insn_encoding is not None:
            field_name = insn_encoding.op_to_field_name.get(name)
            if field_name is None:
                raise ValueError('The {!r} instruction has an operand called '
                                 '{!r}, but the associated encoding has no '
                                 'field that encodes it.'.format(
                                     mnemonic, name))
            enc_scheme_field = insn_encoding.fields[field_name].scheme_field

        if abbrev is not None:
            if name == abbrev:
                raise ValueError('Operand {!r} of the {!r} instruction has '
                                 'an abbreviated name the same as its '
                                 'actual name.'.format(name, mnemonic))
        self.name = name
        self.abbrev = abbrev
        self.op_type = make_operand_type(op_type, pc_rel, name, mnemonic,
                                         enc_scheme_field)
        self.doc = doc
Beispiel #2
0
    def __init__(self, path: str, yml: object) -> None:
        yd = check_keys(yml, 'top-level', ['insn-groups'],
                        ['encoding-schemes'])

        enc_scheme_path = get_optional_str(yd, 'encoding-schemes', 'top-level')
        if enc_scheme_path is None:
            self.encoding_schemes = None
        else:
            src_dir = os.path.dirname(path)
            es_path = os.path.normpath(os.path.join(src_dir, enc_scheme_path))
            es_yaml = load_yaml(es_path, 'encoding schemes')
            try:
                self.encoding_schemes = EncSchemes(es_yaml)
            except ValueError as err:
                raise RuntimeError(
                    'Invalid schema in YAML file at {!r}: {}'.format(
                        es_path, err)) from None

        self.groups = InsnGroups(path, self.encoding_schemes,
                                 yd['insn-groups'])

        # The instructions are grouped by instruction group and stored in
        # self.groups. Most of the time, however, we just want "an OTBN
        # instruction" and don't care about the group. Retrieve them here.
        self.insns = []
        for grp in self.groups.groups:
            self.insns += grp.insns

        self.mnemonic_to_insn = index_list('insns', self.insns,
                                           lambda insn: insn.mnemonic.lower())

        masks_exc, ambiguities = self._get_masks()
        if ambiguities:
            raise ValueError('Ambiguous instruction encodings: ' +
                             ', '.join(ambiguities))

        self._masks = masks_exc
Beispiel #3
0
    def __init__(self, yml: object,
                 encoding_schemes: Optional[EncSchemes]) -> None:
        yd = check_keys(yml, 'instruction', ['mnemonic', 'operands'], [
            'group', 'rv32i', 'synopsis', 'syntax', 'doc', 'errs', 'note',
            'encoding', 'glued-ops', 'literal-pseudo-op', 'python-pseudo-op',
            'lsu', 'straight-line'
        ])

        self.mnemonic = check_str(yd['mnemonic'], 'mnemonic for instruction')

        what = 'instruction with mnemonic {!r}'.format(self.mnemonic)

        encoding_yml = yd.get('encoding')
        self.encoding = None
        if encoding_yml is not None:
            if encoding_schemes is None:
                raise ValueError(
                    '{} specifies an encoding, but the file '
                    'didn\'t specify any encoding schemes.'.format(what))

            self.encoding = Encoding(encoding_yml, encoding_schemes,
                                     self.mnemonic)

        self.operands = [
            Operand(y, self.mnemonic, self.encoding)
            for y in check_list(yd['operands'], 'operands for ' + what)
        ]
        self.name_to_operand = index_list('operands for ' + what,
                                          self.operands, lambda op: op.name)

        # The call to index_list has checked that operand names are distinct.
        # We also need to check that no operand abbreviation clashes with
        # anything else.
        operand_names = set(self.name_to_operand.keys())
        for op in self.operands:
            if op.abbrev is not None:
                if op.abbrev in operand_names:
                    raise ValueError('The name {!r} appears as an operand or '
                                     'abbreviation more than once for '
                                     'instruction {!r}.'.format(
                                         op.abbrev, self.mnemonic))
                operand_names.add(op.abbrev)

        if self.encoding is not None:
            # If we have an encoding, we passed it to the Operand constructors
            # above. This ensured that each operand has a field. However, it's
            # possible that there are some operand names the encoding mentions
            # that don't actually have an operand. Check for that here.
            missing_ops = (set(self.encoding.op_to_field_name.keys()) -
                           set(self.name_to_operand.keys()))
            if missing_ops:
                raise ValueError('Encoding scheme for {} specifies '
                                 'some non-existent operands: {}.'.format(
                                     what, ', '.join(list(missing_ops))))

        self.rv32i = check_bool(yd.get('rv32i', False),
                                'rv32i flag for ' + what)
        self.glued_ops = check_bool(yd.get('glued-ops', False),
                                    'glued-ops flag for ' + what)
        self.synopsis = get_optional_str(yd, 'synopsis', what)
        self.doc = get_optional_str(yd, 'doc', what)
        self.note = get_optional_str(yd, 'note', what)

        self.errs = None
        if 'errs' in yd:
            errs_what = 'errs field for ' + what
            y_errs = check_list(yd.get('errs'), errs_what)
            self.errs = []
            for idx, err_desc in enumerate(y_errs):
                self.errs.append(
                    check_str(err_desc,
                              'element {} of the {}'.format(idx, errs_what)))

        raw_syntax = get_optional_str(yd, 'syntax', what)
        if raw_syntax is not None:
            self.syntax = InsnSyntax.from_yaml(self.mnemonic,
                                               raw_syntax.strip())
        else:
            self.syntax = InsnSyntax.from_list(
                [op.name for op in self.operands])

        pattern, op_to_grp = self.syntax.asm_pattern()
        self.asm_pattern = re.compile(pattern)
        self.pattern_op_to_grp = op_to_grp

        # Make sure we have exactly the operands we expect.
        if set(self.name_to_operand.keys()) != self.syntax.op_set:
            raise ValueError("Operand syntax for {!r} doesn't have the "
                             "same list of operands as given in the "
                             "operand list. The syntax uses {}, "
                             "but the list of operands gives {}.".format(
                                 self.mnemonic,
                                 list(sorted(self.syntax.op_set)),
                                 list(sorted(self.name_to_operand))))

        self.python_pseudo_op = check_bool(yd.get('python-pseudo-op', False),
                                           'python-pseudo-op flag for ' + what)
        if self.python_pseudo_op and self.encoding is not None:
            raise ValueError('{} specifies an encoding and also sets '
                             'python-pseudo-op.'.format(what))

        lpo = yd.get('literal-pseudo-op')
        if lpo is None:
            self.literal_pseudo_op = None
        else:
            lpo_lst = check_list(lpo, 'literal-pseudo-op flag for ' + what)
            for idx, item in enumerate(lpo_lst):
                if not isinstance(item, str):
                    raise ValueError(
                        'Item {} of literal-pseudo-op list for '
                        '{} is {!r}, which is not a string.'.format(
                            idx, what, item))
            self.literal_pseudo_op = cast(Optional[List[str]], lpo_lst)

            if self.python_pseudo_op:
                raise ValueError('{} specifies both python-pseudo-op and '
                                 'literal-pseudo-op.'.format(what))
            if self.encoding is not None:
                raise ValueError('{} specifies both an encoding and '
                                 'literal-pseudo-op.'.format(what))

        lsu_yaml = yd.get('lsu', None)
        if lsu_yaml is None:
            self.lsu = None
        else:
            self.lsu = LSUDesc.from_yaml(lsu_yaml,
                                         'lsu field for {}'.format(what))
            for idx, op_name in enumerate(self.lsu.target):
                if op_name not in self.name_to_operand:
                    raise ValueError('element {} of the target for the lsu '
                                     'field for {} is {!r}, which is not a '
                                     'operand name of the instruction.'.format(
                                         idx, what, op_name))

        self.straight_line = yd.get('straight-line', True)