llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[mlir][bufferization] Incorrect bufferization with LayoutMapOption::IdentityLayoutMap

Open ryanpholt opened this issue 2 years ago • 1 comments

OneShotBufferize incorrectly casts away non-unit layouts on function call arguments when running with the LayoutMapOption::IdentityLayoutMap option.

Reproducer:

// RUN: mlir-opt %s --one-shot-bufferize='bufferize-function-boundaries function-boundary-type-conversion=identity-layout-map

func.func @caller(%arg0: tensor<5xf32>, %offset: index, %size: index) -> (f32) {
    %extracted_slice = tensor.extract_slice %arg0[%offset] [%size] [1] : tensor<5xf32> to tensor<?xf32>
    %result = func.call @callee(%extracted_slice) : (tensor<?xf32>) -> (f32)
    return %result : f32
}
func.func private @callee(%arg0: tensor<?xf32>) -> (f32) {
    %0 = arith.constant 0 : index
    %extracted = tensor.extract %arg0[%0] : tensor<?xf32>
    return %extracted : f32
}

results in:

  func.func @caller(%arg0: memref<5xf32>, %arg1: index, %arg2: index) -> f32 {
    %subview = memref.subview %arg0[%arg1] [%arg2] [1] : memref<5xf32> to memref<?xf32, strided<[1], offset: ?>>
    %cast = memref.cast %subview : memref<?xf32, strided<[1], offset: ?>> to memref<?xf32> 
    %0 = call @callee(%cast) : (memref<?xf32>) -> f32
    return %0 : f32
  }
  func.func private @callee(%arg0: memref<?xf32>) -> f32 {
    %c0 = arith.constant 0 : index
    %0 = memref.load %arg0[%c0] : memref<?xf32>
    return %0 : f32
  }

Notice the memref.cast is eliminating the layout. This will cause callee to load the wrong value when %offset is non-zero. I would have expected a new allocation and a copy at the callsite instead of the memref.cast. The doc for LayoutMapOption indicates that a copy would be the expected behavior as well.

ryanpholt avatar Feb 28 '24 15:02 ryanpholt

Unable to reproduce: memref.cast not present in lowered IR

./bin/mlir-opt ~/compiler/mlir-bug/repro.mlir --one-shot-bufferize='bufferize-function-boundaries function-boundary-type-conversion=identity-layout-map'

module {
  func.func @caller(%arg0: memref<5xf32>, %arg1: index, %arg2: index) -> f32 {
    %subview = memref.subview %arg0[%arg1] [%arg2] [1] : memref<5xf32> to memref<?xf32, strided<[1], offset: ?>>
    %c0 = arith.constant 0 : index
    %dim = memref.dim %subview, %c0 : memref<?xf32, strided<[1], offset: ?>>
    %alloc = memref.alloc(%dim) {alignment = 64 : i64} : memref<?xf32>
    memref.copy %subview, %alloc : memref<?xf32, strided<[1], offset: ?>> to memref<?xf32>
    %0 = call @callee(%alloc) : (memref<?xf32>) -> f32
    return %0 : f32
  }
  func.func private @callee(%arg0: memref<?xf32>) -> f32 {
    %c0 = arith.constant 0 : index
    %0 = memref.load %arg0[%c0] : memref<?xf32>
    return %0 : f32
  }
}

rishabhmadan19 avatar Mar 03 '26 08:03 rishabhmadan19