Skip to content

Commit 9ff307b

Browse files
committed
Inline common cases of String#force_encoding in ZJIT
Handle unchanged encodings and transitions between `ASCII-8BIT`, `UTF-8`, and `US-ASCII`.
1 parent 1f717ae commit 9ff307b

8 files changed

Lines changed: 280 additions & 1 deletion

File tree

‎zjit.c‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ enum zjit_struct_offsets {
3939
ISEQ_BODY_OFFSET_PARAM = offsetof(struct rb_iseq_constant_body, param),
4040
ISEQ_BODY_OFFSET_OUTER_VARIABLES = offsetof(struct rb_iseq_constant_body, outer_variables),
4141
RUBY_OFFSET_THREAD_RACTOR = offsetof(rb_thread_t, ractor),
42+
TDATA_OFFSET_DATA = offsetof(struct RTypedData, data),
43+
RUBY_OFFSET_ENCODING_INDEX = offsetof(rb_encoding, ruby_encoding_index),
4244
};
4345

4446
// Struct offsets that cannot be constants in the checked-in bindgen output

‎zjit/bindgen/src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ fn main() {
193193
.allowlist_var("rb_cNumeric")
194194
.allowlist_var("rb_cRange")
195195
.allowlist_var("rb_cString")
196+
.allowlist_var("rb_cEncoding")
196197
.allowlist_var("rb_cThread")
197198
.allowlist_var("rb_cArray")
198199
.allowlist_var("rb_cHash")

‎zjit/src/codegen.rs‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,7 @@ fn gen_insn(cb: &mut CodeBlock, jit: &mut JITState, asm: &mut Assembler, functio
651651
&Insn::ObjectAllocClass { class, state } => gen_object_alloc_class(jit, asm, function, class, &function.frame_state(state)),
652652
Insn::StringCopy { val, chilled, state } => gen_string_copy(jit, asm, function, *val, opnd!(val), *chilled, &function.frame_state(*state)),
653653
Insn::StringConcat { strings, state } => gen_string_concat(jit, asm, function, opnds!(strings), &function.frame_state(*state)),
654+
Insn::StringForceEncoding { string, encoding, state } => gen_string_force_encoding(jit, asm, function, opnd!(string), opnd!(encoding), &function.frame_state(*state)),
654655
&Insn::StringGetbyte { string, index } => gen_string_getbyte(asm, opnd!(string), opnd!(index)),
655656
Insn::StringByteslice { string, beg, len, state } => gen_string_byteslice(asm, opnd!(string), opnd!(beg), opnd!(len), &function.frame_state(*state)),
656657
Insn::StringSetbyteFixnum { string, index, value } => gen_string_setbyte_fixnum(asm, opnd!(string), opnd!(index), opnd!(value)),
@@ -4218,6 +4219,77 @@ fn gen_string_concat(jit: &mut JITState, asm: &mut Assembler, function: &Functio
42184219
asm_ccall!(asm, rb_str_concat_literals, strings.len().into(), first_string_ptr)
42194220
}
42204221

4222+
fn gen_string_force_encoding(jit: &mut JITState, asm: &mut Assembler, function: &Function, string: Opnd, encoding: Opnd, state: &FrameState) -> Opnd {
4223+
asm_comment!(asm, "String#force_encoding fast path");
4224+
// Avoid the C call only when a direct flag update preserves all rb_str_force_encoding behavior.
4225+
let string = asm.load_mem(string);
4226+
let encoding = asm.load_mem(encoding);
4227+
4228+
// rb_str_force_encoding checks mutability before it checks whether the encoding changed.
4229+
// Side-exit so CRuby can raise for frozen or locked strings and warn for chilled strings.
4230+
let unmodifiable_exit = side_exit(jit, function, state, GuardNotFrozen);
4231+
let flags = asm.load(Opnd::mem(VALUE_BITS, string, RUBY_OFFSET_RBASIC_FLAGS));
4232+
let unmodifiable_mask = RUBY_FL_FREEZE as u64 | RUBY_FL_USER2 as u64 | RUBY_FL_USER7 as u64;
4233+
asm.test(flags, Opnd::UImm(unmodifiable_mask));
4234+
asm.jnz(jit, unmodifiable_exit);
4235+
4236+
// RString stores the encoding index in its flags, so load the index from the Encoding object.
4237+
let encoding_ptr = asm.load(Opnd::mem(VALUE_BITS, encoding, TDATA_OFFSET_DATA as i32));
4238+
let unsupported_encoding_exit = side_exit(jit, function, state, GuardGreaterEq);
4239+
let encoding_index = asm.load(Opnd::mem(32, encoding_ptr, RUBY_OFFSET_ENCODING_INDEX as i32));
4240+
4241+
// The C path manages extra encoding state when the index does not fit in the String flags.
4242+
asm.cmp(encoding_index, Opnd::UImm(RUBY_ENCODING_INLINE_MAX as u64));
4243+
asm.jge(jit, unsupported_encoding_exit.clone());
4244+
4245+
// Check for an unchanged encoding before guards that apply only to encoding transitions.
4246+
let string_encoding = asm.and(flags, Opnd::UImm(RUBY_ENCODING_MASK as u64));
4247+
let string_encoding = asm.rshift(string_encoding, Opnd::UImm(RUBY_ENCODING_SHIFT as u64));
4248+
4249+
// Both the unchanged path and the mutation path must return the original receiver.
4250+
let hir_block_id = asm.current_block().hir_block_id;
4251+
let rpo_idx = asm.current_block().rpo_index;
4252+
let result_block = asm.new_block(hir_block_id, false, rpo_idx);
4253+
let result_edge = Target::Block(Box::new(lir::BranchEdge { target: result_block, args: vec![] }));
4254+
4255+
// Skip every write for the no-op case, as rb_str_force_encoding does.
4256+
asm.cmp(string_encoding.with_num_bits(32), encoding_index);
4257+
asm.je(jit, result_edge.clone());
4258+
4259+
// A changed encoding can require a different string terminator length.
4260+
// ASCII-8BIT, UTF-8, and US-ASCII use one-byte terminators, so a flag-only update is safe.
4261+
asm.cmp(encoding_index, Opnd::UImm(RUBY_ENCINDEX_UTF_16BE as u64));
4262+
asm.jge(jit, unsupported_encoding_exit.clone());
4263+
asm.cmp(string_encoding, Opnd::UImm(RUBY_ENCINDEX_UTF_16BE as u64));
4264+
asm.jge(jit, unsupported_encoding_exit);
4265+
4266+
// Seven-bit bytes remain valid in every supported encoding, so preserve that coderange.
4267+
// Other bytes can change meaning under the new encoding, so clear their cached coderange.
4268+
let flags_without_encoding = asm.and(flags, Opnd::UImm(!(RUBY_ENCODING_MASK as u64)));
4269+
let flags_without_encoding_or_coderange = asm.and(
4270+
flags,
4271+
Opnd::UImm(!(RUBY_ENCODING_MASK as u64 | RUBY_ENC_CODERANGE_MASK as u64)),
4272+
);
4273+
let coderange = asm.and(flags, Opnd::UImm(RUBY_ENC_CODERANGE_MASK as u64));
4274+
asm.cmp(coderange, Opnd::UImm(RUBY_ENC_CODERANGE_7BIT as u64));
4275+
let updated_flags = asm.csel_e(flags_without_encoding, flags_without_encoding_or_coderange);
4276+
4277+
// Preserve unrelated flags because force_encoding changes only encoding metadata.
4278+
let encoding_bits = asm.lshift(
4279+
encoding_index.with_num_bits(VALUE_BITS),
4280+
Opnd::UImm(RUBY_ENCODING_SHIFT as u64),
4281+
);
4282+
let new_flags = asm.or(updated_flags, encoding_bits);
4283+
asm.store(Opnd::mem(VALUE_BITS, string, RUBY_OFFSET_RBASIC_FLAGS), new_flags);
4284+
asm.jmp(result_edge);
4285+
4286+
// Both paths return the receiver to preserve String#force_encoding identity.
4287+
asm.set_current_block(result_block);
4288+
let label = jit.get_label(asm, result_block, hir_block_id);
4289+
asm.write_label(label);
4290+
string
4291+
}
4292+
42214293
// Generate RSTRING_PTR
42224294
fn get_string_ptr(asm: &mut Assembler, string: Opnd) -> Opnd {
42234295
asm_comment!(asm, "get string pointer for embedded or heap");

‎zjit/src/codegen_tests.rs‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::backend::lir::Assembler;
66
use crate::codegen::max_iseq_versions;
77
use crate::cruby::*;
88
use crate::hir::{Insn, iseq_to_hir};
9-
use crate::options::{CallThreshold, get_option, rb_zjit_prepare_options, set_call_threshold, set_inline_threshold, set_max_versions, set_mem_bytes, set_num_exits_until_invalidate};
9+
use crate::options::{enable_zjit_stats, CallThreshold, get_option, rb_zjit_prepare_options, set_call_threshold, set_inline_threshold, set_max_versions, set_mem_bytes, set_num_exits_until_invalidate};
1010
use crate::payload::IseqVersion;
1111
use crate::hir::tests::hir_build_tests::assert_contains_opcode;
1212
use crate::payload::*;
@@ -4599,6 +4599,59 @@ fn test_string_append_broken_coderange() {
45994599
"#), @"[4, false]");
46004600
}
46014601

4602+
#[test]
4603+
fn test_string_force_encoding_fastpath() {
4604+
enable_zjit_stats();
4605+
eval(r#"
4606+
def test(str, enc) = str.force_encoding(enc)
4607+
"#);
4608+
let counters = crate::state::ZJITState::get_counters();
4609+
let optimized_send_count_before = counters.inline_cfunc_optimized_send_count;
4610+
assert_snapshot!(assert_compiles(r#"
4611+
test("\xFF".b, Encoding::UTF_8)
4612+
test("\xFF".b, Encoding::UTF_8)
4613+
str = "\xFF".b
4614+
result = test(str, Encoding::UTF_8)
4615+
[result.equal?(str), str.bytes, str.encoding.name, str.valid_encoding?]
4616+
"#), @r#"[true, [255], "UTF-8", false]"#);
4617+
assert!(
4618+
counters.inline_cfunc_optimized_send_count > optimized_send_count_before,
4619+
"expected String#force_encoding to use the LIR fast path"
4620+
);
4621+
}
4622+
4623+
#[test]
4624+
fn test_string_force_encoding_fastpath_fallbacks() {
4625+
eval(r#"
4626+
def test(str, enc) = str.force_encoding(enc)
4627+
"#);
4628+
assert_snapshot!(assert_compiles_allowing_exits(r#"
4629+
test(String.new("abc"), Encoding::UTF_8)
4630+
test(String.new("abc"), Encoding::UTF_8)
4631+
4632+
changed = "\xFF".b
4633+
changed_result = test(changed, Encoding::UTF_8)
4634+
4635+
frozen = String.new("abc").freeze
4636+
frozen_result = begin
4637+
test(frozen, Encoding::UTF_8)
4638+
rescue FrozenError
4639+
:frozen_error
4640+
end
4641+
4642+
chilled = "abc"
4643+
chilled_result = test(chilled, Encoding::UTF_8)
4644+
4645+
[
4646+
changed_result.equal?(changed),
4647+
changed.encoding.name,
4648+
changed.valid_encoding?,
4649+
frozen_result,
4650+
chilled_result.equal?(chilled),
4651+
]
4652+
"#), @r#"[true, "UTF-8", false, :frozen_error, true]"#);
4653+
}
4654+
46024655
#[test]
46034656
fn test_new_hash_nonempty() {
46044657
eval(r#"

‎zjit/src/cruby_bindings.inc.rs‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎zjit/src/cruby_methods.rs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ pub fn init() -> Annotations {
218218
annotate!(rb_mKernel, "===", inline_eqq);
219219
annotate!(rb_mKernel, "is_a?", inline_kernel_is_a_p);
220220
annotate!(rb_cString, "bytesize", inline_string_bytesize);
221+
annotate!(rb_cString, "force_encoding", inline_string_force_encoding, types::String);
221222
annotate!(rb_cString, "size", types::Fixnum, no_gc, leaf, elidable);
222223
annotate!(rb_cString, "length", types::Fixnum, no_gc, leaf, elidable);
223224
annotate!(rb_cString, "getbyte", inline_string_getbyte);
@@ -472,6 +473,23 @@ fn inline_hash_aset(fun: &mut hir::Function, block: hir::BlockId, recv: hir::Ins
472473
}
473474
}
474475

476+
fn inline_string_force_encoding(fun: &mut hir::Function, block: hir::BlockId, recv: hir::InsnId, args: &[hir::InsnId], state: hir::InsnId) -> Option<hir::InsnId> {
477+
let &[enc] = args else { return None; };
478+
let enc_type = Type::from_class(unsafe { rb_cEncoding });
479+
if !fun.likely_a(recv, types::String, state) || !fun.likely_a(enc, enc_type, state) {
480+
return None;
481+
}
482+
483+
let string = fun.coerce_to(block, recv, types::String, state);
484+
let encoding = fun.coerce_to(block, enc, enc_type, state);
485+
let _ = fun.push_insn(block, hir::Insn::StringForceEncoding {
486+
string,
487+
encoding,
488+
state,
489+
});
490+
Some(string)
491+
}
492+
475493
fn inline_string_bytesize(fun: &mut hir::Function, block: hir::BlockId, recv: hir::InsnId, args: &[hir::InsnId], state: hir::InsnId) -> Option<hir::InsnId> {
476494
if args.is_empty() && fun.likely_a(recv, types::String, state) {
477495
let recv = fun.coerce_to(block, recv, types::String, state);

‎zjit/src/hir.rs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1003,6 +1003,8 @@ pub enum Insn {
10031003
StringCopy { val: InsnId, chilled: bool, state: InsnId },
10041004
StringIntern { val: InsnId, state: InsnId },
10051005
StringConcat { strings: Vec<InsnId>, state: InsnId },
1006+
/// Apply String#force_encoding for a mutable string and an inline encoding.
1007+
StringForceEncoding { string: InsnId, encoding: InsnId, state: InsnId },
10061008
/// Call rb_str_getbyte with known-Fixnum index
10071009
StringGetbyte { string: InsnId, index: InsnId },
10081010
/// Call rb_str_byte_substr with known-Fixnum beg/len
@@ -1426,6 +1428,11 @@ macro_rules! for_each_operand_impl {
14261428
$visit_many!(strings);
14271429
$visit_one!(*state);
14281430
}
1431+
Insn::StringForceEncoding { string, encoding, state, .. } => {
1432+
$visit_one!(*string);
1433+
$visit_one!(*encoding);
1434+
$visit_one!(*state);
1435+
}
14291436
Insn::StringGetbyte { string, index } => {
14301437
$visit_one!(*string);
14311438
$visit_one!(*index);
@@ -1761,6 +1768,7 @@ impl Insn {
17611768
Insn::StringCopy { .. } => allocates,
17621769
Insn::StringIntern { .. } => effects::Any,
17631770
Insn::StringConcat { .. } => effects::Any,
1771+
Insn::StringForceEncoding { .. } => Effect::read_write(abstract_heaps::Memory, abstract_heaps::Control),
17641772
Insn::StringGetbyte { .. } => Effect::read_write(abstract_heaps::Other, abstract_heaps::Empty),
17651773
Insn::StringByteslice { .. } => allocates.union(Effect::read(abstract_heaps::Other)),
17661774
Insn::StringSetbyteFixnum { .. } => effects::Any,
@@ -2156,6 +2164,9 @@ impl<'a> std::fmt::Display for InsnPrinter<'a> {
21562164
write_separated!(f, " ", ", ", strings);
21572165
Ok(())
21582166
}
2167+
Insn::StringForceEncoding { string, encoding, .. } => {
2168+
write!(f, "StringForceEncoding {string}, {encoding}")
2169+
}
21592170
Insn::StringGetbyte { string, index, .. } => {
21602171
write!(f, "StringGetbyte {string}, {index}")
21612172
}
@@ -3679,6 +3690,7 @@ impl Function {
36793690
Insn::StringCopy { .. } => types::StringExact,
36803691
Insn::StringIntern { .. } => types::Symbol,
36813692
Insn::StringConcat { .. } => types::StringExact,
3693+
Insn::StringForceEncoding { string, .. } => self.type_of(*string),
36823694
Insn::StringGetbyte { .. } => types::Fixnum,
36833695
Insn::StringByteslice { .. } => types::StringExact.union(types::NilClass),
36843696
Insn::StringSetbyteFixnum { .. } => types::Fixnum,
@@ -8099,6 +8111,10 @@ impl Function {
80998111
}
81008112
}
81018113
}
8114+
Insn::StringForceEncoding { string, encoding, .. } => {
8115+
self.assert_subtype(insn_id, string, types::String)?;
8116+
self.assert_subtype(insn_id, encoding, Type::from_class(unsafe { rb_cEncoding }))
8117+
}
81028118
Insn::GuardLess { left, right, .. }
81038119
| Insn::GuardGreaterEq { left, right, .. } => {
81048120
self.assert_subtype(insn_id, left, types::CInt64)?;

‎zjit/src/hir/opt_tests.rs‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17171,6 +17171,120 @@ mod hir_opt_tests {
1717117171
");
1717217172
}
1717317173

17174+
#[test]
17175+
fn test_string_force_encoding_inlines_for_exact_arity_and_types() {
17176+
eval(r#"
17177+
def test(s, enc) = s.force_encoding(enc)
17178+
test(String.new("abc"), Encoding::UTF_8)
17179+
test(String.new("abc"), Encoding::UTF_8)
17180+
"#);
17181+
assert_snapshot!(hir_string("test"), @"
17182+
fn test@<compiled>:2:
17183+
bb1():
17184+
EntryPoint interpreter
17185+
v1:BasicObject = LoadSelf
17186+
v2:CPtr = LoadSP
17187+
v3:BasicObject = LoadField v2, :s@0x1000
17188+
v4:BasicObject = LoadField v2, :enc@0x1001
17189+
Jump bb3(v1, v3, v4)
17190+
bb2():
17191+
EntryPoint JIT(0)
17192+
v7:BasicObject = LoadArg :self@0
17193+
v8:BasicObject = LoadArg :s@1
17194+
v9:BasicObject = LoadArg :enc@2
17195+
Jump bb3(v7, v8, v9)
17196+
bb3(v11:BasicObject, v12:BasicObject, v13:BasicObject):
17197+
PatchPoint NoSingletonClass(String@0x1008)
17198+
PatchPoint MethodRedefined(String@0x1008, force_encoding@0x1010, cme:0x1018)
17199+
v28:StringExact = GuardType v12, StringExact recompile
17200+
v29:ObjectSubclass[class_exact:Encoding] = GuardType v13, ObjectSubclass[class_exact:Encoding]
17201+
v30:StringExact = StringForceEncoding v28, v29
17202+
CheckInterrupts
17203+
Return v28
17204+
");
17205+
}
17206+
17207+
#[test]
17208+
fn test_string_force_encoding_does_not_inline_wrong_arity() {
17209+
eval(r#"
17210+
def test_no_args(s) = s.force_encoding
17211+
def test_two_args(s) = s.force_encoding(Encoding::UTF_8, Encoding::UTF_8)
17212+
test_no_args(String.new("abc")) rescue nil
17213+
test_two_args(String.new("abc")) rescue nil
17214+
"#);
17215+
assert_snapshot!(hir_strings!("test_no_args", "test_two_args"), @"
17216+
fn test_no_args@<compiled>:2:
17217+
bb1():
17218+
EntryPoint interpreter
17219+
v1:BasicObject = LoadSelf
17220+
v2:CPtr = LoadSP
17221+
v3:BasicObject = LoadField v2, :s@0x1000
17222+
Jump bb3(v1, v3)
17223+
bb2():
17224+
EntryPoint JIT(0)
17225+
v6:BasicObject = LoadArg :self@0
17226+
v7:BasicObject = LoadArg :s@1
17227+
Jump bb3(v6, v7)
17228+
bb3(v9:BasicObject, v10:BasicObject):
17229+
v15:BasicObject = Send v10, :force_encoding # SendFallbackReason: Argument count does not match parameter count
17230+
CheckInterrupts
17231+
Return v15
17232+
17233+
fn test_two_args@<compiled>:3:
17234+
bb1():
17235+
EntryPoint interpreter
17236+
v1:BasicObject = LoadSelf
17237+
v2:CPtr = LoadSP
17238+
v3:BasicObject = LoadField v2, :s@0x1000
17239+
Jump bb3(v1, v3)
17240+
bb2():
17241+
EntryPoint JIT(0)
17242+
v6:BasicObject = LoadArg :self@0
17243+
v7:BasicObject = LoadArg :s@1
17244+
Jump bb3(v6, v7)
17245+
bb3(v9:BasicObject, v10:BasicObject):
17246+
PatchPoint StableConstantNames(0x1008, Encoding::UTF_8)
17247+
v16:ObjectSubclass[VALUE(0x1010)] = Const Value(VALUE(0x1010))
17248+
PatchPoint StableConstantNames(0x1018, Encoding::UTF_8)
17249+
v19:ObjectSubclass[VALUE(0x1010)] = Const Value(VALUE(0x1010))
17250+
v21:BasicObject = Send v10, :force_encoding, v16, v19 # SendFallbackReason: Argument count does not match parameter count
17251+
CheckInterrupts
17252+
Return v21
17253+
");
17254+
}
17255+
17256+
#[test]
17257+
fn test_string_force_encoding_does_not_inline_string_name() {
17258+
eval(r#"
17259+
def test(s, enc) = s.force_encoding(enc)
17260+
test(String.new("abc"), "UTF-8")
17261+
test(String.new("abc"), "UTF-8")
17262+
"#);
17263+
assert_snapshot!(hir_string("test"), @"
17264+
fn test@<compiled>:2:
17265+
bb1():
17266+
EntryPoint interpreter
17267+
v1:BasicObject = LoadSelf
17268+
v2:CPtr = LoadSP
17269+
v3:BasicObject = LoadField v2, :s@0x1000
17270+
v4:BasicObject = LoadField v2, :enc@0x1001
17271+
Jump bb3(v1, v3, v4)
17272+
bb2():
17273+
EntryPoint JIT(0)
17274+
v7:BasicObject = LoadArg :self@0
17275+
v8:BasicObject = LoadArg :s@1
17276+
v9:BasicObject = LoadArg :enc@2
17277+
Jump bb3(v7, v8, v9)
17278+
bb3(v11:BasicObject, v12:BasicObject, v13:BasicObject):
17279+
PatchPoint NoSingletonClass(String@0x1008)
17280+
PatchPoint MethodRedefined(String@0x1008, force_encoding@0x1010, cme:0x1018)
17281+
v28:StringExact = GuardType v12, StringExact recompile
17282+
v29:String = CCallWithFrame v28, :String#force_encoding@0x1040, v13
17283+
CheckInterrupts
17284+
Return v29
17285+
");
17286+
}
17287+
1717417288
#[test]
1717517289
fn test_inline_string_bytesize() {
1717617290
eval(r#"

0 commit comments

Comments
 (0)