Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

ruby-jit-challenge

> 编程语言
Open source

Tutorial to write a Ruby JIT

190 stars0 likes3 views
WebsiteGitHub

About

Tutorial to write a Ruby JIT

Ruby JIT Challenge

Supplemental material to Ruby JIT Hacking Guide for RubyKaigi 2023

Introduction

This is a small tutorial to write a JIT compiler in Ruby. We don't expect any prior experience in compilers or assembly languages. It's supposed to take only several minutes if you read all hints, but challenging if you don't.

You'll write a JIT that can compile a Fibonacci benchmark. With relaxed implementation requirements, you'll hopefully create a JIT faster than existing Ruby JITs with ease.

The goal of this repository is to make you feel comfortable using and/or contributing to Ruby JIT. More importantly, enjoy writing a compiler in Ruby.

Setup

This repository assumes an x86_64-linux environment. It also requires a Ruby master build to leverage RJIT's interface to integrate a custom JIT.

It's recommended to use the following Docker container environment. There's also bin/docker as a shorthand.

bash
$ docker run -it -v "$(pwd):/app" k0kubun/rjit bash

See Dockerfile if you want to prepare the same environment locally.

Testing

You'll build a JIT in multiple steps. Test scripts in test/*.rb will help you test them one by one. You can run them with your JIT enabled with bin/ruby.

bin/ruby test/none.rb

You can also dump compiled code with bin/ruby --rjit-dump-disasm test/none.rb.

For your convenience, rake test (test/jit/compiler_test.rb) runs all test scripts with your JIT enabled.

1. Compile nil

First, we'll compile the following simple method that just returns nil.

rb
def none
  nil
end

--dump=insns

In CRuby, each Ruby method is internally compiled into an "Instruction Sequence", also known as ISeq. The CRuby interpreter executes Ruby code by looping over instructions in this sequence.

Typically, a CRuby JIT takes an ISeq as input to the JIT compiler and outputs machine code that works in the same way as the ISeq. In this exercise, it's the only input you'll need to take care of.

You can dump ISeqs in a file by ruby --dump=insns option. Let's have a look at the ISeq of none method.

$ ruby --dump=insns test/none.rb
...
== disasm: #
0000 putnil                                                           (   1)[Ca]
0001 leave                                                            (   3)[Re]

This means that none consists of two instructions: putnil and leave.

putnil instruction puts nil on the "stack" of the Ruby interpreter. Imagine `stack = []; stack Assembler

Assembler

lib/jit/assembler.rb has an x86_64 assembler that was copied from RJIT and then simplified. Feel free to remove it and write it from scratch, but this tutorial will not cover how to encode x86_64 instructions.

Here's example code using Assembler.

rb
asm = Assembler.new
asm.mov(:rax, [:rsi, 8])
asm.add(:rax, 2)
write(asm)

This writes the following machine code into memory.

asm
mov rax, [rsi + 8]
add rax, 2

rax and rsi are registers. [rsi + 8] is memory access based off of a register, which reads memory 8 bytes after the address in rsi. 2 is an immediate value.

See lib/jit/assembler.rb for what kind of input it can handle.

Instructions

Instructions

There are various x86_64 instructions. However, it's enough to use only the following instructions to pass tests in this tutorial.

For test/none.rb, only mov, add, and ret are necessary.

Instruction Description Example Effect
mov Assign a value. mov rax, 1 rax = 1
add Add a value. add rax, 1 rax += 1
sub Subtract a value. sub rax, 1 rax -= 1
cmp Compare values. Use it with cmovl. cmp rdi, rsi `rdi

Registers

Registers

Registers are like variables in machine code. You're free to use registers in whatever way, but a reference implementation used only the following registers.

Register Purpose
rdi ec (execution context) is set when a JIT function is called. It represents a Ruby thread. Used when you push/pop a stack frame.
rsi cfp (control frame pointer) is set when a JIT function is called. It represents a stack frame. Used when you fetch a local variable or a receiver.
rax A JIT function return value to be set before ret instruction. It can be also used as a "scratch register" to hold temporary values.
r8 A general-purpose register. The reference implementation used this for the 1st slot of the Ruby VM stack, stack[0].
r9 A general-purpose register. The reference implementation used this for the 2nd slot of the Ruby VM stack, stack[1].
r10 A general-purpose register. The reference implementation used this for the 3rd slot of the Ruby VM stack, stack[2].
r11 A general-purpose register. The reference implementation used this for the 4th slot of the Ruby VM stack, stack[3].

Compiling putnil

Compiling putnil

Open lib/jit/compiler.rb and add a case for putnil.

…

diff STACK = [:r8]

  •  EC = :rdi
  •  CFP = :rsi
    
     # Iterate over each YARV instruction.
     insn_index = 0
     stack_size = 0
     while insn_index cfp`, you need to get a memory address based off of `ec`.

The offset of ec->cfp relative to the head of ec is in C.rb_execution_context_t.offsetof(:cfp). So you can use [EC, C.rb_execution_context_t.offsetof(:cfp)] to get ec->cfp.

Finally, we'll return a value from the JIT function. You should set a stack-top value to rax and then put ret instruction.

diff
       # Iterate over each YARV instruction.
       insn_index = 0
       stack_size = 0
       while insn_index 

## 2. Compile 1 + 2

Next, we'll compile something more interesting: `Integer#+`.

