jserv / amacc

Small C Compiler generating ELF executable Arm architecture, supporting JIT execution
Other
1.01k stars 161 forks source link

Can't place other loop(s) inside another for loop #13

Closed TheKK closed 8 years ago

TheKK commented 8 years ago

To reproduce this, try to compile:

int main(int argc, char **argv)
{
        int i, j;

        for (i = 0; i < 5; i++)
                for (j = 0; j < 5; j++)
                        printf("loop %d\n", i);

        return 0;
}

and we got an infinite loop.

This is a bug of current implementation of for loop. As we know, the order of code chunks while parsing is not what we expect in assembly form, like

// We parse it as: // Init -> Cond -> Bz -> After -> Body -> Jmp

// But we want it to be: // Init -> Cond -> Bz -> Body -> After -> Jmp

To solve this, I simply swap After and Body chunk, and here comes the problem. All address used in Body remain the same and causes unexpected behavior. Here are two ways in my mind:

  1. re-caculate the address of each address used in Body + higher performance - more complex works - increase bunch of code (I think we should keep this project small and simple)
  2. use jump command to control code flow instead of swapping code chunks - lower performance + keep everything as simple as now + need only lines of code to achieve

Not sure which approach would fit the spirit of this project more.

jserv commented 8 years ago

Can you introduce backtracking algorithm for cutting parsing nodes? I prefer the later proposal.

jserv commented 8 years ago

@TheKK ping?