@@ -20,6 +20,10 @@ def lit_eq(op: IROperand, val: int) -> bool:
2020 return isinstance (op , IRLiteral ) and wrap256 (op .value ) == wrap256 (val )
2121
2222
23+ def is_negative (x ):
24+ return bool (x & (1 << 255 ))
25+
26+
2327class AlgebraicOptimizationPass (IRPass ):
2428 """
2529 This pass reduces algebraic evaluatable expressions.
@@ -139,10 +143,6 @@ def _fold_add_chain(self, inst: IRInstruction) -> bool:
139143 assert isinstance (op0 , IRLiteral ) # help mypy
140144 total = eval_arith ("sub" , [op0 , IRLiteral (total )])
141145 base_operand = op1
142- elif self ._is_lit (op1 ) and not self ._is_lit (op0 ):
143- assert isinstance (op1 , IRLiteral ) # help mypy
144- total = eval_arith ("sub" , [IRLiteral (total ), op1 ])
145- base_operand = op0
146146 else :
147147 return False
148148
@@ -201,11 +201,6 @@ def _trace_add_chain(self, operand: IROperand) -> tuple[IROperand, int]:
201201 total = eval_arith ("sub" , [IRLiteral (total ), op0 ])
202202 current = op1
203203 continue
204- if self ._is_lit (op1 ) and not self ._is_lit (op0 ):
205- assert isinstance (op1 , IRLiteral ) # help mypy
206- total = eval_arith ("sub" , [op1 , IRLiteral (total )])
207- current = op0
208- continue
209204 break
210205
211206 break
@@ -311,10 +306,6 @@ def _handle_inst_peephole(self, inst: IRInstruction):
311306 # no more cases for this instruction
312307 return
313308
314- if inst .opcode in {"add" , "sub" }:
315- if self ._fold_add_chain (inst ):
316- return
317-
318309 if inst .opcode in {"add" , "sub" , "xor" }:
319310 # (x - x) == (x ^ x) == 0
320311 if inst .opcode in ("xor" , "sub" ) and operands [0 ] == operands [1 ]:
@@ -338,6 +329,10 @@ def _handle_inst_peephole(self, inst: IRInstruction):
338329 if inst .opcode == "xor" and lit_eq (operands [0 ], - 1 ):
339330 self .updater .update (inst , "not" , [operands [1 ]])
340331 return
332+
333+ if inst .opcode in {"add" , "sub" }:
334+ if self ._fold_add_chain (inst ):
335+ return
341336
342337 return
343338
0 commit comments