[Compiler][Codegen] expose loop-return allocation control arg (#24997) Custom pipelines may return fresh buffers from loops and manage their lifetime after bufferization. Empty-tensor analysis must honor the same policy as bufferization so it does not reject otherwise supported IR, while callers that do not opt in retain the existing equivalence requirement. Co-authored-by: Luis Romero <115032777+L-roro@users.noreply.github.com> Assisted-by: GPT-6-Astra --------- Signed-off-by: Christopher McGirr <mcgirr@roofline.ai>
diff --git a/compiler/src/iree/compiler/Codegen/Common/IREEComprehensiveBufferize.cpp b/compiler/src/iree/compiler/Codegen/Common/IREEComprehensiveBufferize.cpp index 945ee8f..f86fc18 100644 --- a/compiler/src/iree/compiler/Codegen/Common/IREEComprehensiveBufferize.cpp +++ b/compiler/src/iree/compiler/Codegen/Common/IREEComprehensiveBufferize.cpp
@@ -80,6 +80,7 @@ class EliminateEmptyTensorsPass final : public impl::EliminateEmptyTensorsPassBase<EliminateEmptyTensorsPass> { public: + using Base::Base; void getDependentDialects(DialectRegistry ®istry) const override { // BufferizationDialect is needed for using type interfaces, like // TensorLikeType. Because the builtin types, e.g., RankedTensorType, etc., @@ -100,8 +101,10 @@ using Base::Base; explicit IREEComprehensiveBufferizePass( BufferizationOptions::AllocationFn allocationFn, - BufferizationOptions::MemCpyFn memCpyFn) - : allocationFn(allocationFn), memCpyFn(memCpyFn) {} + BufferizationOptions::MemCpyFn memCpyFn, bool allowReturnAllocsFromLoops) + : allocationFn(allocationFn), memCpyFn(memCpyFn) { + this->allowReturnAllocsFromLoops = allowReturnAllocsFromLoops; + } void getDependentDialects(DialectRegistry ®istry) const override { // clang-format off @@ -219,6 +222,7 @@ IRRewriter rewriter(funcOp->getContext()); moveUpMemrefReshapeOps(rewriter, funcOp); auto bufferizationOptions = getBufferizationOptions(); + bufferizationOptions.allowReturnAllocsFromLoops = allowReturnAllocsFromLoops; OneShotAnalysisState state(funcOp, bufferizationOptions); // Analyze IR. if (failed(analyzeOp(funcOp, state))) { @@ -273,6 +277,7 @@ IREEOneShotBufferizationOptions options = getBufferizationOptions(); options.testAnalysisOnly = testAnalysisOnly; options.printConflicts = printConflicts; + options.allowReturnAllocsFromLoops = allowReturnAllocsFromLoops; options.allocationFn = allocationFn; options.memCpyFn = memCpyFn; // Disable parallel-region conflict checks to avoid conservative copies. @@ -339,15 +344,17 @@ std::unique_ptr<InterfacePass<mlir::FunctionOpInterface>> createIREEComprehensiveBufferizePass( std::optional<BufferizationOptions::AllocationFn> allocationFn, - std::optional<BufferizationOptions::MemCpyFn> memCpyFn) { + std::optional<BufferizationOptions::MemCpyFn> memCpyFn, + LoopAllocationMode loopAllocationMode) { if (!allocationFn) { allocationFn = defaultAllocationFn; } if (!memCpyFn) { memCpyFn = defaultMemCpyFn; } - return std::make_unique<IREEComprehensiveBufferizePass>(allocationFn.value(), - memCpyFn.value()); + return std::make_unique<IREEComprehensiveBufferizePass>( + allocationFn.value(), memCpyFn.value(), + loopAllocationMode == LoopAllocationMode::CallerManagesLifetime); } void addIREEPostBufferizationPasses(OpPassManager &funcPassManager) { @@ -365,11 +372,16 @@ void addIREEComprehensiveBufferizePasses( OpPassManager &funcPassManager, std::optional<BufferizationOptions::AllocationFn> allocationFn, - std::optional<BufferizationOptions::MemCpyFn> memCpyFn) { - funcPassManager.addPass(createEliminateEmptyTensorsPass()); + std::optional<BufferizationOptions::MemCpyFn> memCpyFn, + LoopAllocationMode loopAllocationMode) { + const bool allowReturnAllocsFromLoops = + loopAllocationMode == LoopAllocationMode::CallerManagesLifetime; + EliminateEmptyTensorsPassOptions eliminateOptions; + eliminateOptions.allowReturnAllocsFromLoops = allowReturnAllocsFromLoops; + funcPassManager.addPass(createEliminateEmptyTensorsPass(eliminateOptions)); funcPassManager.addPass(bufferization::createEmptyTensorToAllocTensorPass()); - funcPassManager.addPass( - createIREEComprehensiveBufferizePass(allocationFn, memCpyFn)); + funcPassManager.addPass(createIREEComprehensiveBufferizePass( + allocationFn, memCpyFn, loopAllocationMode)); addIREEPostBufferizationPasses(funcPassManager); }
diff --git a/compiler/src/iree/compiler/Codegen/Common/Passes.h b/compiler/src/iree/compiler/Codegen/Common/Passes.h index f1c9273..ca99c4a 100644 --- a/compiler/src/iree/compiler/Codegen/Common/Passes.h +++ b/compiler/src/iree/compiler/Codegen/Common/Passes.h
@@ -55,11 +55,16 @@ void addIREEPostBufferizationPasses(OpPassManager &funcPassManager); using bufferization::BufferizationOptions; +enum class LoopAllocationMode { Disallow, CallerManagesLifetime }; +// Apply the loop-allocation policy consistently to empty-tensor analysis and +// bufferization. CallerManagesLifetime requires callers to arrange +// deallocation of loop-returned allocations after bufferization. void addIREEComprehensiveBufferizePasses( OpPassManager &funcPassManager, std::optional<BufferizationOptions::AllocationFn> allocationFn = std::nullopt, - std::optional<BufferizationOptions::MemCpyFn> memCpyFn = std::nullopt); + std::optional<BufferizationOptions::MemCpyFn> memCpyFn = std::nullopt, + LoopAllocationMode loopAllocationMode = LoopAllocationMode::Disallow); /// Populate Encoding to Nop pass and canonicalizer pass to the pipeline. void addEncodingToNopPasses(FunctionLikeNest &passManager); @@ -90,7 +95,8 @@ std::unique_ptr<InterfacePass<FunctionOpInterface>> createIREEComprehensiveBufferizePass( std::optional<BufferizationOptions::AllocationFn> allocationFn, - std::optional<BufferizationOptions::MemCpyFn> memCpyFn); + std::optional<BufferizationOptions::MemCpyFn> memCpyFn, + LoopAllocationMode loopAllocationMode = LoopAllocationMode::Disallow); /// Create an IREE-specific Transform dialect interpreter pass with all /// registrations necessary for IREE.
diff --git a/compiler/src/iree/compiler/Codegen/Common/Passes.td b/compiler/src/iree/compiler/Codegen/Common/Passes.td index ca0da66..b5be739 100644 --- a/compiler/src/iree/compiler/Codegen/Common/Passes.td +++ b/compiler/src/iree/compiler/Codegen/Common/Passes.td
@@ -519,6 +519,11 @@ def EliminateEmptyTensorsPass : InterfacePass<"iree-eliminate-empty-tensors", "mlir::FunctionOpInterface"> { let summary = "Eliminate tensor.empty ops to avoid buffer allocations"; + let options = [ + Option<"allowReturnAllocsFromLoops", "allow-return-allocs-from-loops", "bool", + /*default=*/"false", + "Allow newly allocated buffers to be returned from loops">, + ]; } def EmulateNarrowTypePass : @@ -764,6 +769,9 @@ InterfacePass<"iree-codegen-iree-comprehensive-bufferize", "mlir::FunctionOpInterface"> { let summary = "Convert from to Linalg ops on tensors to buffers"; let options = [ + Option<"allowReturnAllocsFromLoops", "allow-return-allocs-from-loops", "bool", + /*default=*/"false", + "Allow newly allocated buffers to be returned from loops">, Option<"testAnalysisOnly", "test-analysis-only", "bool", /*default=*/"false", "Only runs inplaceability analysis (for testing purposes only)">,
diff --git a/compiler/src/iree/compiler/Codegen/Common/test/BUILD.bazel b/compiler/src/iree/compiler/Codegen/Common/test/BUILD.bazel index a49caa6..623eaf3 100644 --- a/compiler/src/iree/compiler/Codegen/Common/test/BUILD.bazel +++ b/compiler/src/iree/compiler/Codegen/Common/test/BUILD.bazel
@@ -78,6 +78,8 @@ "iree_bufferize_constants.mlir", "iree_codegen_canonicalize.mlir", "iree_comprehensive_bufferize.mlir", + "iree_comprehensive_bufferize_loop_allocs.mlir", + "iree_comprehensive_bufferize_loop_allocs_invalid.mlir", "iree_expand_strided_metadata.mlir", "iree_expand_strided_metadata_with_subview_expansion.mlir", "iree_inject_assume_alignment.mlir",
diff --git a/compiler/src/iree/compiler/Codegen/Common/test/CMakeLists.txt b/compiler/src/iree/compiler/Codegen/Common/test/CMakeLists.txt index 9e293b4..b0c5465 100644 --- a/compiler/src/iree/compiler/Codegen/Common/test/CMakeLists.txt +++ b/compiler/src/iree/compiler/Codegen/Common/test/CMakeLists.txt
@@ -73,6 +73,8 @@ "iree_bufferize_constants.mlir" "iree_codegen_canonicalize.mlir" "iree_comprehensive_bufferize.mlir" + "iree_comprehensive_bufferize_loop_allocs.mlir" + "iree_comprehensive_bufferize_loop_allocs_invalid.mlir" "iree_expand_strided_metadata.mlir" "iree_expand_strided_metadata_with_subview_expansion.mlir" "iree_inject_assume_alignment.mlir"
diff --git a/compiler/src/iree/compiler/Codegen/Common/test/iree_comprehensive_bufferize_loop_allocs.mlir b/compiler/src/iree/compiler/Codegen/Common/test/iree_comprehensive_bufferize_loop_allocs.mlir new file mode 100644 index 0000000..570eeb2 --- /dev/null +++ b/compiler/src/iree/compiler/Codegen/Common/test/iree_comprehensive_bufferize_loop_allocs.mlir
@@ -0,0 +1,116 @@ +// RUN: iree-opt %s --split-input-file --pass-pipeline="builtin.module(func.func(iree-eliminate-empty-tensors{allow-return-allocs-from-loops=true},empty-tensor-to-alloc-tensor,iree-codegen-iree-comprehensive-bufferize{allow-return-allocs-from-loops=true}))" | FileCheck %s +// RUN: iree-opt %s --split-input-file --pass-pipeline="builtin.module(func.func(iree-codegen-iree-comprehensive-bufferize{allow-return-allocs-from-loops=true}))" | FileCheck %s +// RUN: iree-opt %s --split-input-file --pass-pipeline="builtin.module(func.func(iree-eliminate-empty-tensors{allow-return-allocs-from-loops=true},empty-tensor-to-alloc-tensor,iree-codegen-iree-comprehensive-bufferize{allow-return-allocs-from-loops=true},ownership-based-buffer-deallocation,buffer-deallocation-simplification,bufferization-lower-deallocations))" | FileCheck %s --check-prefix=OWNED + +// Opt-in permits fresh loop results. Ownership remains the caller's policy. +// CHECK-LABEL: func.func @for_yields_allocation( +// CHECK: %[[LOOP:.*]] = scf.for {{.*}} iter_args(%[[ITER:.*]] = {{.*}}) -> (memref<4xi32>) { +// CHECK: %[[ALLOC:.*]] = memref.alloc() : memref<4xi32> +// CHECK: linalg.generic {{.*}} ins(%[[ITER]] : memref<4xi32>) outs(%[[ALLOC]] : memref<4xi32>) +// CHECK: scf.yield %[[ALLOC]] : memref<4xi32> +// CHECK: return %[[LOOP]] : memref<4xi32> +// OWNED-LABEL: func.func @for_yields_allocation( +// OWNED: %[[FALSE:.*]] = arith.constant false +// OWNED: %[[LOOP:.*]]:2 = scf.for {{.*}} iter_args(%[[ITER:.*]] = {{.*}}, %[[OWNS:.*]] = %[[FALSE]]) +// OWNED: %[[ALLOC:.*]] = memref.alloc() +// OWNED: %[[BASE:[^, ]+]], {{.*}} = memref.extract_strided_metadata %[[ITER]] +// OWNED: scf.if %[[OWNS]] { +// OWNED: memref.dealloc %[[BASE]] +// OWNED: scf.yield %[[ALLOC]], {{.*}} : memref<4xi32>, i1 +// OWNED: %[[RESULT:.*]] = scf.if %[[LOOP]]#1 +// OWNED: scf.yield %[[LOOP]]#0 +// OWNED: } else { +// OWNED: bufferization.clone %[[LOOP]]#0 +// OWNED: return %[[RESULT]] : memref<4xi32> +func.func @for_yields_allocation(%input: memref<4xi32>, %count: index) -> memref<4xi32> { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %tensor = bufferization.to_tensor %input restrict writable : memref<4xi32> to tensor<4xi32> + %result = scf.for %i = %c0 to %count step %c1 iter_args(%iter = %tensor) -> tensor<4xi32> { + %copy = bufferization.alloc_tensor() copy(%iter) : tensor<4xi32> + scf.yield %copy : tensor<4xi32> + } + %buffer = bufferization.to_buffer %result : tensor<4xi32> to memref<4xi32> + return %buffer : memref<4xi32> +} + +// ----- + +// CHECK-LABEL: func.func @while_yields_allocation( +// CHECK: %[[LOOP:.*]] = scf.while +// CHECK: %[[BEFORE:.*]] = memref.alloc() +// CHECK: scf.condition({{.*}}) %[[BEFORE]] : memref<4xi32> +// CHECK: } do { +// CHECK: %[[AFTER:.*]] = memref.alloc() +// CHECK: scf.yield %[[AFTER]] : memref<4xi32> +// CHECK: return %[[LOOP]] : memref<4xi32> +// OWNED-LABEL: func.func @while_yields_allocation( +// OWNED: %[[FALSE:.*]] = arith.constant false +// OWNED: %[[LOOP:.*]]:2 = scf.while (%[[ITER:[^ ]+]] = {{.*}}, %[[OWNS:[^ ]+]] = %[[FALSE]]) +// OWNED: %[[BEFORE:.*]] = memref.alloc() +// OWNED: %[[BASE:[^, ]+]], {{.*}} = memref.extract_strided_metadata %[[ITER]] +// OWNED: scf.if %[[OWNS]] { +// OWNED: memref.dealloc %[[BASE]] +// OWNED: scf.condition({{.*}}) %[[BEFORE]], {{.*}} : memref<4xi32>, i1 +// OWNED: } do { +// OWNED: ^bb0(%[[ITER2:[^:]+]]: memref<4xi32>, %[[OWNS2:[^:]+]]: i1): +// OWNED: %[[AFTER:.*]] = memref.alloc() +// OWNED: %[[BASE2:[^, ]+]], {{.*}} = memref.extract_strided_metadata %[[ITER2]] +// OWNED: scf.if %[[OWNS2]] { +// OWNED: memref.dealloc %[[BASE2]] +// OWNED: scf.yield %[[AFTER]], {{.*}} : memref<4xi32>, i1 +// OWNED: %[[RESULT:.*]] = scf.if %[[LOOP]]#1 +// OWNED: scf.yield %[[LOOP]]#0 +// OWNED: } else { +// OWNED: bufferization.clone %[[LOOP]]#0 +// OWNED: return %[[RESULT]] : memref<4xi32> +func.func @while_yields_allocation(%input: memref<4xi32>, %condition: i1) -> memref<4xi32> { + %tensor = bufferization.to_tensor %input restrict writable : memref<4xi32> to tensor<4xi32> + %result = scf.while (%iter = %tensor) : (tensor<4xi32>) -> tensor<4xi32> { + scf.condition(%condition) %iter : tensor<4xi32> + } do { + ^bb0(%iter: tensor<4xi32>): + %copy = bufferization.alloc_tensor() copy(%iter) : tensor<4xi32> + scf.yield %copy : tensor<4xi32> + } + %buffer = bufferization.to_buffer %result : tensor<4xi32> to memref<4xi32> + return %buffer : memref<4xi32> +} + +// ----- + +// CHECK-LABEL: func.func @for_preserves_alias( +// CHECK: %[[LOOP:.*]] = scf.for {{.*}} iter_args(%[[ITER:.*]] = {{.*}}) +// CHECK-NOT: memref.alloc +// CHECK: scf.yield %[[ITER]] : memref<4xi32> +// CHECK: return %[[LOOP]] : memref<4xi32> +// OWNED-LABEL: func.func @for_preserves_alias( +// OWNED: bufferization.clone +// OWNED: return +func.func @for_preserves_alias(%input: memref<4xi32>, %count: index) -> memref<4xi32> { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %tensor = bufferization.to_tensor %input restrict writable : memref<4xi32> to tensor<4xi32> + %result = scf.for %i = %c0 to %count step %c1 iter_args(%iter = %tensor) -> tensor<4xi32> { + scf.yield %iter : tensor<4xi32> + } + %buffer = bufferization.to_buffer %result : tensor<4xi32> to memref<4xi32> + return %buffer : memref<4xi32> +} + +// ----- + +// CHECK-LABEL: func.func @copy_without_loop( +// CHECK: %[[ALLOC:.*]] = memref.alloc() +// CHECK: linalg.generic {{.*}} outs(%[[ALLOC]] : memref<4xi32>) +// CHECK: return %[[ALLOC]] : memref<4xi32> +// OWNED-LABEL: func.func @copy_without_loop( +// OWNED: %[[ALLOC:.*]] = memref.alloc() +// OWNED-NOT: memref.dealloc +// OWNED: return %[[ALLOC]] : memref<4xi32> +func.func @copy_without_loop(%input: memref<4xi32>) -> memref<4xi32> { + %tensor = bufferization.to_tensor %input restrict writable : memref<4xi32> to tensor<4xi32> + %copy = bufferization.alloc_tensor() copy(%tensor) : tensor<4xi32> + %buffer = bufferization.to_buffer %copy : tensor<4xi32> to memref<4xi32> + return %buffer : memref<4xi32> +}
diff --git a/compiler/src/iree/compiler/Codegen/Common/test/iree_comprehensive_bufferize_loop_allocs_invalid.mlir b/compiler/src/iree/compiler/Codegen/Common/test/iree_comprehensive_bufferize_loop_allocs_invalid.mlir new file mode 100644 index 0000000..f6b931e --- /dev/null +++ b/compiler/src/iree/compiler/Codegen/Common/test/iree_comprehensive_bufferize_loop_allocs_invalid.mlir
@@ -0,0 +1,34 @@ +// RUN: iree-opt %s --split-input-file --verify-diagnostics --pass-pipeline="builtin.module(func.func(iree-eliminate-empty-tensors))" +// RUN: iree-opt %s --split-input-file --verify-diagnostics --pass-pipeline="builtin.module(func.func(iree-eliminate-empty-tensors{allow-return-allocs-from-loops=false}))" +// RUN: iree-opt %s --split-input-file --verify-diagnostics --pass-pipeline="builtin.module(func.func(iree-codegen-iree-comprehensive-bufferize))" +// RUN: iree-opt %s --split-input-file --verify-diagnostics --pass-pipeline="builtin.module(func.func(iree-codegen-iree-comprehensive-bufferize{allow-return-allocs-from-loops=false}))" + +// Default and explicit false preserve the loop equivalence requirement. +func.func @for_yields_allocation(%input: memref<4xi32>, %count: index) -> memref<4xi32> { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %tensor = bufferization.to_tensor %input restrict writable : memref<4xi32> to tensor<4xi32> + %result = scf.for %i = %c0 to %count step %c1 iter_args(%iter = %tensor) -> tensor<4xi32> { + %copy = bufferization.alloc_tensor() copy(%iter) : tensor<4xi32> + // expected-error @+1 {{Yield operand #0 is not equivalent to the corresponding iter bbArg}} + scf.yield %copy : tensor<4xi32> + } + %buffer = bufferization.to_buffer %result : tensor<4xi32> to memref<4xi32> + return %buffer : memref<4xi32> +} + +// ----- + +func.func @while_yields_allocation(%input: memref<4xi32>, %condition: i1) -> memref<4xi32> { + %tensor = bufferization.to_tensor %input restrict writable : memref<4xi32> to tensor<4xi32> + %result = scf.while (%iter = %tensor) : (tensor<4xi32>) -> tensor<4xi32> { + scf.condition(%condition) %iter : tensor<4xi32> + } do { + ^bb0(%iter: tensor<4xi32>): + %copy = bufferization.alloc_tensor() copy(%iter) : tensor<4xi32> + // expected-error @+1 {{Yield operand #0 is not equivalent to the corresponding iter bbArg}} + scf.yield %copy : tensor<4xi32> + } + %buffer = bufferization.to_buffer %result : tensor<4xi32> to memref<4xi32> + return %buffer : memref<4xi32> +}
diff --git a/compiler/src/iree/compiler/Codegen/Common/unittests/BUILD.bazel b/compiler/src/iree/compiler/Codegen/Common/unittests/BUILD.bazel new file mode 100644 index 0000000..315b1f8 --- /dev/null +++ b/compiler/src/iree/compiler/Codegen/Common/unittests/BUILD.bazel
@@ -0,0 +1,30 @@ +# Copyright 2026 The IREE Authors +# Licensed under the Apache License v2.0 with LLVM Exceptions. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +load("//build_tools/bazel:build_defs.oss.bzl", "iree_compiler_cc_test") + +package( + features = ["layering_check"], + licenses = ["notice"], +) + +iree_compiler_cc_test( + name = "BufferizePassesTest", + srcs = ["BufferizePassesTest.cpp"], + deps = [ + "//compiler/src/iree/compiler/Codegen/Common", + "//compiler/src/iree/compiler/Codegen/Interfaces:BufferizationInterfaces", + "//compiler/src/iree/testing:gtest_main", + "@com_google_googletest//:gtest", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:ArithDialect", + "@llvm-project//mlir:BufferizationDialect", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:MemRefDialect", + "@llvm-project//mlir:Parser", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:SCFDialect", + ], +)
diff --git a/compiler/src/iree/compiler/Codegen/Common/unittests/BufferizePassesTest.cpp b/compiler/src/iree/compiler/Codegen/Common/unittests/BufferizePassesTest.cpp new file mode 100644 index 0000000..bbfd018 --- /dev/null +++ b/compiler/src/iree/compiler/Codegen/Common/unittests/BufferizePassesTest.cpp
@@ -0,0 +1,97 @@ +// Copyright 2026 The IREE Authors +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#include <iterator> +#include <string> +#include "gtest/gtest.h" + +#include "iree/compiler/Codegen/Common/Passes.h" +#include "iree/compiler/Codegen/Interfaces/BufferizationInterfaces.h" +#include "llvm/Support/raw_ostream.h" +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/Bufferization/IR/Bufferization.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" +#include "mlir/Dialect/MemRef/IR/MemRef.h" +#include "mlir/Dialect/SCF/IR/SCF.h" +#include "mlir/IR/BuiltinOps.h" +#include "mlir/IR/Diagnostics.h" +#include "mlir/IR/Verifier.h" +#include "mlir/Parser/Parser.h" +#include "mlir/Pass/PassManager.h" + +namespace mlir::iree_compiler { +namespace { +constexpr StringLiteral kLoop = R"mlir( +func.func @loop(%input: memref<4xi32>, %count: index) -> memref<4xi32> { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %tensor = bufferization.to_tensor %input restrict writable : memref<4xi32> to tensor<4xi32> + %result = scf.for %i = %c0 to %count step %c1 iter_args(%iter = %tensor) -> tensor<4xi32> { + %copy = bufferization.alloc_tensor() copy(%iter) : tensor<4xi32> + scf.yield %copy : tensor<4xi32> + } + %buffer = bufferization.to_buffer %result : tensor<4xi32> to memref<4xi32> + return %buffer : memref<4xi32> +} +)mlir"; + +class BufferizePassesTest : public ::testing::Test { +protected: + BufferizePassesTest() { + DialectRegistry registry; + registry + .insert<arith::ArithDialect, bufferization::BufferizationDialect, + func::FuncDialect, memref::MemRefDialect, scf::SCFDialect>(); + registerBufferizationInterfaces(registry); + context.appendDialectRegistry(registry); + } + MLIRContext context; +}; + +TEST_F(BufferizePassesTest, RejectsLoopAllocationsByDefault) { + auto module = parseSourceString<ModuleOp>(kLoop, &context); + ASSERT_TRUE(module); + std::string diagnostics; + llvm::raw_string_ostream stream(diagnostics); + ScopedDiagnosticHandler handler(&context, [&](Diagnostic &diagnostic) { + diagnostic.print(stream); + return success(); + }); + PassManager manager(&context); + addIREEComprehensiveBufferizePasses(manager.nest<func::FuncOp>()); + EXPECT_TRUE(failed(manager.run(*module))); + EXPECT_NE(diagnostics.find("not equivalent to the corresponding iter bbArg"), + std::string::npos) + << diagnostics; +} + +TEST_F(BufferizePassesTest, AllowsLoopAllocationsWithCustomCopy) { + auto module = parseSourceString<ModuleOp>(kLoop, &context); + ASSERT_TRUE(module); + auto copy = [](OpBuilder &builder, Location loc, Value from, Value to) { + memref::CopyOp::create(builder, loc, from, to); + return success(); + }; + PassManager manager(&context); + addIREEComprehensiveBufferizePasses( + manager.nest<func::FuncOp>(), + /*allocationFn=*/std::nullopt, copy, + LoopAllocationMode::CallerManagesLifetime); + ASSERT_TRUE(succeeded(manager.run(*module))); + ASSERT_TRUE(succeeded(verify(*module))); + scf::ForOp loop; + module->walk([&](scf::ForOp op) { loop = op; }); + ASSERT_TRUE(loop); + auto yield = cast<scf::YieldOp>(loop.getBody()->getTerminator()); + auto allocation = yield.getOperand(0).getDefiningOp<memref::AllocOp>(); + ASSERT_TRUE(allocation) << "Loop must yield its new allocation"; + EXPECT_EQ(allocation->getBlock(), loop.getBody()); + auto copies = loop.getBody()->getOps<memref::CopyOp>(); + ASSERT_EQ(std::distance(copies.begin(), copies.end()), 1); + auto copyOp = *copies.begin(); + EXPECT_EQ(copyOp.getSource(), loop.getRegionIterArgs().front()); + EXPECT_EQ(copyOp.getTarget(), allocation.getResult()); +} +} // namespace +} // namespace mlir::iree_compiler
diff --git a/compiler/src/iree/compiler/Codegen/Common/unittests/CMakeLists.txt b/compiler/src/iree/compiler/Codegen/Common/unittests/CMakeLists.txt new file mode 100644 index 0000000..275670f --- /dev/null +++ b/compiler/src/iree/compiler/Codegen/Common/unittests/CMakeLists.txt
@@ -0,0 +1,35 @@ +################################################################################ +# Autogenerated by build_tools/bazel_to_cmake/bazel_to_cmake.py from # +# compiler/src/iree/compiler/Codegen/Common/unittests/BUILD.bazel # +# # +# Use iree_cmake_extra_content from iree/build_defs.oss.bzl to add arbitrary # +# CMake-only content. # +# # +# To disable autogeneration for this file entirely, delete this header. # +################################################################################ + +iree_add_all_subdirs() + +iree_cc_test( + NAME + BufferizePassesTest + SRCS + "BufferizePassesTest.cpp" + DEPS + LLVMSupport + MLIRArithDialect + MLIRBufferizationDialect + MLIRFuncDialect + MLIRIR + MLIRMemRefDialect + MLIRParser + MLIRPass + MLIRSCFDialect + gmock + gtest + iree::compiler::Codegen::Common + iree::compiler::Codegen::Interfaces::BufferizationInterfaces + iree::testing::gtest_main +) + +### BAZEL_TO_CMAKE_PRESERVES_ALL_CONTENT_BELOW_THIS_LINE ###