move FPDIV, FPMUL (etc) to ISAFPHelpers class
[openpower-isa.git] / src / openpower / decoder / pseudo / parser.py
index ed9fae793903fab942c89f0ec2feab218634ef40..b2215d38aa8e9abf81f9dd778c317a5be3f37140 100644 (file)
@@ -25,10 +25,12 @@ import ast
 
 regs = ['RA', 'RS', 'RB', 'RC', 'RT']
 fregs = ['FRA', 'FRS', 'FRB', 'FRC', 'FRT', 'FRS']
+SPECIAL_HELPERS = {'concat', 'MEM', 'GPR', 'FPR', 'SPR'}
+
 
 def Assign(autoassign, assignname, left, right, iea_mode):
     names = []
-    print("Assign", assignname, left, right)
+    print("Assign", autoassign, assignname, left, right)
     if isinstance(left, ast.Name):
         # Single assignment on left
         # XXX when doing IntClass, which will have an "eq" function,
@@ -62,10 +64,12 @@ def Assign(autoassign, assignname, left, right, iea_mode):
             # the declaration makes the slice-assignment "work"
             lower, upper, step = ls.lower, ls.upper, ls.step
             print("lower, upper, step", repr(lower), repr(upper), step)
-            if not isinstance(lower, ast.Constant) or \
-               not isinstance(upper, ast.Constant):
-                return res
-            qty = ast.Num(upper.value-lower.value)
+            # XXX relax constraint that indices on auto-assign have
+            # to be constants x[0:32]
+            #if not isinstance(lower, ast.Constant) or \
+            #   not isinstance(upper, ast.Constant):
+            #    return res
+            qty = ast.BinOp(upper, binary_ops['-'], lower)
             keywords = [ast.keyword(arg='repeat', value=qty)]
             l = [ast.Num(0)]
             right = ast.Call(ast.Name("concat", ast.Load()), l, keywords)
@@ -176,10 +180,22 @@ def check_concat(node):  # checks if the comparison is already a concat
 
 # identify SelectableInt pattern [something] * N
 # must return concat(something, repeat=N)
+# here is a TEMPORARY hack to support minimal expressions
+# such as (XLEN-16), looking for ast.BinOp
+# have to keep an eye on this
 def identify_sint_mul_pattern(p):
+    """here we are looking for patterns of this type:
+        [item] * something
+    these must specifically be returned as concat(item, repeat=something)
+    """
+    #print ("identify_sint_mul_pattern")
+    #for pat in p:
+    #    print("    ", astor.dump_tree(pat))
     if p[2] != '*':  # multiply
         return False
-    if not isinstance(p[3], ast.Constant):  # rhs = Num
+    if (not isinstance(p[3], ast.Constant) and  # rhs = Num
+        not isinstance(p[3], ast.BinOp) and     # rhs = (XLEN-something)
+        not isinstance(p[3], ast.Name)):        # rhs = XLEN
         return False
     if not isinstance(p[1], ast.List):  # lhs is a list
         return False
@@ -201,6 +217,10 @@ def apply_trailer(atom, trailer, read_regs):
                 name = arg.id
                 if name in regs + fregs:
                     read_regs.add(name)
+        # special-case, these functions must NOT be made "self.xxxx"
+        if atom.id not in SPECIAL_HELPERS:
+            name = ast.Name("self", ast.Load())
+            atom = ast.Attribute(name, atom, ast.Load())
         return ast.Call(atom, trailer[1], [])
         # if p[1].id == 'print':
         #    p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
@@ -268,8 +288,9 @@ class PowerParser:
         ("left", "INVERT"),
     )
 
-    def __init__(self, form, include_carry_in_write=False):
+    def __init__(self, form, include_carry_in_write=False, helper=False):
         self.include_ca_in_write = include_carry_in_write
+        self.helper = helper
         self.gprs = {}
         if form is not None:
             form = self.sd.sigforms[form]
@@ -333,10 +354,11 @@ class PowerParser:
     def p_parameters(self, p):
         """parameters : LPAR RPAR
                       | LPAR varargslist RPAR"""
-        if len(p) == 3:
-            args = []
-        else:
-            args = p[2]
+        args = []
+        if self.helper:
+            args.append("self")
+        if len(p) != 3:
+            args += p[2]
         p[0] = ast.arguments(args=args, vararg=None, kwarg=None, defaults=[])
         # during the time between parameters identified and suite is not
         # there is a window of opportunity to declare the function parameters
