LibJS: Dead code elimination for always truthy/falsey conditions

This improves and expands the ability to do dead code elimination on
conditions which are always truthy or falsey.

The following cases are now optimized:
* `if (true){}` -> Only emit `if` block, ignore `else`
* `if (false){}` -> Only emit `else if`/`else` block
* `while (false){}` -> Ignore `while` loop entirely
* `for (x;false;){}` -> Only emit `x` (if it exists), skip `for` block
* Ternary -> Directly return left/right hand side if condition is const
This commit is contained in:
dosisod
2026-01-25 10:57:43 -08:00
committed by Andreas Kling
parent 89cbe44c71
commit 2c3077b878
Notes: github-actions[bot] 2026-02-06 10:51:09 +00:00
4 changed files with 341 additions and 34 deletions

View File

@@ -1404,15 +1404,11 @@ bool Generator::fuse_compare_and_jump(ScopedOperand const& condition, Label true
void Generator::emit_jump_if(ScopedOperand const& condition, Label true_target, Label false_target)
{
if (condition.operand().is_constant()) {
auto value = m_constants[condition.operand().index()];
if (value.is_boolean()) {
if (value.as_bool()) {
emit<Op::Jump>(true_target);
} else {
emit<Op::Jump>(false_target);
}
return;
}
auto value = get_constant(condition);
auto is_always_true = value.to_boolean_slow_case();
emit<Op::Jump>(is_always_true ? true_target : false_target);
return;
}
// NOTE: It's only safe to fuse compare-and-jump if the condition is a temporary with no other dependents.