aptos-labs / aptos-core

Aptos is a layer 1 blockchain built to support the widespread use of blockchain through better technology and user experience.
https://aptosfoundation.org
Other
6.19k stars 3.66k forks source link

[Feature Request] Implement "eager pushes" optimization #15339

Open vineethk opened 5 days ago

vineethk commented 5 days ago

🚀 Feature Request

As an analogue to the flush writes optimization (https://github.com/aptos-labs/aptos-core/blob/main/third_party/move/move-compiler-v2/src/pipeline/flush_writes_processor.rs#L4), implement an "eager pushes" optimization which identifies cases where eagerly pushing a value onto the stack (safely) will result in fewer StLoc-MovLoc pairs later.

For example, compiling the code below with compiler v2:

module 0xc0ffee::m {
    fun one(): u64 {
        1
    }

    fun bar(x: &mut u64, i: u64) {
        *x = i;
    }

    public fun foo(x: &mut u64, len: u64) {
        while (len > 0) {
            bar(x, one());
            len = len - 1;
        };
    }
}

Will result in the following bytecode for the function foo:

public foo(Arg0: &mut u64, Arg1: u64) /* def_idx: 1 */ {
L2: loc0: u64
L3: loc1: &mut u64
B0:
    0: CopyLoc[1](Arg1: u64)
    1: LdU64(0)
    2: Gt
    3: BrFalse(16)
B1:
    4: CopyLoc[0](Arg0: &mut u64)
    5: StLoc[3](loc1: &mut u64)
    6: Call one(): u64
    7: StLoc[2](loc0: u64)
    8: MoveLoc[3](loc1: &mut u64)
    9: MoveLoc[2](loc0: u64)
    10: Call bar(&mut u64, u64)
    11: MoveLoc[1](Arg1: u64)
    12: LdU64(1)
    13: Sub
    14: StLoc[1](Arg1: u64)
    15: Branch(0)
B2:
    16: MoveLoc[0](Arg0: &mut u64)
    17: Pop
    18: Ret
}

Of particular interest is the basic block B1, where instructions numbered 5, 7, 8, 9 can be deleted without affecting the semantics.

This example and several others reduced from the framework are part of the tests in third_party/move/move-compiler-v2/tests/eager-pushes/.