On Tue, Sep 1, 2015 at 1:42 PM, Vyacheslav Egorov <
dmarc-noreply@xxxxxxxxxxxxx> wrote:
On Tue, Sep 1, 2015 at 8:48 PM Coda Highland <chighland@xxxxxxxxx> wrote:Yes, the __index metamethod is a lua_cfunction because it does a branching
If you have:
a.b.c.d()
a.b.c.e()
then internally LuaJIT will do something like
local f = a.b.c
f.d()
f.e()
This is a somewhat inaccurate description of what's actually happening.
Even assuming that all '.'-s in the code above are essentially
rawget-s the described CSE
transformation would only be correct if function d is guaranteed to
never re-enter Lua,
which is impossible to prove in general.
In fact LuaJIT always stops tracing when it encounters lua_CFunction
call and on FFI-calls it imposes
a special restriction (see http://luajit.org/ext_ffi_semantics.html):
One thing that's not allowed, is to let an FFI call into a C
function get JIT-compiled,
which in turn calls a callback, calling into Lua again. Usually
this attempt is caught
by the interpreter first and the C function is blacklisted for
compilation.
This is done specifically to stay on trace across FFI calls and
perform optimizations across them.
From the way original question is formulated I am guessing that
__index metamethod is actually a lua_CFunction.
This means there will be *no* CSE like you describe because in
expressions 'a.b' tracer will immediately stop as soon as it
encounters call to this __index metamethod.
Rewriting __index as a Lua function will "reopen" the possibility for
such optimizations (if the rest of the code path through __index can
be traced).
But it is impossible to say for sure whether this will be the case and
how big an improvement it will bring without knowing more about the
code in question.
In general I'd recommend to start by actually profiling your code.
Then if Lua execution is taking any observable amount of time look if
your __index is a hot-spot itself or causes LuaJIT to stop tracing
important hot loops. Otherwise - I would not worry too much.
--
Vyacheslav Egorov