Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,10 +281,15 @@ Notes; finished-work narrative does not.
same-shape literal edits can lower/emit only changed owners, including actual Castle Fight and Zombie Defense
functions. See `docs/MAP_COMMIT_REPLAY.md` for controlled measurements and the distinction from whole-commit coverage.
Fresh compile-time execution still forks the whole graph; semantic receipts, full-file assembly, ABI hashing and
payload comparison still scan global state. Next: producer-owned vararg/native helper descriptors and class/generic
payload comparison still scan global state. Vararg/native producers now report argument-preserving call replacements;
frozen target graphs and bindings admit ordinary callers of Math.min/max, R2I, nullable-handle wrappers and
hashtable stubs under the existing shape/dependency receipts and cold equality gates. Next: class/generic
products, versioned dependency queries instead of global receipts, compile-time closure-only materialisation and
incremental payload indexing. Port producer contracts rather than parsing generated names or synthesising empty
function headers. The real Zombie Defense armor-cost edit currently falls back because Math.min/max use varargs.
function headers. The real Zombie Defense armor-cost edit now lowers/emits one runtime function; controlled
timings and remaining whole-program costs are recorded in `docs/MAP_COMMIT_REPLAY.md`.
Exact/shape receipt hashing now shares one schema encoding and UTF-8 tokens; matching-master alternating
probes removed the observed Castle Fight control regression while retaining the min/max improvement.

- **Audit the remaining Lua emission for waste.** The Lua backend began as "make Lua mode usable", and
recent fixes (`git log --grep "Lua"`) keep finding helper calls, allocations and dead bindings that
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1044,7 +1044,9 @@ public LuaCompilationUnit transformProgToLua() {
// static argument count go to fixed-arity copies, so the emitted Lua packs no table and the
// copies can inline; originals stay for dispatch, function references and calls above the bound.
beginPhase(4, "eliminate varargs");
new VarargEliminator(imProg, true).run();
CallLoweringObserver callLowerings = incrementalImTranslation == null ? CallLoweringObserver.NONE
: incrementalImTranslation.symbolBackend().callLoweringObserver();
new VarargEliminator(imProg, true, callLowerings).run();
imTranslator.assertProperties();
timeTaker.endPhase();

Expand All @@ -1054,7 +1056,7 @@ public LuaCompilationUnit transformProgToLua() {
// Lower Lua-specific native calls into IM-level wrappers before optimization,
// so the optimizer can inline and eliminate the nil-safety checks and remapped stubs.
beginPhase(4, "lua native lowering");
LuaNativeLowering.transform(imProg, imTranslator2);
LuaNativeLowering.transform(imProg, imTranslator2, callLowerings);
LuaTypedKeyedReads.transform(imProg, imTranslator2);
timeTaker.endPhase();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package de.peeeq.wurstscript.translation.imtranslation;

import de.peeeq.wurstscript.jassIm.ImFunctionCall;

/** A producer reports a call replacement while both its source and lowered target are available. */
@FunctionalInterface
public interface CallLoweringObserver {
CallLoweringObserver NONE = (source, lowered) -> { };
void replaced(ImFunctionCall source, ImFunctionCall lowered);
}
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,10 @@ private static void removeDestroyCalls(Element e) {
}

public static void transform(ImProg prog, ImTranslator translator) {
transform(prog, translator, CallLoweringObserver.NONE);
}

public static void transform(ImProg prog, ImTranslator translator, CallLoweringObserver observer) {
// Replace all reads of MagicFunctions_isLua with true.
// This must happen before any optimizer passes so that dead-code elimination
// can remove Jass-only branches at compile time.
Expand All @@ -183,7 +187,7 @@ public static void transform(ImProg prog, ImTranslator translator) {
removeRedundantTypeAssurance(prog, translator);
lowerStringConcatenation(prog, translator);
lowerDivMod(prog, translator);
lowerRealToInt(prog, translator);
lowerRealToInt(prog, translator, observer);

// Maps original BJ function → replacement (IS_NATIVE hashtable stub).
// Populated lazily during the traversal.
Expand Down Expand Up @@ -218,11 +222,11 @@ public void visit(ImFunctionCall call) {
if (!deferredAdditions.contains(replacement)) {
deferredAdditions.add(replacement);
}
call.replaceBy(JassIm.ImFunctionCall(
replaceCall(call, JassIm.ImFunctionCall(
call.attrTrace(), replacement,
JassIm.ImTypeArguments(),
call.getArguments().copy(),
false, CallType.NORMAL));
false, CallType.NORMAL), observer);
}
return;
}
Expand All @@ -234,11 +238,11 @@ public void visit(ImFunctionCall call) {
if (!deferredAdditions.contains(replacement)) {
deferredAdditions.add(replacement);
}
call.replaceBy(JassIm.ImFunctionCall(
replaceCall(call, JassIm.ImFunctionCall(
call.attrTrace(), replacement,
JassIm.ImTypeArguments(),
call.getArguments().copy(),
false, CallType.NORMAL));
false, CallType.NORMAL), observer);
}
return;
}
Expand Down Expand Up @@ -276,11 +280,11 @@ public void visit(ImFunctionCall call) {
return;
}

call.replaceBy(JassIm.ImFunctionCall(
replaceCall(call, JassIm.ImFunctionCall(
call.attrTrace(), replacement,
JassIm.ImTypeArguments(),
call.getArguments().copy(),
false, CallType.NORMAL));
false, CallType.NORMAL), observer);
}
});

