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 @@ -608,6 +608,16 @@ private void optimizeIf(ImIf imIf) {
}
}

/**
* The most operators {@link #optimizeConsecutiveSet} nests in the left operand of one assignment. Each merge
* makes the expression one level deeper, and one walk merges a whole run of statements, so a generated run of
* {@code sum += gN} became one expression as deep as the run is long. The recursive walkers after it overflowed
* the Java stack from about a thousand statements, the flatten first; and where the operators alternate, each
* level is a parenthesis in the Lua output, and luac rejects more than 200 levels. A merge saves one assignment,
* so a long run still loses all but one assignment in this many.
*/
public static final int MAX_MERGED_OPERATORS = 64;

/**
* Optimizes
* <p>
Expand All @@ -618,7 +628,8 @@ private void optimizeIf(ImIf imIf) {
* <p>
* set x = expr1 ⊕ expr2
* <p>
* like code that is created by the branch merger
* like code that is created by the branch merger, while expr1 is nested fewer than {@link #MAX_MERGED_OPERATORS}
* levels deep.
*/
private void optimizeConsecutiveSet(ImSet imSet1, ImSet imSet2) {
ImVar leftVar1;
Expand All @@ -642,7 +653,7 @@ private void optimizeConsecutiveSet(ImSet imSet1, ImSet imSet2) {
if (rightOpCall2.getArguments().size() == 2) {
if (rightOpCall2.getArguments().get(0) instanceof ImVarAccess) {
ImVarAccess imVarAccess2 = (ImVarAccess) rightOpCall2.getArguments().get(0);
if (imVarAccess2.getVar() == leftVar2) {
if (imVarAccess2.getVar() == leftVar2 && !hasMergeLimitOfOperators(rightExpr1)) {
if (sideEffectAnalysis.cannotUseVar(rightOpCall2.getArguments().get(1), leftVar1)) {
rightExpr1.setParent(null);
imVarAccess2.replaceBy(rightExpr1);
Expand All @@ -656,4 +667,28 @@ private void optimizeConsecutiveSet(ImSet imSet1, ImSet imSet2) {
}
}

/**
* Whether {@code e} is nested {@link #MAX_MERGED_OPERATORS} levels deep or more, on any of its operands: each merge
* puts it one level deeper. The walk stops at the limit, so it costs at most the part of {@code e} above it.
*/
private static boolean hasMergeLimitOfOperators(ImExpr e) {
return reachesDepth(e, MAX_MERGED_OPERATORS);
}

/** Whether {@code e} holds expressions nested {@code levels} deep; a list of arguments is no level of its own. */
private static boolean reachesDepth(Element e, int levels) {
if (e instanceof ImExpr) {
if (levels <= 1) {
return true;
}
levels--;
}
for (int i = 0; i < e.size(); i++) {
if (reachesDepth(e.get(i), levels)) {
return true;
}
}
return false;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,114 @@ public void test_varRemoval() {
"endpackage");
}

@Test
public void longRunOfAccumulatingStatementsCompiles() {
// A long generated init function, `sum += g0` ... `sum += g3299`. Merging the run into one assignment made an
// expression 3300 levels deep, and the flatten after the merge overflowed the stack.
int count = 3300;
List<String> lines = new ArrayList<>();
lines.add("package test");
lines.add("native testSuccess()");
for (int i = 0; i < count; i++) {
lines.add("int g" + i + " = " + i);
}
lines.add("init");
lines.add(" var sum = 0");
for (int i = 0; i < count; i++) {
lines.add(" sum += g" + i);
}
lines.add(" if sum > 0");
lines.add(" testSuccess()");
test().executeProg().lines(lines.toArray(new String[0]));
}

@Test
public void runMergedOntoADeepRightOperandLoadsInLua() {
// The first value is 90 levels deep on its right operands, which the bound did not count: merging 64 pairs
// of `h *= a` and `h += b` onto it made more nested levels than luac takes (200).
String deep = "b";
for (int i = 0; i < 90; i++) {
deep = "(a + " + deep + ")";
}
List<String> lines = new ArrayList<>();
lines.add("package test");
lines.add("native testSuccess()");
lines.add("function mix(int a, int b) returns int");
lines.add(" var h = " + deep);
for (int i = 0; i < 64; i++) {
lines.add(" h *= a");
lines.add(" h += b");
}
lines.add(" return h");
lines.add("init");
lines.add(" if mix(1, 1) == 155");
lines.add(" testSuccess()");
test().testLua(true).localOptimizations().executeProg().lines(lines.toArray(new String[0]));
}

@Test
public void longRunOfAlternatingOperatorsLoadsInLua() {
// Merged into one assignment, 150 pairs of `h *= a` and `h += b` were 300 nested parentheses in Lua, and
// luac stops at 200 levels.
List<String> lines = new ArrayList<>();
lines.add("package test");
lines.add("native testSuccess()");
lines.add("function mix(int a, int b) returns int");
lines.add(" var h = a");
for (int i = 0; i < 150; i++) {
lines.add(" h *= a");
lines.add(" h += b");
}
lines.add(" return h");
lines.add("init");
lines.add(" if mix(1, 1) == 151");
lines.add(" testSuccess()");
test().testLua(true).localOptimizations().executeProg().lines(lines.toArray(new String[0]));
}

@Test
public void mergingConsecutiveAssignmentsNestsBoundedly() {
// `x = 0` and then `x = x + gI` a thousand times: the assignments still merge, but no merged expression has
// more than MAX_MERGED_OPERATORS operators down its left operands.
int count = 1000;
WurstModel model = Ast.WurstModel();
ImTranslator translator = new ImTranslator(model, true, new RunArgs());
ImProg prog = translator.getImProg();
ImVar x = JassIm.ImVar(model, TypesHelper.imInt(), "x", false);
ImStmts body = JassIm.ImStmts(JassIm.ImSet(model, JassIm.ImVarAccess(x), JassIm.ImIntVal(0)));
for (int i = 0; i < count; i++) {
ImVar g = JassIm.ImVar(model, TypesHelper.imInt(), "g" + i, false);
prog.getGlobals().add(g);
body.add(JassIm.ImSet(model, JassIm.ImVarAccess(x), JassIm.ImOperatorCall(
de.peeeq.wurstscript.WurstOperator.PLUS, JassIm.ImExprs(JassIm.ImVarAccess(x), JassIm.ImVarAccess(g)))));
}
ImVar p = JassIm.ImVar(model, TypesHelper.imInt(), "p", false);
ImFunction sink = JassIm.ImFunction(model, "sink", JassIm.ImTypeVars(), JassIm.ImVars(p), JassIm.ImVoid(),
JassIm.ImVars(), JassIm.ImStmts(), List.of(FunctionFlagEnum.IS_NATIVE));
prog.getFunctions().add(sink);
body.add(JassIm.ImFunctionCall(model, sink, JassIm.ImTypeArguments(), JassIm.ImExprs(JassIm.ImVarAccess(x)),
false, CallType.NORMAL));
ImFunction main = JassIm.ImFunction(model, "main", JassIm.ImTypeVars(), JassIm.ImVars(), JassIm.ImVoid(),
JassIm.ImVars(x), body, Collections.emptyList());
prog.getFunctions().add(main);

new de.peeeq.wurstscript.intermediatelang.optimizer.SimpleRewrites().optimize(translator);

int max = de.peeeq.wurstscript.intermediatelang.optimizer.SimpleRewrites.MAX_MERGED_OPERATORS;
int sets = 0;
for (ImStmt s : main.getBody()) {
if (s instanceof ImSet set) {
sets++;
int operators = 0;
for (ImExpr e = set.getRight(); e instanceof ImOperatorCall op; e = op.getArguments().get(0)) {
operators++;
}
assertTrue(operators <= max, "a merged assignment has " + operators + " operators");
}
}
assertTrue(sets <= count / max + 2, "the assignments did not merge: " + sets + " are left");
}


private String makeCode(String... body) {
return Utils.join(body, "\n");
Expand Down
Loading