Skip to content

ZJIT: Read stale value after inlining a send-ish instruction #976

@nozomemein

Description

@nozomemein

Issue Detail

ZJIT can read a stale local value after a block-backed send-ish instruction is optimized away by later passes.

In the reproducer below, the local a is assigned 1 and then foo {} is called. After optimization, the send is effectively inlined away, but the post-send local reload still remains in HIR. That reload reads a from the VM frame instead of using the current FrameState value. Because the call was optimized away, the local value was never spilled back to the VM frame slot, so the reload can observe a stale value (for example nil) instead of the current value 1.

As a result, it returns a stale value from the frame slot and a becomes nil on the compiled execution.

Reproduction

def foo(&block) = 1

def test
  a = 1
  foo {}
  a
end

p [test, test]

This should be:

ruby ../test.rb
[1,1]

When ZJIT is enabled:

./miniruby --zjit --zjit-call-threshold=2 ../test.rb
[1,nil]

Dumped HIR snap:

bb3(v8:BasicObject, v9:NilClass):
  v13:Fixnum[1] = Const Value(1)
  PatchPoint MethodRedefined(Object@0x102a4efe0, foo@0x9ee1, cme:0x102b84f68)
  v32:ObjectSubclass[class_exact*:Object@VALUE(0x102a4efe0)] = GuardType v8, ObjectSubclass[class_exact*:Object@VALUE(0x102a4efe0)]
  v19:CPtr = GetEP 0                    # start of surviving local reload
  v20:BasicObject = LoadField v19, :a@-0x18  # reload local `a` from VM frame slot
  PatchPoint NoEPEscape(test)
  CheckInterrupts
  Return v20

Possible direction

The root problem seems to be that post-send local reloads are inserted eagerly.
Later passes may inline or eliminate the send-ish instruction, but the reload can remain and read a stale VM frame slot.

Deferring reload insertion until after inlining / call optimization would likely avoid this issue,
since reloads would only be emitted for send-ish instructions that still survive in the final HIR.

Related: #774

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions