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

[mlir][bufferization] Ownership dealloc: tests for `IsolatedFromAbove`

Open nikalra opened this issue 2 years ago • 4 comments

Add tests for IsolatedFromAbove operations in ownership-based-buffer-deallocation.

nikalra avatar Jul 04 '24 03:07 nikalra

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

github-actions[bot] avatar Jul 04 '24 03:07 github-actions[bot]

@llvm/pr-subscribers-mlir

@llvm/pr-subscribers-mlir-bufferization

Author: Nikhil Kalra (nikalra)

Changes

Handle IsolatedFromAbove operations in ownership-based-buffer-deallocation by using the same contract as function boundaries. Specifically, IsolatedFromAbove ops cannot take ownership of their arguments, and rely on the caller to deallocate them.


Full diff: https://github.com/llvm/llvm-project/pull/97669.diff

5 Files Affected:

  • (modified) mlir/lib/Dialect/Bufferization/Transforms/BufferViewFlowAnalysis.cpp (+5)
  • (modified) mlir/lib/Dialect/Bufferization/Transforms/OwnershipBasedBufferDeallocation.cpp (+3-2)
  • (added) mlir/test/Dialect/Bufferization/Transforms/OwnershipBasedBufferDeallocation/dealloc-isolated-group.mlir (+125)
  • (modified) mlir/test/lib/Dialect/Test/TestOpDefs.cpp (+12)
  • (modified) mlir/test/lib/Dialect/Test/TestOps.td (+18-1)
diff --git a/mlir/lib/Dialect/Bufferization/Transforms/BufferViewFlowAnalysis.cpp b/mlir/lib/Dialect/Bufferization/Transforms/BufferViewFlowAnalysis.cpp
index 72f47b8b468ea..d9525cb640e1c 100644
--- a/mlir/lib/Dialect/Bufferization/Transforms/BufferViewFlowAnalysis.cpp
+++ b/mlir/lib/Dialect/Bufferization/Transforms/BufferViewFlowAnalysis.cpp
@@ -174,6 +174,11 @@ void BufferViewFlowAnalysis::build(Operation *op) {
         }
       }
 
+      if (op->hasTrait<OpTrait::IsIsolatedFromAbove>()) {
+        // Mark the entry block arguments and results as terminal.
+        populateTerminalValues(op);
+      }
+
       return WalkResult::advance();
     }
 
diff --git a/mlir/lib/Dialect/Bufferization/Transforms/OwnershipBasedBufferDeallocation.cpp b/mlir/lib/Dialect/Bufferization/Transforms/OwnershipBasedBufferDeallocation.cpp
index ca5d0688b5b59..a52906174fb07 100644
--- a/mlir/lib/Dialect/Bufferization/Transforms/OwnershipBasedBufferDeallocation.cpp
+++ b/mlir/lib/Dialect/Bufferization/Transforms/OwnershipBasedBufferDeallocation.cpp
@@ -640,8 +640,9 @@ LogicalResult BufferDeallocation::deallocate(Block *block) {
       continue;
 
     // Adhere to function boundary ABI: no ownership of function argument
-    // MemRefs is taken.
-    if (isa<FunctionOpInterface>(block->getParentOp()) &&
+    // MemRefs is taken. Likewise for ops marked IsolatedFromAbove.
+    if ((isa<FunctionOpInterface>(block->getParentOp()) ||
+         block->getParentOp()->hasTrait<OpTrait::IsIsolatedFromAbove>()) &&
         block->isEntryBlock()) {
       Value newArg = buildBoolValue(builder, arg.getLoc(), false);
       state.updateOwnership(arg, newArg);
diff --git a/mlir/test/Dialect/Bufferization/Transforms/OwnershipBasedBufferDeallocation/dealloc-isolated-group.mlir b/mlir/test/Dialect/Bufferization/Transforms/OwnershipBasedBufferDeallocation/dealloc-isolated-group.mlir
new file mode 100644
index 0000000000000..0c3ceda5237cc
--- /dev/null
+++ b/mlir/test/Dialect/Bufferization/Transforms/OwnershipBasedBufferDeallocation/dealloc-isolated-group.mlir
@@ -0,0 +1,125 @@
+// RUN: mlir-opt -verify-diagnostics -ownership-based-buffer-deallocation \
+// RUN:   -buffer-deallocation-simplification -split-input-file %s | FileCheck %s
+
+func.func @function_call() {
+  %alloc = memref.alloc() : memref<f64>
+  %alloc2 = memref.alloc() : memref<f64>
+  %ret = test.isolated_one_region_with_recursive_memory_effects %alloc {
+  ^bb0(%arg1: memref<f64>):
+    test.region_yield %arg1 : memref<f64>
+  } : (memref<f64>) -> memref<f64>
+  test.copy(%ret, %alloc2) : (memref<f64>, memref<f64>)
+  return
+}
+
+// CHECK-LABEL: func @function_call()
+//       CHECK: [[ALLOC0:%.+]] = memref.alloc(
+//  CHECK-NEXT: [[ALLOC1:%.+]] = memref.alloc(
+//  CHECK-NEXT: [[RET:%.+]]:2 = test.isolated_one_region_with_recursive_memory_effects [[ALLOC0]]
+//  CHECK-NEXT: ^bb0([[ARG:%.+]]: memref<f64>)
+//       CHECK:   test.region_yield [[ARG]]
+//   CHECK-NOT:   bufferization.dealloc
+//       CHECK: }
+//  CHECK-NEXT: test.copy
+//  CHECK-NEXT: [[BASE:%[a-zA-Z0-9_]+]]{{.*}} = memref.extract_strided_metadata [[RET]]#0
+//  CHECK-NEXT: bufferization.dealloc ([[ALLOC0]], [[ALLOC1]], [[BASE]] :{{.*}}) if (%true, %true, [[RET]]#1)
+
+// -----
+
+func.func @function_call_requries_merged_ownership_mid_block(%arg0: i1) {
+  %alloc = memref.alloc() : memref<f64>
+  %alloc2 = memref.alloca() : memref<f64>
+  %0 = arith.select %arg0, %alloc, %alloc2 : memref<f64>
+  %ret = test.isolated_one_region_with_recursive_memory_effects %0 {
+  ^bb0(%arg1: memref<f64>):
+    test.region_yield %arg1 : memref<f64>
+  } : (memref<f64>) -> (memref<f64>)
+  test.copy(%ret, %alloc) : (memref<f64>, memref<f64>)
+  return
+}
+
+// CHECK-LABEL: func @function_call_requries_merged_ownership_mid_block
+//       CHECK:   [[ALLOC0:%.+]] = memref.alloc(
+//  CHECK-NEXT:   [[ALLOC1:%.+]] = memref.alloca(
+//  CHECK-NEXT:   [[SELECT:%.+]] = arith.select{{.*}}[[ALLOC0]], [[ALLOC1]]
+//  CHECK-NEXT:   [[RET:%.+]]:2 = test.isolated_one_region_with_recursive_memory_effects [[SELECT]]
+//  CHECK-NEXT:   ^bb0([[ARG:%.+]]: memref<f64>)
+//       CHECK:     test.region_yield [[ARG]]
+//   CHECK-NOT:     bufferization.dealloc
+//       CHECK:   }
+//  CHECK-NEXT:   test.copy
+//  CHECK-NEXT:   [[BASE:%[a-zA-Z0-9_]+]]{{.*}} = memref.extract_strided_metadata [[RET]]#0
+//  CHECK-NEXT:   bufferization.dealloc ([[ALLOC0]], [[BASE]] :
+//  CHECK-SAME:     if (%true, [[RET]]#1)
+//   CHECK-NOT:     retain
+//  CHECK-NEXT:   return
+
+// -----
+
+func.func @g(%arg0: memref<f32>) -> memref<f32> {
+  %0 = test.isolated_one_region_with_recursive_memory_effects %arg0 {
+  ^bb0(%arg1: memref<f32>):
+    test.region_yield %arg1 : memref<f32>
+  } : (memref<f32>) -> (memref<f32>)
+  return %0 : memref<f32>
+}
+
+// CHECK-LABEL:   func.func @g(
+// CHECK-SAME:                 %[[VAL_0:.*]]: memref<f32>) -> memref<f32> {
+// CHECK:           %[[BLOCK:.*]]:2 = test.isolated_one_region_with_recursive_memory_effects %[[VAL_0]] {
+// CHECK:           ^bb0(%[[ARG:.*]]: memref<f32>):
+// CHECK:             test.region_yield %[[ARG]], %false : memref<f32>, i1
+// CHECK:           } : (memref<f32>) -> (memref<f32>, i1)
+// CHECK:           %[[VAL_4:.*]] = scf.if %[[BLOCK]]#1 -> (memref<f32>) {
+// CHECK:             scf.yield %[[BLOCK]]#0 : memref<f32>
+// CHECK:           } else {
+// CHECK:             %[[VAL_6:.*]] = bufferization.clone %[[BLOCK]]#0 : memref<f32> to memref<f32>
+// CHECK:             scf.yield %[[VAL_6]] : memref<f32>
+// CHECK:           }
+// CHECK:           %[[BUF:.*]], %[[OFFSET:.*]] = memref.extract_strided_metadata %[[BLOCK]]#0 : memref<f32> -> memref<f32>, index
+// CHECK:           %[[VAL_11:.*]] = bufferization.dealloc (%[[BUF]] : memref<f32>) if (%[[BLOCK]]#1) retain (%[[VAL_4]] : memref<f32>)
+// CHECK:           return %[[VAL_4]] : memref<f32>
+// CHECK:         }
+
+// -----
+
+func.func @alloc_yielded_from_block() {
+  %alloc = memref.alloc() : memref<f64>
+  %alloc2 = memref.alloc() : memref<f64>
+  %ret = test.isolated_one_region_with_recursive_memory_effects %alloc {
+  ^bb0(%arg1: memref<f64>):
+    %0 = memref.load %arg1[] : memref<f64>
+    %c1 = arith.constant 1.0 : f64
+    %r0 = arith.cmpf oeq, %0, %c1 : f64
+    %1 = scf.if %r0 -> memref<f64> {
+      %alloc3 = memref.alloc() : memref<f64>
+      scf.yield %alloc3 : memref<f64>
+    } else {
+      scf.yield %arg1 : memref<f64>
+    }
+    test.region_yield %1 : memref<f64>
+  } : (memref<f64>) -> memref<f64>
+  test.copy(%ret, %alloc2) : (memref<f64>, memref<f64>)
+  return
+}
+
+// CHECK-LABEL:   func.func @alloc_yielded_from_block() {
+// CHECK:           %true = arith.constant true
+// CHECK:           %[[ALLOC:.*]] = memref.alloc() : memref<f64>
+// CHECK:           %[[BLOCK:.*]]:2 = test.isolated_one_region_with_recursive_memory_effects %[[ALLOC]] {
+// CHECK:           ^bb0(%[[ARG:.*]]: memref<f64>):
+// CHECK:             %[[VAL_9:.*]] = arith.cmpf oeq
+// CHECK:             %[[VAL_10:.*]]:2 = scf.if %[[VAL_9]] -> (memref<f64>, i1) {
+// CHECK:               %[[BLOCK_ALLOC:.*]] = memref.alloc() : memref<f64>
+// CHECK:               scf.yield %[[BLOCK_ALLOC]], %true_{{[0-9]*}} : memref<f64>, i1
+// CHECK:             } else {
+// CHECK:               scf.yield %[[ARG]], %false : memref<f64>, i1
+// CHECK:             }
+// CHECK:             test.region_yield %[[VAL_10]]#0, %[[VAL_10]]#1 : memref<f64>, i1
+// CHECK:           } : (memref<f64>) -> (memref<f64>, i1)
+// CHECK:           test.copy
+// CHECK:           %[[BUF:.*]], %[[OFFSET:.*]] = memref.extract_strided_metadata %[[BLOCK]]#0 : memref<f64> -> memref<f64>, index
+// CHECK:           bufferization.dealloc (%[[ALLOC]], %{{.*}}, %[[BUF]] : memref<f64>, memref<f64>, memref<f64>) if (%true, %true, %[[BLOCK]]#1)
+// CHECK:           return
+// CHECK:         }
+
diff --git a/mlir/test/lib/Dialect/Test/TestOpDefs.cpp b/mlir/test/lib/Dialect/Test/TestOpDefs.cpp
index fbaa102d3e33c..6666c9b86db42 100644
--- a/mlir/test/lib/Dialect/Test/TestOpDefs.cpp
+++ b/mlir/test/lib/Dialect/Test/TestOpDefs.cpp
@@ -110,6 +110,18 @@ void IsolatedRegionOp::print(OpAsmPrinter &p) {
   p.printRegion(getRegion(), /*printEntryBlockArgs=*/false);
 }
 
+//===----------------------------------------------------------------------===//
+// IsolatedOneRegionWithRecursiveMemoryEffectsOp
+//===----------------------------------------------------------------------===//
+
+void IsolatedOneRegionWithRecursiveMemoryEffectsOp::getSuccessorRegions(
+    RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
+  if (point.isParent())
+    regions.emplace_back(&getBody());
+  else
+    regions.emplace_back((*this)->getResults());
+}
+
 //===----------------------------------------------------------------------===//
 // SSACFGRegionOp
 //===----------------------------------------------------------------------===//
diff --git a/mlir/test/lib/Dialect/Test/TestOps.td b/mlir/test/lib/Dialect/Test/TestOps.td
index e1ec1428ee6d6..bbe84572868b2 100644
--- a/mlir/test/lib/Dialect/Test/TestOps.td
+++ b/mlir/test/lib/Dialect/Test/TestOps.td
@@ -507,6 +507,23 @@ def OneRegionWithRecursiveMemoryEffectsOp
   let regions = (region SizedRegion<1>:$body);
 }
 
+def IsolatedOneRegionWithRecursiveMemoryEffectsOp
+    : TEST_Op<"isolated_one_region_with_recursive_memory_effects", [
+        RecursiveMemoryEffects,
+        IsolatedFromAbove,
+        SingleBlockImplicitTerminator<"RegionYieldOp">,
+        DeclareOpInterfaceMethods<RegionBranchOpInterface>]> {
+  let description = [{
+    IsolatedFromAbove Op that has one region and recursive side effects.
+  }];
+  let arguments = (ins Variadic<AnyType>:$operands);
+  let results = (outs Variadic<AnyType>:$results);
+  let regions = (region SizedRegion<1>:$body);
+  let assemblyFormat = [{
+    attr-dict-with-keyword $operands $body `:` functional-type(operands, results)
+  }];
+}
+
 //===----------------------------------------------------------------------===//
 // NoTerminator Operation
 //===----------------------------------------------------------------------===//
@@ -2147,7 +2164,7 @@ def RegionYieldOp : TEST_Op<"region_yield",
     This operation is used in a region and yields the corresponding type for
     that operation.
   }];
