Commit b0f79557

b0f7955700e9Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified

Description

Make int_array #[] return int? for value-level nil (#1180)

A bare arr[i] on an int_array now infers int? instead of int, so an out-of-bounds read surfaces as Ruby nil (SP_INT_NIL, already returned by sp_IntArray_get) rather than a silent 0. int? shares mrb_int storage with int, so this adds zero hot-loop read overhead -- only the static type changes.

The flip's int? cascades through shared inference, so it ships with int?-placeholder parity fixes that keep int? as non-committal as a bare int wherever int already had a "transient placeholder, adopt the concrete observation" rule:

  • unify_call_types: int? old_pt / int? arg mirror the int placeholder arm
  • merge_refined_local_type: int? refines to a concrete pointer like int
  • infer_array_elem_type_from_ids: [int, int?] stays int_array (same storage)
  • map block result int? -> int_array; Array#fetch returns the present element
  • register_tuple_type: base_type-canonicalize so tuple:int? and tuple:int share one C typedef (codegen mirrors this)

Post-fixpoint re-narrow (renarrow_poly_hash_params_from_calls): the flip adds a fixpoint hop. A hash literal whose values come from a not-yet-settled arr[i] read is transiently str_poly_hash when a read-only callee param first adopts it from the int placeholder, and the monotonic str_poly_hash || ... -> str_poly_hash unify rule never lets the later settled str_str_hash arg narrow it back -- the literal re-infers to str_str_hash each round, so the param is the only casualty (bm_jekyll_lite's Template#render(vars)). Reset read-only poly-hash params, re-derive from the settled call args, and restore the poly type for any slot reached only via poly dispatch. Mirrors the post-fixpoint re-pick pattern (e48bdae / 5c9790c) instead of touching the monotonic in-loop unify rules.

Gate green: 849 tests, 57 benchmarks (bm_jekyll_lite included), optcarrot 59662, analyze/codegen IR+C self-host fixpoint OK.

Refs #1180

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

Details

Commit
b0f7955700e9
Parent
e084a30b5123

spinel_analyze.rbmodifiedView file

@@ -2950,12 +2950,19 @@
29502950 while k < elems.length
29512951 et2 = infer_type(elems[k])
29522952 if et2 != et
2953+ # int and int? share mrb_int storage (the nil lives in-band as
2954+ # SP_INT_NIL), so a mixed `[int, int?]` literal is still an int_array.
2955+ # The #1180 Array#[]->int? flip makes an element read int? where it
2956+ # used to be int (`[1, buf[8]]`), and without this the literal
2957+ # collapses to poly_array and loses Array#max/#min/etc.
2958+ if base_type(et) == "int" && base_type(et2) == "int"
2959+ # compatible; continue
29532960 # Under promote mode, int / bigint are numerically interchangeable
29542961 # (the literal codegen unboxes via sp_bigint_to_int for IntArray
29552962 # storage). Stale-int cache on an arith CallNode whose actual
29562963 # value is bigint causes a spurious mismatch here -- recognize
29572964 # int<>bigint as compatible.
2958- if @int_overflow_mode == "promote" && (et == "int" || et == "bigint") && (et2 == "int" || et2 == "bigint")
2965+ elsif @int_overflow_mode == "promote" && (et == "int" || et == "bigint") && (et2 == "int" || et2 == "bigint")
29592966 # compatible; continue
29602967 else
29612968 return "poly_array"
@@ -5315,6 +5322,17 @@
53155322 if mname == "fetch"
53165323 if recv >= 0
53175324 rt = infer_type(recv)
5325+ # Typed-array fetch(i): the element is proven-present (Array#fetch
5326+ # raises IndexError on a miss, it never returns nil), so the result
5327+ # is the plain element type, not the nullable `[]` element type
5328+ # (#1180). This keeps the compiler's own in-bounds node-id reads
5329+ # (`aargs.fetch(0)`) non-null after the Array#[] -> int? flip.
5330+ if rt == "int_array"
5331+ return "int"
5332+ end
5333+ if rt == "sym_array"
5334+ return "symbol"
5335+ end
53185336 # int-leaf hash with string default — Ruby's `params.fetch
53195337 # "k", ""` idiom. The leaf int is convertible to string via
53205338 # sp_int_to_s, so surface the result as string; codegen-side
@@ -6544,7 +6562,13 @@
65446562 if bret == "float"
65456563 return "float_array"
65466564 end
6547- if bret == "int"
6565+ if bret == "int" || bret == "int?"
6566+ # A block returning a maybe-missing element (int? under the #1180
6567+ # Array#[]->int? flip, e.g. `each_cons(n).map { |pair| pair[0] }`)
6568+ # maps to an int_array: int? shares mrb_int storage, sentinel and
6569+ # all. Without int? parity here bret falls through to the array-of-
6570+ # arrays (_ptr_array) arms below and the result type diverges from
6571+ # the int_array codegen builds.
65486572 return "int_array"
65496573 end
65506574 # Promote-mode bigint block return: there's no bigint_array
@@ -6720,7 +6744,8 @@
67206744 end
67216745 if rt == "int_array"
67226746 # a[range] / a[start, len] returns a slice (still int_array);
6723- # bare a[i] returns the element.
6747+ # bare a[i] returns the element, maybe-missing (OOB -> nil) so int?
6748+ # (sp_IntArray_get already returns SP_INT_NIL out of range). #1180.
67246749 args_id = @nd_arguments[nid]
67256750 if args_id >= 0
67266751 a = get_args(args_id)
@@ -6731,7 +6756,7 @@
67316756 return "int_array"
67326757 end
67336758 end
6734- return "int"
6759+ return "int?"
67356760 end
67366761 if rt == "sym_array"
67376762 return "symbol"
@@ -7975,6 +8000,22 @@
79758000
79768001 def register_tuple_type(t)
79778002 if is_tuple_type(t) == 1
8003+ # Canonicalize element types via base_type before dedup. A tuple of
8004+ # int? has identical C storage and the same tuple_c_name as a tuple
8005+ # of int (both -> sp_Tuple_int_int_int), so the #1180 Array#[]->int?
8006+ # flip must not register a separate tuple:int?,... entry: two registry
8007+ # entries sharing one C typedef name emit a duplicate typedef (the
8008+ # registry is serialized into the IR and drives codegen's typedef
8009+ # loop). base_type strips only the nullable "?" and keeps pointer
8010+ # bases, so GC tracing of pointer-element tuples is unaffected.
8011+ inner_rt = t[6, t.length - 6]
8012+ parts_rt = inner_rt.split(",", -1)
8013+ kk = 0
8014+ while kk < parts_rt.length
8015+ parts_rt[kk] = base_type(parts_rt[kk])
8016+ kk = kk + 1
8017+ end
8018+ t = "tuple:" + parts_rt.join(",")
79788019 k = 0
79798020 found = 0
79808021 while k < @tuple_types.length
@@ -16108,6 +16149,20 @@
1610816149 end
1610916150 return at
1611016151 end
16152+ # int? mirror of the int placeholder rule above. An early param pass
16153+ # can stamp a slot int? from a transient maybe-missing array-element
16154+ # read -- the #1180 Array#[]->int? flip turned these placeholder reads
16155+ # from int into int? -- and a later concrete arg should win, exactly
16156+ # as it does for the bare-int default. Genuine nullable-int merges
16157+ # (an int / int? arg) keep int?; any other concrete arg is adopted.
16158+ # Without this parity, str_array/string param slots that first observe
16159+ # such a placeholder collapse to poly on the next real arg.
16160+ if old_pt == "int?"
16161+ if at == "int" || at == "int?"
16162+ return "int?"
16163+ end
16164+ return at
16165+ end
1611116166 if is_array_type(old_pt) == 1 && is_array_type(at) == 1
1611216167 if old_pt == "poly_array" || at == "poly_array"
1611316168 @needs_rb_value = 1
@@ -16176,6 +16231,19 @@
1617616231 # Inferred int (likely fallback): keep existing type.
1617716232 return old_pt
1617816233 end
16234+ # int? arg mirror of the inferred-int placeholder rule above. A
16235+ # non-literal int? arg (a maybe-missing array-element read under the
16236+ # #1180 flip) is as non-committal as an inferred int; it must not
16237+ # widen an established concrete slot to poly. A genuinely nullable-int
16238+ # slot is preserved by the base_type merge below (int? base == int).
16239+ if at == "int?"
16240+ if is_scalar_nullable_type(old_pt) == 1
16241+ return old_pt
16242+ end
16243+ if arg_is_literal == 0
16244+ return old_pt
16245+ end
16246+ end
1617916247 if base_type(old_pt) == base_type(at)
1618016248 # Nullable-compatible variants of the same base.
1618116249 if is_nullable_type(at) == 1
@@ -22679,7 +22747,10 @@
2267922747 if stmts.length == 0
2268022748 return 0
2268122749 end
22682- types = []
22750+ # str_array of return-path type names. An empty `[]` literal would
22751+ # infer as int_array, whose element read is now int? (#1180), so the
22752+ # `t` local would type mrb_int and break its sp_str_eq comparisons.
22753+ types = "".split(",", -1)
2268322754 collect_return_types_nid(body_id, types)
2268422755 last_id = stmts.last
2268522756 last_t = infer_type(last_id)
@@ -23904,6 +23975,31 @@
2390423975 end
2390523976 return new_t
2390623977 end
23978+ # int? placeholder -> concrete refinement, mirroring the bare-int
23979+ # rule above. The #1180 Array#[]->int? flip makes a transient pre-
23980+ # promotion array-element read type int? where it used to be int
23981+ # (e.g. `got = arr[0]` before `arr` promotes from the empty-[]
23982+ # int_array default to a ptr/typed array). Without parity the int?
23983+ # sticks and the slot keeps mrb_int storage against a pointer value
23984+ # (-Wint-conversion). A genuine nullable-int observation (new_t int/
23985+ # int?) is preserved by the new_t=="int" guard above and the nullable
23986+ # rules below.
23987+ if cur_t == "int?"
23988+ if new_t == "nil"
23989+ return ""
23990+ end
23991+ # Only adopt a concrete pointer/aggregate observation (the empty-[]
23992+ # int_array placeholder promoting to a ptr / typed array, e.g.
23993+ # `got = arr[0]` before arr's push(ptr) resolves). A scalar new_t
23994+ # (int / float / symbol / ...) must leave a genuine nullable-int slot
23995+ # intact -- adopting it would silently drop the int? nullability on a
23996+ # real `h[k]`-style local. Scoped narrower than the bare-int rule
23997+ # above precisely because int? carries the extra nil bit.
23998+ if return_type_is_pointer(new_t) == 1
23999+ return new_t
24000+ end
24001+ return ""
24002+ end
2390724003 # nil starting type → nullable pointer. Add "?" so the C slot
2390824004 # gets NULL-init and tag handling. is_nullable_type already
2390924005 # checks for trailing "?".
@@ -27644,6 +27740,14 @@
2764427740 infer_function_body_call_types
2764527741 infer_class_body_call_types
2764627742 infer_all_returns
27743+ # Undo any hash param locked to a poly variant by a transient int? read
27744+ # (the #1180 Array#[]->int? fixpoint hop), re-deriving it from settled call
27745+ # args. Placed after the hash params have stabilized to their poly variant.
27746+ renarrow_poly_hash_params_from_calls
27747+ infer_all_returns
27748+ infer_function_body_call_types
27749+ infer_class_body_call_types
27750+ infer_all_returns
2764727751 # Body-usage array inference (#545). Runs ONCE post-fixpoint:
2764827752 # by this point any param that has a typed call site has been
2764927753 # widened to a concrete narrow variant (int_array, str_array,
@@ -35527,6 +35631,136 @@
3552735631 end
3552835632 end
3552935633
35634+ # Post-fixpoint re-pick for hash params locked to a poly variant by a
35635+ # transient. The #1180 Array#[]->int? flip adds a fixpoint hop: a hash
35636+ # literal whose values come from a yet-to-settle `arr[i]` read (int? before
35637+ # the array promotes to its real element type) is transiently str_poly_hash
35638+ # when a callee param FIRST adopts it from the int placeholder, and the
35639+ # monotonic `str_poly_hash || ... -> str_poly_hash` unify rule never lets a
35640+ # later settled str_str_hash arg narrow it back. The literal itself re-infers
35641+ # to str_str_hash each round (its final type is correct), so the param is the
35642+ # only casualty. Reset poly-hash params to the int placeholder, re-derive them
35643+ # purely from settled call-site args (single str_str_hash caller -> narrows to
35644+ # str_str_hash; genuinely heterogeneous callers -> re-widens to *_poly_hash),
35645+ # and restore the original poly type for any param with no direct call-site
35646+ # evidence (reached only through poly-receiver dispatch) so nothing is lost.
35647+ # A hash param is "read-only" for re-narrow purposes when its body calls no
35648+ # mutating method on it -- so its value-type set is established entirely by the
35649+ # call sites and re-deriving from settled args cannot drop a body-introduced
35650+ # value kind. Any `[]=` / store / merge! / delete / ... receiver disqualifies.
35651+ def param_hash_is_read_only(bid, pname)
35652+ if bid < 0
35653+ return 0
35654+ end
35655+ called = "".split(",", -1)
35656+ collect_param_methods(bid, pname, called)
35657+ i = 0
35658+ while i < called.length
35659+ m = called[i]
35660+ if m == "[]=" || m == "store" || m == "merge!" || m == "update" || m == "delete" || m == "clear" || m == "delete_if" || m == "reject!" || m == "select!" || m == "replace"
35661+ return 0
35662+ end
35663+ i = i + 1
35664+ end
35665+ return 1
35666+ end
35667+
35668+ def renarrow_poly_hash_params_from_calls
35669+ saved = "".split(",", -1)
35670+ # Top-level methods: snapshot + reset.
35671+ mi = 0
35672+ while mi < @meth_names.length
35673+ bid_rn = @meth_body_ids[mi]
35674+ pnames_rn = @meth_param_names[mi].split(",", -1)
35675+ ptypes = @meth_param_types[mi].split(",", -1)
35676+ changed = 0
35677+ pk = 0
35678+ while pk < ptypes.length
35679+ if (ptypes[pk] == "str_poly_hash" || ptypes[pk] == "sym_poly_hash") && pk < pnames_rn.length && param_hash_is_read_only(bid_rn, pnames_rn[pk]) == 1
35680+ saved.push("m:" + mi.to_s + ":" + pk.to_s + ":" + ptypes[pk])
35681+ ptypes[pk] = "int"
35682+ changed = 1
35683+ end
35684+ pk = pk + 1
35685+ end
35686+ if changed == 1
35687+ @meth_param_types[mi] = ptypes.join(",")
35688+ end
35689+ mi = mi + 1
35690+ end
35691+ # Class instance methods: snapshot + reset.
35692+ ci = 0
35693+ while ci < @cls_names.length
35694+ all_ptypes = @cls_meth_ptypes[ci].split("|", -1)
35695+ bodies_rn = @cls_meth_bodies[ci].split(";", -1)
35696+ cls_changed = 0
35697+ mj = 0
35698+ while mj < all_ptypes.length
35699+ bid_rn_c = -1
35700+ if mj < bodies_rn.length
35701+ bid_rn_c = bodies_rn[mj].to_i
35702+ end
35703+ pnames_rn_c = cls_meth_pnames_get(ci, mj)
35704+ cm_ptypes = all_ptypes[mj].split(",", -1)
35705+ m_changed = 0
35706+ pk2 = 0
35707+ while pk2 < cm_ptypes.length
35708+ if (cm_ptypes[pk2] == "str_poly_hash" || cm_ptypes[pk2] == "sym_poly_hash") && pk2 < pnames_rn_c.length && param_hash_is_read_only(bid_rn_c, pnames_rn_c[pk2]) == 1
35709+ saved.push("c:" + ci.to_s + ":" + mj.to_s + ":" + pk2.to_s + ":" + cm_ptypes[pk2])
35710+ cm_ptypes[pk2] = "int"
35711+ m_changed = 1
35712+ end
35713+ pk2 = pk2 + 1
35714+ end
35715+ if m_changed == 1
35716+ all_ptypes[mj] = cm_ptypes.join(",")
35717+ cls_changed = 1
35718+ end
35719+ mj = mj + 1
35720+ end
35721+ if cls_changed == 1
35722+ @cls_meth_ptypes[ci] = all_ptypes.join("|")
35723+ @cls_meth_ptypes_version = @cls_meth_ptypes_version + 1
35724+ end
35725+ ci = ci + 1
35726+ end
35727+ if saved.length == 0
35728+ return
35729+ end
35730+ # Re-derive the reset slots from the now-settled call sites.
35731+ infer_main_call_types
35732+ infer_function_body_call_types
35733+ infer_class_body_call_types
35734+ # Restore the original poly type for any slot that the re-derivation left at
35735+ # the int placeholder (no direct caller widened it -- it is reached only via a
35736+ # poly-receiver dispatch and must keep its poly storage).
35737+ si = 0
35738+ while si < saved.length
35739+ parts = saved[si].split(":", -1)
35740+ if parts[0] == "m"
35741+ rmi = parts[1].to_i
35742+ rpk = parts[2].to_i
35743+ orig = parts[3]
35744+ ptypes = @meth_param_types[rmi].split(",", -1)
35745+ if rpk < ptypes.length && (ptypes[rpk] == "int" || ptypes[rpk] == "nil")
35746+ ptypes[rpk] = orig
35747+ @meth_param_types[rmi] = ptypes.join(",")
35748+ end
35749+ else
35750+ rci = parts[1].to_i
35751+ rmj = parts[2].to_i
35752+ rpk2 = parts[3].to_i
35753+ orig2 = parts[4]
35754+ cur = cls_meth_ptypes_get(rci, rmj)
35755+ if rpk2 < cur.length && (cur[rpk2] == "int" || cur[rpk2] == "nil")
35756+ cur[rpk2] = orig2
35757+ cls_meth_ptypes_put(rci, rmj, cur)
35758+ end
35759+ end
35760+ si = si + 1
35761+ end
35762+ end
35763+
3553035764 # hash-each block-arg widening for nested cmeth /
3553135765 # method calls. The in-pipeline scan_new_calls runs without
3553235766 # the iterator's k/v scope pushed, so a call site like