From 6b8b91de620d6caad15a931d3ff9618d46d88070 Mon Sep 17 00:00:00 2001 From: Jan Matyas Date: Wed, 8 Jan 2025 20:55:37 +0100 Subject: [PATCH] registers.py: Fix subtractions in generated C code The registers.py generator outputs expressions with subtractions into the C code of debug_defines.{h,c} in this form: ``` ((XLEN) + -6ULL) ``` Such code may look awkward to code readers and also triggers GCC's -Wconversion warnings (when enabled). Fix the generator to produce the expressions with subtraction in a natural form: ``` ((XLEN) - 6ULL) ``` --- registers.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/registers.py b/registers.py index d936a075..84cd8106 100755 --- a/registers.py +++ b/registers.py @@ -472,7 +472,22 @@ def sympy_to_c(expression, sym_to_c = lambda s: f"({s})", unsigned=True): elif isinstance(expression, sympy.Symbol): return sym_to_c(expression) elif isinstance(expression, sympy.Add): - return "(" + " + ".join(stc(t) for t in reversed(expression.args)) + ")" + args = list(reversed(expression.args)) + result = "" + for i in range(len(args)): + arg = args[i] + is_first = (i == 0) + if is_first: + result += stc(arg) + else: + # Simplify additions of negative constants: + # Use (a - 1) instead of (a + -1) + negative_constant = arg.is_constant() and (arg < 0) + result += " - " if negative_constant else " + " + if negative_constant: + arg = -arg # flip to positive + result += stc(arg) + return "(" + result + ")" elif isinstance(expression, sympy.Mul): return "(" + " * ".join(stc(t) for t in expression.args) + ")" elif isinstance(expression, sympy.Pow):