solidity
solidity copied to clipboard
Loop unrolling during optimization
Abstract
I propose adding support for loop unrolling as a compiler optimization step.
Motivation
In the protocol I am working on, many operations are repeated a fixed number of times. For example:
uint256 constant _TOKEN_CNT = 6;
uint256[_TOKEN_CNT] memory calculatedData;
for (uint i = 0; i < _TOKEN_CNT; i++) {
calculatedData[i] = ...
}
All such loops in my code have a small bound, known at compile-time. Manually unrolling them results in gas savings, but it makes the code less maintainable, and more error-prone to silly mistakes if I want to deploy with different values of _TOKEN_CNT.
Specification
The compiler could decide which constant-bound loops to unroll based on the body of the loop and the runs parameter of the optimization settings. Even better, it would be amazing if I could hint to the compiler that I want specific loop(s) to be unrolled no matter what.
Backwards Compatibility
I don't think this would bring any breaking changes, but a simple toggle to disable loop unrolling altogether would make this fully backwards compatible.