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
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,12 @@ public class CompiletimeFunctionRunner implements AutoCloseable {
private final ImTranslator translator;
private boolean injectObjects;
private final Deque<Runnable> delayedActions = new ArrayDeque<>();
private final Map<ClassManagementVars, List<CompiletimeObjectInit>> compiletimeObjects = new LinkedHashMap<>();
/**
* The objects to allocate in the compile-time state, by allocator: the {@link ClassManagementVars} of their
* inheritance group on Jass, and {@link #SHARED_LUA_ALLOCATOR} for all of them on Lua.
*/
private final Map<Object, List<CompiletimeObjectInit>> compiletimeObjects = new LinkedHashMap<>();
private static final Object SHARED_LUA_ALLOCATOR = new Object();
private final Map<String, Long> compiletimeFunctionNanos = new LinkedHashMap<>();
private long compiletimeExprNanos = 0L;

Expand Down Expand Up @@ -91,6 +96,9 @@ public CompiletimeFunctionRunner(
// The interpreter is handed a program; this hands over the one thing it cannot work out from
// the program alone, which is what a specialised node was copied from.
globalState.setSpecialisations(tr);
if (tr.isLuaTarget()) {
globalState.useOneObjectIdSpace();
}
initializeBackendConstants();
this.interpreter = new ILInterpreter(imProg, gui, mapFile, globalState);

Expand Down Expand Up @@ -532,8 +540,10 @@ private ImExpr constantToExpr(Element trace, ILconst value, @Nullable ImType exp
}

private void registerCompiletimeObject(ILconstObject obj, ImVar targetVar) {
ClassManagementVars mVars = translator.getClassManagementVarsFor(obj.getType().getClassDef());
compiletimeObjects.computeIfAbsent(mVars, k -> new ArrayList<>())
Object allocator = translator.isLuaTarget()
? SHARED_LUA_ALLOCATOR
: translator.getClassManagementVarsFor(obj.getType().getClassDef());
compiletimeObjects.computeIfAbsent(allocator, k -> new ArrayList<>())
.add(new CompiletimeObjectInit(obj, targetVar));
}

Expand All @@ -544,29 +554,31 @@ private void emitCompiletimeObjectAllocs() {

List<ImStmt> objectInits = new ArrayList<>();

for (Map.Entry<ClassManagementVars, List<CompiletimeObjectInit>> entry : compiletimeObjects.entrySet()) {
for (Map.Entry<Object, List<CompiletimeObjectInit>> entry : compiletimeObjects.entrySet()) {
List<CompiletimeObjectInit> objs = entry.getValue();
if (objs.isEmpty()) {
continue;
}

objs.sort(Comparator.comparingInt(o -> o.object.getObjectId()));

ClassManagementVars mVars = entry.getKey();
// Ensure replayed allocations are driven by maxIndex and not by stale free-list state.
objectInits.add(JassIm.ImSet(objs.get(0).object.getTrace(),
JassIm.ImVarAccess(mVars.freeCount), JassIm.ImIntVal(0)));
// Lua has one allocator for every class; its intrinsic empties the free list along with each
// new maximum, so it is called before the first object even when that one needs no gap.
@Nullable ClassManagementVars mVars = entry.getKey() instanceof ClassManagementVars v ? v : null;
if (mVars != null) {
// Ensure replayed allocations are driven by maxIndex and not by stale free-list state.
objectInits.add(JassIm.ImSet(objs.get(0).object.getTrace(),
JassIm.ImVarAccess(mVars.freeCount), JassIm.ImIntVal(0)));
}

int currentMax = 0;
int finalMax = globalState.getMaxAllocatedId(objs.get(0).object.getImClass());

for (CompiletimeObjectInit init : objs) {
int desiredId = init.object.getObjectId();
int targetMax = desiredId - 1;
if (targetMax > currentMax) {
objectInits.add(JassIm.ImSet(init.object.getTrace(),
JassIm.ImVarAccess(mVars.maxIndex),
JassIm.ImIntVal(targetMax)));
if (targetMax > currentMax || (mVars == null && init == objs.get(0))) {
objectInits.add(setMaxObjectId(init.object.getTrace(), mVars, targetMax));
currentMax = targetMax;
}

Expand All @@ -578,14 +590,22 @@ private void emitCompiletimeObjectAllocs() {
}

if (finalMax > currentMax) {
objectInits.add(JassIm.ImSet(objs.get(0).object.getTrace(),
JassIm.ImVarAccess(mVars.maxIndex), JassIm.ImIntVal(finalMax)));
objectInits.add(setMaxObjectId(objs.get(0).object.getTrace(), mVars, finalMax));
}
}

getCompiletimeStateInitFunction().getBody().addAll(0, objectInits);
}

/** The next allocation is maxId + 1: Jass sets the group's maxIndex, Lua resumes its one allocator. */
private ImStmt setMaxObjectId(Element trace, @Nullable ClassManagementVars mVars, int maxId) {
if (mVars != null) {
return JassIm.ImSet(trace, JassIm.ImVarAccess(mVars.maxIndex), JassIm.ImIntVal(maxId));
}
return JassIm.ImFunctionCall(trace, translator.luaResumeObjectIdsFunc(), JassIm.ImTypeArguments(),
JassIm.ImExprs(JassIm.ImIntVal(maxId)), false, CallType.NORMAL);
}

private static class CompiletimeObjectInit {
private final ILconstObject object;
private final ImVar targetVar;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ public class ProgramState extends State implements AutoCloseable {
private final Set<String> missingNativeFuncs = new HashSet<>();
private ImProg prog;
private final Map<ImClass, Object> classKeyLookup = new HashMap<>();
/** The key of the one id space all classes share; see {@link #useOneObjectIdSpace}. */
private static final Object SHARED_ID_SPACE = new Object();
private boolean oneObjectIdSpace;
/** See {@link #isGenericHierarchy}; only looked up, never iterated. */
private final Map<ImClass, Boolean> genericHierarchy = new IdentityHashMap<>();
/** See {@link #dispatch}; only looked up, never iterated. */
Expand Down Expand Up @@ -222,9 +225,25 @@ public ILconstObject allocate(ImClassType clazz, Element trace) {
}

protected Object classKey(ImClass clazz) {
if (oneObjectIdSpace) {
return SHARED_ID_SPACE;
}
return classKeyLookup.getOrDefault(clazz, clazz);
}

/**
* Hands out the ids of all classes from one counter and one free list, as the Lua target does
* (docs/WC3_RUNTIME.md), instead of one per inheritance group as Jass does. A compile-time object
* keeps its id in the generated script, so the ids must come from the allocator of the target.
* Called before anything is allocated.
*/
public void useOneObjectIdSpace() {
if (!objectIdSpaces.isEmpty()) {
throw new IllegalStateException("The id spaces are chosen before the first allocation.");
}
oneObjectIdSpace = true;
}

public void deallocate(ILconstObject obj, ImClass clazz, Element trace) {
assertAllocated(obj, trace);
obj.destroy();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,30 @@ public boolean isTrapFreeLuaIntrinsicCall(ImFunctionCall call) {
public boolean isLuaTableRead(ImFunction f) {
return LuaKeyedMap.readStubName(this, f) != null || LuaHashtable.isRead(this, f);
}

/**
* {@code __wurst_resumeObjectIds(n)}: the Lua allocator hands out n + 1 next and recycles nothing, as the
* compile-time state sets a class's maxIndex and freeCount on Jass. The Lua backend prints a call to this exact
* node as the two assignments (StmtTranslation).
*/
@Nullable public ImFunction luaResumeObjectIdsFunc = null;

/**
* {@link #luaResumeObjectIdsFunc}, created on first use: the compile-time state calls it so that each object
* made at compile time keeps its id.
*/
public ImFunction luaResumeObjectIdsFunc() {
ImFunction f = luaResumeObjectIdsFunc;
if (f == null) {
ImVar maxId = JassIm.ImVar(imProg.getTrace(), TypesHelper.imInt(), "maxId", false);
f = JassIm.ImFunction(imProg.getTrace(), "__wurst_resumeObjectIds", JassIm.ImTypeVars(), JassIm.ImVars(maxId),
JassIm.ImVoid(), JassIm.ImVars(), JassIm.ImStmts(), Collections.singletonList(FunctionFlagEnum.IS_NATIVE));
imProg.getFunctions().add(f);
luaResumeObjectIdsFunc = f;
}
return f;
}

@Nullable public ImFunction luaIntDivFunc = null;
@Nullable public ImFunction luaModIntFunc = null;
@Nullable public ImFunction luaModRealFunc = null;
Expand All @@ -275,7 +299,7 @@ public List<ImFunction> pinnedFunctions() {
luaRawFloorDivIntFunc, luaRawFmodIntFunc, luaRawFloorModIntFunc,
luaRawConcatFunc,
luaRawOrEmptyFunc, luaRawR2IFunc, luaRawToNumberIntFunc, luaRawToNumberRealFunc, luaRawToIntegerFunc,
luaRawToStringFunc, luaIntDivFunc, luaModIntFunc, luaModRealFunc,
luaRawToStringFunc, luaResumeObjectIdsFunc, luaIntDivFunc, luaModIntFunc, luaModRealFunc,
debugPrintFunction, errorFunc, genericNewMarker, globalInitFunc}) {
if (f != null) {
result.add(f);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,11 @@ public static LuaExpr translate(ImFunctionCall e, LuaTranslator tr) {
throw new CompileError(e.attrTrace().attrSource(),
"Lua backend: " + imFuncName + " used as an expression; a keyed-map store must be a statement.");
}
if (e.getFunc() == tr.imTr.luaResumeObjectIdsFunc) {
// Two assignments, so a statement; see StmtTranslation#translateResumeObjectIds.
throw new CompileError(e.attrTrace().attrSource(),
"Lua backend: " + imFuncName + " used as an expression; it must be a statement.");
}
LuaHashtable.Op hashtableOp = LuaHashtable.op(tr.imTr, e.getFunc());
if (hashtableOp != null) {
return LuaHashtableTranslation.expression(e, hashtableOp, tr);
Expand Down Expand Up @@ -223,6 +228,7 @@ static boolean isBackendIntrinsic(ImFunction function, LuaTranslator tr) {
|| function == tr.imTr.luaRawFloorModIntFunc
|| function == tr.imTr.luaRawConcatFunc
|| function == tr.imTr.luaRawOrEmptyFunc
|| function == tr.imTr.luaResumeObjectIdsFunc
|| LuaKeyedMap.readStubName(tr.imTr, function) != null
|| LuaKeyedMap.writeStubName(tr.imTr, function) != null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ public static void translate(ImExpr e, List<LuaStatement> res, LuaTranslator tr)
emitLuaInitXpcall(call.getFunc(), res, tr);
return;
}
if (call.getFunc() == tr.imTr.luaResumeObjectIdsFunc) {
translateResumeObjectIds(call, res, tr);
return;
}
String keyedWrite = LuaKeyedMap.writeStubName(tr.imTr, call.getFunc());
if (keyedWrite != null) {
translateKeyedMapWrite(call, keyedWrite, res, tr);
Expand All @@ -40,6 +44,16 @@ public static void translate(ImExpr e, List<LuaStatement> res, LuaTranslator tr)
res.add(expr);
}

/**
* {@code __wurst_resumeObjectIds(n)} as {@code __wurst_objectFreeCount = 0; __wurst_objectMax = n}: the next
* allocation of any class is n + 1, as the compile-time state needs to give each of its objects its id.
*/
private static void translateResumeObjectIds(ImFunctionCall call, List<LuaStatement> res, LuaTranslator tr) {
res.add(LuaAst.LuaAssignment(LuaAst.LuaExprVarAccess(tr.objectFreeCount), LuaAst.LuaExprIntVal("0")));
res.add(LuaAst.LuaAssignment(LuaAst.LuaExprVarAccess(tr.objectMax),
call.getArguments().get(0).translateToLua(tr)));
}

/**
* How an operand of a store printed in place of its stub may be moved: see {@link #translateKeyedMapWrite}
* and {@link LuaHashtableTranslation}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -657,9 +657,40 @@ public void testPersistCompiletimeClassTuple() {
" testSuccess()");
}

@Test
public void testCompiletimeObjectKeepsIdAfterDroppedObject() throws IOException {
// The object which is not kept still took an id, so the kept one has id 2 on both targets.
test().testLua(true).luaOnly(false).executeProg(true)
.runCompiletimeFunctions(true)
.executeProgOnlyAfterTransforms()
.lines("package Test",
"native testSuccess()",
"class A",
" int storedId",
"function compiletime<T:>(T t) returns T",
" return t",
"@compiletime function build() returns A",
" new A",
" let keep = new A",
" keep.storedId = keep castTo int",
" return keep",
"let kept = compiletime(build())",
"init",
" if kept castTo int == kept.storedId",
" testSuccess()");
// Lua's one allocator continues after the dropped object's id before the kept one is made, and the
// id the kept object stored at compile time is the one it gets.
String lua = compiledLua("testCompiletimeObjectKeepsIdAfterDroppedObject");
java.util.regex.Matcher replay = java.util.regex.Pattern.compile(
"__wurst_objectFreeCount = 0\\s+__wurst_objectMax = (\\d+)\\s+(\\w+) = A:create\\(\\)\\s+"
+ "A_storedId_storage\\[\\2\\] = (\\d+)").matcher(lua);
assertTrue(replay.find(), lua);
assertEquals(Integer.parseInt(replay.group(3)), Integer.parseInt(replay.group(1)) + 1, lua);
}

@Test
public void testCompiletimeObjectIdMigration() {
test().executeProg(true)
test().testLua(true).luaOnly(false).executeProg(true)
.runCompiletimeFunctions(true)
.executeProgOnlyAfterTransforms()
.lines("package Test",
Expand Down Expand Up @@ -732,6 +763,66 @@ public void testCompiletimeObjectIdMigrationStress() {
" testSuccess()");
}

/**
* Lua has one id space for all classes where Jass has one per inheritance group, so the compile-time
* objects of unrelated classes have distinct ids there and an object made at run time follows the
* highest id of any class.
*/
@Test
public void testCompiletimeObjectIdMigrationSharesOneIdSpaceOnLua() {
test().testLua(true).executeProg(true)
.runCompiletimeFunctions(true)
.executeProgOnlyAfterTransforms()
.lines("package Test",
"native testSuccess()",
"class A",
" int idSnapshot",
"class B",
" int idSnapshot",
"tuple BuildResult(A keepA, B keepB, A lastA, int maxId)",
"function compiletime<T:>(T t) returns T",
" return t",
"@compiletime function build() returns BuildResult",
" A keepA = null",
" B keepB = null",
" A lastA = null",
" int maxId = 0",
" for i = 1 to 200",
" let a = new A",
" a.idSnapshot = a castTo int",
" maxId = max(maxId, a castTo int)",
" if i % 25 == 0",
" keepA = a",
" else",
" destroy a",
" let b = new B",
" b.idSnapshot = b castTo int",
" maxId = max(maxId, b castTo int)",
" if i % 30 == 0",
" keepB = b",
" else",
" destroy b",
" lastA = new A",
" lastA.idSnapshot = lastA castTo int",
" maxId = max(maxId, lastA castTo int)",
" return BuildResult(keepA, keepB, lastA, maxId)",
"function max(int a, int b) returns int",
" if a > b",
" return a",
" return b",
"let result = compiletime(build())",
"init",
" let newA = new A",
" let newB = new B",
" if result.keepA.idSnapshot == result.keepA castTo int",
" and result.keepB.idSnapshot == result.keepB castTo int",
" and result.lastA.idSnapshot == result.lastA castTo int",
" and result.keepA castTo int != result.keepB castTo int",
" and newA castTo int == result.maxId + 1",
" and newB castTo int == result.maxId + 2",
" testSuccess()");
}

@Test
public void testInterpreterIdRecyclingWithHashMap() {
test().withStdLib()
Expand Down
Loading