Skip to content

scriptcomp: Optimize typical for loop construct instructions#86

Merged
mtijanic merged 2 commits intoniv:masterfrom
mtijanic:optimize-forloop
Dec 25, 2023
Merged

scriptcomp: Optimize typical for loop construct instructions#86
mtijanic merged 2 commits intoniv:masterfrom
mtijanic:optimize-forloop

Conversation

@mtijanic
Copy link
Copy Markdown
Collaborator

@mtijanic mtijanic commented Jul 18, 2023

The common loop pattern of for (i = 0; i < 1000; ++i) gets compiled into

     8  RUNSTACK_ADD, TYPE_STRING               
    10  CONSTANT, TYPE_INTEGER, 0               
    16  RUNSTACK_COPY, TYPE_VOID, -4, 4         
    24  CONSTANT, TYPE_INTEGER, 1000            
    30  LT, TYPETYPE_INTEGER_INTEGER            
    32  JZ, 32                                  
    38  INCREMENT, TYPE_INTEGER, -4             
    44  RUNSTACK_COPY, TYPE_VOID, -4, 4         
    52  MODIFY_STACK_POINTER, -4                
    58  JMP, -42                                

The inc/dec operations can reach all across the stack and don't need to be copied over to top of stack. However, since ++i returns a value we have to emit the RUNSTACK_COPY. But, when we don't use that value, we just immediately clear it with MODIFY_STACK_POINTER. Just don't do either.

Testing

Added an extra test case with ++i and runtime check on iteration count.
Verified disassembly of

void main() {
    int i;
    for (i = 0; i < 1000; ++i) { }
}

is sane.

Changelog

Performance Improvements

  • Optimized the common for loop construct for (i = 0; i < N; ++i)

Licence

  • I am licencing my change under the project's MIT licence, including all changes to GPL-3.0 licenced parts of the codebase.

@mtijanic mtijanic merged commit ae7b436 into niv:master Dec 25, 2023
@mtijanic mtijanic deleted the optimize-forloop branch December 25, 2023 22:11
niv pushed a commit that referenced this pull request Jan 28, 2025
This optimization appears to cause issues with increment/decrement ops,
like infinite loops. Disabling it for now.

Open issue: #141
Related PR: #86

## Testing

The script in the open issue mentioned above that hit the TMI limit due
to an infinite loop now works correctly.

## Changelog

### Changed

- scriptcomp: disabled a for loop optimization where the compiler would
sometimes generate code that caused an infinite loop.

## Licence

- [x] I am licencing my change under the project's MIT licence,
including all changes to GPL-3.0 licenced parts of the codebase.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant