Skip to content

Commit 474be1a

Browse files
committed
Add phi node optimization
Implement trivial phi node elimination: - Remove phi nodes where all operands are the same variable - Replace with simple assignment (phi(x,x,x) = x) - Fold phi nodes with all same constant values - Convert to load_constant for compile-time evaluation This optimization reduces unnecessary phi operations in SSA form, improving both compile time and generated code quality by eliminating redundant merge points.
1 parent 9b42b28 commit 474be1a

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

src/ssa.c

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2056,7 +2056,57 @@ void optimize(void)
20562056
}
20572057
}
20582058

2059-
/* TODO: Phi node optimization */
2059+
/* Phi node optimization - eliminate trivial phi nodes */
2060+
for (func_t *func = FUNC_LIST.head; func; func = func->next) {
2061+
for (basic_block_t *bb = func->bbs; bb; bb = bb->rpo_next) {
2062+
for (insn_t *insn = bb->insn_list.head; insn; insn = insn->next) {
2063+
if (insn->opcode == OP_phi && insn->phi_ops) {
2064+
/* Count unique operands and check if all are the same */
2065+
var_t *first_var = insn->phi_ops->var;
2066+
bool all_same = true;
2067+
bool all_const = true;
2068+
int const_val = 0;
2069+
int num_ops = 0;
2070+
2071+
for (phi_operand_t *op = insn->phi_ops; op; op = op->next) {
2072+
num_ops++;
2073+
/* Check if all same variable */
2074+
if (op->var != first_var) {
2075+
all_same = false;
2076+
}
2077+
/* Check if all same constant */
2078+
if (op->var && op->var->is_const) {
2079+
if (op == insn->phi_ops) {
2080+
const_val = op->var->init_val;
2081+
} else if (op->var->init_val != const_val) {
2082+
all_const = false;
2083+
}
2084+
} else {
2085+
all_const = false;
2086+
}
2087+
}
2088+
2089+
/* Trivial phi: all operands are the same variable */
2090+
if (all_same && first_var && insn->rd) {
2091+
insn->opcode = OP_assign;
2092+
insn->rs1 = first_var;
2093+
insn->rs2 = NULL;
2094+
insn->phi_ops = NULL;
2095+
}
2096+
/* Constant phi: all operands have the same constant value
2097+
*/
2098+
else if (all_const && num_ops > 0 && insn->rd) {
2099+
insn->opcode = OP_load_constant;
2100+
insn->rd->is_const = true;
2101+
insn->rd->init_val = const_val;
2102+
insn->rs1 = NULL;
2103+
insn->rs2 = NULL;
2104+
insn->phi_ops = NULL;
2105+
}
2106+
}
2107+
}
2108+
}
2109+
}
20602110

20612111
/* Mark useful instructions */
20622112
for (func_t *func = FUNC_LIST.head; func; func = func->next) {

0 commit comments

Comments
 (0)