Expand Down Expand Up @@ -563,6 +567,11 @@ public void visit(ImOperatorCall call) {
prog.getFunctions().addAll(funcs.createdFunctions());
}

private static void replaceCall(ImFunctionCall source, ImFunctionCall lowered, CallLoweringObserver observer) {
observer.replaced(source, lowered);
source.replaceBy(lowered);
}

/**
* Rewrites calls to the native {@code R2I} to {@code __wurst_R2I}, which truncates in Lua arithmetic:
* {@code x // 1 | 0} for a non-negative real, and its negation for a negative one. That is exact
Expand All @@ -574,7 +583,7 @@ public void visit(ImOperatorCall call) {
* included. The helper returns one intrinsic call, so it inlines anywhere, and the intrinsic is
* printed as a single Lua expression ({@code ExprTranslation#realToInt}) with no call in range.
*/
private static void lowerRealToInt(ImProg prog, ImTranslator translator) {
private static void lowerRealToInt(ImProg prog, ImTranslator translator, CallLoweringObserver observer) {
ImFunction[] shim = {null};
List<ImFunction> added = new ArrayList<>();
prog.accept(new Element.DefaultVisitor() {
Expand All @@ -588,8 +597,8 @@ public void visit(ImFunctionCall call) {
if (shim[0] == null) {
shim[0] = buildRealToInt(translator, added);
}
call.replaceBy(JassIm.ImFunctionCall(call.attrTrace(), shim[0], JassIm.ImTypeArguments(),
JassIm.ImExprs(call.getArguments().removeAll()), false, CallType.NORMAL));
replaceCall(call, JassIm.ImFunctionCall(call.attrTrace(), shim[0], JassIm.ImTypeArguments(),
JassIm.ImExprs(call.getArguments().removeAll()), false, CallType.NORMAL), observer);
}
});
if (shim[0] != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public class VarargEliminator {
* calls are redirected, and unreferenced originals are left to garbage removal.
*/
private final boolean luaTarget;
private final CallLoweringObserver observer;
// original + number of args --> new function
private final Table<ImFunction, Integer, ImFunction> varargFuncs = HashBasedTable.create();

Expand All @@ -45,8 +46,13 @@ public VarargEliminator(ImProg prog) {
}

public VarargEliminator(ImProg prog, boolean luaTarget) {
this(prog, luaTarget, CallLoweringObserver.NONE);
}

public VarargEliminator(ImProg prog, boolean luaTarget, CallLoweringObserver observer) {
this.prog = prog;
this.luaTarget = luaTarget;
this.observer = observer;
}

public void run() {
Expand Down Expand Up @@ -357,6 +363,7 @@ private void redirectCall(ImFunctionCall call, ImFunction newFunc) {
ImFunctionCall newCall = JassIm.ImFunctionCall(call.getTrace(), newFunc,
JassIm.ImTypeArguments(call.getTypeArguments().removeAll()),
JassIm.ImExprs(call.getArguments().removeAll()), call.getTuplesEliminated(), call.getCallType());
observer.replaced(call, newCall);
call.replaceBy(newCall);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package de.peeeq.wurstscript.translation.lua.translation;

import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.translation.imtranslation.ReferenceRewritingCopy;
import de.peeeq.wurstscript.translation.imtranslation.CallType;
import de.peeeq.wurstscript.translation.imtranslation.ImMetadataAdapter;
import de.peeeq.wurstscript.translation.imtranslation.ImTranslator;

import java.util.*;

/** Frozen producer-selected targets. Only argument-preserving call replacements are replayed. */
record CallLoweringProducts(NodeGraphs.Snapshot graph, List<String> names, Map<Integer, Target> calls, int owner,
List<Type> types, List<Source> sources, Set<Integer> hashtables) {
record Target(int helper, boolean tuplesEliminated, CallType callType) { }
record Replacement(ImFunction function, boolean tuplesEliminated, CallType callType) { }
/** A generated helper's source is relative to its producer's source function, or explicitly synthetic. */
record Source(int function, List<Integer> path) {
static Source freeze(de.peeeq.wurstscript.ast.Element source, ImBackendInput input) {
if (source instanceof de.peeeq.wurstscript.ast.NoExpr && source.getParent() == null) return new Source(-1, List.of());
List<Integer> path = new ArrayList<>();
for (var node = source; node != null; node = node.getParent()) {
Integer function = input.sourceFunctions().get(node);
if (function != null) return new Source(function, List.copyOf(path));
var parent = node.getParent();
if (parent != null) {
for (int i = 0; i < parent.size(); i++) if (parent.get(i) == node) { path.add(i); break; }
}
}
throw new ImBackendInput.Unsupported("helper source outside input functions");
}
de.peeeq.wurstscript.ast.Element materialize(ImBackendInput input) {
if (function < 0) return de.peeeq.wurstscript.ast.Ast.NoExpr();
var source = input.functions.get(function).getTrace();
for (int i = path.size() - 1; i >= 0; i--) source = source.get(path.get(i));
return source;
}
}
/** Types introduced by lowering are structural values, independent of this request's input registry. */
record Type(String kind, String name, Type entry) {
static Type freeze(ImType type) {
if (type instanceof ImSimpleType simple) return new Type("simple", simple.getTypename(), null);
if (type instanceof ImVoid) return new Type("void", "", null);
if (type instanceof ImArrayType array) return new Type("array", "", freeze(array.getEntryType()));
throw new ImBackendInput.Unsupported("helper type " + type.getClass().getSimpleName());
}
ImType materialize() {
return switch (kind) {
case "simple" -> JassIm.ImSimpleType(name);
case "void" -> JassIm.ImVoid();
case "array" -> JassIm.ImArrayType(entry.materialize());
default -> throw new IllegalStateException("Unknown helper type " + kind);
};
}
}
private static NodeGraphs.Adapter adapter(ImBackendInput input, List<Type> types, List<Source> sources) {
return new ImMetadataAdapter() {
@Override public NodeGraphs.Symbol symbol(String field, Object value) {
if (value instanceof ImType type) {
Type frozen = Type.freeze(type);
int index = types.indexOf(frozen);
if (index < 0) { index = types.size(); types.add(frozen); }
return new NodeGraphs.Symbol("helper-type", Integer.toString(index));
}
if (value instanceof de.peeeq.wurstscript.ast.Element source) {
Source frozen = Source.freeze(source, input);
int index = sources.indexOf(frozen);
if (index < 0) { index = sources.size(); sources.add(frozen); }
return new NodeGraphs.Symbol("helper-source", Integer.toString(index));
}
return input.symbol(field, value);
}
@Override public Object resolve(NodeGraphs.Symbol symbol) {
return switch (symbol.namespace()) {
case "helper-type" -> types.get(Integer.parseInt(symbol.key())).materialize();
case "helper-source" -> sources.get(Integer.parseInt(symbol.key())).materialize(input);
default -> input.resolve(symbol);
};
}
};
}

static CallLoweringProducts capture(ImBackendInput input, int owner, Map<Integer, Replacement> replacements,
LuaTranslator translated) {
List<ImFunction> helpers = new ArrayList<>();
Map<ImFunction, Integer> indexes = new IdentityHashMap<>();
Map<Integer, Target> calls = new LinkedHashMap<>();
List<Integer> sourceCalls = input.calls.getOrDefault(owner, List.of());
for (int i = 0; i < sourceCalls.size(); i++) {
Replacement replacement = replacements.get(sourceCalls.get(i));
if (replacement == null) continue;
int index = add(replacement.function, helpers, indexes);
calls.put(i, new Target(index, replacement.tuplesEliminated, replacement.callType));
}
// Include generated dependencies as owned graphs, including recursive helper groups.
for (int i = 0; i < helpers.size(); i++) {
NodeGraphs.references(helpers.get(i), node -> {
if (node instanceof ImFunction function && !input.ids.containsKey(function)) add(function, helpers, indexes);
}, input);
}
List<String> names = helpers.stream().map(translated::functionBinding).toList();
Set<Integer> hashtables = new LinkedHashSet<>();
for (int i = 0; i < helpers.size(); i++) if (translated.hashtableStub(helpers.get(i))) hashtables.add(i);
ImFunctions copies = JassIm.ImFunctions();
Map<ImFunction, ImFunction> copied = new IdentityHashMap<>();
for (int i = 0; i < helpers.size(); i++) {
ImFunction original = helpers.get(i), copy = ReferenceRewritingCopy.copy(original);
input.product(original, owner + ":" + i, names.get(i));
copies.add(copy); copied.put(original, copy);
}
copies.accept(new Element.DefaultVisitor() {
@Override public void visit(ImFunctionCall call) {
super.visit(call);
ImFunction target = copied.get(call.getFunc());
if (target != null) call.setFunc(target);
}
@Override public void visit(ImFuncRef ref) {
ImFunction target = copied.get(ref.getFunc());
if (target != null) ref.setFunc(target);
}
});
List<Type> types = new ArrayList<>();
List<Source> sources = new ArrayList<>();
NodeGraphs.Snapshot graph = NodeGraphs.freeze(copies, adapter(input, types, sources));
return new CallLoweringProducts(graph, List.copyOf(names), Map.copyOf(calls), owner, List.copyOf(types), List.copyOf(sources), Set.copyOf(hashtables));
}

private static int add(ImFunction function, List<ImFunction> helpers, Map<ImFunction, Integer> indexes) {
Integer old = indexes.get(function);
if (old != null) return old;
int index = helpers.size(); indexes.put(function, index); helpers.add(function); return index;
}

void lower(ImFunction function, ImBackendInput input, ImTranslator context) {
if (calls.isEmpty()) return;
ImFunctions helpers = (ImFunctions) graph.materialize(adapter(input, types, sources));
for (int i = 0; i < helpers.size(); i++) input.product(helpers.get(i), owner + ":" + i, names.get(i));
for (int index : hashtables) {
ImFunction stub = helpers.get(index);
context.luaHashtableStubs.put(stub.getName(), stub);
}
List<ImFunctionCall> source = new ArrayList<>();
function.accept(new Element.DefaultVisitor() {
@Override public void visit(ImFunctionCall call) { source.add(call); super.visit(call); }
});
calls.forEach((ordinal, target) -> {
ImFunctionCall call = source.get(ordinal);
call.setFunc(helpers.get(target.helper));
call.setTuplesEliminated(target.tuplesEliminated);
call.setCallType(target.callType);
});
}
}
Loading
Loading