Commit 20065f23

20065f23ed0dMerged

Yusuke Endoh <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified

Description

fix(codegen): narrow <poly>[k] to int when the source poly_array's elements all return int

compile_poly_method_call("[]") defaults to a poly return because the static dispatch can't pin the element type. When the receiver came from <poly_array>[i] and every element kind observed for that slot has an int-returning [] (IntArray + Method, optcarrot's __fetch__ shape), narrow the outer dispatch back to int. Without this, consuming slots like pc = arr[i][j] cascade to poly and break downstream iv += 1, ~iv, sp_box_int(iv), etc.

Element-kind derivation: read @cls_ivar_observed_types[ci] for the resolved ivar — each observation entry encodes the slot type the ivar held during some scan iteration (int_array, obj_Method_ptr_array, …). When every entry maps to a known int-returning [] shape, narrow safely; bail out otherwise.

LV alias resolution: when the receiver is a local variable (optcarrot's optimized body uses __fetch__ = @fetch aliases), try the codegen-time scope alias first (set_var_ivar_alias populated on lv = @ivar writes), then fall back to walking the enclosing class's method bodies for an unambiguous lv_name = @ivar write (memoized in @lv_alias_cache). The fallback covers the inference-time path where the scope stack isn't yet populated.

Dispatch-arm gating: when narrowing fires, suppress arms that would type-mismatch against the int-typed result temp — PtrArray, PolyArray, and user classes whose [] doesn't return int. Those arms are unreachable at runtime by construction (the observation set excluded them).

Companion to PR #pr/poly-int-auto-unify-arith (operator-site auto-unbox). Together they drop the six .to_i injection patches in optcarrot_build.sh and keep optcarrot at OK:59662.

Details

Commit
20065f23ed0d
Parent
59f48e594a9d

spinel_codegen.rbmodifiedView file

@@ -153,6 +153,10 @@
153153 # distinct types per ivar; the outer dimension is semicolon-
154154 # separated and parallel to `@cls_ivar_names[ci]`.
155155 @cls_ivar_observed_types = "".split(",")
156+ # Memoization for `find_lv_ivar_alias_in_ast`. Keyed by
157+ # `"<class_idx>:<lv_name>"`, value is the resolved ivar name (or
158+ # `""` when the LV has multiple sources / non-ivar writes).
159+ @lv_alias_cache = {}
156160 # Top-level (script-scope) ivars. Lowered to `static` file-scope
157161 # globals because `main()` / top-level `def` bodies have no `self`.
158162 @toplevel_ivar_names = "".split(",")
@@ -237,6 +241,13 @@
237241 # ---- Scope stack for local variables ----
238242 @scope_names = "".split(",")
239243 @scope_types = "".split(",")
244+ # Parallel to `@scope_names`: when a local was assigned directly
245+ # from an ivar read (`lv = @ivar`), record the ivar name here so
246+ # later sites that need ivar-side metadata (notably the
247+ # `<poly>[k]` narrowing in `compile_poly_method_call`) can
248+ # resolve through the alias. Empty string when the local has no
249+ # such alias (or had a non-ivar write since).
250+ @scope_ivar_alias = "".split(",")
240251
241252 # Issue #207: type narrowing introduced by `is_a?`/`kind_of?`
242253 # guards. While walking the then-arm of `if v.is_a?(Hash)` or
@@ -1278,6 +1289,7 @@
12781289 def push_scope
12791290 @scope_names.push("---")
12801291 @scope_types.push("---")
1292+ @scope_ivar_alias.push("---")
12811293 0
12821294 end
12831295
@@ -1287,16 +1299,19 @@
12871299 if top_name == "---"
12881300 @scope_names.pop
12891301 @scope_types.pop
1302+ @scope_ivar_alias.pop
12901303 return
12911304 end
12921305 @scope_names.pop
12931306 @scope_types.pop
1307+ @scope_ivar_alias.pop
12941308 end
12951309 end
12961310
12971311 def declare_var(name, vtype)
12981312 @scope_names.push(name)
12991313 @scope_types.push(vtype)
1314+ @scope_ivar_alias.push("")
13001315 0
13011316 end
13021317
@@ -1327,6 +1342,31 @@
13271342 end
13281343 end
13291344
1345+ # Record / clear an ivar alias for a local variable. Walks the
1346+ # `@scope_*` parallel stacks like `set_var_type` does. `iname` is
1347+ # the source ivar name (e.g. `@fetch`); pass `""` to clear.
1348+ def set_var_ivar_alias(name, iname)
1349+ i = @scope_names.length - 1
1350+ while i >= 0
1351+ if @scope_names[i] == name
1352+ @scope_ivar_alias[i] = iname
1353+ return
1354+ end
1355+ i = i - 1
1356+ end
1357+ end
1358+
1359+ def find_var_ivar_alias(name)
1360+ i = @scope_names.length - 1
1361+ while i >= 0
1362+ if @scope_names[i] == name
1363+ return @scope_ivar_alias[i]
1364+ end
1365+ i = i - 1
1366+ end
1367+ ""
1368+ end
1369+
13301370 def find_var_type(name)
13311371 # Type-narrow override (issue #207): walk top-down so the
13321372 # innermost is_a? guard wins. Skipped for the unscoped global
@@ -4303,6 +4343,13 @@
43034343 return "string"
43044344 end
43054345 if rt == "poly"
4346+ # Approach 2: narrow `<poly>[k]` to int when the receiver
4347+ # came from a poly_array whose observed element kinds all
4348+ # imply int-returning `[]`. Mirrors the codegen-side
4349+ # narrowing in `compile_poly_method_call`.
4350+ if poly_index_narrow_int(nid) == 1
4351+ return "int"
4352+ end
43064353 return "poly"
43074354 end
43084355 if rt == "int_array"
@@ -4763,6 +4810,15 @@
47634810 return "bool"
47644811 end
47654812 if mname == "[]"
4813+ # Narrow `<poly>[k]` to int when the receiver came from a
4814+ # poly_array whose observed slot-type history all imply
4815+ # int-returning element kinds (IntArray, Method). Keep this
4816+ # in sync with `compile_poly_method_call`'s codegen-side
4817+ # narrowing — divergence widens the consuming slot to poly
4818+ # while emit produces int.
4819+ if poly_index_narrow_int(nid) == 1
4820+ return "int"
4821+ end
47664822 return "poly"
47674823 end
47684824 # Scan every user class that defines this method. If they all
@@ -27131,6 +27187,186 @@
2713127187 0
2713227188 end
2713327189
27190+ # Decide whether a `<poly>[k]` call site (the outer `[]` in
27191+ # `arr[i][k]` chains) can return int instead of poly. The poly
27192+ # value came from `arr[i]` where `arr` is a poly_array; if every
27193+ # element kind observed for `arr`'s slot has an int-returning
27194+ # `[]` (IntArray + Method, the optcarrot `__fetch__` shape), the
27195+ # outer dispatch is guaranteed to land on a poly carrying an int
27196+ # tag, and we can read it as `mrb_int` directly. Returns 0
27197+ # whenever the chain doesn't fit the pattern, so the default
27198+ # poly-typed temp is preserved for everything else.
27199+ def poly_index_narrow_int(nid)
27200+ recv_id = @nd_receiver[nid]
27201+ if recv_id < 0
27202+ return 0
27203+ end
27204+ # The receiver must itself be a `[]` call (`arr[i]`).
27205+ if @nd_type[recv_id] != "CallNode" || @nd_name[recv_id] != "[]"
27206+ return 0
27207+ end
27208+ inner_recv = @nd_receiver[recv_id]
27209+ if inner_recv < 0
27210+ return 0
27211+ end
27212+ # Resolve the inner receiver to an ivar (directly, or via a
27213+ # one-step LV alias from `lv = @ivar`).
27214+ iname = ""
27215+ if @nd_type[inner_recv] == "InstanceVariableReadNode"
27216+ iname = @nd_name[inner_recv]
27217+ elsif @nd_type[inner_recv] == "LocalVariableReadNode"
27218+ lv_name = @nd_name[inner_recv]
27219+ # Codegen-time scope alias takes priority (set by the LV-write
27220+ # handler when `lv = @ivar` is emitted in this scope).
27221+ iname = find_var_ivar_alias(lv_name)
27222+ # Fallback for inference-time (`infer_type` before codegen,
27223+ # when the scope stack hasn't been populated yet): walk the
27224+ # enclosing method bodies for a single, unambiguous
27225+ # `lv_name = @ivar` write. If the LV is reassigned from a
27226+ # non-ivar elsewhere, leave iname empty and let the caller
27227+ # bail out — the alias is no longer load-bearing.
27228+ if iname == ""
27229+ iname = find_lv_ivar_alias_in_ast(lv_name)
27230+ end
27231+ end
27232+ if iname == "" || @current_class_idx < 0
27233+ return 0
27234+ end
27235+ # The slot must currently be a poly_array — the only shape that
27236+ # produces a poly via `[i]`.
27237+ slot_t = cls_ivar_type(@current_class_idx, iname)
27238+ if slot_t != "poly_array"
27239+ return 0
27240+ end
27241+ # Derive the heterogeneous element kinds from
27242+ # `cls_ivar_observed_types`. Each entry there is a slot type
27243+ # the ivar held at some scan iteration: `int_array` means int
27244+ # elements were stored, `obj_Method_ptr_array` means Method
27245+ # elements, etc. The final `poly_array` entry just records the
27246+ # widened state and adds no info. A bare `poly` observation
27247+ # (whole-ivar `@x = something_poly`) is unknown — bail out.
27248+ obs = cls_ivar_observed_types_for(@current_class_idx, iname)
27249+ if obs == ""
27250+ return 0
27251+ end
27252+ distinct = obs.split(",")
27253+ saw_any = 0
27254+ di = 0
27255+ while di < distinct.length
27256+ t = distinct[di]
27257+ if t == "" || t == "poly_array"
27258+ # ignore — uninformative
27259+ elsif t == "int_array" || t == "obj_Method_ptr_array"
27260+ # int-returning element kind
27261+ saw_any = 1
27262+ else
27263+ # any other observed slot type (str_array, float_array,
27264+ # other ptr_array variants, "poly" whole-ivar writes…) is
27265+ # not safely narrowable.
27266+ return 0
27267+ end
27268+ di = di + 1
27269+ end
27270+ saw_any
27271+ end
27272+
27273+ # Inference-time fallback for resolving `lv_name -> @ivar` when the
27274+ # codegen scope alias isn't available yet. Walks every method body
27275+ # in the current class for `lv_name = @ivar` writes. Returns the
27276+ # ivar name only if the LV is unambiguously aliased (one ivar
27277+ # source, no non-ivar reassignment); empty string otherwise. Cached
27278+ # in `@lv_alias_cache_<class>:<lv>` to keep the per-narrow cost
27279+ # down — this is called during type inference, which runs many
27280+ # iterations.
27281+ def find_lv_ivar_alias_in_ast(lv_name)
27282+ if @current_class_idx < 0
27283+ return ""
27284+ end
27285+ cache_key = @current_class_idx.to_s + ":" + lv_name
27286+ if @lv_alias_cache.key?(cache_key)
27287+ return @lv_alias_cache[cache_key]
27288+ end
27289+ found = ""
27290+ bodies = @cls_meth_bodies[@current_class_idx].split(";")
27291+ bi = 0
27292+ while bi < bodies.length
27293+ bid = bodies[bi].to_i
27294+ if bid >= 0
27295+ r = scan_lv_alias_for(bid, lv_name)
27296+ if r == "?"
27297+ # Ambiguous: at least one non-ivar write to this LV. The
27298+ # alias is unstable and unsafe to use for narrowing.
27299+ found = ""
27300+ break
27301+ end
27302+ if r != ""
27303+ if found != "" && found != r
27304+ found = ""
27305+ break
27306+ end
27307+ found = r
27308+ end
27309+ end
27310+ bi = bi + 1
27311+ end
27312+ @lv_alias_cache[cache_key] = found
27313+ found
27314+ end
27315+
27316+ # Recursive AST walk under `nid`. Returns:
27317+ # "" — no `lv_name = ...` write seen
27318+ # "?" — `lv_name = <non-ivar>` write seen (alias is unstable)
27319+ # "@x" — exactly one ivar source `lv_name = @x` seen
27320+ def scan_lv_alias_for(nid, lv_name)
27321+ if nid < 0
27322+ return ""
27323+ end
27324+ found = ""
27325+ if @nd_type[nid] == "LocalVariableWriteNode" && @nd_name[nid] == lv_name
27326+ ex_id = @nd_expression[nid]
27327+ if ex_id >= 0 && @nd_type[ex_id] == "InstanceVariableReadNode"
27328+ found = @nd_name[ex_id]
27329+ else
27330+ return "?"
27331+ end
27332+ end
27333+ cs = []
27334+ push_child_ids(nid, cs)
27335+ k = 0
27336+ while k < cs.length
27337+ r = scan_lv_alias_for(cs[k], lv_name)
27338+ if r == "?"
27339+ return "?"
27340+ end
27341+ if r != ""
27342+ if found != "" && found != r
27343+ return "?"
27344+ end
27345+ found = r
27346+ end
27347+ k = k + 1
27348+ end
27349+ found
27350+ end
27351+
27352+ # Read the comma-separated whole-ivar observation list for a given
27353+ # ivar by name. Used by `poly_index_narrow_int`.
27354+ def cls_ivar_observed_types_for(ci, iname)
27355+ if ci < 0 || ci >= @cls_ivar_observed_types.length
27356+ return ""
27357+ end
27358+ names = @cls_ivar_names[ci].split(";")
27359+ parts = @cls_ivar_observed_types[ci].split(";", -1)
27360+ k = 0
27361+ while k < names.length
27362+ if names[k] == iname && k < parts.length
27363+ return parts[k]
27364+ end
27365+ k = k + 1
27366+ end
27367+ ""
27368+ end
27369+
2713427370 def poly_dispatch_return_type(mname)
2713527371 if mname == "[]"
2713627372 @needs_rb_value = 1
@@ -27294,6 +27530,21 @@
2729427530 # classes disagree on that type, the result is sp_RbVal and each
2729527531 # branch boxes its concrete return value.
2729627532 ret_type = poly_dispatch_return_type(mname)
27533+ # Approach 2 narrowing: `<poly>[k]` defaults to poly because the
27534+ # static `[]` dispatch can't pin the return; check whether the
27535+ # poly receiver here came from `<poly_array>[i]` whose every
27536+ # observed element kind has an int-returning `[]` (IntArray,
27537+ # Method-with-int-return). If so, narrow to int so the slot
27538+ # @_pc / @_addr / etc. on the caller side stays mrb_int instead
27539+ # of widening to sp_RbVal and breaking downstream `iv += 1`,
27540+ # `~poly`, and friends.
27541+ narrowed_int_idx = 0
27542+ if ret_type == "poly" && mname == "[]"
27543+ narrowed_int_idx = poly_index_narrow_int(nid)
27544+ if narrowed_int_idx == 1
27545+ ret_type = "int"
27546+ end
27547+ end
2729727548 is_poly_ret = ret_type == "poly" ? 1 : 0
2729827549 ret_ct = c_type(ret_type)
2729927550 ret_def = c_default_val(ret_type)
@@ -27393,7 +27644,16 @@
2739327644 this_rt = cls_method_return(i, mname)
2739427645 rhs = box_val_to_poly(call_expr, this_rt)
2739527646 end
27396- emit(" if (" + recv_tmp + ".cls_id == " + i.to_s + ") " + tmp + " = " + rhs + ";")
27647+ # Narrowed `[]` arms (Approach 2): suppress user-class arms
27648+ # whose `[]` doesn't return int — the dead-code emit would
27649+ # otherwise assign e.g. a string to the now-mrb_int result
27650+ # temp and fail the C compile. The runtime can't reach these
27651+ # arms anyway because the observation set narrowed past them.
27652+ if narrowed_int_idx == 1 && cls_method_return(i, mname) != "int"
27653+ # skip
27654+ else
27655+ emit(" if (" + recv_tmp + ".cls_id == " + i.to_s + ") " + tmp + " = " + rhs + ";")
27656+ end
2739727657 elsif cls_has_attr_reader(i, mname) == 1
2739827658 # An auto-registered attr_reader doesn't appear in
2739927659 # @cls_meth_names, so the explicit-method walk above misses it.
@@ -27404,12 +27664,16 @@
2740427664 this_rt = cls_ivar_type(i, "@" + mname)
2740527665 rhs = box_val_to_poly(ivar_expr, this_rt)
2740627666 end
27407- emit(" if (" + recv_tmp + ".cls_id == " + i.to_s + ") " + tmp + " = " + rhs + ";")
27667+ if narrowed_int_idx == 1 && cls_ivar_type(i, "@" + mname) != "int"
27668+ # skip non-int attr_reader arms on a narrowed `[]`
27669+ else
27670+ emit(" if (" + recv_tmp + ".cls_id == " + i.to_s + ") " + tmp + " = " + rhs + ";")
27671+ end
2740827672 end
2740927673 i = i + 1
2741027674 end
2741127675 # Built-in type dispatch (cls_id < 0).
27412- emit_poly_builtin_dispatch(recv_tmp, mname, arg_compiled, arg_types, tmp, is_poly_ret)
27676+ emit_poly_builtin_dispatch(recv_tmp, mname, arg_compiled, arg_types, tmp, is_poly_ret, narrowed_int_idx)
2741327677 emit(" }")
2741427678 tmp
2741527679 end
@@ -27417,7 +27681,7 @@
2741727681 # Emit branches for the built-in (negative cls_id) entries. Each
2741827682 # entry maps a (SP_BUILTIN_*, method) pair to a C expression.
2741927683 # Adding a new built-in type means one more `if` branch here.
27420- def emit_poly_builtin_dispatch(recv_tmp, mname, arg_compiled, arg_types, result_tmp, is_poly_ret)
27684+ def emit_poly_builtin_dispatch(recv_tmp, mname, arg_compiled, arg_types, result_tmp, is_poly_ret, narrowed_int = 0)
2742127685 a0 = ""
2742227686 if arg_compiled.length > 0
2742327687 a0 = arg_compiled[0]
@@ -27465,16 +27729,26 @@
2746527729 # implicitly convertible to any pointer for the non-poly path
2746627730 # (result_tmp may be `sp_Foo *`) and accepted directly by
2746727731 # sp_box_obj for the poly path. Casting through mrb_int would
27468- # fail to compile when result_tmp is a pointer type.
27469- pc = "sp_PtrArray_get((sp_PtrArray *)" + recv_tmp + ".v.p, " + a0 + ")"
27470- prhs = is_poly_ret == 1 ? "sp_box_obj(" + pc + ", 0)" : pc
27471- emit(" if (" + recv_tmp + ".cls_id == SP_BUILTIN_PTR_ARRAY) " + result_tmp + " = " + prhs + ";")
27732+ # fail to compile when result_tmp is a pointer type — and the
27733+ # narrowed-`[]` path (Approach 2) types result_tmp as mrb_int,
27734+ # so PtrArray cls_ids are unobserved by construction. Skip the
27735+ # arm in that case.
27736+ if narrowed_int == 0
27737+ pc = "sp_PtrArray_get((sp_PtrArray *)" + recv_tmp + ".v.p, " + a0 + ")"
27738+ prhs = is_poly_ret == 1 ? "sp_box_obj(" + pc + ", 0)" : pc
27739+ emit(" if (" + recv_tmp + ".cls_id == SP_BUILTIN_PTR_ARRAY) " + result_tmp + " = " + prhs + ";")
27740+ end
2747227741 # PolyArray dispatch — sp_PolyArray_get returns sp_RbVal directly.
2747327742 # When the result temp is poly, just assign; otherwise unbox via .v.i
2747427743 # (the typed temp's static type drives caller-side conversion).
27475- polyc = "sp_PolyArray_get((sp_PolyArray *)" + recv_tmp + ".v.p, " + a0 + ")"
27476- polyrhs = is_poly_ret == 1 ? polyc : "(" + polyc + ").v.i"
27477- emit(" if (" + recv_tmp + ".cls_id == SP_BUILTIN_POLY_ARRAY) " + result_tmp + " = " + polyrhs + ";")
27744+ # Narrowed-`[]` likewise excludes PolyArray from the observed
27745+ # set: the arm is unreachable, and emitting `.v.i` against a
27746+ # cls_id that won't match at runtime is harmless but noisy.
27747+ if narrowed_int == 0
27748+ polyc = "sp_PolyArray_get((sp_PolyArray *)" + recv_tmp + ".v.p, " + a0 + ")"
27749+ polyrhs = is_poly_ret == 1 ? polyc : "(" + polyc + ").v.i"
27750+ emit(" if (" + recv_tmp + ".cls_id == SP_BUILTIN_POLY_ARRAY) " + result_tmp + " = " + polyrhs + ";")
27751+ end
2747827752 # Method dispatch — `bm[arg]` / `bm[a1, a2]` on a Method instance
2747927753 # is `bm.call(...)`. When bm came through a heterogeneous
2748027754 # poly_array (e.g. optcarrots `@fetch[i] = method(:peek_X)` mixed
@@ -29715,6 +29989,16 @@
2971529989 set_var_type(lname, rhs_t)
2971629990 end
2971729991 end
29992+ # Track `lv = @ivar` as a one-step alias so the `<poly>[k]`
29993+ # narrowing can resolve through the local back to the ivar's
29994+ # element-observation list. Any non-ivar RHS (or a subsequent
29995+ # write of a non-ivar) clears the alias.
29996+ ivar_alias = ""
29997+ ex_id = @nd_expression[nid]
29998+ if ex_id >= 0 && @nd_type[ex_id] == "InstanceVariableReadNode"
29999+ ivar_alias = @nd_name[ex_id]
30000+ end
30001+ set_var_ivar_alias(lname, ivar_alias)
2971830002 return
2971930003 end
2972030004 if t == "LocalVariableOperatorWriteNode"