Making Dynamic Lua Values Fast Without Asking Programmers to Help
I did not want a compiler-only dialect of Lua. No pragmas, no typed arrays, no ffi, no “write this differently so the compiler notices”. The whole point of luacomp is that ordinary Lua source should become a native program.
That constraint makes optimization harder, but it also keeps the contract honest. Every fast path has to prove itself at runtime, and every miss has to land back in the canonical Lua semantics. Metatables, coercion, errors, multiple returns, varargs, and the difference between Lua 5.1 doubles and Lua 5.4 integers are not edge cases to me. They are the specification.
Evaluate operands once and in source order. Set the error site once. Check
meta == NULLbefore raw table access. On every miss, call the canonical runtime helper.
Those four rules drove seven stages. Some produced clear wins. Some produced modest median changes and worse means. I am keeping those details in.
The stage map
| Stage | Change | Measurement I kept | Honest note |
|---|---|---|---|
| 1 | One guarded boxed-arithmetic helper | dynamic_values 15.3 → 13.3 ms |
LuaJIT was 7.5 ms; still ahead. |
| 2 | Numeric upvalues stay typed | median 5.94 → 5.40 ms | mean got worse, 6.10 → 6.87 ms. |
| 3 | Typed side entries for escaped numeric calls | median 8.16 → 6.55 ms | Callbacks and stored functions stay generic. |
| 4 | Typed/versioned global cache | median 7.29 → 7.19 ms | mean 10.78 → 10.98 ms; LLVM already folded many checks. |
| 5 | One shared string-field probe | field_access 20.53 → 19.42 ms |
An early version regressed to 26 ms. |
| 6 | Explicit (fid, variant) emission claims |
IR emit 183.88 → 180.69 ms | Compiler-time win, not a runtime win. |
| 7 | Advisory profile for probe skips | field_access 19.7 → 18.3 ms |
Default IR stayed byte-identical. |
The test suite grew alongside this: 33, then 35, 37, 39, 41, 44, and 45 passing programs. Two known failures (meta and typed) stayed present throughout. I am not hiding them; they are part of the baseline.
Stage 1: one guarded arithmetic helper
The first useful generalization was to stop writing tiny guarded patterns for each syntactic shape. sum = sum + t[i], a field comparison, and two boxed locals all want the same thing: check tags, use raw machine arithmetic when the tags are numeric, and fall back otherwise.
A simplified sketch of the shape:
; Before: every operand is a boxed %V, even when both carry plain numbers.
%sumv = call ptr @lr_index(ptr %t, ptr %key)
call void @lr_add(ptr %result, ptr %sumv, ptr %valv)
; After sketch: evaluate once, guard once, then use the raw payload.
%tag = load i64, ptr %slot
%is_i = icmp eq i64 %tag, 2
%is_f = icmp eq i64 %tag, 3
%both = and i1 %left_numeric, %right_numeric
br i1 %both, label %fast, label %slow
fast:
%payload_left = ...
%payload_right = ...
%raw = add i64 %payload_left, %payload_right
br label %join
slow:
call void @lr_add(ptr %result, ptr %left_slot, ptr %right_slot)
br label %joinThat is a sketch, not literal emitted IR, but the ordering is the important part. The operands have already been evaluated by the time the guard runs. The error site is set once, before the operation, so a fallback error points at the same Lua line no matter which path produced it.
Lua 5.1 goes through the float path for arithmetic because it has no integer number model. Division and power use the float path in both dialects. No fast-math; reassociation would change observable Lua results.
Stages 2–4: typed state without typed source
Once the arithmetic helper existed, the next question was where typed facts could survive between operations.
| Stage | What stays typed | What forces the generic path |
|---|---|---|
| 2 | Captured locals when every write is numeric | Any write that can change the type |
| 3 | Escaped numeric functions with scalar signatures | Upvalues, callbacks, stored functions, coercion |
| 4 | Globals with one observed numeric write type | _G, rawget, rawset, metatables, tag miss |
For upvalues, inference follows assignments through captured refs. The shared box keeps a typed payload and generated code reads it with raw scalar ops. The box pointer is loaded once per function, not once per operation. Static functions whose parameters are captured keep the generic ABI, so a typed caller cannot bypass the shared box.
For callable side entries, a second inference pass runs with escape widening disabled. A static call with numeric arguments can use a typed native side entry. A value call still goes through the closure body. This is a good example of the rule I keep repeating: the fast path is an alternate door, not a new definition of the language.
The global cache guards on the live node tag, table version, and absence of a metatable. On a hit it hands a raw payload to guarded arithmetic. On a miss it uses the boxed path, so _G, rawget, rawset, coercion, and errors keep their ordinary behavior.
The numbers were mixed. Stage 2 improved the median from 5.94 ms to 5.40 ms but the mean rose from 6.10 ms to 6.87 ms. Stage 4 improved the median from 7.29 ms to 7.19 ms and the mean rose from 10.78 ms to 10.98 ms. LLVM already folds many of the tag checks, so those stages are correctness and structure wins more than headline speed wins.
Stage 5: four probes become one
There were four hand-written string-key probes: constant reads, constant writes, sort side entries, and accumulator reads. Each one checked roughly the same thing. I replaced them with one string_probe helper.
object is a table?
├── no → lr_index / lr_setindex
└── yes → metatable == NULL?
├── no → lr_index / lr_setindex
└── yes → hash size > 0?
├── no → fallback
└── yes → node tag is string AND key pointer matches?
├── yes → raw payload load/store
└── no → lr_index / lr_setindex
The C runtime had separate lr_getfield and lr_setfield helpers that duplicated lr_index and lr_setindex. They are gone. The canonical helpers now use table_findstr directly, so equal-content keys with a different LStr object still take a fast content comparison.
That detail mattered. An early version sent dynamic string keys to a generic lr_index without the specialized string probe and regressed field_access to 26 ms. Adding table_findstr to the canonical helper removed the regression. I nearly shipped a “simplification” that made the common case worse.
The game benchmark stayed flat: idle 2,718 → 2,715 ms, demo 3,794 → 3,787 ms over nine runs. That was expected. The game mostly uses constant field keys that already took the inline path.
Stage 6: stop hiding duplicate symbols
The old compiler had a text-level dedupe_functions pass. If two code paths emitted the same LLVM symbol, it quietly dropped one definition. That works until the two definitions are actually different functions or different ABI variants.
Now emission claims each (fid, variant):
| Variant | Meaning |
|---|---|
Generic |
Ordinary closure body |
Typed |
Raw native call for inferred numeric arguments |
TypedSide |
Typed side entry for an escaped numeric function |
FastCompare |
Recognized relational comparator shape |
A repeated AST function from a guarded loop is skipped. Two different bodies or variants claiming one symbol now fail early in the compiler instead of becoming a confusing clang error later.
The emitted IR was byte-identical except for four removed blank lines where textual dedupe used to leave a gap. Those blank lines changed the executable cache digest but not machine code. aststress emit-ir moved from 183.88 ms to 180.69 ms in a 21-run interleaved comparison. Small, but real, and it made the backend easier to trust.
Evaluation order is not optional
This is the part I would refuse to trade away. In Lua, a call evaluates the prefix before the arguments. For api.add(replace(), 7), the field api.add is read before replace() runs. If replace() assigns a new function to api.add, the original call still uses the function that was read first.
The regression test is deliberately blunt:
local function replace()
api.add = function(a, b) return -a, -b end
return 10
end
print("order", api.add(replace(), 7))The log must show the old function receiving 10 and 7. If it showed -10 and -7, the optimization would be faster and wrong.
The same test also covers string coercion, dynamic equal-content keys, __index, __call, multi-return spread, varargs, two returns, and return context. A fast path is only as good as the cases it refuses to touch.
For guarded arithmetic the rule is similar: evaluate both operands once in source order, then set lr_site once for the fallible operation. For field calls, read the callee through the metatable-safe probe before filling the argument array.
Stage 7: a profile that may only remove a shortcut
By Stage 7 I had a lot of guarded choices, and one of them was clearly wasteful in some programs. Baked tables rebuild string keys with str_new, so a compile-time constant key has a different LStr pointer and every inline pointer-identity probe falls back. The fallback is correct, but the probe is dead weight.
So I added an opt-in guard-outcome profiler:
LUACOMP_PROFILE=<path>builds a training binary that counts hit/fall outcomes and dumps a versioned, digested profile at exit.LUACOMP_ADVISOR=1/autoreads that profile and skips the inline probe only at a site with at least 100 samples and more than 95% fallbacks.LUACOMP_ADVISOR=conservativeskips the probe without a profile, for tests and bisecting.- Normal builds emit no counters and keep today’s exact IR.
Profile ids are source lines, which are deterministic for a given source and do not shift when advisor decisions change emission. The digest covers the compiler version, dialect, LÖVE mode, and all source texts. Stale, truncated, unknown-version, missing, or malformed profiles warn and fall back to default emission.
On field_access, the advisor skipped those always-falling probes and the interleaved median moved from 19.7 ms to 18.3 ms over 11 runs per compiler. The canonical lr_index still did content comparison, so output stayed the same. The game benchmark told a quieter story: an early pass showed idle -0.3% and demo +1.6%, then a repeat showed +0.6% and +0.2%. Default IR was unchanged, so that was noise.
Why the ML part stays advisory
It would be easy to let a model decide which guards are “probably fine”. I do not want that compiler.
The Stage 7 thresholds are fixed, not learned weights shipped in the binary. Even there, the advisor only ranks an existing guarded choice. It does not remove a guard, narrow a Value, change a layout, touch baked bytes, alter an ABI, promote TAny, or approve a build.
The deterministic helper remains the correctness authority. If the profile says a probe almost never hits, the compiler skips the optional shortcut and uses the same canonical helper that already handles every Lua case. If the profile is stale, the compiler ignores it.
That boundary also shapes the Stage 8 memory-risk idea I have written down but not implemented:
| The advisor may | The advisor may not |
|---|---|
| rank allocation sites for review | declare a program safe |
| choose which deterministic check to run next | suppress a sanitizer finding |
| fail closed on stale evidence | remove a guard |
| report “needs follow-up” | change emitted IR |
I gave that boundary its own post in What the Advisors Are Actually Doing.
A longer-term model could predict whether a value needs 64 bits or whether a struct could be reordered for less padding. It still would not be the correctness authority. Lua 5.4 integer overflow, Lua 5.1 double-only numbers, bitwise operations, large table indexes, hashes, and pointers must not be narrowed because a classifier feels confident.
Rules I did not trade away
Across all seven stages the rules stayed the same:
- Evaluate operands once, in Lua source order.
- Set
lr_siteexactly once per fallible operation. - Check
meta == NULLbefore any raw table access. - On every miss, call the canonical runtime helper.
- Build and run the full suite before calling a stage done.
- Keep default IR unchanged unless the change earns it.
The wins I trust most are the ones where the fallback is easy to point at. The wins I distrust are the ones that only appear in a game benchmark with rendering in the way. For that side of the story, including why I separate speed from stability, see Stability Over Bragging Rights.
I still have work to do on equal-content string keys, baked-table pointers, and the callback ABI. But I now have a compiler that can improve plain Lua without asking the programmer to write compiler-shaped Lua. That constraint was worth keeping.