Skip to content

Commit 4c41c87

Browse files
committed
Implement SSA optimizations for phi nodes
This eliminates trivial phi nodes with identical operands, converts division by power-of-2 to right shift, and converts modulo by power-of-2 to bitwise AND.
1 parent 826a107 commit 4c41c87

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

src/ssa.c

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2397,7 +2397,56 @@ void optimize(void)
23972397
}
23982398
}
23992399

2400-
/* TODO: Phi node optimization */
2400+
/* Phi node optimization - eliminate trivial phi nodes */
2401+
if (insn->opcode == OP_phi && insn->phi_ops) {
2402+
/* Count unique operands */
2403+
var_t *first_var = insn->phi_ops->var;
2404+
bool all_same = true;
2405+
2406+
for (phi_operand_t *op = insn->phi_ops->next; op;
2407+
op = op->next) {
2408+
if (op->var != first_var) {
2409+
all_same = false;
2410+
break;
2411+
}
2412+
}
2413+
2414+
/* Replace trivial phi with simple assignment */
2415+
if (all_same && first_var) {
2416+
insn->opcode = OP_assign;
2417+
insn->rs1 = first_var;
2418+
insn->rs2 = NULL;
2419+
}
2420+
}
2421+
2422+
/* Simple strength reduction for division by power of 2 */
2423+
if (insn->opcode == OP_div && insn->rs2 &&
2424+
insn->rs2->is_const) {
2425+
int val = insn->rs2->init_val;
2426+
/* Check if power of 2 */
2427+
if (val > 0 && (val & (val - 1)) == 0) {
2428+
/* Convert to right shift */
2429+
int shift = 0;
2430+
while (val > 1) {
2431+
val >>= 1;
2432+
shift++;
2433+
}
2434+
insn->opcode = OP_rshift;
2435+
insn->rs2->init_val = shift;
2436+
}
2437+
}
2438+
2439+
/* Simple strength reduction for modulo by power of 2 */
2440+
if (insn->opcode == OP_mod && insn->rs2 &&
2441+
insn->rs2->is_const) {
2442+
int val = insn->rs2->init_val;
2443+
/* Check if power of 2 */
2444+
if (val > 0 && (val & (val - 1)) == 0) {
2445+
/* Convert to bitwise AND */
2446+
insn->opcode = OP_bit_and;
2447+
insn->rs2->init_val = val - 1;
2448+
}
2449+
}
24012450

24022451
/* more optimizations */
24032452
}

0 commit comments

Comments
 (0)