Commit d20b4715
d20b4715d1e6Merged
Yusuke Endoh <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified
Description
fix(codegen): skip body emission when if/unless predicate folds to static FALSE/TRUE
compile_cond_expr already returns the literal "FALSE" string
when the predicate is statically nil (e.g. an attr_reader for an
ivar whose only init is = nil) — same for "TRUE" on a
statically-truthy predicate. Today the if/unless emit always
wraps the body in if (cond) { ... }, so a if @stackprof_mode
where @stackprof_mode is statically nil emits
if (FALSE) { lv_out = sp_str_sub(_t, "MODE", iv_stackprof_mode); }
with iv_stackprof_mode defaulted to mrb_int (the only assignment
visible was = nil). The body is unreachable but still passes
through the C compiler and trips -Wint-conversion.
Drop the body entirely when cond is statically FALSE; for the
else side, emit it at the surrounding scope. Symmetric handling
in compile_unless_stmt. Behavior is preserved (the dead body
was already unreachable at runtime); the only change is that
type errors hidden inside the dead branch no longer reach gcc.
Details
- Commit
- d20b4715d1e6
- Parent
- 59f48e594a9d
spinel_codegen.rbmodifiedView file
def compile_if_stmt(nid) cond = compile_cond_expr(@nd_predicate[nid]) # Static-false fold: a predicate whose static type is `nil` # (e.g. an attr_reader for an ivar only ever assigned `nil`) # collapses to `if (FALSE) { … }`. The body is unreachable, but # its statements still pass through the C compiler — and they # often type-error against ivars/methods whose shapes only make # sense when the predicate is true. Drop the body entirely; emit # the else branch (if any) at the surrounding scope. if cond == "FALSE" sub_sf = @nd_subsequent[nid] if sub_sf >= 0 if @nd_type[sub_sf] == "ElseNode" compile_stmts_body(@nd_body[sub_sf]) else compile_if_stmt(sub_sf) end end return end if cond == "TRUE" compile_stmts_body(@nd_body[nid]) return end emit(" if (" + cond + ") {") @indent = @indent + 1 compile_stmts_body(@nd_body[nid]) def compile_unless_stmt(nid) cond = compile_cond_expr(@nd_predicate[nid]) # Symmetric to compile_if_stmt's static-fold: an `unless` whose # predicate is statically TRUE drops its body, FALSE drops the # else branch. if cond == "TRUE" ec_sf = @nd_else_clause[nid] if ec_sf >= 0 compile_stmts_body(@nd_body[ec_sf]) end return end if cond == "FALSE" compile_stmts_body(@nd_body[nid]) return end emit(" if (!(" + cond + ")) {") @indent = @indent + 1 compile_stmts_body(@nd_body[nid])test/if_static_false_skips_dead_branch_compile.rbaddedView file
Loading diff…
test/if_static_false_skips_dead_branch_compile.rb.expectedaddedView file
Loading diff…