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
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,8 @@ Rules for backend work:
counts the changes of a function and of everything below it, through every setter and list) is the same exactly
while nothing in the function was modified. A pass which is only needed for the functions which changed, or a
result which is kept for a function (the flatten does this), compares the count it saw. Prefer it to a
`functionChanged(f)` call which a pass has to remember (the facts of the garbage removal still use one, see
`BACKLOG.md`).
`functionChanged(f)` call which a pass has to remember. Facts which follow references outside the function also
validate those dependencies: the garbage removal checks the implementations of virtual call targets.

### Lua performance policy

Expand Down
8 changes: 3 additions & 5 deletions BACKLOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,11 @@ Notes; finished-work narrative does not.
keeps: `modification counts: ImFunction` in `jass_im.parseq`). Left:
(1) more removals which remove nothing: one which the test suite shows to find nothing becomes an `assertNoGarbage`,
as the second removal, the one in `optimize` and the one in front of the empty package initialisers did (the one in
front of the first local optimisation is a candidate); (2) facts which live longer than one removal, valid
while `modificationCount()` of the function is the same (it replaces `ImTranslator.functionChanged`, which a pass
can forget to call), so that the first round of a removal does not walk the functions no pass touched; (3) `LocalPlayerContextAnalyzer`, built again for the whole program after each
pass which is not local-player aware (see "Build the local-player analysis fewer times" above); (4) the flatten after the tuples
front of the first local optimisation is a candidate); (2) `LocalPlayerContextAnalyzer`, built again for the whole program after each
pass which is not local-player aware (see "Build the local-player analysis fewer times" above); (3) the flatten after the tuples
are eliminated is the one which does work (about 565 to 800 functions of castle fight): the producers of
statement expressions (`EliminateTuples`, `SimpleRewrites`, the inliner) could emit statements as the removal does;
(5) a chain of assignments to unread variables (`v1 = v0; v2 = v1; ...`, nothing reads the last) takes a round for
(4) a chain of assignments to unread variables (`v1 = v0; v2 = v1; ...`, nothing reads the last) takes a round for
each link, and a round costs the functions which changed (a walk of each, the rewrite of its statement list, its
locals), so the cost grows with the square of the length. Measured in a unit test (the checks of unit-test mode on,
one removal): a chain inside one function takes 0.24 s for 1,000 links, 1.5 s for 4,000 and 16.7 s for 16,000; with
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ public void assertNoGarbage(String why) {
}

