xref: /qemu/target/hexagon/hex_common.py (revision 7bdd67a5)
1#!/usr/bin/env python3
2
3##
4##  Copyright(c) 2019-2023 Qualcomm Innovation Center, Inc. All Rights Reserved.
5##
6##  This program is free software; you can redistribute it and/or modify
7##  it under the terms of the GNU General Public License as published by
8##  the Free Software Foundation; either version 2 of the License, or
9##  (at your option) any later version.
10##
11##  This program is distributed in the hope that it will be useful,
12##  but WITHOUT ANY WARRANTY; without even the implied warranty of
13##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14##  GNU General Public License for more details.
15##
16##  You should have received a copy of the GNU General Public License
17##  along with this program; if not, see <http://www.gnu.org/licenses/>.
18##
19
20import sys
21import re
22import string
23
24behdict = {}          # tag ->behavior
25semdict = {}          # tag -> semantics
26attribdict = {}       # tag -> attributes
27macros = {}           # macro -> macro information...
28attribinfo = {}       # Register information and misc
29tags = []             # list of all tags
30overrides = {}        # tags with helper overrides
31idef_parser_enabled = {} # tags enabled for idef-parser
32
33# We should do this as a hash for performance,
34# but to keep order let's keep it as a list.
35def uniquify(seq):
36    seen = set()
37    seen_add = seen.add
38    return [x for x in seq if x not in seen and not seen_add(x)]
39
40regre = re.compile(
41    r"((?<!DUP)[MNORCPQXSGVZA])([stuvwxyzdefg]+)([.]?[LlHh]?)(\d+S?)")
42immre = re.compile(r"[#]([rRsSuUm])(\d+)(?:[:](\d+))?")
43reg_or_immre = \
44    re.compile(r"(((?<!DUP)[MNRCOPQXSGVZA])([stuvwxyzdefg]+)" + \
45                "([.]?[LlHh]?)(\d+S?))|([#]([rRsSuUm])(\d+)[:]?(\d+)?)")
46relimmre = re.compile(r"[#]([rR])(\d+)(?:[:](\d+))?")
47absimmre = re.compile(r"[#]([sSuUm])(\d+)(?:[:](\d+))?")
48
49finished_macros = set()
50
51def expand_macro_attribs(macro,allmac_re):
52    if macro.key not in finished_macros:
53        # Get a list of all things that might be macros
54        l = allmac_re.findall(macro.beh)
55        for submacro in l:
56            if not submacro: continue
57            if not macros[submacro]:
58                raise Exception("Couldn't find macro: <%s>" % l)
59            macro.attribs |= expand_macro_attribs(
60                macros[submacro], allmac_re)
61            finished_macros.add(macro.key)
62    return macro.attribs
63
64# When qemu needs an attribute that isn't in the imported files,
65# we'll add it here.
66def add_qemu_macro_attrib(name, attrib):
67    macros[name].attribs.add(attrib)
68
69immextre = re.compile(r'f(MUST_)?IMMEXT[(]([UuSsRr])')
70
71def is_cond_jump(tag):
72    if tag == 'J2_rte':
73        return False
74    if ('A_HWLOOP0_END' in attribdict[tag] or
75        'A_HWLOOP1_END' in attribdict[tag]):
76        return False
77    return \
78        re.compile(r"(if.*fBRANCH)|(if.*fJUMPR)").search(semdict[tag]) != None
79
80def is_cond_call(tag):
81    return re.compile(r"(if.*fCALL)").search(semdict[tag]) != None
82
83def calculate_attribs():
84    add_qemu_macro_attrib('fREAD_PC', 'A_IMPLICIT_READS_PC')
85    add_qemu_macro_attrib('fTRAP', 'A_IMPLICIT_READS_PC')
86    add_qemu_macro_attrib('fWRITE_P0', 'A_WRITES_PRED_REG')
87    add_qemu_macro_attrib('fWRITE_P1', 'A_WRITES_PRED_REG')
88    add_qemu_macro_attrib('fWRITE_P2', 'A_WRITES_PRED_REG')
89    add_qemu_macro_attrib('fWRITE_P3', 'A_WRITES_PRED_REG')
90    add_qemu_macro_attrib('fSET_OVERFLOW', 'A_IMPLICIT_WRITES_USR')
91    add_qemu_macro_attrib('fSET_LPCFG', 'A_IMPLICIT_WRITES_USR')
92    add_qemu_macro_attrib('fLOAD', 'A_SCALAR_LOAD')
93    add_qemu_macro_attrib('fSTORE', 'A_SCALAR_STORE')
94
95    # Recurse down macros, find attributes from sub-macros
96    macroValues = list(macros.values())
97    allmacros_restr = "|".join(set([ m.re.pattern for m in macroValues ]))
98    allmacros_re = re.compile(allmacros_restr)
99    for macro in macroValues:
100        expand_macro_attribs(macro,allmacros_re)
101    # Append attributes to all instructions
102    for tag in tags:
103        for macname in allmacros_re.findall(semdict[tag]):
104            if not macname: continue
105            macro = macros[macname]
106            attribdict[tag] |= set(macro.attribs)
107    # Figure out which instructions write predicate registers
108    tagregs = get_tagregs()
109    for tag in tags:
110        regs = tagregs[tag]
111        for regtype, regid, toss, numregs in regs:
112            if regtype == "P" and is_written(regid):
113                attribdict[tag].add('A_WRITES_PRED_REG')
114    # Mark conditional jumps and calls
115    #     Not all instructions are properly marked with A_CONDEXEC
116    for tag in tags:
117        if is_cond_jump(tag) or is_cond_call(tag):
118            attribdict[tag].add('A_CONDEXEC')
119
120def SEMANTICS(tag, beh, sem):
121    #print tag,beh,sem
122    behdict[tag] = beh
123    semdict[tag] = sem
124    attribdict[tag] = set()
125    tags.append(tag)        # dicts have no order, this is for order
126
127def ATTRIBUTES(tag, attribstring):
128    attribstring = \
129        attribstring.replace("ATTRIBS","").replace("(","").replace(")","")
130    if not attribstring:
131        return
132    attribs = attribstring.split(",")
133    for attrib in attribs:
134        attribdict[tag].add(attrib.strip())
135
136class Macro(object):
137    __slots__ = ['key','name', 'beh', 'attribs', 're']
138    def __init__(self, name, beh, attribs):
139        self.key = name
140        self.name = name
141        self.beh = beh
142        self.attribs = set(attribs)
143        self.re = re.compile("\\b" + name + "\\b")
144
145def MACROATTRIB(macname,beh,attribstring):
146    attribstring = attribstring.replace("(","").replace(")","")
147    if attribstring:
148        attribs = attribstring.split(",")
149    else:
150        attribs = []
151    macros[macname] = Macro(macname,beh,attribs)
152
153def compute_tag_regs(tag):
154    return uniquify(regre.findall(behdict[tag]))
155
156def compute_tag_immediates(tag):
157    return uniquify(immre.findall(behdict[tag]))
158
159##
160##  tagregs is the main data structure we'll use
161##  tagregs[tag] will contain the registers used by an instruction
162##  Within each entry, we'll use the regtype and regid fields
163##      regtype can be one of the following
164##          C                control register
165##          N                new register value
166##          P                predicate register
167##          R                GPR register
168##          M                modifier register
169##          Q                HVX predicate vector
170##          V                HVX vector register
171##          O                HVX new vector register
172##      regid can be one of the following
173##          d, e             destination register
174##          dd               destination register pair
175##          s, t, u, v, w    source register
176##          ss, tt, uu, vv   source register pair
177##          x, y             read-write register
178##          xx, yy           read-write register pair
179##
180def get_tagregs():
181    return dict(zip(tags, list(map(compute_tag_regs, tags))))
182
183def get_tagimms():
184    return dict(zip(tags, list(map(compute_tag_immediates, tags))))
185
186def is_pair(regid):
187    return len(regid) == 2
188
189def is_single(regid):
190    return len(regid) == 1
191
192def is_written(regid):
193    return regid[0] in "dexy"
194
195def is_writeonly(regid):
196    return regid[0] in "de"
197
198def is_read(regid):
199    return regid[0] in "stuvwxy"
200
201def is_readwrite(regid):
202    return regid[0] in "xy"
203
204def is_scalar_reg(regtype):
205    return regtype in "RPC"
206
207def is_hvx_reg(regtype):
208    return regtype in "VQ"
209
210def is_old_val(regtype, regid, tag):
211    return regtype+regid+'V' in semdict[tag]
212
213def is_new_val(regtype, regid, tag):
214    return regtype+regid+'N' in semdict[tag]
215
216def need_slot(tag):
217    if (('A_CONDEXEC' in attribdict[tag] and
218         'A_JUMP' not in attribdict[tag]) or
219        'A_STORE' in attribdict[tag] or
220        'A_LOAD' in attribdict[tag]):
221        return 1
222    else:
223        return 0
224
225def need_part1(tag):
226    return re.compile(r"fPART1").search(semdict[tag])
227
228def need_ea(tag):
229    return re.compile(r"\bEA\b").search(semdict[tag])
230
231def need_PC(tag):
232    return 'A_IMPLICIT_READS_PC' in attribdict[tag]
233
234def helper_needs_next_PC(tag):
235    return 'A_CALL' in attribdict[tag]
236
237def need_pkt_has_multi_cof(tag):
238    return 'A_COF' in attribdict[tag]
239
240def need_condexec_reg(tag, regs):
241    if 'A_CONDEXEC' in attribdict[tag]:
242        for regtype, regid, toss, numregs in regs:
243            if is_writeonly(regid) and not is_hvx_reg(regtype):
244                return True
245    return False
246
247def skip_qemu_helper(tag):
248    return tag in overrides.keys()
249
250def is_tmp_result(tag):
251    return ('A_CVI_TMP' in attribdict[tag] or
252            'A_CVI_TMP_DST' in attribdict[tag])
253
254def is_new_result(tag):
255    return ('A_CVI_NEW' in attribdict[tag])
256
257def is_idef_parser_enabled(tag):
258    return tag in idef_parser_enabled
259
260def imm_name(immlett):
261    return "%siV" % immlett
262
263def read_semantics_file(name):
264    eval_line = ""
265    for line in open(name, 'rt').readlines():
266        if not line.startswith("#"):
267            eval_line += line
268            if line.endswith("\\\n"):
269                eval_line.rstrip("\\\n")
270            else:
271                eval(eval_line.strip())
272                eval_line = ""
273
274def read_attribs_file(name):
275    attribre = re.compile(r'DEF_ATTRIB\(([A-Za-z0-9_]+), ([^,]*), ' +
276            r'"([A-Za-z0-9_\.]*)", "([A-Za-z0-9_\.]*)"\)')
277    for line in open(name, 'rt').readlines():
278        if not attribre.match(line):
279            continue
280        (attrib_base,descr,rreg,wreg) = attribre.findall(line)[0]
281        attrib_base = 'A_' + attrib_base
282        attribinfo[attrib_base] = {'rreg':rreg, 'wreg':wreg, 'descr':descr}
283
284def read_overrides_file(name):
285    overridere = re.compile("#define fGEN_TCG_([A-Za-z0-9_]+)\(.*")
286    for line in open(name, 'rt').readlines():
287        if not overridere.match(line):
288            continue
289        tag = overridere.findall(line)[0]
290        overrides[tag] = True
291
292def read_idef_parser_enabled_file(name):
293    global idef_parser_enabled
294    with open(name, "r") as idef_parser_enabled_file:
295        lines = idef_parser_enabled_file.read().strip().split("\n")
296        idef_parser_enabled = set(lines)
297