What you're missing is that this optimization is complicated to implement (while perfectly possible).
For all declared & initialized variables, there is need to have the initial value itself memorized in the compiler itself. If the variables are ever affected with anything other than a constant literal value (or another value that reduces to a constant literal) then it should be marked as "scratched".
Then when a while or for loop is encountered, the test condition has to be checked at compile time against the variables. If anything in the expression tree is marked as "scratched" then you can perrform no optimisation. Else you can evaluate the expression fully, and it'll either evaluate to "true" or "false".
If it evaluates to "false" then you can remove the loop completely (and it'd be a good idea to issue a warning to the user, as it's probably an error of his side).
If it evaluates to "true" then you can turn it into a do-while loop, so you avoid a dummy check at loop entering.
Note that this is my interpretation of the problem, the actual implementation might need to be even more complex than this short description.
@Shiru : Wow, CC65 can produce such code ? Declaring the variables as "static" makes so much a difference ? I'm very impressed
Definitely far to optimal code, but it's somewhat decent compared as to what it produces under normal conditions.
I should try to use CC65 again and declare everything "static" and see how it turns out.
Still it should be doable to hack the compiler so that everything is "static". Although this keywoard always confused the heck out of me in C. As far as I undestand it can have completely different meaning depending on where it's used. With GCC "static" global variables are invisible to other files, and "static" functions can use nonstandard calling convention (leading often to much more optimal code). In fact all functions should be static ideally but then you can give up separate compilation and intermixing with other languages.