private boolean removeGarbageWithFacts() {
// The rounds change one function at a time and say which, so the analysis keeps what it read of the others.
// Reuse unchanged bodies across rounds and across separate removals.
trans.rememberFunctionFacts();
try {
return removeGarbageInRounds();
Expand Down Expand Up @@ -374,7 +374,6 @@ private boolean garbageRound(boolean incremental, @Nullable List<ImVar> newlyUnr
if (!replacements.isEmpty()) {
changes = true;
replaceByEffects(f, replacements);
trans.functionChanged(f);
replacedIn.add(f);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,6 @@ public void visit(ImReturn ret) {
dropFromReturn(member, ret, read, analyzer);
}
member.setReturnType(newType.copy());
trans.functionChanged(member);
}

for (ImVar local : locals) {
Expand Down Expand Up @@ -233,7 +232,6 @@ public void visit(ImVarAccess access) {
} else {
local.setType(newType.copy());
}
trans.functionChanged(owner);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Set;

/**
Expand All @@ -20,6 +22,7 @@
final class FunctionFactsCollector extends ImFunction.DefaultVisitor {
final Set<ImFunction> usedFunctions = new LinkedHashSet<>();
final Set<ImVar> readVariables = new LinkedHashSet<>();
final Map<ImMethod, List<ImFunction>> methodTargets = new LinkedHashMap<>();
/** The assignments, the ones inside another assignment before it; null when they were not asked for. */
final List<ImSet> sets;

Expand Down Expand Up @@ -48,6 +51,14 @@ public void visit(ImFuncRef e) {
@Override
public void visit(ImMethodCall e) {
super.visit(e);
methodTargets.computeIfAbsent(e.getMethod(), method -> {
List<ImFunction> targets = new ArrayList<>(method.getSubMethods().size() + 1);
targets.add(method.getImplementation());
for (ImMethod sub : method.getSubMethods()) {
targets.add(sub.getImplementation());
}
return targets;
});
for (ImMethod sub : e.getMethod().getSubMethods()) {
usedFunctions.add(sub.getImplementation());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1973,7 +1973,7 @@ private void calculateCallRelationsAndVariables(boolean includeUsedVariables) {
readVariables = new ObjectOpenHashSet<>(varEstimate);
readCounts = null;
readByBjInitialisers = new ObjectOpenHashSet<>();
retiredFacts = functionFacts == null ? null : new IdentityHashMap<>();
retiredFacts = null;

final ImFunction main = getMainFunc();
if (main != null) calculateCallRelations(main, includeUsedVariables);
Expand Down Expand Up @@ -2015,6 +2015,7 @@ private void calculateCallRelationsAndVariables(boolean includeUsedVariables) {
}
}
}
retiredFacts = functionFacts == null ? null : new IdentityHashMap<>();
}

private void calculateCallRelations(ImFunction rootFunction, boolean includeUsedVariables) {
Expand Down Expand Up @@ -2057,27 +2058,55 @@ private void calculateCallRelations(ImFunction rootFunction, boolean includeUsed
}

/**
* What the analysis read out of the body of a function, and its assignments, kept while garbage is removed.
* <p>
* The removal analyses the program once per round, and each of the three questions about a function is a walk
* over its whole body, which is not cached. A round changes a few functions only, and says which
* ({@link #functionChanged}); the rest keep their answers until {@link #forgetFunctionFacts}.
* Body facts survive separate garbage removals while the function's modification count and the implementations
* of its virtual call targets are unchanged. The active map is null outside a removal; the saved map belongs to
* this translator only, and drops unreachable functions when a removal finishes.
*/
private final Map<ImFunction, FunctionFacts> savedFunctionFacts = new IdentityHashMap<>();
private @Nullable Map<ImFunction, FunctionFacts> functionFacts;

private static final class FunctionFacts {
final int modificationCount;
@Nullable Set<ImVar> usedVariables;
@Nullable Set<ImVar> readVariables;
@Nullable Set<ImFunction> usedFunctions;
@Nullable List<ImSet> sets;
Map<ImMethod, List<ImFunction>> methodTargets = Collections.emptyMap();

FunctionFacts(ImFunction function) {
modificationCount = function.modificationCount();
}

boolean isCurrent(ImFunction function) {
if (modificationCount != function.modificationCount()) {
return false;
}
// Methods and their submethod lists are references, outside the caller's counted tree.
for (var entry : methodTargets.entrySet()) {
ImMethod method = entry.getKey();
List<ImFunction> targets = entry.getValue();
if (method.getImplementation() != targets.get(0) || method.getSubMethods().size() + 1 != targets.size()) {
return false;
}
for (int i = 0; i < method.getSubMethods().size(); i++) {
if (method.getSubMethods().get(i).getImplementation() != targets.get(i + 1)) {
return false;
}
}
}
return true;
}
}

/** From now on the analysis keeps what it learns of a function, until it is told that the function changed. */
/** Use the saved facts, checking their dependencies before each reuse. */
public void rememberFunctionFacts() {
functionFacts = new IdentityHashMap<>();
functionFacts = savedFunctionFacts;
}

public void forgetFunctionFacts() {
if (usedFunctions != null) {
savedFunctionFacts.keySet().retainAll(usedFunctions);
}
functionFacts = null;
retiredFacts = null;
readCounts = null;
Expand All @@ -2093,16 +2122,6 @@ public void forgetFunctionFacts() {
/** The variables which the initialisers of the common.j and blizzard.j globals which are read, read. */
private @Nullable Set<ImVar> readByBjInitialisers;

/** The body of the function was changed: the analysis has to look at it again. */
public void functionChanged(ImFunction function) {
if (functionFacts != null) {
FunctionFacts old = functionFacts.remove(function);
if (old != null && retiredFacts != null) {
retiredFacts.putIfAbsent(function, old);
}
}
}

/**
* Brings the read variables of the last call relation analysis in line with functions which changed, without
* analysing the program again. A function which still calls the same functions leaves the reachable functions as
Expand Down Expand Up @@ -2141,10 +2160,14 @@ public void functionChanged(ImFunction function) {
List<ImVar> lostReads = new ArrayList<>();
for (ImFunction function : changed) {
FunctionFacts before = retiredFacts.remove(function);
if (before == null) {
before = functionFacts.get(function);
}
if (before == null || before.usedFunctions == null || before.readVariables == null) {
return null;
}
FunctionFacts now = relationFactsOf(function);
retiredFacts.remove(function);
if (!now.usedFunctions.equals(before.usedFunctions)) {
return null;
}
Expand Down Expand Up @@ -2192,7 +2215,18 @@ private boolean isGlobalOf(ImVar v) {
}

private @Nullable FunctionFacts factsOf(ImFunction function) {
return functionFacts == null ? null : functionFacts.computeIfAbsent(function, f -> new FunctionFacts());
if (functionFacts == null) {
return null;
}
FunctionFacts facts = functionFacts.get(function);
if (facts == null || !facts.isCurrent(function)) {
if (facts != null && retiredFacts != null) {
retiredFacts.putIfAbsent(function, facts);
}
facts = new FunctionFacts(function);
functionFacts.put(function, facts);
}
return facts;
}

private Set<ImVar> usedVariablesOf(ImFunction function) {
Expand All @@ -2214,19 +2248,20 @@ private FunctionFacts relationFactsOf(ImFunction function) {
FunctionFacts facts = factsOf(function);
boolean kept = facts != null;
if (facts == null) {
facts = new FunctionFacts();
facts = new FunctionFacts(function);
}
if (facts.usedFunctions == null || facts.readVariables == null) {
FunctionFactsCollector collector = FunctionFactsCollector.collect(function, kept && facts.sets == null);
if (isUnitTestMode) {
assertSameAsSeparateWalks(function, collector);
}
facts.usedFunctions = collector.usedFunctions;
facts.readVariables = collector.readVariables;
facts.methodTargets = collector.methodTargets;
if (collector.sets != null) {
facts.sets = collector.sets;
}
}
if (isUnitTestMode) {
assertSameAsSeparateWalks(function, facts);
}
return facts;
}

Expand Down Expand Up @@ -2259,14 +2294,14 @@ public void visit(ImSet e) {
* What the single walk answers has to be what the separate walks answer, in the same order: unit tests compare
* every function the analysis meets, with the walks which {@link FunctionFactsCollector} replaces.
*/
private static void assertSameAsSeparateWalks(ImFunction function, FunctionFactsCollector collector) {
private static void assertSameAsSeparateWalks(ImFunction function, FunctionFacts facts) {
List<ImFunction> expectedUsed = new ArrayList<>(function.calcUsedFunctions());
List<ImFunction> actualUsed = new ArrayList<>(collector.usedFunctions);
List<ImFunction> actualUsed = new ArrayList<>(facts.usedFunctions);
assertSameElements("functions used by " + function.getName(), expectedUsed, actualUsed);
assertSameElements("variables read by " + function.getName(),
new ArrayList<>(function.calcReadVariables()), new ArrayList<>(collector.readVariables));
if (collector.sets != null) {
assertSameElements("assignments in " + function.getName(), referenceSetStatementsOf(function), collector.sets);
new ArrayList<>(function.calcReadVariables()), new ArrayList<>(facts.readVariables));
if (facts.sets != null) {
assertSameElements("assignments in " + function.getName(), referenceSetStatementsOf(function), facts.sets);
}
}

Expand Down
Loading
Loading