Commit 2165f0b4

2165f0b4b844Merged

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

Description

fix(codegen): bit-extraction on poly-typed int receiver

int[i] on a Ruby integer is a bit-extraction operator — (int >> i) & 1, returning bit i of the integer. The codegen for [] dispatch lowered this correctly when the receiver was statically typed int, but missed the case where the receiver was typed sp_RbVal carrying an SP_TAG_INT runtime value (common when an ivar / local has been widened to poly via mixed- type writes elsewhere).

emit_poly_builtin_dispatch only emitted branches inside an if (recv.tag == SP_TAG_OBJ) block — handling IntArray, FltArray, StrArray, SymArray, PtrArray, and (when present) Method. SP_TAG_INT receivers fell through to the default nil-by-default result, so every v[i] returned 0 / nil.

The downstream effect was particularly nasty for code that checks bits to drive control flow: tmp[8] == pc[8] ? a : b collapses to nil == nil → true regardless of input, the same-arm branch is always taken, and any logic depending on the bit comparison silently degrades.

Emit a SP_TAG_INT branch in the [] dispatch ahead of the SP_TAG_OBJ block that produces (recv.v.i >> arg) & 1. The arg-unbox handling matches the existing arms (auto .v.i when the arg itself is poly).

Test exercises the failure mode: a Holder with mixed-type ivar writes makes @x widen to poly; h.x[i] reads then hit the SP_TAG_INT receiver path. Without the fix, every puts v[i] prints blank and same_page? returns true for both inputs because nil == nil.

Details

Commit
2165f0b4b844
Parent
15f7e5f356d7

spinel_codegen.rbmodifiedView file

@@ -21673,6 +21673,21 @@
2167321673 end
2167421674 tmp = new_temp
2167521675 emit(" " + ret_ct + " " + tmp + " = " + ret_def + ";")
21676+ # `int[i]` (bit-extraction) on a poly receiver. When a CPU
21677+ # register / scratch ivar is widened to sp_RbVal but still
21678+ # carries an int value, `pc[8]` (the page-bit test in branch
21679+ # instructions etc.) must compile to `(pc >> 8) & 1`, not to
21680+ # the array dispatch in the SP_TAG_OBJ block below — which
21681+ # would silently leave the result at nil and miscount cycles.
21682+ if mname == "[]" && arg_compiled.length >= 1
21683+ a0_int = arg_compiled[0]
21684+ if arg_types.length > 0 && arg_types[0] == "poly"
21685+ a0_int = "(" + a0_int + ").v.i"
21686+ end
21687+ bit = "((" + recv_tmp + ".v.i >> (" + a0_int + ")) & 1)"
21688+ brhs = is_poly_ret == 1 ? "sp_box_int(" + bit + ")" : bit
21689+ emit(" if (" + recv_tmp + ".tag == SP_TAG_INT) " + tmp + " = " + brhs + ";")
21690+ end
2167621691 emit(" if (" + recv_tmp + ".tag == SP_TAG_OBJ) {")
2167721692 # User-class dispatch
2167821693 i = 0