Skip to content

Commit 6b8b91d

Browse files
committed
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) ```
1 parent a467810 commit 6b8b91d

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

registers.py

+16-1
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,22 @@ def sympy_to_c(expression, sym_to_c = lambda s: f"({s})", unsigned=True):
472472
elif isinstance(expression, sympy.Symbol):
473473
return sym_to_c(expression)
474474
elif isinstance(expression, sympy.Add):
475-
return "(" + " + ".join(stc(t) for t in reversed(expression.args)) + ")"
475+
args = list(reversed(expression.args))
476+
result = ""
477+
for i in range(len(args)):
478+
arg = args[i]
479+
is_first = (i == 0)
480+
if is_first:
481+
result += stc(arg)
482+
else:
483+
# Simplify additions of negative constants:
484+
# Use (a - 1) instead of (a + -1)
485+
negative_constant = arg.is_constant() and (arg < 0)
486+
result += " - " if negative_constant else " + "
487+
if negative_constant:
488+
arg = -arg # flip to positive
489+
result += stc(arg)
490+
return "(" + result + ")"
476491
elif isinstance(expression, sympy.Mul):
477492
return "(" + " * ".join(stc(t) for t in expression.args) + ")"
478493
elif isinstance(expression, sympy.Pow):

0 commit comments

Comments
 (0)