Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code optimization misses forward modification in loops #232

Open
hsaturn opened this issue Mar 28, 2024 · 0 comments
Open

Code optimization misses forward modification in loops #232

hsaturn opened this issue Mar 28, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@hsaturn
Copy link

hsaturn commented Mar 28, 2024

Hello

(EDIT -> See smaller test case at the bottom)

This bug exists both in released and unreleased version:

byte is set to mem[idx + offset] at line 4 of the script
in the while loop, the optimizer thinks that idx+offset is unchanged.
But in the idx is changed inside the while loop, after the mem[idx] = mem[idx + offset]

(don't try to figure out the goal of this script, this is a reduced version of my big script)

var idx = 0;
var offset = 100;
const mem: Memory = new Memory(getBuilding("cell1"));
var byte = mem[idx + offset];
while (byte % 100) {
    var count = byte % 100;
    while (count--) {
        mem[idx] = mem[idx + offset];
        idx++;
    }
    byte = mem[idx + offset];
    idx++;
}

Generated code is

set idx:1:4 0
set offset:2:4 100
op add &t0 idx:1:4 offset:2:4    <--- HERE &t0  = idx + offset
read byte:4:4 cell1 &t0


// WHILE LOOP
  op mod &t1 byte:4:4 100
  jump 18 equal &t1 0
  set count:6:8 &t1
  set &t2 count:6:8
  op sub count:6:8 count:6:8 1
  jump 14 equal &t2 0
  read &t3 cell1 &t0                        <---- THERE THE BUG
  write &t3 cell1 idx:1:4
  op add idx:1:4 idx:1:4 1               <--------- Because here the update of idx
  jump 7 always
  op add &t3 idx:1:4 offset:2:4    <------- Idx has changed, index is re-computed
  read byte:4:4 cell1 &t3
  op add idx:1:4 idx:1:4 1
jump 4 always
end

Smaller test case

var idx = 10;
const mem: Memory = new Memory(getBuilding("cell1"));
var byte = mem[idx + 10];
while (idx < 20) {
    mem[idx] = mem[idx + 10];
    idx++;
}

Wrong at generated code for mem[idx] = mem[idx + 10] in the while loop

Best regards, Mlogjs rocks !

@hsaturn hsaturn changed the title Math optimization misses forward modification Code optimization misses forward modification in loops Mar 28, 2024
@JeanJPNM JeanJPNM added the bug Something isn't working label Mar 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants