From 6ffc5197e365cbe4d35d14704edb5f9f2fe4bd30 Mon Sep 17 00:00:00 2001 From: Richard Van Tassel Date: Thu, 20 Feb 2025 14:16:12 -0500 Subject: [PATCH] Additional label optimization (#2218) --- DMCompiler/Optimizer/BytecodeOptimizer.cs | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/DMCompiler/Optimizer/BytecodeOptimizer.cs b/DMCompiler/Optimizer/BytecodeOptimizer.cs index dc1ffb7c7f..cfed5be887 100644 --- a/DMCompiler/Optimizer/BytecodeOptimizer.cs +++ b/DMCompiler/Optimizer/BytecodeOptimizer.cs @@ -12,8 +12,17 @@ internal void Optimize(List 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 input) { @@ -40,6 +49,22 @@ private void RemoveUnreferencedLabels(List input) { } } + /** + * Removes jumps for which the next element is the jump's destination + */ + private void RemoveImmediateJumps(List 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(0); + if (jumpLabelName.LabelName == followingLabel.LabelName) { + input.RemoveAt(i); + } + } + } + } + } + private void JoinAndForwardLabels(List input) { Dictionary labelAliases = new(); for (int i = 0; i < input.Count; i++) {