Skip to content

Commit

Permalink
Re-runs label optimizations again after peephole optimizations to tak…
Browse files Browse the repository at this point in the history
…e advantage of any removed jumps. Adds an optimization which removes jumps that point to an immediately following bytecode label.
  • Loading branch information
Ruzihm committed Feb 17, 2025
1 parent 23cd63a commit 9f9f334
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions DMCompiler/Optimizer/BytecodeOptimizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,17 @@ internal void Optimize(List<IAnnotatedBytecode> input) {
RemoveUnreferencedLabels(input);
JoinAndForwardLabels(input);
RemoveUnreferencedLabels(input);
RemoveImmediateJumps(input);
RemoveUnreferencedLabels(input);

_peepholeOptimizer.RunPeephole(input);

// Run label optimizations again due to possibly removed jumps in peephole optimizers
RemoveUnreferencedLabels(input);
JoinAndForwardLabels(input);
RemoveUnreferencedLabels(input);
RemoveImmediateJumps(input);
RemoveUnreferencedLabels(input);
}

private void RemoveUnreferencedLabels(List<IAnnotatedBytecode> input) {
Expand All @@ -40,6 +49,24 @@ private void RemoveUnreferencedLabels(List<IAnnotatedBytecode> input) {
}
}

/**
* <summary>Removes jumps for which the next element is the jump's destination</summary>
*/
private void RemoveImmediateJumps(List<IAnnotatedBytecode> input) {
Dictionary<string, int> labelReferences = new();
for (int i = input.Count-2; i >= 0; i--) {
IAnnotatedBytecode curCode = input[i];
if (curCode is AnnotatedBytecodeInstruction instruction && instruction.Opcode == Bytecode.DreamProcOpcode.Jump) {
if (input[i+1] is AnnotatedBytecodeLabel followingLabel) {
AnnotatedBytecodeLabel jumpLabelName = instruction.GetArg<AnnotatedBytecodeLabel>(0);
if (jumpLabelName.LabelName == followingLabel.LabelName) {
input.RemoveAt(i);
}
}
}
}
}

private void JoinAndForwardLabels(List<IAnnotatedBytecode> input) {
Dictionary<string, string> labelAliases = new();
for (int i = 0; i < input.Count; i++) {
Expand Down

0 comments on commit 9f9f334

Please sign in to comment.