2022-12-17 13:39:35 -08:00
|
|
|
require 'mjit/insn_compiler'
|
|
|
|
require 'mjit/instruction'
|
|
|
|
require 'mjit/x86_assembler'
|
2022-12-11 21:42:25 -08:00
|
|
|
|
2022-12-17 13:39:35 -08:00
|
|
|
module RubyVM::MJIT
|
|
|
|
# Compilation status
|
|
|
|
KeepCompiling = :keep_compiling
|
|
|
|
CantCompile = :cant_compile
|
|
|
|
EndBlock = :end_block
|
2022-12-11 21:42:25 -08:00
|
|
|
|
2022-12-17 13:39:35 -08:00
|
|
|
class Compiler
|
|
|
|
# Ruby constants
|
|
|
|
Qundef = Fiddle::Qundef
|
2022-12-11 21:42:25 -08:00
|
|
|
|
2022-12-17 13:39:35 -08:00
|
|
|
attr_accessor :write_pos
|
2022-09-04 21:53:46 -07:00
|
|
|
|
2022-12-17 13:39:35 -08:00
|
|
|
# @param mem_block [Integer] JIT buffer address
|
|
|
|
def initialize(mem_block)
|
|
|
|
@mem_block = mem_block
|
|
|
|
@write_pos = 0
|
|
|
|
@insn_compiler = InsnCompiler.new
|
|
|
|
end
|
2022-11-28 21:33:55 -08:00
|
|
|
|
2022-12-17 13:39:35 -08:00
|
|
|
# @param iseq [RubyVM::MJIT::CPointer::Struct]
|
|
|
|
def compile(iseq)
|
|
|
|
return if iseq.body.location.label == '<main>'
|
|
|
|
iseq.body.jit_func = compile_iseq(iseq)
|
|
|
|
rescue Exception => e
|
|
|
|
# TODO: check --mjit-verbose
|
|
|
|
$stderr.puts e.full_message
|
|
|
|
end
|
2022-12-11 21:42:25 -08:00
|
|
|
|
2022-12-17 13:39:35 -08:00
|
|
|
def write_addr
|
|
|
|
@mem_block + @write_pos
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
2022-12-15 22:20:43 -08:00
|
|
|
|
2022-12-17 13:39:35 -08:00
|
|
|
# ec -> RDI, cfp -> RSI
|
|
|
|
def compile_iseq(iseq)
|
|
|
|
addr = write_addr
|
|
|
|
asm = X86Assembler.new
|
2022-12-15 22:20:43 -08:00
|
|
|
|
2022-12-17 13:39:35 -08:00
|
|
|
index = 0
|
|
|
|
while index < iseq.body.iseq_size
|
|
|
|
insn = decode_insn(iseq.body.iseq_encoded[index])
|
|
|
|
status = compile_insn(asm, insn)
|
|
|
|
if status == EndBlock
|
|
|
|
break
|
|
|
|
end
|
|
|
|
index += insn.len
|
|
|
|
end
|
2022-12-15 22:20:43 -08:00
|
|
|
|
2022-12-17 13:39:35 -08:00
|
|
|
asm.compile(self)
|
|
|
|
addr
|
|
|
|
end
|
2022-12-15 22:20:43 -08:00
|
|
|
|
2022-12-17 13:39:35 -08:00
|
|
|
def compile_insn(asm, insn)
|
|
|
|
case insn.name
|
|
|
|
when :putnil then @insn_compiler.compile_putnil(asm)
|
|
|
|
when :leave then @insn_compiler.compile_leave(asm)
|
|
|
|
else raise NotImplementedError, "insn '#{insn.name}' is not supported yet"
|
|
|
|
end
|
|
|
|
end
|
2022-12-15 22:20:43 -08:00
|
|
|
|
2022-12-17 13:39:35 -08:00
|
|
|
def decode_insn(encoded)
|
|
|
|
INSNS.fetch(C.rb_vm_insn_decode(encoded))
|
|
|
|
end
|
2022-12-15 22:20:43 -08:00
|
|
|
end
|
2022-09-04 21:53:46 -07:00
|
|
|
end
|