Commit 155b5e4c

155b5e4c75abMerged

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

Description

fix(analyze): narrow poly-recv widening to ivar's observed class set

Closes #513. The poly-receiver param-widening pass in scan_new_calls used to enumerate every user class that defined mname and unify its ptypes from the call-site arg types -- unrelated classes (Server#run vs the Worker.run dispatch in the issue's repro) had their params widened to sp_RbVal even though no instance of theirs could ever reach the dispatch.

Two new helpers in analyze:

  • observed_class_ids_for_recv(recv_nid, ci_context) returns the comma-separated class index set for an InstanceVariableReadNode receiver. Reads cls_ivar_observed_types_for first; when the observed entry is just "poly" (because the rhs of @x = w was a poly param), falls back to recover_concrete_classes_for_ivar.

  • recover_concrete_classes_for_ivar(ci, iname) walks the class's method bodies for @iname = expr writes, classifies param-sourced rhs, and walks the global AST for <Class>.new(...) (or <Class>.<meth>(...)) call sites, collecting concrete obj types from the matching arg position. Memoized per (ci, iname). Any non-trivial rhs poisons the result ("?") and the caller bails to the existing all-classes enumeration.

The poly-recv branch in scan_new_calls' CallNode arm consults the helper. When narrowing applies, only classes in the set are param-widened. Classes outside the set keep their original (concrete) signatures, and the existing arm_incompat check in compile_poly_method_call's cls_id-switch emit naturally drops their arms at codegen time.

For the issue's repro, Server#run's port now stays mrb_int instead of being widened to sp_RbVal, and the Server.new.run(80) call site compiles as straight int arithmetic instead of going through a box/unbox dance.

Test fixture (test/poly_recv_dispatch_narrow.rb) is the issue's 49-line repro; cross-checked against CRuby. Local: 488 tests pass, optcarrot checksum 59662. The Worker dispatch arms (cls_id 21 = WorkerA, 22 = WorkerB) survive; the Server arm (cls_id 24) is correctly dropped from Holder#use's switch.

