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

[RISCV][Zba] Optimize mul with SH*ADD #68144

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

vacmannnn
Copy link

@vacmannnn vacmannnn commented Oct 3, 2023

This patch does the optimization of mul with a constant by different patterns of SH*ADD.

Optimized multiplication by constants 23, 29, 35, 39, 43, 47, 49, 51, 53, 55, 57, 59, 61, 69, 75, 77, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101, 103, 105, 107, 109, 111, 113, 117, 121, 123, 125, 135, 137, 145, 147, 149, 153, 155, 157, 161, 163, 165, 169, 171, 173, 181, 185, 189, 201, 203, 205, 217, 219, 225, 243, 293, 297, 301, 305, 325, 329, 333, 361, 365, 369, 405, 585, 593, 649, 657, 729

Example of patterns:
shXadd a1 a0 a0
shYadd a0 a1 a1
shZadd a0 a1 a0
Mathematically, this is the same as multiplying by (2^x + 1)(2^z) + (2^x + 1)(2^y + 1). You can go through all X, Y, Z and find those constants that optimization cannot generate.

@topperc
Copy link
Collaborator

topperc commented Oct 3, 2023

Is this always profitable?

Optimized multiplication by constants 23, 29, 35, 39, 43, 47,
49, 51, 53, 55, 57, 59, 61, 69, 75, 77, 83, 85, 87, 89, 91,
93, 95, 97, 99, 101, 103, 105, 107, 109, 111, 113, 117, 121,
123, 125, 135, 137, 145, 147, 149, 153, 155, 157, 161, 163,
165, 169, 171, 173, 181, 185, 189, 201, 203, 205, 217, 219,
225, 243, 293, 297, 301, 305, 325, 329, 333, 361, 365, 369,
405, 585, 593, 649, 657, 729
vacmannnn and others added 3 commits November 23, 2023 11:04
Due to the new optimization with shXadds, the old tests expect a "naive mul",
replaced it with a new constant that was not replaced by shXadds.
@@ -983,6 +983,1299 @@ define i64 @mul81(i64 %a) {
ret i64 %c
}


define i64 @mul153(i64 %a) {
; RV64I-LABEL: mul153:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

llvm-mca doesn't think this is an improvement for sifive-x280 https://godbolt.org/z/6ahP11xrq

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your feedback,
tests show that 3 shXadds is a little slower than mul, but for some reason GCC uses 3 shXadds - https://godbolt.org/z/oez5Pddde
And even 4 - https://godbolt.org/z/czK3Kd7bs
I'll try to find out why they do this and write later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants