In lesson 129 every opt_plus asked, each time it ran, whether both sides were Integers and Integer#+ was still the original. A just-in-time compiler, a JIT, turns code that runs often into machine code that has answered such questions in advance. CRuby has had one since Ruby 3.1: YJIT (Yet Another Ruby JIT), written at Shopify, in Rust since 3.2, and the JIT that Ruby 3.x and 4.0 run in production. Its idea comes from research by Maxime Chevalier-Boisvert and Marc Feeley: lazy basic block versioning. Each of those words is a step in this lesson.
YJIT is not in this page, though: it writes x86-64 or arm64 machine code, and this Ruby runs as WebAssembly.
puts RUBY_DESCRIPTION
p defined?(RubyVM::YJIT)nil – no YJIT here. (On your computer, ruby --yjit adds +YJIT to the description.) So this lesson builds YJIT's steps as a small Ruby model that runs here, on this Ruby's real instructions.
1. Basic blocks
Every call of a method adds 1 to a counter in its instruction sequence. At call 30 YJIT starts (--yjit-call-threshold; once an application has more than 40,000 instruction sequences, it moves to 120). But it does not compile the method. It compiles one basic block: the instructions from where execution stands up to the next branchif, branchunless, jump or leave – a stretch that runs from top to bottom with no way out in the middle. The model takes a method's real instructions (to_a, as in lesson 129), names each by its position, the pc, and cuts out the block that starts at a pc. Then it follows every block's exits to the next one:
def savings(weeks)
total = 0
while weeks > 0
total += 2.5
weeks -= 1
end
total
end
# YARV's instructions as { pc => [name, *operands] }: a jump's label
# becomes the pc it points to, a local's index becomes its name
def yarv_body(meth)
iseq = RubyVM::InstructionSequence.of(meth).to_a
locals = iseq[10]
labels = {}
body = {}
pc = 0
iseq.last.each do |item|
labels[item] = pc if item.to_s.start_with?("label_")
next unless item.is_a?(Array)
body[pc] = item
pc += item.size
end
body.transform_values do |name, *ops|
ops = [locals[locals.size - ops[0] + 2]] if name.end_with?("local_WC_0")
[name, *ops.map { |op| labels.fetch(op, op) }]
end
end
# A basic block: from start up to the first branch, jump or leave
def block_at(body, start)
pc = start
block = []
loop do
block << [pc, *body.fetch(pc)]
return block if %i[branchif branchunless jump leave].include?(body[pc][0])
pc += body[pc].size
end
end
def show_block(block)
puts "block #{block[0][0]}:"
block.each do |pc, name, *ops|
shown = ops.map { |op| op.is_a?(Hash) ? op[:mid] : op }
puts " %04d #{[name, *shown].join(" ")}" % pc
end
end
body = yarv_body(method(:savings))
todo = [0] # follow every exit, starting at 0
seen = []
until todo.empty?
start = todo.shift
next if seen.include?(start)
seen << start
block = block_at(body, start)
show_block block
pc, name, target = block.last
todo << target unless name == :leave
todo << pc + body[pc].size if name == :branchif || name == :branchunless
endFour blocks, and two things a compiler of whole methods would see differently. Block 9 runs on through 24: a block ends at a branch, not where a jump lands, so 24 to 29 are in two blocks and are compiled twice. And 5 to 7 (putnil, pop, jump, left over from compiling while) are in no block at all: nothing gets there.
2. Lazy
The walk above followed every exit. YJIT does not. When it compiles branchif 9, it compiles neither block 9 nor block 31. For each it writes a branch stub instead, a few instructions that call back into the compiler. The first time the branch goes that way, the stub compiles the block and patches the jump to lead straight to the new code. Code that never runs is never compiled – the error branch, the half of a method that only the tests call. (A plain jump is the exception: its target is compiled right away.)
Until then, and whenever compiled code gives up, the interpreter runs. Here is the model's: one instruction at a time, and opt_gt or opt_plus is a method call like any other, every time:
# One instruction, the way the interpreter runs it. Gives the pc to
# jump to, :leave at the end, or nil: go on with the next one
def yarv_step(insn, locals, stack)
name, op = insn
case name
when :putnil then stack << nil
when :pop then stack.pop
when :putobject then stack << op
when :putobject_INT2FIX_0_ then stack << 0
when :putobject_INT2FIX_1_ then stack << 1
when :getlocal_WC_0 then stack << locals[op]
when :setlocal_WC_0 then locals[op] = stack.pop
when :jump then return op
when :branchif then return op if stack.pop
when :branchunless then return op unless stack.pop
when :leave then return :leave
else # opt_plus, opt_gt ...: a method call like any other
arg = stack.pop
stack << stack.pop.public_send(op[:mid], arg)
end
nil
end
def interpret(body, pc, locals, stack)
loop do
jump = yarv_step(body.fetch(pc), locals, stack)
return stack.pop if jump == :leave
pc = jump || pc + body[pc].size
end
end
interpret(body, 0, { weeks: 4 }, [])Four weeks at 2.5 make 10.0.
3. Versions
While it compiles a block, YJIT keeps a type context: what it knows about each local and each value on the stack. After putobject_INT2FIX_0_ and setlocal total it knows that total is an Integer. Where it meets an opt_gt or opt_plus with an operand whose type it does not know, it looks at the value – the block is being compiled right now, the first time execution gets there, so the value is there to see. A Fixnum? Then it writes a guard, one type check at run time, notes Integer in the context and adds two machine words without calling a method. The rest of the block, and every block it leads to, inherits the context and checks no more.
So the same block can be reached with different contexts – and then it is compiled again, once per context: a version. YJIT keeps its versions by block and context. The model does the same, and its compile walks a block with types instead of values:
# A model of YJIT: a block is compiled when first reached -
# once per type context
class TinyYjit
attr_reader :versions, :log
def initialize(meth)
@meth = meth
@body = yarv_body(meth)
@versions = Hash.new { |hash, pc| hash[pc] = {} } # pc => { context => version }
@log = []
@locals = {}
end
def version_for(pc, ctx)
@versions[pc][ctx] ||= compile(pc, ctx)
end
# "Compiling": once through the block, with types instead of values. An opt_plus
# on two Integers gets guards for the operands whose type is not known
# yet - what the locals hold right now decides.
def compile(pc, ctx)
types = ctx.dup
temps = []
code = block_at(@body, pc).map do |at, name, op|
guards = []
case name
when :getlocal_WC_0 then temps << [types[op], op]
when :setlocal_WC_0 then types[op] = temps.pop[0]
when :putobject_INT2FIX_0_, :putobject_INT2FIX_1_ then temps << [Integer]
when :putobject then temps << [op.class]
when :putnil then temps << [NilClass]
when :pop, :branchif, :branchunless then temps.pop
when :opt_plus, :opt_minus, :opt_lt, :opt_gt
operands = [temps.pop, temps.pop]
fast = operands.all? do |type, local|
type == Integer || (type.nil? && @locals[local].is_a?(Integer))
end
operands.each_with_index do |(type, local), depth|
next unless fast && type.nil?
guards << [depth, local]
types[local] = Integer
end
temps << [(Integer if fast && (name == :opt_plus || name == :opt_minus))]
end
[at, [name, op].compact, guards]
end
@log << "compile block #{pc} for #{ctx}"
[code, types.compact]
end
def run_block(code, stack)
code.each do |pc, insn, guards|
guards.each do |depth, local|
next if stack[-1 - depth].is_a?(Integer)
@log << "side exit at #{pc}: #{local} is #{stack[-1 - depth].inspect}"
return [:exit, interpret(@body, pc, @locals, stack)]
end
jump = yarv_step(insn, @locals, stack)
return [:leave, stack.pop] if jump == :leave
return [:jump, jump] if jump
end
pc, insn, = code.last
[:jump, pc + insn.size]
end
def call(*args)
@locals = @meth.parameters.map(&:last).zip(args).to_h
stack = []
pc = 0
ctx = {}
loop do
code, ctx_after = version_for(pc, ctx)
how, value = run_block(code, stack)
return value unless how == :jump
pc = value
ctx = ctx_after
end
end
end
jit = TinyYjit.new(method(:savings))
p jit.call(4)
p jit.call(3)
puts jit.log
puts jit.versions.map { |pc, versions| "block #{pc}: #{versions.size} version(s)" }Follow the log. Block 24 is compiled with total known, and its guard on weeks adds weeks: Integer. Block 9 gets that context and needs no guard at all. But total += 2.5 is no Integer arithmetic: it is a method call whose result the compiler does not know, so total drops out of the context. The branch back to 9 arrives with {weeks: Integer} – a new context, a second version of block 9, and from then on the loop runs in that one. The second call compiled nothing: every version it needed was there.
4. Side exits
The guards bet on what the first call saw. And if a later call is different?
p jit.call(2.5)
p savings(2.5)
puts jit.log.lastThe guard at 27 found weeks = 2.5 and took a side exit: the compiled code hands its frame, stack and pc to the interpreter, which carries on at that very instruction – 7.5, as plain Ruby says. (Real YJIT tries harder first: a failing guard compiles one more version for the type it sees, up to five deep, and only then exits.)
Versions cost memory, so there is a limit, --yjit-max-versions (4; ruby --help does not list it). When a block is about to get its fourth version, YJIT compiles a generic one instead: its context is empty, it assumes nothing and guards everything, and it fits every context that comes later.
And if someone redefines Integer#+? The fast path assumes the original. YJIT notes that assumption for every block that makes it, and a redefinition makes CRuby call rb_yjit_bop_redefined: all those blocks are invalidated, patched to exit to the interpreter, and compiled anew when they are reached again. With Warning[:performance] = true Ruby says so: Redefining 'Integer#+' disables interpreter and JIT optimizations. The next lesson shows ZJIT, which takes the other road: it waits, profiles, and compiles a whole method at once – with the same kind of promise, its PatchPoint.
- Counting calls:
yjit_compile:516andrb_yjit_threshold_hit:472in vm.c; 30 and 120 inSMALL_CALL_THRESHOLD:6(options.rs), the version limitmax_versions:44with its defaultmax_versions: 4:98. - One block:
gen_single_block:1258compiles until an instruction ends the block – and first askslimit_block_versions:2276whether it is time for the generic context. A block's key isBlockId:1219: an instruction sequence and an index. - Lazy:
gen_branchunless:4689makes a branch with two stubs;branch_stub_hit_body:3521compiles a target when its stub is hit.defer_compilation:3970even ends a block early when YJIT wants to see a value first. - Versions:
find_block_version:2220picks the version of a block that fits a context best. - Guards:
gen_opt_plus:1736callsguard_two_fixnums:3492, which checks only what the context does not know and then upgrades the types; a failing guard chains a new version injit_chain_guard:2797. - Redefinition:
assume_bop_not_redefined:98andrb_yjit_bop_redefined:266in invariants.rs, called in vm.c beside the warning:rb_yjit_bop_redefined:2371.
ruby --yjit -e 'p RubyVM::YJIT.enabled?' prints true, and RubyVM::YJIT.enable switches it on in a running program. Put savings and the three calls into a file and run ruby --yjit --yjit-call-threshold=1 --yjit-log savings.rb: at the end it lists every block YJIT compiled, like savings@savings.rb:4 (index: 9) – index 9 more than once, those are versions – and (index: 27, chain_depth: 1), the guard that met 2.5. You will see more and smaller blocks than in the model: YJIT ends a block early wherever it wants to see a value first.version_for(pc, ctx) for CappedYjit, a TinyYjit with --yjit-max-versions. @versions[pc] is the block's { context => version }. If it has a version for ctx, give that back. Otherwise compile a new one – unless that would be the block's max_versions-th: then take the generic context {} instead, compiled once and shared from then on. drift is made for it: on each pass through its loop one more of a, b, c stops being an Integer, so its loop block is reached with four contexts, and the fourth must become {}.def drift(n)
a = 0
b = 0
c = 0
while n > 0
c = b
b = a
a = a + 0.5
n -= 1
end
c
end
class CappedYjit < TinyYjit
def version_for(pc, ctx)
max_versions = 4 # --yjit-max-versions
# a version for ctx exists already: use it. Otherwise, if a new one
# would be the block's max_versions-th, use ctx = {} instead
super
end
end
jit = CappedYjit.new(method(:drift))
p jit.call(6)
puts jit.log