Known limitations of this iteration:

  • Only InstanceVariableReadNode receivers are narrowed. LocalVariableReadNode and parameter receivers fall through to the all-classes enumeration (the issue's repro doesn't hit those shapes; roundhouse/tep's @worker pattern is the ivar shape).

  • The source walk only handles @x = LocalVariableRead(param) on the rhs. Constructor-call rhs (@x = Worker.new) is already covered by the direct-obs path. Other rhs shapes (chained calls, fetches from another collection) bail to the conservative "all classes" enumeration.

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

Details

Commit
155b5e4c75ab
Parent
7f94e2c65514

spinel_analyze.rbmodifiedView file

@@ -10840,25 +10840,56 @@
1084010840 # default-`int`-typed param produces a Wint-conversion or
1084110841 # incompatible-pointer error. unify_call_types collapses to
1084210842 # `poly` if another call site disagrees.
10843+ #
10844+ # Narrowing (issue #513): when the receiver reads an ivar
10845+ # whose observed-types set is a closed set of obj classes,
10846+ # restrict the walk to that set so unrelated same-named
10847+ # methods (e.g. `Server#run` when the dispatch is through
10848+ # a `@worker` slot that only ever holds Worker* instances)
10849+ # don't get their params widened. observed_class_ids_for_recv
10850+ # returns "" when no narrowing is possible (unknown shape,
10851+ # non-obj observations, or empty set).
1084310852 if rt == "poly"
1084410853 args_id_p = @nd_arguments[nid]
1084510854 if args_id_p >= 0
1084610855 arg_ids_p = get_args(args_id_p)
10856+ obs_ids = observed_class_ids_for_recv(@nd_receiver[nid], @current_class_idx)
10857+ obs_filter = (obs_ids != "")
10858+ obs_list = "".split(",")
10859+ if obs_filter
10860+ obs_list = obs_ids.split(",")
10861+ end
1084710862 ci_p = 0
1084810863 while ci_p < @cls_names.length
10849- midx_p = cls_find_method_direct(ci_p, mname)
10850- if midx_p >= 0
10851- ptypes_p = cls_meth_ptypes_get(ci_p, midx_p)
10852- if ptypes_p.length > 0
10853- kk_p = 0
10854- while kk_p < arg_ids_p.length
10855- if kk_p < ptypes_p.length
10856- at_p = infer_type(arg_ids_p[kk_p])
10857- ptypes_p[kk_p] = unify_call_types(ptypes_p[kk_p], at_p, arg_ids_p[kk_p])
10864+ skip_p = 0
10865+ if obs_filter
10866+ in_set = 0
10867+ ol = 0
10868+ while ol < obs_list.length
10869+ if obs_list[ol].to_i == ci_p
10870+ in_set = 1
10871+ end
10872+ ol = ol + 1
10873+ end
10874+ if in_set == 0
10875+ skip_p = 1
10876+ end
10877+ end
10878+ if skip_p == 0
10879+ midx_p = cls_find_method_direct(ci_p, mname)
10880+ if midx_p >= 0
10881+ ptypes_p = cls_meth_ptypes_get(ci_p, midx_p)
10882+ if ptypes_p.length > 0
10883+ kk_p = 0
10884+ while kk_p < arg_ids_p.length
10885+ if kk_p < ptypes_p.length
10886+ at_p = infer_type(arg_ids_p[kk_p])
10887+ ptypes_p[kk_p] = unify_call_types(ptypes_p[kk_p], at_p, arg_ids_p[kk_p])
10888+ end
10889+ kk_p = kk_p + 1
1085810890 end
10859- kk_p = kk_p + 1
10891+ cls_meth_ptypes_put(ci_p, midx_p, ptypes_p)
1086010892 end
10861- cls_meth_ptypes_put(ci_p, midx_p, ptypes_p)
1086210893 end
1086310894 end
1086410895 ci_p = ci_p + 1
@@ -21630,6 +21661,281 @@
2163021661 ""
2163121662 end
2163221663
21664+ # For a `recv.mname(...)` call where `recv` reads a poly-typed
21665+ # slot, return the comma-separated list of class indices that
21666+ # observation/inference suggests can actually flow into the
21667+ # slot. Returns "" when the analysis can't narrow (unknown
21668+ # receiver shape, no observations, or the set is too wide to
21669+ # filter usefully). The caller — both the analyze poly-recv
21670+ # widening pass and the codegen cls_id-switch emitter — uses
21671+ # the result to skip arms for classes that source-level can't
21672+ # reach the dispatch site. Issue #513.
21673+ #
21674+ # Currently supports InstanceVariableReadNode receivers (the
21675+ # roundhouse / tep shape). When @cls_ivar_observed_types shows
21676+ # "poly" rather than a concrete set (because the rhs of
21677+ # `@x = expr` was a poly-typed param), fall back to an
21678+ # on-demand walk that finds the ivar's writers, traces
21679+ # param-sourced rhs back through the class's call sites, and
21680+ # collects concrete obj types from those arg positions.
21681+ def observed_class_ids_for_recv(recv_nid, ci_context)
21682+ if recv_nid < 0
21683+ return ""
21684+ end
21685+ if @nd_type[recv_nid] != "InstanceVariableReadNode"
21686+ return ""
21687+ end
21688+ if ci_context < 0
21689+ return ""
21690+ end
21691+ iname = @nd_name[recv_nid]
21692+ obs = cls_ivar_observed_types_for(ci_context, iname)
21693+ out = ""
21694+ have_poly = 0
21695+ seen_non_obj = 0
21696+ if obs != ""
21697+ parts = obs.split(",")
21698+ k = 0
21699+ while k < parts.length
21700+ t = parts[k]
21701+ if is_obj_type(t) == 1
21702+ cname = t[4, t.length - 4]
21703+ cidx = find_class_idx(cname)
21704+ if cidx >= 0
21705+ out = obs_add(out, cidx.to_s)
21706+ end
21707+ elsif t == "poly"
21708+ have_poly = 1
21709+ else
21710+ seen_non_obj = 1
21711+ end
21712+ k = k + 1
21713+ end
21714+ end
21715+ # If only obj_X entries (no poly / non-obj noise), return what
21716+ # we have. Empty obs string and a "poly" entry both trigger the
21717+ # source walk below.
21718+ if have_poly == 0 && obs != ""
21719+ if seen_non_obj == 1
21720+ return ""
21721+ end
21722+ return out
21723+ end
21724+ if seen_non_obj == 1
21725+ return ""
21726+ end
21727+ # Source walk: find every `@<iname> = expr` write in the
21728+ # class's method bodies. For each, if expr is a
21729+ # LocalVariableRead of a known param of the enclosing method,
21730+ # walk the AST for call sites of `<Class>.new(...)` (or the
21731+ # enclosing method) and add the concrete obj types observed at
21732+ # the matching arg position. Any rhs that isn't param-sourced
21733+ # or that we can't trace bails out (returns ""), so the caller
21734+ # falls back to the existing all-classes enumeration.
21735+ walked = recover_concrete_classes_for_ivar(ci_context, iname)
21736+ if walked == "?"
21737+ return ""
21738+ end
21739+ if walked != ""
21740+ walked.split(",").each { |w| out = obs_add(out, w) }
21741+ end
21742+ if out == ""
21743+ return ""
21744+ end
21745+ out
21746+ end
21747+
21748+ # Helper: append `cidx_str` to a comma-separated list, dedup'd.
21749+ def obs_add(out, cidx_str)
21750+ if out == ""
21751+ return cidx_str
21752+ end
21753+ cur = out.split(",")
21754+ k = 0
21755+ while k < cur.length
21756+ if cur[k] == cidx_str
21757+ return out
21758+ end
21759+ k = k + 1
21760+ end
21761+ out + "," + cidx_str
21762+ end
21763+
21764+ # On-demand AST walk: for ivar `@<iname>` on class `ci`,
21765+ # find every write site, and for the param-sourced ones,
21766+ # collect concrete obj types from the enclosing method's
21767+ # call sites. Returns:
21768+ # - comma-separated class indices when every write site
21769+ # traces cleanly to a finite obj-typed set
21770+ # - "?" when any write site has a non-param-sourced rhs we
21771+ # can't analyze (poison; caller bails)
21772+ # - "" when no writes were found at all
21773+ # Memoized by (ci, iname) so repeated dispatch-site queries
21774+ # don't re-walk the AST.
21775+ def recover_concrete_classes_for_ivar(ci, iname)
21776+ if @ivar_concrete_recover_cache == nil
21777+ @ivar_concrete_recover_cache = {}
21778+ end
21779+ ck = ci.to_s + ":" + iname
21780+ if @ivar_concrete_recover_cache.key?(ck)
21781+ return @ivar_concrete_recover_cache[ck]
21782+ end
21783+ out = ""
21784+ mnames_w = @cls_meth_names[ci].split(";")
21785+ bodies_w = @cls_meth_bodies[ci].split(";")
21786+ mi_w = 0
21787+ while mi_w < mnames_w.length
21788+ bid_w = -1
21789+ if mi_w < bodies_w.length
21790+ bid_w = bodies_w[mi_w].to_i
21791+ end
21792+ if bid_w >= 0
21793+ meth_name_w = mnames_w[mi_w]
21794+ pnames_w = cls_meth_pnames_get(ci, mi_w)
21795+ result_for_meth = walk_ivar_writes_for_param_sources(bid_w, iname, pnames_w, ci, meth_name_w)
21796+ if result_for_meth == "?"
21797+ @ivar_concrete_recover_cache[ck] = "?"
21798+ return "?"
21799+ end
21800+ if result_for_meth != ""
21801+ result_for_meth.split(",").each { |w| out = obs_add(out, w) }
21802+ end
21803+ end
21804+ mi_w = mi_w + 1
21805+ end
21806+ @ivar_concrete_recover_cache[ck] = out
21807+ out
21808+ end
21809+
21810+ # Walks `bid` for `@<iname> = expr` writes. For each, classifies
21811+ # rhs as param-sourced (returns the param name and we trace
21812+ # call sites) or other (poison "?"). Aggregates concrete obj
21813+ # types found at the call sites' matching arg positions.
21814+ def walk_ivar_writes_for_param_sources(bid, iname, pnames, ci, meth_name)
21815+ out = ""
21816+ poison = 0
21817+ walk_stack = [bid]
21818+ while walk_stack.length > 0
21819+ n = walk_stack.pop
21820+ if n < 0
21821+ next
21822+ end
21823+ if @nd_type[n] == "InstanceVariableWriteNode" && @nd_name[n] == iname
21824+ expr_w = @nd_expression[n]
21825+ if expr_w < 0 || @nd_type[expr_w] != "LocalVariableReadNode"
21826+ poison = 1
21827+ else
21828+ rhs_name = @nd_name[expr_w]
21829+ param_idx = -1
21830+ k = 0
21831+ while k < pnames.length
21832+ if pnames[k] == rhs_name
21833+ param_idx = k
21834+ end
21835+ k = k + 1
21836+ end
21837+ if param_idx < 0
21838+ poison = 1
21839+ else
21840+ call_obs = walk_call_sites_for_class_method(ci, meth_name, param_idx)
21841+ if call_obs == "?"
21842+ poison = 1
21843+ elsif call_obs != ""
21844+ call_obs.split(",").each { |w| out = obs_add(out, w) }
21845+ end
21846+ end
21847+ end
21848+ end
21849+ # Recurse into child slots. Mirror scan_ivars's set of fields.
21850+ if @nd_body[n] >= 0
21851+ walk_stack.push(@nd_body[n])
21852+ end
21853+ if @nd_expression[n] >= 0
21854+ walk_stack.push(@nd_expression[n])
21855+ end
21856+ if @nd_predicate[n] >= 0
21857+ walk_stack.push(@nd_predicate[n])
21858+ end
21859+ if @nd_subsequent[n] >= 0
21860+ walk_stack.push(@nd_subsequent[n])
21861+ end
21862+ if @nd_else_clause[n] >= 0
21863+ walk_stack.push(@nd_else_clause[n])
21864+ end
21865+ if @nd_left[n] >= 0
21866+ walk_stack.push(@nd_left[n])
21867+ end
21868+ if @nd_right[n] >= 0
21869+ walk_stack.push(@nd_right[n])
21870+ end
21871+ stmts_w = parse_id_list(@nd_stmts[n])
21872+ sk = 0
21873+ while sk < stmts_w.length
21874+ walk_stack.push(stmts_w[sk])
21875+ sk = sk + 1
21876+ end
21877+ end
21878+ if poison == 1
21879+ return "?"
21880+ end
21881+ out
21882+ end
21883+
21884+ # For method `meth_name` on class index `ci`, walk the entire
21885+ # AST for `<Class>.new(...)` or `<Class>.<meth>(...)` call
21886+ # sites and return concrete obj class indices observed at
21887+ # position `param_idx`. `?` if any site supplies a non-obj
21888+ # type (poison). Only invocations of `initialize` translate to
21889+ # `<Class>.new(args)` shape; non-initialize methods don't need
21890+ # the .new->initialize remap.
21891+ def walk_call_sites_for_class_method(ci, meth_name, param_idx)
21892+ cname = @cls_names[ci]
21893+ want_new = (meth_name == "initialize")
21894+ out = ""
21895+ poison = 0
21896+ nid = 0
21897+ while nid < @nd_type.length
21898+ if @nd_type[nid] == "CallNode"
21899+ recv_cs = @nd_receiver[nid]
21900+ cs_mname = @nd_name[nid]
21901+ match = 0
21902+ if recv_cs >= 0 && @nd_type[recv_cs] == "ConstantReadNode" && @nd_name[recv_cs] == cname
21903+ if want_new && cs_mname == "new"
21904+ match = 1
21905+ elsif !want_new && cs_mname == meth_name
21906+ match = 1
21907+ end
21908+ end
21909+ if match == 1
21910+ args_cs_id = @nd_arguments[nid]
21911+ if args_cs_id >= 0
21912+ a_cs = get_args(args_cs_id)
21913+ if param_idx < a_cs.length
21914+ at_cs = infer_type(a_cs[param_idx])
21915+ if is_obj_type(at_cs) == 1
21916+ cn = at_cs[4, at_cs.length - 4]
21917+ cidx_cs = find_class_idx(cn)
21918+ if cidx_cs >= 0
21919+ out = obs_add(out, cidx_cs.to_s)
21920+ end
21921+ elsif at_cs == "poly"
21922+ # Caller's arg is already poly — can't narrow further.
21923+ poison = 1
21924+ else
21925+ poison = 1
21926+ end
21927+ end
21928+ end
21929+ end
21930+ end
21931+ nid = nid + 1
21932+ end
21933+ if poison == 1
21934+ return "?"
21935+ end
21936+ out
21937+ end
21938+
2163321939 def poly_dispatch_return_type(mname)
2163421940 if mname == "[]"
2163521941 @needs_rb_value = 1