Commit 1ea24b3b

1ea24b3bdc46Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified

Description

fix(codegen): DCE uncalled cls methods to skip non-compiling bodies

A class method defined but never called still emitted a body that must type-check. When the body had bare new(args) and the defining class's own new had different arity (typically because initialize is no-arg), the C compiler rejected sp_<class>_new with "too many arguments". With a default-arg initialize the failure pivoted to type mismatch — sp_<class>_new got synthesized with a typed param while the uncalled cls method's own param couldn't be inferred without a caller.

The canonical Active Record def self.create(attrs); new(attrs); ...; end on ActiveRecord::Base (where Base#initialize is no-arg) hit this. With the propagate pass from issue #224, the broken body multiplied across every subclass. Sam Ruby's Roundhouse blog hit four of six remaining real-blog C errors on this single shape.

Independent of #224 (the dispatch fix): bisecting Sam's repro showed the same C output on e4af8e9 (pre-#224) and 63f6c84 (post-#224). Sister bug, unreached-emit complement.

Implementation: dead-code eliminate cls methods with no call site. compute_live_cls_methods runs before forward-decl + body emit:

  • Phase A walks the AST collecting calls of three shapes: <Const>.<m>(...) — explicit class receiver <Mod>.<acc>.<m>(...) — module singleton accessor constant-folded by Pass 2.7 to a class name (issue #126 / #229 interaction; the receiver is a CallNode at AST level so the constant arm doesn't catch it directly) self.<m>(...) and bare <m>(...) inside cls method bodies — but only when ctx_ci is set, i.e. the body walk knows which class's cls method we're in.

  • Phase B iterates: for each live entry, walk its body with ctx_ci set so transitive cls-to-cls calls reach. Stops at fixpoint or 8 iterations.

  • emit_forward_decls + emit_class_methods both consult @cls_cmeth_live and skip uncalled entries.

Replaces the issue #224 body_has_bare_new_with_args skip. That skip only handled the no-initialize-in-chain case; default- arg-initialize's type-mismatch surface needed the more general "would this body C-compile?" question, which DCE sidesteps.

Selfhost gotcha: String#index returns nil in CRuby but mrb_int (-1 / 0+) in spinel, and ix == nil compiles to ix == 0. The first listed live entry would misclassify as missing. Lookup uses String#include? instead (clean true/false in both).

Bootstrap clean (gen2.c == gen3.c). 283 pass, 0 fail. Test fixture covers all three Sam-Ruby variants: solo class with arity mismatch, 3-class inheritance with one leaf called, default-arg initialize type mismatch.

Closes #229 Refs #224

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
1ea24b3bdc46
Parent
60f1b75ea8d0

spinel_codegen.rbmodifiedView file

@@ -11409,6 +11409,13 @@
1140911409 end
1141011410 gi = gi + 1
1141111411 end
11412+ # Issue #229: compute the live set of cls methods before any
11413+ # cls-method-related emit. Forward decls + bodies both consult
11414+ # @cls_cmeth_live to skip uncalled methods that may otherwise
11415+ # emit non-compiling bodies (uncalled `def self.factory(attrs);
11416+ # new(attrs); end` against a 0-arg or differently-typed
11417+ # constructor).
11418+ compute_live_cls_methods
1141211419 emit_forward_decls
1141311420 emit_global_constants
1141411421 emit_raw("/*LAMBDA_INSERT_POINT*/")
@@ -13199,12 +13206,20 @@
1319913206 cm_ptypes = @cls_cmeth_ptypes[i].split("|")
1320013207 j = 0
1320113208 while j < cmnames.length
13202- rt = "int"
13203- if j < cm_returns.length
13204- rt = cm_returns[j]
13209+ # Issue #229: skip forward decls for dead cls methods so the
13210+ # linker doesn't see "declared here" without a definition
13211+ # (the corresponding emit_class_methods skip would still
13212+ # otherwise leave the prototype dangling).
13213+ if cls_cmeth_is_live(i, cmnames[j]) == 0
13214+ j = j + 1
13215+ else
13216+ rt = "int"
13217+ if j < cm_returns.length
13218+ rt = cm_returns[j]
13219+ end
13220+ emit_raw("static " + c_type(rt) + " sp_" + cname + "_cls_" + sanitize_name(cmnames[j]) + "(" + cls_method_params_decl(j, cm_params, cm_ptypes) + ");")
13221+ j = j + 1
1320513222 end
13206- emit_raw("static " + c_type(rt) + " sp_" + cname + "_cls_" + sanitize_name(cmnames[j]) + "(" + cls_method_params_decl(j, cm_params, cm_ptypes) + ");")
13207- j = j + 1
1320813223 end
1320913224 i = i + 1
1321013225 end
@@ -13581,17 +13596,16 @@
1358113596 if j < cm_ptypes.length
1358213597 ptypes = cm_ptypes[j].split(",")
1358313598 end
13584- # Issue #224: a class's cls method whose body has bare
13585- # `new(args)` would emit `sp_<this_class>_new(args)`. If
13586- # this class has no resolvable initialize (no own one and
13587- # no inherited one), the synthesized constructor is 0-arg —
13588- # so the call wouldn't C-compile. This shape only arises
13589- # when a *parent* class defines `def self.factory(attrs);
13590- # new(attrs); ...; end` to be inherited by subclasses with
13591- # an attrs-taking initialize; calling the parent's version
13592- # directly is a runtime error in CRuby anyway. Skip emit
13593- # rather than producing a non-compiling body.
13594- if bid > 0 && find_init_class(i) < 0 && body_has_bare_new_with_args(bid) == 1
13599+ # Issue #229: dead-code-eliminate cls methods with no call
13600+ # site. The bug is that an unused `def self.factory(attrs);
13601+ # new(attrs); ...; end` emits a body whose `sp_<this>_new(args)`
13602+ # may not match the defining class's actual constructor
13603+ # arity/types — spinel can't infer types for an uncalled
13604+ # method, so the body fails to C-compile. compute_live_cls_methods
13605+ # ran before emit and seeded live entries from explicit
13606+ # `<Class>.<m>(...)` call sites + transitive self/bare calls
13607+ # within live cls method bodies.
13608+ if cls_cmeth_is_live(i, cmnames[j]) == 0
1359513609 j = j + 1
1359613610 else
1359713611 emit_class_level_method(i, cmnames[j], pnames, ptypes, rt, bid)
@@ -13602,101 +13616,232 @@
1360213616 end
1360313617 end
1360413618
13605- # Issue #224: detect bare `new(args)` (recv < 0, args.length > 0)
13606- # anywhere in a cls method body. Used by emit_class_methods to
13607- # skip emitting a class's version of an inherited method when the
13608- # class has no resolvable initialize — emitting would synthesize
13609- # `sp_<class>_new(args)` against a 0-arg default constructor and
13610- # the C compiler would reject the body. The synthetic copies on
13611- # subclasses (with their own initialize) emit normally.
13612- def body_has_bare_new_with_args(nid)
13613- if nid < 0
13619+ # Issue #229: dead-code elimination for cls methods. An uncalled
13620+ # `def self.factory(attrs); new(attrs); ...; end` on a parent
13621+ # class whose own `initialize` has different arity emits a body
13622+ # that doesn't C-compile (`sp_<class>_new(args)` against a 0-arg
13623+ # constructor; or, with a default-arg `initialize`, against a
13624+ # typed param when the uncalled method's own param can't be
13625+ # inferred). The reachability set seeds from explicit
13626+ # `<Class>.<m>(...)` call sites in the AST, then propagates
13627+ # through bare/self calls inside live cls method bodies. Anything
13628+ # not reached is skipped at forward-decl + body emit time.
13629+ #
13630+ # Live entries are stored as `<ClassName>::<methodName>` joined
13631+ # by `;` in @cls_cmeth_live. Idempotent: marking an already-live
13632+ # entry is a no-op.
13633+ def compute_live_cls_methods
13634+ @cls_cmeth_live = ""
13635+ collect_cls_calls(@root_id, -1)
13636+ iter = 0
13637+ prev_len = @cls_cmeth_live.length
13638+ while iter < 8
13639+ i = 0
13640+ while i < @cls_names.length
13641+ cmnames = @cls_cmeth_names[i].split(";")
13642+ cm_bodies = @cls_cmeth_bodies[i].split(";")
13643+ j = 0
13644+ while j < cmnames.length
13645+ if cmnames[j] != "" && cls_cmeth_is_live(i, cmnames[j]) == 1
13646+ bid = -1
13647+ if j < cm_bodies.length
13648+ bs = cm_bodies[j]
13649+ if bs != ""
13650+ bid = bs.to_i
13651+ end
13652+ end
13653+ if bid > 0
13654+ collect_cls_calls(bid, i)
13655+ end
13656+ end
13657+ j = j + 1
13658+ end
13659+ i = i + 1
13660+ end
13661+ cur_len = @cls_cmeth_live.length
13662+ if cur_len == prev_len
13663+ return
13664+ end
13665+ prev_len = cur_len
13666+ iter = iter + 1
13667+ end
13668+ end
13669+
13670+ def cls_cmeth_is_live(ci, mname)
13671+ if ci < 0 || ci >= @cls_names.length
1361413672 return 0
1361513673 end
13616- if @nd_type[nid] == "CallNode" && @nd_name[nid] == "new" && @nd_receiver[nid] < 0
13617- args_id = @nd_arguments[nid]
13618- if args_id >= 0
13619- arg_ids = get_args(args_id)
13620- if arg_ids.length > 0
13621- return 1
13674+ if @cls_cmeth_live == nil || @cls_cmeth_live == ""
13675+ return 0
13676+ end
13677+ # Sentinel-bracketed lookup so "Foo::bar" doesn't match
13678+ # "Foo::barbaz". `String#include?` returns a clean true/false in
13679+ # both CRuby and spinel; `String#index` works in CRuby but in
13680+ # spinel returns mrb_int (-1 / 0+) and `ix == nil` compiles to
13681+ # `ix == 0`, misclassifying the first-listed entry as missing.
13682+ needle = ";" + @cls_names[ci] + "::" + mname + ";"
13683+ haystack = ";" + @cls_cmeth_live + ";"
13684+ if haystack.include?(needle)
13685+ return 1
13686+ end
13687+ 0
13688+ end
13689+
13690+ def cls_cmeth_mark_live(ci, mname)
13691+ if ci < 0 || ci >= @cls_names.length
13692+ return
13693+ end
13694+ cmnames = @cls_cmeth_names[ci].split(";")
13695+ has = 0
13696+ k = 0
13697+ while k < cmnames.length
13698+ if cmnames[k] == mname
13699+ has = 1
13700+ end
13701+ k = k + 1
13702+ end
13703+ if has == 0
13704+ return
13705+ end
13706+ if cls_cmeth_is_live(ci, mname) == 1
13707+ return
13708+ end
13709+ entry = @cls_names[ci] + "::" + mname
13710+ if @cls_cmeth_live == ""
13711+ @cls_cmeth_live = entry
13712+ else
13713+ @cls_cmeth_live = @cls_cmeth_live + ";" + entry
13714+ end
13715+ end
13716+
13717+ # Walk the subtree at `nid`, marking cls methods reached by:
13718+ # - `<Const>.<m>(...)` (any context)
13719+ # - `self.<m>(...)` (only when ctx_ci >= 0, i.e.
13720+ # we're walking inside a cls method body of class ctx_ci)
13721+ # - bare `<m>(...)` with no recv (ditto; `<m>` resolves to
13722+ # a cls method on ctx_ci if one exists with that name)
13723+ #
13724+ # ctx_ci is propagated unchanged through normal nodes, but cleared
13725+ # to -1 when descending into a DefNode body (a nested method has
13726+ # its own scope; bare calls there resolve to top-level methods or
13727+ # to that DefNode's own class context, neither of which we want
13728+ # to attribute to the outer cls method).
13729+ def collect_cls_calls(nid, ctx_ci)
13730+ if nid < 0
13731+ return
13732+ end
13733+ if @nd_type[nid] == "CallNode"
13734+ recv = @nd_receiver[nid]
13735+ mname = @nd_name[nid]
13736+ if recv >= 0
13737+ if @nd_type[recv] == "ConstantReadNode" || @nd_type[recv] == "ConstantPathNode"
13738+ cname = constructor_class_name(recv)
13739+ if cname != ""
13740+ tci = find_class_idx(cname)
13741+ if tci >= 0
13742+ cls_cmeth_mark_live(tci, mname)
13743+ end
13744+ end
13745+ end
13746+ if @nd_type[recv] == "SelfNode" && ctx_ci >= 0
13747+ cls_cmeth_mark_live(ctx_ci, mname)
1362213748 end
13749+ # Issue #126 / #229 interaction: `<Module>.<acc>.<method>`
13750+ # where `<Module>.<acc>` was constant-folded by Pass 2.7
13751+ # (resolve_module_singleton_accessors) to a class name.
13752+ # The receiver is a CallNode at AST level, so the
13753+ # ConstantReadNode branch above doesn't catch it. Look up
13754+ # the fold and mark the resolved class's cls method live.
13755+ if @nd_type[recv] == "CallNode"
13756+ inner_recv = @nd_receiver[recv]
13757+ if inner_recv >= 0 && @nd_type[inner_recv] == "ConstantReadNode"
13758+ mod_name = @nd_name[inner_recv]
13759+ resolved = module_acc_resolved(mod_name, @nd_name[recv])
13760+ if resolved != "" && resolved != "?"
13761+ rnames = resolved.split(";")
13762+ ri = 0
13763+ while ri < rnames.length
13764+ tci2 = find_class_idx(rnames[ri])
13765+ if tci2 >= 0
13766+ cls_cmeth_mark_live(tci2, mname)
13767+ end
13768+ ri = ri + 1
13769+ end
13770+ end
13771+ end
13772+ end
13773+ else
13774+ if ctx_ci >= 0
13775+ cls_cmeth_mark_live(ctx_ci, mname)
13776+ end
1362313777 end
1362413778 end
13779+ # Don't descend into nested DefNode bodies: they have their own
13780+ # scope and a separate phase walks each live cls method body
13781+ # with the correct ctx_ci.
13782+ if @nd_type[nid] == "DefNode"
13783+ return
13784+ end
1362513785 if @nd_body[nid] >= 0
13626- if body_has_bare_new_with_args(@nd_body[nid]) == 1
13627- return 1
13628- end
13786+ collect_cls_calls(@nd_body[nid], ctx_ci)
1362913787 end
13630- bn_stmts = parse_id_list(@nd_stmts[nid])
13788+ cs_stmts = parse_id_list(@nd_stmts[nid])
1363113789 k = 0
13632- while k < bn_stmts.length
13633- if body_has_bare_new_with_args(bn_stmts[k]) == 1
13634- return 1
13635- end
13790+ while k < cs_stmts.length
13791+ collect_cls_calls(cs_stmts[k], ctx_ci)
1363613792 k = k + 1
1363713793 end
1363813794 if @nd_receiver[nid] >= 0
13639- if body_has_bare_new_with_args(@nd_receiver[nid]) == 1
13640- return 1
13641- end
13795+ collect_cls_calls(@nd_receiver[nid], ctx_ci)
1364213796 end
1364313797 if @nd_arguments[nid] >= 0
13644- if body_has_bare_new_with_args(@nd_arguments[nid]) == 1
13645- return 1
13646- end
13798+ collect_cls_calls(@nd_arguments[nid], ctx_ci)
1364713799 end
13648- bn_args = parse_id_list(@nd_args[nid])
13800+ cs_args = parse_id_list(@nd_args[nid])
1364913801 k = 0
13650- while k < bn_args.length
13651- if body_has_bare_new_with_args(bn_args[k]) == 1
13652- return 1
13653- end
13802+ while k < cs_args.length
13803+ collect_cls_calls(cs_args[k], ctx_ci)
1365413804 k = k + 1
1365513805 end
1365613806 if @nd_expression[nid] >= 0
13657- if body_has_bare_new_with_args(@nd_expression[nid]) == 1
13658- return 1
13659- end
13807+ collect_cls_calls(@nd_expression[nid], ctx_ci)
1366013808 end
1366113809 if @nd_predicate[nid] >= 0
13662- if body_has_bare_new_with_args(@nd_predicate[nid]) == 1
13663- return 1
13664- end
13810+ collect_cls_calls(@nd_predicate[nid], ctx_ci)
1366513811 end
1366613812 if @nd_subsequent[nid] >= 0
13667- if body_has_bare_new_with_args(@nd_subsequent[nid]) == 1
13668- return 1
13669- end
13813+ collect_cls_calls(@nd_subsequent[nid], ctx_ci)
1367013814 end
1367113815 if @nd_else_clause[nid] >= 0
13672- if body_has_bare_new_with_args(@nd_else_clause[nid]) == 1
13673- return 1
13674- end
13816+ collect_cls_calls(@nd_else_clause[nid], ctx_ci)
1367513817 end
1367613818 if @nd_left[nid] >= 0
13677- if body_has_bare_new_with_args(@nd_left[nid]) == 1
13678- return 1
13679- end
13819+ collect_cls_calls(@nd_left[nid], ctx_ci)
1368013820 end
1368113821 if @nd_right[nid] >= 0
13682- if body_has_bare_new_with_args(@nd_right[nid]) == 1
13683- return 1
13684- end
13822+ collect_cls_calls(@nd_right[nid], ctx_ci)
1368513823 end
1368613824 if @nd_block[nid] >= 0
13687- if body_has_bare_new_with_args(@nd_block[nid]) == 1
13688- return 1
13689- end
13825+ collect_cls_calls(@nd_block[nid], ctx_ci)
1369013826 end
13691- bn_elems = parse_id_list(@nd_elements[nid])
13827+ cs_elems = parse_id_list(@nd_elements[nid])
1369213828 k = 0
13693- while k < bn_elems.length
13694- if body_has_bare_new_with_args(bn_elems[k]) == 1
13695- return 1
13696- end
13829+ while k < cs_elems.length
13830+ collect_cls_calls(cs_elems[k], ctx_ci)
13831+ k = k + 1
13832+ end
13833+ cs_conds = parse_id_list(@nd_conditions[nid])
13834+ k = 0
13835+ while k < cs_conds.length
13836+ collect_cls_calls(cs_conds[k], ctx_ci)
13837+ k = k + 1
13838+ end
13839+ cs_parts = parse_id_list(@nd_parts[nid])
13840+ k = 0
13841+ while k < cs_parts.length
13842+ collect_cls_calls(cs_parts[k], ctx_ci)
1369713843 k = k + 1
1369813844 end
13699- 0
1370013845 end
1370113846
1370213847 def emit_constructor(ci)