```rb
def plus
  1 + 2
end

--dump=insns

$ ruby --dump=insns test/plus.rb
...
== disasm: #
0000 putobject_INT2FIX_1_                                             (   2)[LiCa]
0001 putobject                              2
0003 opt_plus                               [CcCr]
0005 leave                                                            (   3)[Re]

…

rb
STACK = [:r8, :r9]

in :putobject_INT2FIX_1_
  asm.mov(STACK[stack_size], C.to_value(1))
  stack_size += 1

For putobject, you need to get an operand from iseq.body.iseq_encoded as explained above. You could write:

rb
in :putobject
  operand = iseq.body.iseq_encoded[insn_index + 1]
  asm.mov(STACK[stack_size], operand)
  stack_size += 1

Compiling opt_plus

Compiling opt_plus

opt_plus is capable of handling any #+ methods, but specifically optimizes a few methods such as Integer#+. In this tutorial, we're going to handle only Integers. It's okay to assume operands are all Integers.

In CRuby, a small-enough Integer is expressed as `(num

3. Compile fibonacci

Finally, we'll have a look at the benchmark target, Fibonacci.

rb
def fib(n)
  if n [CcCr]
0006 branchunless                           11
0008 getlocal_WC_0                          n@0                       (   3)[Li]
0010 leave                                  [Re]
0011 putself                                                          (   5)[Li]
0012 getlocal_WC_0                          n@0
0014 putobject_INT2FIX_1_
0015 opt_minus                              [CcCr]
0017 opt_send_without_block                 
0019 putself
0020 getlocal_WC_0                          n@0
0022 putobject                              2
0024 opt_minus                              [CcCr]
0026 opt_send_without_block                 
0028 opt_plus                               [CcCr]
0030 leave                                                            (   6)[Re]

…

rb
in :getlocal_WC_0
  # Get EP
  asm.mov(:rax, [CFP, C.rb_control_frame_t.offsetof(:ep)])

  # Load the local variable
  idx = iseq.body.iseq_encoded[insn_index + 1]
  asm.mov(STACK[stack_size], [:rax, -idx * C.VALUE.size])

  stack_size += 1

Test the instruction with bin/ruby --rjit-dump-disasm test/local.rb.

Compiling opt_lt

Compiling opt_lt

Again, assume operands are Integers. Comparing `(num1

Compiling putself

Compiling putself

fib method is called without an argument. In Ruby, it implicitly uses the receiver of the current frame (cfp). cfp is in rsi, and the offset to cfp->self (receiver) is implemented at C.rb_control_frame_t.offsetof(:self). So [:rsi, C.rb_control_frame_t.offsetof(:self)] can be used to fetch a receiver.

An example implementation looks like this.

rb
in :putself
  asm.mov(STACK[stack_size], [CFP, C.rb_control_frame_t.offsetof(:self)])
  stack_size += 1

…


| locals | cme | block_handler | frame type (callee EP) | stack bottom (callee SP) |

…

rb
in :opt_send_without_block
  # Compile the callee ISEQ
  cd = C.rb_call_data.new(iseq.body.iseq_encoded[insn_index + 1])
  callee_iseq = cd.cc.cme_.def.body.iseq.iseqptr
  if callee_iseq.body.jit_func == 0
    compile(callee_iseq)
  end

  # Get SP
  asm.mov(:rax, [CFP, C.rb_control_frame_t.offsetof(:sp)])
  # Spill arguments
  C.vm_ci_argc(cd.ci).times do |i|
    asm.mov([:rax, C.VALUE.size * i], STACK[stack_size - C.vm_ci_argc(cd.ci) + i])
  end

  # Push cfp: ec->cfp = cfp - 1
  asm.sub(CFP, C.rb_control_frame_t.size)
  asm.mov([EC, C.rb_execution_context_t.offsetof(:cfp)], CFP)
  # Set SP
  asm.add(:rax, C.VALUE.size * (C.vm_ci_argc(cd.ci) + 3))
  asm.mov([CFP, C.rb_control_frame_t.offsetof(:sp)], :rax)
  # Set EP
  asm.sub(:rax, C.VALUE.size)
  asm.mov([CFP, C.rb_control_frame_t.offsetof(:ep)], :rax)
  # Set receiver
  asm.mov(:rax, STACK[stack_size - C.vm_ci_argc(cd.ci) - 1])
  asm.mov([CFP, C.rb_control_frame_t.offsetof(:self)], :rax)

  # Save stack registers
  STACK.each do |reg|
    asm.push(reg)
  end

  # Call the JIT func
  asm.call(callee_iseq.body.jit_func)

  # Pop stack registers
  STACK.reverse_each do |reg|
    asm.pop(reg)
  end

  # Set a return value
  asm.mov(STACK[stack_size - C.vm_ci_argc(cd.ci) - 1], :rax)

  stack_size -= C.vm_ci_argc(cd.ci)

…


== disasm: #
local table (size: 1, argc: 1 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1])
[ 1] flag@0
0000 getlocal_WC_0                          flag@0                    (   2)[LiCa]
0002 branchunless                           6

0004 putobject_INT2FIX_1_                                             (   3)[Li]
0005 leave                                                            (   7)[Re]

0006 putobject_INT2FIX_0_                                             (   5)[Li]
0007 leave                                                            (   7)[Re]

…

diff
--- a/lib/jit/assembler.rb
+++ b/lib/jit/assembler.rb
@@ -50,6 +50,7 @@ module JIT
     end

     def assemble(addr)
+      set_start_addrs(addr)
       resolve_rel32(addr)
       resolve_labels

@@ -905,6 +876,12 @@ module JIT
       @labels[label] = @bytes.size
     end

+    # Mark the starting addresses of a branch
+    def branch(branch)
+      @branches[@bytes.size] 

## 4. Benchmark

Let's measure the performance.
[bin/bench](./bin/bench) allows you to compare your JIT (ruby-jit) and other CRuby JITs.

$ bin/bench Calculating ------------------------------------- no-jit rjit yjit ruby-jit fib(32) 5.250 19.481 32.841 58.145 i/s

Comparison: fib(32) ruby-jit:

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言