Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Optimisation] Constant/variable folding & propagation #5

Open
MinekPo1 opened this issue May 28, 2023 · 1 comment
Open

[Optimisation] Constant/variable folding & propagation #5

MinekPo1 opened this issue May 28, 2023 · 1 comment
Labels
enhancement New feature or request

Comments

@MinekPo1
Copy link

MinekPo1 commented May 28, 2023

Take the following code as an example:

#include <mlogevo/io.h>
#include <mlogevo/mlog_object.h>
extern struct MLogObject message1;

void main() {
    int a = 1 + 2;
    print("1 + 2 = ", a);
    printflush(message1);
}

It can be observed that the value of 1 + 2 can be determined at the compile time to be equal to 3.

Furthermore, it can be observed that therefore the value of a can be determined at compile time.

Currently the outputed code (with -O 3)

op add _a@main 1 2
print "1 + 2 = "
print _a@main
printflush message1
end

However, we can simplify this to:

print "1 + 2 = 3"
printflush message1
end

I believe one of the ways to do this is, at the abstract syntax tree optimization step, to observe when an operation is done on two (for binary operations or one for unary operations) literals or constants and precompute the calculation.

Note, that variable can be constant at some times, but not constant in others.

#include <mlogevo/io.h>
#include <mlogevo/mlog_object.h>
extern struct MLogObject message1;

void main() {
    int a = 0;
    print("a before: ", a, "\n");
    a = someFunction();
    print("a after: ", a, "\n");
    printflush(message1);
}

The first print statement can be optimized to print("a before: 0\n");. The second can not be optimized in this way.

Variable folding & propagation is a bit more difficult than doing the same on constants, but can optimize common patterns, such as assigning a set of bit flags to a variable:

int a = 1 | 2 | 3;

At the current state this compiles to two instructions, though it can be compiled to only one.

Edit: typo

@MinekPo1
Copy link
Author

Also, consecutive print instructions on literals are not optimized. Seems like an easy thing to do imho. I might try to contribute.

@UMRnInside UMRnInside added the enhancement New feature or request label May 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants