Re: Adding assembler code to Lua programs

  • From: Mike Pall <mike-1403@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sat, 1 Mar 2014 11:28:05 +0100

Luke Gorrie wrote:
> I'm looking for a good way to add assembler code to a LuaJIT program.

If it's just some static code that doesn't change, then use GCC
inline assembler, compile it (once) to a .so and load it.

> Is there a convenient way to generate machine code directly from Lua and
> call it? (Could DynASM be adapted to this use case in some good way?)

Right now, DynASM only translates/generates C code. And the (tiny)
machine-specific encoding engines are in C, too. It's certainly
doable to port those to Lua, but so far nobody had a need.

> Otherwise, is DynASM the obvious choice? (The alternative being gas/nasm
> but I'm not sure if they offer any advantages worth thinking about?)

DynASM is mainly useful if the assembler code to be generated is
truly 'dynamic'. That is, the order and the parameters of the code
fragments change at runtime. E.g. a JIT-compiler for a packet
filter would qualify.

The other option is to generate Lua source code on-the-fly and let
LuaJIT chew on it. But don't forget that Lua is a general purpose
dynamic language -- depending on the source DSL, there's some
unavoidable impedance loss.

It's hard to match the efficiency of functions assembled from
hand-optimized machine code fragments. OTOH, it's hard to devise
those fragments, the register assignments and the logic behind all
of it in the first place. It might be helpful to prototype it in
Lua first and optimize it later on (if needed).

--Mike

Other related posts: