solang icon indicating copy to clipboard operation
solang copied to clipboard

Run optimization passes multiple times

Open xermicus opened this issue 2 years ago • 2 comments

We need to change the current model so that optimization passes can run multiple times. Extracted from a discussion in the chat:

What I can say about constant folding is that it is not complete.
E.g.
int a = 1;
int b = 4;
int c = a+b;
int d = c+1;

After constant folding you have:
int c = 1+4;
int d = c+1;
Ideally we would run the optmization many times to eliminate all the constants. 

My opinion is that any optimization pass should be able to be run as many times as we want. The only thing that should happen that the code might get further optimized with more iterations of the same pass.

Compile time ABI encoding depends on this. Some optimization passes in can also benefit mutually from having multiple pass runs, for example constant folding and CSE. I think we should run optimizations until the CFG doesn't change after running them any more (converges) or a limit (maximum runs) is reached.

xermicus avatar Jul 20 '23 09:07 xermicus

contract A {
    function h() public pure returns (uint) {
        uint a = 1;
        uint b = 4;
        uint c = a+b;
        uint d = c+1;
        return d;
    }
}

This is the CFG emitted when the above code is compiled

# function A::A::function::h public:true selector:50dd0ebade8d719b nonpayable:true
# params: 
# returns: uint256
block0: # entry
    ty:uint256 %a = uint256 1
    ty:uint256 %b = uint256 4
    ty:uint256 %c = uint256 5
    ty:uint256 %d = uint256 6
    return uint256 6

It looks like the constant folding produced the desired output, but unused variables were not removed. An explicit optimisation pass that takes care of removing unused variables, after constant folding has run, may be useful here.

chioni16 avatar Jul 21 '23 10:07 chioni16

Yes, as discussed in the chat; In my opinion the proper way to fix that is to turn unused variable elimination into an optimization pass, and then run all passes passes multiple times until the code converges or a limit is reached. This is also another good example why we want to run all optimization passes multiple times. Thanks!

xermicus avatar Jul 21 '23 11:07 xermicus