-  let arguments = (ins AnyType:$result);
+  let arguments = (ins Variadic<AnyType>:$result);
   let assemblyFormat = [{
     $result `:` type($result) attr-dict
   }];

llvmbot avatar Jul 04 '24 03:07 llvmbot

What's the reason that you'd like IsolatedFromAbove ops to be treated like functions?

matthias-springer avatar Jul 04 '24 06:07 matthias-springer

What's the reason that you'd like IsolatedFromAbove ops to be treated like functions?

I guess it's less important that IsolatedFromAbove ops be treated like functions, but rather that the existing pass was crashing + producing invalid IR.

For some psuedo-ish input IR:

%0 = memref.alloc() : memref<64xf32>

%1 = isolated_from_above(%0) ({
^bb0(%a0: memref<64xf32>):
  %2 = do_something(%a0) : memref<64xf32> -> memref<32xf32>
  yield %2 : memref<32xf32> -> ()
}) : (memref<64xf32>) -> memref<32xf32>

return %1

The first problem I ran into was that the buffer-flow analysis pass was crashing because it assumed %a0 was captured from the enclosing region, but as it traversed the use-def chain, couldn't find the source allocation. That's fixed by: https://github.com/llvm/llvm-project/blob/103d76069cdc7d92a6fdf10954c3624d9c539109/mlir/lib/Dialect/Bufferization/Transforms/BufferViewFlowAnalysis.cpp#L177

The second issue I ran into was that the pass assumed it could take ownership of the block argument and deallocate it after use, leading to something like this:

%0 = memref.alloc() : memref<64xf32>

isolated_from_above(%0) ({
^bb0(%a0: memref<64xf32>):
  do_something(%a0) : memref<64xf32> -> ()
  memref.dealloc(%a0) : memref<64xf32>  // last use of %a0 but it aliases %0
}) : memref<64xf32> -> ()

memref.dealloc(%0) : memref<64xf32>  // last use of %0

Treating IsolatedFromAbove ops like functions seemed like the most expedient way to produce valid IR, since the function contract prohibits taking ownership of the arguments.

nikalra avatar Jul 04 '24 18:07 nikalra