Commit b10e51c2

b10e51c2499cMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified

Description

Inline String#getbyte to a direct byte load

s.getbyte(i) emitted a call to sp_str_getbyte, which recomputes the string's byte length and does range checks on every call -- the C compiler can't hoist that out of a byte loop because an aliasing setbyte may have run. Emit a direct (mrb_int)(unsigned char)(s)[i] load instead, matching the legacy generator. An out-of-range index reads adjacent bytes (legacy's behavior); in practice getbyte is used under an in-range loop guard.

bm_ruby_xor 1.77x -> 1.01x vs legacy. make test 845, make bench 57, optcarrot checksum 59662.

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

Details

Commit
b10e51c2499c
Parent
395236a0923d

src/codegen_call.cmodifiedView file

@@ -7425,7 +7425,13 @@
74257425 else if (!strcmp(name, "byteslice") && argc == 2) { buf_printf(b, "sp_str_byteslice(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); }
74267426 else if (!strcmp(name, "byteslice") && argc == 1) { buf_printf(b, "sp_str_byteslice(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", 1)"); }
74277427 else if (!strcmp(name, "setbyte") && argc == 2) { buf_printf(b, "sp_str_setbyte(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); }
7428- else if (!strcmp(name, "getbyte") && argc == 1) { buf_printf(b, "sp_str_getbyte(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); }
7428+ else if (!strcmp(name, "getbyte") && argc == 1) {
7429+ /* inline to a direct byte load (matches the legacy generator): the
7430+ per-byte sp_str_getbyte call recomputes the string length and bounds
7431+ every iteration, which the C compiler can't hoist across an aliasing
7432+ setbyte. An out-of-range index reads adjacent bytes (as in legacy). */
7433+ buf_printf(b, "((mrb_int)(unsigned char)(%s)[", r); emit_int_expr(c, argv[0], b); buf_puts(b, "])");
7434+ }
74297435 else if (!strcmp(name, "squeeze") && argc == 0) buf_printf(b, "sp_str_squeeze(%s)", r);
74307436 else if (!strcmp(name, "squeeze") && argc == 1) { buf_printf(b, "sp_str_squeeze_chars(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); }
74317437 else if (!strcmp(name, "squeeze") && argc >= 2) {