Commit 8e604f0a

8e604f0a7ef9Merged

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

Description

fix(analyze): re-fix #495 with cls_ivar_nil_checked gate (#497)

Refs #497. The original #495 widened any scalar+nil-mixed ivar to poly, which broke optcarrot's APU::Pulse / Triangle / Noise arithmetic — @wave_length was nil-initialized then assigned int and used purely in @freq = (@wave_length + 1) * 2 * @fixed style math, never via .nil?. The cascade widened @freq, @timer, @step to poly and broke every int += / & call site under -Werror=int-conversion. Reverted at e45e735.

Narrower trigger: widen scalar+nil mixes to poly only when the ivar is actually read via a nil predicate (<ivar>.nil?, <ivar> == nil, <ivar> != nil) somewhere in the program.

Implementation:

  1. New @cls_ivar_nil_checked parallel array per class — semicolon-joined set of ivar names that appear inside a nil predicate read.

  2. Pre-pass scan_ivar_nil_predicates(@root_id) at the start of analyze_phase walks the whole AST once, tracking @current_class_idx through ClassNode / ModuleNode descents, and marks every (ci, ivar_name) where it sees:

    • CallNode mname=="nil?" with InstanceVariableReadNode receiver
    • CallNode mname=="==" / "!=" with ivar receiver and NilNode arg
    • the mirror form (nil receiver, ivar arg)
  3. Three gates re-introduce the #495 widening, each AND-ed with cls_ivar_nil_checked?(ci, iname) == 1:

    • update_ivar_type path 1: nil_scalar_ivar_mix? arm.
    • update_ivar_types_from_params path 3: param-write widening, which is what HitState#hit!(idx) / ParamResetState#set(idx) need.
    • scan_writer_calls path 4: new at == "nil" branch that routes plain @x = nil literal writes through update_ivar_type (the new behavior PR #495 introduced), plus a complementary cls_ivar_type == "nil" arm so a subsequent int write widens correctly.

Tests:

  • test/nil_scalar_ivar_widen.rb: the original #495 test, three classes (HitState param-write, ResetState literal nil write, ParamResetState param-write with nil caller), each verifies .nil? differentiates pre / post mutation.

  • test/nil_ivar_no_predicate_stays_scalar.rb: regression guard modeled on the APU::Pulse shape. @wave_length is nil-init, later int-assigned, used in (@wave_length + 1) * 2 * @fixed arithmetic, never with .nil?. Must compile cleanly under -Werror=int-conversion (harness drops cc stderr, so failure surfaces as a missing binary).

Local: 467 tests pass, optcarrot runs with checksum 59662.

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

Details

Commit
8e604f0a7ef9
Parent
05f0efac1e37

spinel_analyze.rbmodifiedView file

@@ -166,6 +166,16 @@
166166 # dimension is semicolon-separated and parallel to
167167 # `@cls_ivar_names[ci]`.
168168 @cls_ivar_observed_types = "".split(",")
169+ # Per-class set of ivar names that are read with a nil predicate
170+ # somewhere in the program — `<ivar>.nil?`, `<ivar> == nil`,
171+ # `<ivar> != nil`. Gates nil-scalar widening to poly so an ivar
172+ # mixed-typed at the slot but never actually nil-checked stays at
173+ # its scalar type (optcarrot's `@wave_length = nil` then arithmetic
174+ # is the regression sentinel — without the gate, nil-write
175+ # widening cascaded `@freq` / `@timer` / `@step` to poly and broke
176+ # the int math emit). Populated by scan_ivar_nil_predicates before
177+ # the iter loop; semicolon-joined names parallel to @cls_ivar_names.
178+ @cls_ivar_nil_checked = "".split(",")
169179 # Memoization for `find_lv_ivar_alias_in_ast`. Keyed by
170180 # `"<class_idx>:<lv_name>"`, value is the resolved ivar name (or
171181 # `""` when the LV has multiple sources / non-ivar writes).
@@ -6880,6 +6890,7 @@
68806890 sk3 = sk3 + 1
68816891 end
68826892 @cls_ivar_observed_types.push(obs_init)
6893+ @cls_ivar_nil_checked.push("")
68836894 # Auto-generate initialize method for struct-derived classes
68846895 if struct_fields.length > 0
68856896 init_params = ""
@@ -7800,7 +7811,8 @@
78007811 # `@m = method(:foo)` initially scans as int and a
78017812 # refinement promotes it to `obj_Method` — no heterogeneity
78027813 # to widen for).
7803- if (old == "int" || old == "nil") && is_obj_type(new_type) == 1 && cls_ivar_definite_flag(ci, iname) == 1
7814+ if (nil_scalar_ivar_mix?(old, new_type) && cls_ivar_nil_checked?(ci, iname) == 1) ||
7815+ ((old == "int" || old == "nil") && is_obj_type(new_type) == 1 && cls_ivar_definite_flag(ci, iname) == 1)
78047816 types[k] = "poly"
78057817 @needs_rb_value = 1
78067818 @cls_ivar_types[ci] = types.join(";")
@@ -8035,6 +8047,15 @@
80358047 0
80368048 end
80378049
8050+ def scalar_ivar_type?(t)
8051+ t == "int" || t == "float" || t == "bool" || t == "symbol"
8052+ end
8053+
8054+ def nil_scalar_ivar_mix?(old_type, new_type)
8055+ (old_type == "nil" && scalar_ivar_type?(new_type)) ||
8056+ (new_type == "nil" && scalar_ivar_type?(old_type))
8057+ end
8058+
80388059 def cls_ivar_definite_flag(ci, iname)
80398060 names = @cls_ivar_names[ci].split(";")
80408061 flags = @cls_ivar_init_definite[ci].split(";")
@@ -8051,6 +8072,189 @@
80518072 0
80528073 end
80538074
8075+ # Returns 1 if the ivar is read with a nil predicate
8076+ # (`<ivar>.nil?`, `<ivar> == nil`, `<ivar> != nil`) somewhere in
8077+ # the program. The nil-scalar widening pass uses this to decide
8078+ # whether mixing nil and scalar writes is observable — if the
8079+ # ivar is never compared against nil, an `@x = nil` write can
8080+ # collapse into the scalar storage at runtime without breaking
8081+ # any user predicate, and we keep the cheaper int slot. Without
8082+ # this gate, the widening cascades into unrelated arithmetic
8083+ # (optcarrot's `@wave_length` → `@freq` chain was the
8084+ # regression that triggered the original revert).
8085+ def cls_ivar_nil_checked?(ci, iname)
8086+ if ci < 0 || ci >= @cls_ivar_nil_checked.length
8087+ return 0
8088+ end
8089+ if @cls_ivar_nil_checked[ci] == ""
8090+ return 0
8091+ end
8092+ names = @cls_ivar_nil_checked[ci].split(";")
8093+ k = 0
8094+ while k < names.length
8095+ if names[k] == iname
8096+ return 1
8097+ end
8098+ k = k + 1
8099+ end
8100+ 0
8101+ end
8102+
8103+ def mark_ivar_nil_checked(ci, iname)
8104+ if ci < 0 || ci >= @cls_ivar_nil_checked.length
8105+ return
8106+ end
8107+ if cls_ivar_nil_checked?(ci, iname) == 1
8108+ return
8109+ end
8110+ if @cls_ivar_nil_checked[ci] == ""
8111+ @cls_ivar_nil_checked[ci] = iname
8112+ else
8113+ @cls_ivar_nil_checked[ci] = @cls_ivar_nil_checked[ci] + ";" + iname
8114+ end
8115+ end
8116+
8117+ # Pre-pass that walks the whole program once and marks every
8118+ # `(ci, ivar_name)` where `<ivar>` is observed inside a nil
8119+ # predicate read site. Tracks `@current_class_idx` through the
8120+ # walk so a `@x.nil?` inside `class A` marks A's slot, not the
8121+ # toplevel one. Toplevel ivar nil-checks (outside any class)
8122+ # don't need a class flag — the toplevel_ivar tables don't share
8123+ # the scalar-widening path that needs gating, so we just early-
8124+ # return when @current_class_idx is -1.
8125+ def scan_ivar_nil_predicates(nid)
8126+ if nid < 0
8127+ return
8128+ end
8129+ t = @nd_type[nid]
8130+ if t == "ClassNode"
8131+ cname_id = @nd_constant_path[nid]
8132+ cname = ""
8133+ if cname_id >= 0
8134+ cname = const_ref_flat_name(cname_id)
8135+ end
8136+ if @current_lexical_scope != ""
8137+ cname = @current_lexical_scope + "_" + cname
8138+ end
8139+ cci = find_class_idx(cname)
8140+ saved_ci = @current_class_idx
8141+ saved_scope = @current_lexical_scope
8142+ if cci >= 0
8143+ @current_class_idx = cci
8144+ end
8145+ @current_lexical_scope = cname
8146+ body = @nd_body[nid]
8147+ if body >= 0
8148+ scan_ivar_nil_predicates(body)
8149+ end
8150+ @current_class_idx = saved_ci
8151+ @current_lexical_scope = saved_scope
8152+ return
8153+ end
8154+ if t == "ModuleNode"
8155+ mname_id = @nd_constant_path[nid]
8156+ mname = ""
8157+ if mname_id >= 0
8158+ mname = const_ref_flat_name(mname_id)
8159+ end
8160+ if @current_lexical_scope != ""
8161+ mname = @current_lexical_scope + "_" + mname
8162+ end
8163+ saved_scope = @current_lexical_scope
8164+ @current_lexical_scope = mname
8165+ body = @nd_body[nid]
8166+ if body >= 0
8167+ scan_ivar_nil_predicates(body)
8168+ end
8169+ @current_lexical_scope = saved_scope
8170+ return
8171+ end
8172+ if t == "CallNode"
8173+ mname = @nd_name[nid]
8174+ recv = @nd_receiver[nid]
8175+ # `@x.nil?`
8176+ if mname == "nil?" && recv >= 0 && @nd_type[recv] == "InstanceVariableReadNode"
8177+ if @current_class_idx >= 0
8178+ mark_ivar_nil_checked(@current_class_idx, @nd_name[recv])
8179+ end
8180+ end
8181+ # `@x == nil` / `@x != nil` — Prism lowers these to CallNode
8182+ # with mname "==" / "!=" on the lhs receiver, single arg.
8183+ if mname == "==" || mname == "!="
8184+ args_id = @nd_arguments[nid]
8185+ if recv >= 0 && @nd_type[recv] == "InstanceVariableReadNode" && args_id >= 0
8186+ a_ids = get_args(args_id)
8187+ if a_ids.length == 1 && @nd_type[a_ids[0]] == "NilNode"
8188+ if @current_class_idx >= 0
8189+ mark_ivar_nil_checked(@current_class_idx, @nd_name[recv])
8190+ end
8191+ end
8192+ end
8193+ # `nil == @x` / `nil != @x` — mirror form
8194+ if recv >= 0 && @nd_type[recv] == "NilNode" && args_id >= 0
8195+ a_ids = get_args(args_id)
8196+ if a_ids.length == 1 && @nd_type[a_ids[0]] == "InstanceVariableReadNode"
8197+ if @current_class_idx >= 0
8198+ mark_ivar_nil_checked(@current_class_idx, @nd_name[a_ids[0]])
8199+ end
8200+ end
8201+ end
8202+ end
8203+ end
8204+ # Recurse through common child slots. Mirrors scan_ivars_children's
8205+ # walking shape so the same set of node kinds is covered.
8206+ if t == "DefNode"
8207+ body = @nd_body[nid]
8208+ if body >= 0
8209+ scan_ivar_nil_predicates(body)
8210+ end
8211+ return
8212+ end
8213+ if @nd_body[nid] >= 0
8214+ scan_ivar_nil_predicates(@nd_body[nid])
8215+ end
8216+ if @nd_type[nid] == "StatementsNode"
8217+ stmts = get_stmts(nid)
8218+ k = 0
8219+ while k < stmts.length
8220+ scan_ivar_nil_predicates(stmts[k])
8221+ k = k + 1
8222+ end
8223+ end
8224+ if @nd_expression[nid] >= 0
8225+ scan_ivar_nil_predicates(@nd_expression[nid])
8226+ end
8227+ if @nd_predicate[nid] >= 0
8228+ scan_ivar_nil_predicates(@nd_predicate[nid])
8229+ end
8230+ if @nd_subsequent[nid] >= 0
8231+ scan_ivar_nil_predicates(@nd_subsequent[nid])
8232+ end
8233+ if @nd_else_clause[nid] >= 0
8234+ scan_ivar_nil_predicates(@nd_else_clause[nid])
8235+ end
8236+ if @nd_receiver[nid] >= 0
8237+ scan_ivar_nil_predicates(@nd_receiver[nid])
8238+ end
8239+ if @nd_arguments[nid] >= 0
8240+ args = get_args(@nd_arguments[nid])
8241+ k = 0
8242+ while k < args.length
8243+ scan_ivar_nil_predicates(args[k])
8244+ k = k + 1
8245+ end
8246+ end
8247+ if @nd_left[nid] >= 0
8248+ scan_ivar_nil_predicates(@nd_left[nid])
8249+ end
8250+ if @nd_right[nid] >= 0
8251+ scan_ivar_nil_predicates(@nd_right[nid])
8252+ end
8253+ if @nd_block[nid] >= 0
8254+ scan_ivar_nil_predicates(@nd_block[nid])
8255+ end
8256+ end
8257+
80548258 def scan_ivars(ci, nid)
80558259 if nid < 0
80568260 return
@@ -9509,6 +9713,7 @@
95099713 @cls_ivar_types.push("obj_Method;int")
95109714 @cls_ivar_init_definite.push("1;1")
95119715 @cls_ivar_observed_types.push("obj_Method;int")
9716+ @cls_ivar_nil_checked.push("")
95129717 @cls_meth_names.push("initialize")
95139718 @cls_meth_params.push("self_obj,fn_ptr")
95149719 @cls_meth_ptypes.push("obj_Method,int")
@@ -9541,6 +9746,7 @@
95419746 @cls_ivar_types.push("")
95429747 @cls_ivar_init_definite.push("")
95439748 @cls_ivar_observed_types.push("")
9749+ @cls_ivar_nil_checked.push("")
95449750 @cls_meth_names.push("")
95459751 @cls_meth_params.push("")
95469752 @cls_meth_ptypes.push("")
@@ -11017,7 +11223,14 @@
1101711223 if ij < ivar_types.length
1101811224 if ivar_names[ij] == iname
1101911225 if ptypes[pi] != ""
11020- ivar_types[ij] = unify_call_types(ivar_types[ij], ptypes[pi], -1)
11226+ old_t = ivar_types[ij]
11227+ new_t = ptypes[pi]
11228+ if nil_scalar_ivar_mix?(old_t, new_t) && cls_ivar_nil_checked?(i, iname) == 1
11229+ ivar_types[ij] = "poly"
11230+ @needs_rb_value = 1
11231+ else
11232+ ivar_types[ij] = unify_call_types(old_t, new_t, -1)
11233+ end
1102111234 end
1102211235 end
1102311236 end
@@ -13800,7 +14013,20 @@
1380014013 update_ivar_type(@current_class_idx, chain_inames[ci_idx], at)
1380114014 ci_idx = ci_idx + 1
1380214015 end
13803- elsif at != "int" && at != "nil"
14016+ elsif at == "nil"
14017+ # Plain `@x = nil` literal. Pre-gate (the original PR #495
14018+ # behavior) routed every nil write through update_ivar_type and
14019+ # cascaded scalar-mixed slots to poly, breaking optcarrot's
14020+ # `@wave_length = nil` + `@wave_length = 0 if @wave_length` +
14021+ # int arithmetic chain. Only widen now if the ivar is actually
14022+ # tested via a nil predicate (`<ivar>.nil?` / `== nil` / `!= nil`)
14023+ # somewhere in the program — that's the signal that the user
14024+ # depends on the nil-vs-scalar distinction.
14025+ if scalar_ivar_type?(cls_ivar_type(@current_class_idx, iname)) &&
14026+ cls_ivar_nil_checked?(@current_class_idx, iname) == 1
14027+ update_ivar_type(@current_class_idx, iname, at)
14028+ end
14029+ elsif at != "int" || cls_ivar_type(@current_class_idx, iname) == "nil"
1380414030 update_ivar_type(@current_class_idx, iname, at)
1380514031 end
1380614032 end
@@ -17016,6 +17242,13 @@
1701617242 # treat its inputs as read-only.
1701717243 def analyze_phase
1701817244 collect_all
17245+ # Pre-pass: which ivars are actually read with a nil predicate?
17246+ # Gates the scan_writer_calls nil-scalar widening so an ivar
17247+ # mixed-typed at the slot but never tested with `.nil?` /
17248+ # `== nil` stays at its scalar type instead of cascading to
17249+ # poly. Walks once; the resulting @cls_ivar_nil_checked set is
17250+ # then consulted by scan_writer_calls inside the iter loop.
17251+ scan_ivar_nil_predicates(@root_id)
1701917252 infer_main_call_types
1702017253 infer_function_body_call_types
1702117254 infer_class_body_call_types