@@ -393,10 +415,10 @@ class PowerParser:
                       | expr_stmt"""
         if isinstance(p[1], ast.Call):
             p[0] = ast.Expr(p[1])
-        elif isinstance(p[1], ast.Name) and p[1].id == 'TRAP':
-            # TRAP needs to actually be a function
+        elif isinstance(p[1], ast.Name) and p[1].id not in SPECIAL_HELPERS:
+            fname = p[1].id
             name = ast.Name("self", ast.Load())
-            name = ast.Attribute(name, "TRAP", ast.Load())
+            name = ast.Attribute(name, fname, ast.Load())
             p[0] = ast.Call(name, [], [])
         else:
             p[0] = p[1]
@@ -421,8 +443,14 @@ class PowerParser:
             if isinstance(p[1], ast.Name):
                 name = p[1].id
             elif isinstance(p[1], ast.Subscript):
+                print ("assign subscript", p[1].value,
+                                           self.declared_vars,
+                                           self.fnparm_vars,
+                                           self.special_regs)
+                print(astor.dump_tree(p[1]))
                 if isinstance(p[1].value, ast.Name):
                     name = p[1].value.id
+                    print ("assign subscript value to name", name)
                     if name in self.gprs:
                         # add to list of uninitialised
                         self.uninit_regs.add(name)
@@ -490,20 +518,12 @@ class PowerParser:
         p[0] = ast.Break()
 
     def p_for_stmt(self, p):
-        """for_stmt : FOR atom EQ test TO test COLON suite
-                    | DO atom EQ test TO test COLON suite
+        """for_stmt : FOR atom EQ comparison TO comparison COLON suite
+                    | DO atom EQ comparison TO comparison COLON suite
         """
         start = p[4]
         end = p[6]
-        if start.value > end.value:  # start greater than end, must go -ve
-            # auto-subtract-one (sigh) due to python range
-            end = ast.BinOp(p[6], ast.Add(), ast.Constant(-1))
-            arange = [start, end, ast.Constant(-1)]
-        else:
-            # auto-add-one (sigh) due to python range
-            end = ast.BinOp(p[6], ast.Add(), ast.Constant(1))
-            arange = [start, end]
-        it = ast.Call(ast.Name("range", ast.Load()), arange, [])
+        it = ast.Call(ast.Name("RANGE", ast.Load()), (start, end), [])
         p[0] = ast.For(p[2], it, p[8], [])
 
     def p_while_stmt(self, p):
@@ -648,7 +668,7 @@ class PowerParser:
                       | comparison BITXOR comparison
                       | comparison BITAND comparison
                       | PLUS comparison
-                      | comparison MINUS
+                      | MINUS comparison
                       | INVERT comparison
                       | comparison APPEND comparison
                       | power"""
@@ -726,7 +746,9 @@ class PowerParser:
         if self.include_ca_in_write:
             if name in ['CA', 'CA32']:
                 self.write_regs.add(name)
-        if name in ['CR', 'LR', 'CTR', 'TAR', 'FPSCR', 'MSR', 'SVSTATE']:
+        if name in ['CR', 'LR', 'CTR', 'TAR', 'FPSCR', 'MSR',
+                     'SVSTATE', 'SVREMAP',
+                     'SVSHAPE0', 'SVSHAPE1', 'SVSHAPE2', 'SVSHAPE3']:
             self.special_regs.add(name)
             self.write_regs.add(name)  # and add to list to write
         p[0] = ast.Name(id=name, ctx=ast.Load())
@@ -891,10 +913,10 @@ class PowerParser:
 
 
 class GardenSnakeParser(PowerParser):
-    def __init__(self, lexer=None, debug=False, form=None, incl_carry=False):
+    def __init__(self, lexer=None, debug=False, form=None, incl_carry=False, helper=False):
         if form is not None:
             self.sd = create_pdecode()
-        PowerParser.__init__(self, form, incl_carry)
+        PowerParser.__init__(self, form, incl_carry, helper=helper)
         self.debug = debug
         if lexer is None:
             lexer = IndentLexer(debug=0)
@@ -906,6 +928,8 @@ class GardenSnakeParser(PowerParser):
     def parse(self, code):
         # self.lexer.input(code)
         result = self.parser.parse(code, lexer=self.lexer, debug=self.debug)
+        if self.helper:
+            result = [ast.ClassDef("ISACallerFnHelper", ["ISACallerHelper"], [], result, decorator_list=[])]
         return ast.Module(result)
 
 
@@ -918,19 +942,19 @@ _CACHE_PARSERS = True
 
 
 class GardenSnakeCompiler(object):
-    def __init__(self, debug=False, form=None, incl_carry=False):
+    def __init__(self, debug=False, form=None, incl_carry=False, helper=False):
         if _CACHE_PARSERS:
             try:
-                parser = _CACHED_PARSERS[debug, form, incl_carry]
+                parser = _CACHED_PARSERS[debug, form, incl_carry, helper]
             except KeyError:
                 parser = GardenSnakeParser(debug=debug, form=form,
-                                           incl_carry=incl_carry)
-                _CACHED_PARSERS[debug, form, incl_carry] = parser
+                                           incl_carry=incl_carry, helper=helper)
+                _CACHED_PARSERS[debug, form, incl_carry, helper] = parser
 
             self.parser = deepcopy(parser)
         else:
             self.parser = GardenSnakeParser(debug=debug, form=form,
-                                            incl_carry=incl_carry)
+                                            incl_carry=incl_carry, helper=helper)
 
     def compile(self, code, mode="exec", filename="<string>"):
         tree = self.parser.parse(code)