Skip to content

Commit

Permalink
Additional label optimization (#2218)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ruzihm authored Feb 20, 2025
1 parent 9b76a54 commit 6ffc519
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 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,22 @@ 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) {
for (int i = input.Count - 2; i >= 0; i--) {
if (input[i] is AnnotatedBytecodeInstruction { Opcode: Bytecode.DreamProcOpcode.Jump } instruction) {
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 6ffc519

Please sign in to comment.