https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128737
Bug ID: 128737
Summary: associative arithmetic can be done in parallel with
four or more operands
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Severity: enhancement
Priority: P3
Component: rtl-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: tkoenig at gcc dot gnu.org
Target Milestone: ---
Consider the following code, where the parentheses in the _v2 versions
constrain the evaluation order. Addition and multiplication are
commutative, and the result is the same regardless of rearrangement
of the variables.
function add_v1 (a,b,c,d) result (res)
integer(8), value :: a, b, c, d
integer(8) :: res
res = a + b + c + d
end function add_v1
function add_v2 (a,b,c,d) result (res)
integer(8), value :: a, b, c, d
integer(8) :: res
res = (a + b) + (c + d)
end function add_v2
function mul_v1 (a,b,c,d) result (res)
integer(8), value :: a, b, c, d
integer(8) :: res
res = a * b * c * d
end function mul_v1
function mul_v2 (a,b,c,d) result (res)
integer(8), value :: a, b, c, d
integer(8) :: res
res = (a * b) * (c * d)
end function mul_v2
This gives
add_v1_:
addq %rsi, %rdi
addq %rdx, %rdi
leaq (%rdi,%rcx), %rax
ret
add_v2_:
addq %rsi, %rdi
addq %rcx, %rdx
leaq (%rdi,%rdx), %rax
ret
mul_v1_:
imulq %rsi, %rdi
imulq %rdx, %rdi
movq %rdi, %rax
imulq %rcx, %rax
ret
mul_v2_:
imulq %rsi, %rdi
imulq %rcx, %rdx
movq %rdi, %rax
imulq %rdx, %rax
ret
where the v1 versions have some extra latency because of the dependency
chain, at least on OoO architectures.
This is not architecture specific, for example POWER has
add_v1_:
add 3,3,4
add 3,3,5
add 3,3,6
blr
add_v2_:
add 3,3,4
add 5,5,6
add 3,3,5
blr
mul_v1_:
mulld 3,3,4
mulld 3,3,5
mulld 3,3,6
blr
mul_v2_:
mulld 3,3,4
mulld 5,5,6
mulld 3,3,5
blr