llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.82k stars 11.91k forks source link

[flang] missing null check when using where construct #59803

Open tblah opened 1 year ago

tblah commented 1 year ago
subroutine where_allocatable_assignments(a, b)
  integer :: a(:)
  integer, allocatable :: b(:)
  where(b > 0)
    b = a
  elsewhere
    b(:) = 0
  endwhere
end subroutine

Results in FIR like this:

func.func @_QPwhere_allocatable_assignments(%arg0: !fir.box<!fir.array<?xi32>> {fir.bindc_name = "a"}, %arg1: !fir.ref<!fir.box<!fir.heap<!fir.array<?xi32>>>> {fir.bindc_name = "b"}) {
    %0 = fir.load %arg1 : !fir.ref<!fir.box<!fir.heap<!fir.array<?xi32>>>> // %arg1 might be null
    %c0 = arith.constant 0 : index
    %1:3 = fir.box_dims %0, %c0 : (!fir.box<!fir.heap<!fir.array<?xi32>>>, index) -> (index, index, index)
    %2 = fir.box_addr %0 : (!fir.box<!fir.heap<!fir.array<?xi32>>>) -> !fir.heap<!fir.array<?xi32>>
    %3 = fir.shape_shift %1#0, %1#1 : (index, index) -> !fir.shapeshift<1>
    %4 = fir.array_load %2(%3) : (!fir.heap<!fir.array<?xi32>>, !fir.shapeshift<1>) -> !fir.array<?xi32> // load %arg1 without checking if it is nulll
   [... no null check ...]
    %9 = fir.do_loop %arg2 = %c0_0 to %8 step %c1 unordered iter_args(%arg3 = %7) -> (!fir.array<?x!fir.logical<4>>) {
      %34 = fir.array_fetch %4, %arg2 : (!fir.array<?xi32>, index) -> i32 // read from %arg1 without checking if it is null
      [... this loop computes the mask array ...]
    }
    [... array_load %arg0 ...]
    %13 = fir.load %arg1 : !fir.ref<!fir.box<!fir.heap<!fir.array<?xi32>>>>
    %14 = fir.box_addr %13 : (!fir.box<!fir.heap<!fir.array<?xi32>>>) -> !fir.heap<!fir.array<?xi32>>
    %15 = fir.convert %14 : (!fir.heap<!fir.array<?xi32>>) -> i64
    %c0_i64 = arith.constant 0 : i64
    %16 = arith.cmpi ne, %15, %c0_i64 : i64 // %arg1 is checked here
    [...]

The above FIR shows that %arg1 (b) is read from before we check if the pointer is null.

See also https://github.com/llvm/llvm-project/issues/56921

llvmbot commented 1 year ago

@llvm/issue-subscribers-bug