Shopify / yjit

Optimizing JIT compiler built inside CRuby
658 stars 19 forks source link

`opt_nil_p` check could avoid guard known class #303

Closed maximecb closed 2 years ago

maximecb commented 2 years ago

I've encountered an instance where the opt_nil_p instruction generates the following machine code:

  # opt_nil_p
  0x10ea308d5: mov rax, qword ptr [rbx]
  # guard not immediate
  0x10ea308d8: test rax, 7
  0x10ea308df: jne 0x116a3009d
  0x10ea308e5: cmp rax, 8
  0x10ea308e9: jbe 0x116a300b6
  # guard known class
  0x10ea308ef: movabs rcx, 0x10d5c3358
  0x10ea308f9: cmp qword ptr [rax + 8], rcx
  0x10ea308fd: jne 0x116a300cf
  # nil? == false
  0x10ea30903: mov qword ptr [rbx], 0

It seems to me that if we know that the value is not an immediate, then we know it can't be nil, and we could avoid the guard known class check 🤔

This might be slightly tricky since we currently delegate to gen_opt_send_without_block to handle all the cases.

maximecb commented 2 years ago

@jhawthorn Am I wrong about this? Can an arbitrary class redefine nil? to return true ? 🤔

jhawthorn commented 2 years ago

Unfortunately, yes, arbitrary classes can redefine nil? and it is (IMO horrifyingly) done somewhat regularly in practice as well (here's one of many examples)

maximecb commented 2 years ago

Welp, this is awful.