| Issue |
243045
|
| Summary |
[flang][HLFIR] COUNT/ANY/SUM over a character elemental materialize a character array temporary since 239312
|
| Labels |
flang:fir-hlfir
|
| Assignees |
|
| Reporter |
eugeneepshteyn
|
Since 239312 (a93922b35b75), a character elemental that feeds COUNT, ANY or SUM is no longer fused into the reduction loop, and bufferization materializes a whole character array temporary instead.
The new check in `flang/lib/Optimizer/HLFIR/Transforms/InlineElementals.cpp` refuses to inline an `hlfir.elemental` whose `hlfir.yield_element` has a cleanup region when the `hlfir.apply` is not inside another `hlfir.elemental`, unless the elemental's `hlfir.destroy` is in the apply's block ("cannot preserve element cleanup when inlining"). By the time this pattern runs, SimplifyHLFIRIntrinsics has already expanded the reduction into a loop nest that contains the `hlfir.apply`, so the check fails for these reductions.
```fortran
integer function idx_sum(a, n, l)
integer :: n, l
character(l) :: a(n)
idx_sum = sum(index(a(:)(1:l-1)//'xyz', 'z'))
end function
integer function count_match(a, b, n, l)
integer :: n, l
character(l) :: a(n), b(n)
count_match = count(a(:)(1:l-1)//'x' == b)
end function
```
```console
$ flang -fc1 -O2 -emit-fir -mmlir --mlir-print-ir-after=bufferize-hlfir reductions.f90 -o /dev/null 2>&1 | grep -oE 'func.func @_QP[a-z_]+|fir.allocmem !fir.array<[^>]*>+'
```
Main (e0b437836a21):
```text
func.func @_QPidx_sum
fir.allocmem !fir.array<?x!fir.char<1,?>>
func.func @_QPcount_match
fir.allocmem !fir.array<?x!fir.char<1,?>>
```
With 239312 reverted:
```text
func.func @_QPidx_sum
func.func @_QPcount_match
fir.allocmem !fir.array<?x!fir.logical<4>>
```
`idx_sum` now allocates an n*len-byte character temporary where it allocated none, and `count_match` swaps a logical array temporary for a character one.
The driver below calls `idx_sum` ten times on 100000 strings of length 512. The result is the same either way (51400000), but peak RSS goes from about 52 MB to 102 MB, and run time from about 0.03 s to 0.15 s:
```fortran
program main
integer, parameter :: n = 100000, l = 512
character(:), allocatable :: a(:)
integer :: j, r
integer, external :: idx_sum
allocate(character(l) :: a(n))
do j = 1, n
a(j) = 'a'
end do
do j = 1, 10
r = idx_sum(a, n, l)
end do
print *, r
end program
```
```console
$ flang -O2 reductions.f90 driver.f90 -o red && /usr/bin/time -f "%e s %M kB" ./red
```
Expected: the elemental is inlined into the reduction loop as before, with its cleanup emitted in the apply's block after the last use of the element value when that use does not leave the iteration.
(This issue was filed with the help of AI)
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs