Skip to content

Commit 40eb20c

Browse files
andrey-golubevmahesh-attarde
authored andcommitted
[mlir][bufferization] Support custom types at function boundaries (llvm#159766)
Support custom types (3/N): allow custom tensor and buffer types in function signatures and at call-sites. This is one of the major building blocks to move in the direction of module-level one-shot-bufferization support. To achieve this, `BufferizationOptions::FunctionArgTypeConverterFn` callback is converted to work with tensor-like and buffer-like types, instead of the builtin counterparts. The default behavior for builtins remains unchanged, while custom types by default go through `TensorLikeType::getBufferType()` which is a general conversion interface.
1 parent bde00ca commit 40eb20c

File tree

5 files changed

+155
-59
lines changed

5 files changed

+155
-59
lines changed

mlir/include/mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -260,12 +260,12 @@ struct BufferizationOptions {
260260
std::function<LogicalResult(OpBuilder &, Location, Value, Value)>;
261261
/// Initializer function for analysis state.
262262
using AnalysisStateInitFn = std::function<void(AnalysisState &)>;
263-
/// Tensor -> MemRef type converter.
264-
/// Parameters: tensor type, memory space, func op, bufferization options
263+
/// Tensor-like -> Buffer-like type conversion.
264+
/// Parameters: tensor-like type, memory space, func op, bufferization options
265265
using FunctionArgTypeConverterFn =
266-
std::function<BaseMemRefType(TensorType, Attribute memorySpace,
266+
std::function<BufferLikeType(TensorLikeType, Attribute memorySpace,
267267
func::FuncOp, const BufferizationOptions &)>;
268-
/// Tensor -> MemRef type converter.
268+
/// Tensor -> MemRef type conversion.
269269
/// Parameters: tensor type, memory space, bufferization options
270270
using UnknownTypeConverterFn = std::function<BaseMemRefType(
271271
TensorType, Attribute memorySpace, const BufferizationOptions &)>;
@@ -335,10 +335,12 @@ struct BufferizationOptions {
335335
/// predictable.
336336
void setFunctionBoundaryTypeConversion(LayoutMapOption layoutMapOption);
337337

338-
/// Type converter from tensors to memrefs. This type converter is used to
339-
/// determine bufferized function argument and result types. By default, a
340-
/// type converter that returns a memref type with a fully dynamic layout map
341-
/// is used.
338+
/// Type conversion from tensors to buffers. This type conversion is used to
339+
/// determine bufferized function argument and result types.
340+
///
341+
/// By default, if tensor is a (builtin) tensor type, it is converted to a
342+
/// memref type with a fully dynamic layout map; if tensor is a (generic)
343+
/// tensor-like type, it is converted using TensorLikeType::getBufferType().
342344
///
343345
/// If `bufferizeFunctionBoundaries` is not set, this function isn't used.
344346
FunctionArgTypeConverterFn functionArgTypeConverterFn = nullptr;
@@ -350,10 +352,9 @@ struct BufferizationOptions {
350352
/// If `bufferizeFunctionBoundaries` is not set, this flag has no effect.
351353
bool inferFunctionResultLayout = true;
352354

353-
/// Type converter from tensors to memrefs. This type converter is used if no
354-
/// memref type could be inferred during bufferization. By default, a type
355-
/// converter that returns a memref type with a fully dynamic layout map is
356-
/// used.
355+
/// Type conversion from tensors to memrefs. This type conversion is used if
356+
/// no memref type could be inferred during bufferization. By default, returns
357+
/// a memref type with a fully dynamic layout map.
357358
UnknownTypeConverterFn unknownTypeConverterFn = nullptr;
358359

359360
// Use during type conversion to determine the memory space for memref based

mlir/lib/Dialect/Bufferization/IR/BufferizableOpInterface.cpp

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -338,11 +338,21 @@ bool OpFilter::isOpAllowed(Operation *op) const {
338338
namespace {
339339

340340
/// Default function arg type converter: Use a fully dynamic layout map.
341-
BaseMemRefType
342-
defaultFunctionArgTypeConverter(TensorType type, Attribute memorySpace,
341+
BufferLikeType
342+
defaultFunctionArgTypeConverter(TensorLikeType type, Attribute memorySpace,
343343
func::FuncOp funcOp,
344344
const BufferizationOptions &options) {
345-
return getMemRefTypeWithFullyDynamicLayout(type, memorySpace);
345+
if (auto tensorType = mlir::dyn_cast<TensorType>(type)) {
346+
return cast<BufferLikeType>(
347+
getMemRefTypeWithFullyDynamicLayout(tensorType, memorySpace));
348+
}
349+
350+
// If not builtin, fallback to TensorLikeType::getBufferType()
351+
auto bufferType =
352+
type.getBufferType(options, [&]() { return funcOp->emitError(); });
353+
assert(succeeded(bufferType) &&
354+
"a valid buffer is always expected at function boundary");
355+
return *bufferType;
346356
}
347357
/// Default unknown type converter: Use a fully dynamic layout map.
348358
BaseMemRefType
@@ -385,14 +395,25 @@ BufferizationOptions::dynCastBufferizableOp(Value value) const {
385395

386396
void BufferizationOptions::setFunctionBoundaryTypeConversion(
387397
LayoutMapOption layoutMapOption) {
388-
functionArgTypeConverterFn = [=](TensorType tensorType, Attribute memorySpace,
398+
functionArgTypeConverterFn = [=](TensorLikeType type, Attribute memorySpace,
389399
func::FuncOp funcOp,
390400
const BufferizationOptions &options) {
391-
if (layoutMapOption == LayoutMapOption::IdentityLayoutMap)
392-
return bufferization::getMemRefTypeWithStaticIdentityLayout(tensorType,
393-
memorySpace);
394-
return bufferization::getMemRefTypeWithFullyDynamicLayout(tensorType,
395-
memorySpace);
401+
if (auto tensorType = mlir::dyn_cast<TensorType>(type)) {
402+
if (layoutMapOption == LayoutMapOption::IdentityLayoutMap)
403+
return cast<BufferLikeType>(
404+
bufferization::getMemRefTypeWithStaticIdentityLayout(tensorType,
405+
memorySpace));
406+
return cast<BufferLikeType>(
407+
bufferization::getMemRefTypeWithFullyDynamicLayout(tensorType,
408+
memorySpace));
409+
}
410+
411+
// If not builtin, fallback to TensorLikeType::getBufferType()
412+
auto bufferType =
413+
type.getBufferType(options, [&]() { return funcOp->emitError(); });
414+
assert(succeeded(bufferType) &&
415+
"a valid buffer is always expected at function boundary");
416+
return *bufferType;
396417
};
397418
inferFunctionResultLayout =
398419
layoutMapOption == LayoutMapOption::InferLayoutMap;

mlir/lib/Dialect/Bufferization/Transforms/Bufferize.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ bufferization::bufferizeBlockSignature(Block *block, RewriterBase &rewriter,
401401
// Compute the new signature.
402402
SmallVector<Type> newTypes;
403403
for (BlockArgument &bbArg : block->getArguments()) {
404-
auto tensorType = dyn_cast<TensorType>(bbArg.getType());
404+
auto tensorType = dyn_cast<TensorLikeType>(bbArg.getType());
405405
if (!tensorType) {
406406
newTypes.push_back(bbArg.getType());
407407
continue;

mlir/lib/Dialect/Bufferization/Transforms/FuncBufferizableOpInterfaceImpl.cpp

Lines changed: 55 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -49,29 +49,47 @@ void FuncAnalysisState::startFunctionAnalysis(FuncOp funcOp) {
4949
#endif // NDEBUG
5050
}
5151

52+
// Note: this is a local adaptor to unify TensorType and TensorLikeType code
53+
// paths that both work with BufferizationOptions.
54+
static mlir::Attribute
55+
getDefaultMemorySpace(const BufferizationOptions &options,
56+
TensorLikeType type) {
57+
if (auto tensorType = dyn_cast<TensorType>(type)) {
58+
return *options.defaultMemorySpaceFn(tensorType);
59+
}
60+
return nullptr;
61+
}
62+
5263
/// Return the index-th bufferized function argument type. This assumes that the
5364
/// specified argument is a tensor. If the tensor is ranked, a layout map may be
5465
/// specified by the user (as per `options.functionArgTypeConverterFn`).
55-
static BaseMemRefType
66+
static BufferLikeType
5667
getBufferizedFunctionArgType(FuncOp funcOp, int64_t index,
5768
const BufferizationOptions &options) {
58-
auto tensorType =
59-
dyn_cast<TensorType>(funcOp.getFunctionType().getInput(index));
60-
assert(tensorType && "expected TensorType");
61-
62-
BaseMemRefType memrefType = options.functionArgTypeConverterFn(
63-
tensorType, *options.defaultMemorySpaceFn(tensorType), funcOp, options);
64-
65-
auto layoutAttr = funcOp.getArgAttrOfType<MemRefLayoutAttrInterface>(
66-
index, BufferizationDialect::kBufferLayoutAttrName);
67-
if (!layoutAttr)
68-
return memrefType;
69-
70-
auto rankedMemrefType = dyn_cast<MemRefType>(memrefType);
71-
assert(rankedMemrefType && "buffer layout not supported on unranked tensors");
72-
return MemRefType::get(rankedMemrefType.getShape(),
73-
rankedMemrefType.getElementType(), layoutAttr,
74-
rankedMemrefType.getMemorySpace());
69+
auto type =
70+
dyn_cast<TensorLikeType>(funcOp.getFunctionType().getInput(index));
71+
assert(type && "expected TensorLikeType");
72+
73+
// Note: For builtin tensors there is additional logic related to layout.
74+
if (auto tensorType = dyn_cast<TensorType>(type)) {
75+
BufferLikeType memrefType = options.functionArgTypeConverterFn(
76+
type, *options.defaultMemorySpaceFn(tensorType), funcOp, options);
77+
78+
auto layoutAttr = funcOp.getArgAttrOfType<MemRefLayoutAttrInterface>(
79+
index, BufferizationDialect::kBufferLayoutAttrName);
80+
if (!layoutAttr)
81+
return memrefType;
82+
83+
auto rankedMemrefType = dyn_cast<MemRefType>(memrefType);
84+
assert(rankedMemrefType &&
85+
"buffer layout not supported on unranked tensors");
86+
return cast<BufferLikeType>(MemRefType::get(
87+
rankedMemrefType.getShape(), rankedMemrefType.getElementType(),
88+
layoutAttr, rankedMemrefType.getMemorySpace()));
89+
}
90+
91+
return options.functionArgTypeConverterFn(type, /*memSpace=*/nullptr, funcOp,
92+
options);
7593
}
7694

7795
/// Return the FuncOp called by `callOp`.
@@ -227,13 +245,13 @@ struct CallOpInterface
227245
FunctionType funcType = funcOp.getFunctionType();
228246
Type resultType =
229247
funcType.getResult(cast<OpResult>(value).getResultNumber());
230-
if (auto bufferizedType = dyn_cast<BaseMemRefType>(resultType))
231-
return cast<BufferLikeType>(bufferizedType);
248+
if (auto bufferizedType = dyn_cast<BufferLikeType>(resultType))
249+
return bufferizedType;
232250

233251
// Otherwise, call the type converter to compute the bufferized type.
234-
auto tensorType = cast<TensorType>(resultType);
252+
auto tensorType = cast<TensorLikeType>(resultType);
235253
return cast<BufferLikeType>(options.functionArgTypeConverterFn(
236-
tensorType, *options.defaultMemorySpaceFn(tensorType), funcOp,
254+
tensorType, getDefaultMemorySpace(options, tensorType), funcOp,
237255
options));
238256
}
239257

@@ -248,7 +266,7 @@ struct CallOpInterface
248266
SmallVector<Type> resultTypes;
249267
for (Value result : callOp.getResults()) {
250268
Type returnType = result.getType();
251-
if (!isa<TensorType>(returnType)) {
269+
if (!isa<TensorLikeType>(returnType)) {
252270
// Non-tensor values are returned.
253271
resultTypes.push_back(returnType);
254272
continue;
@@ -272,7 +290,7 @@ struct CallOpInterface
272290

273291
for (OpOperand &opOperand : callOp->getOpOperands()) {
274292
// Non-tensor operands are just copied.
275-
if (!isa<TensorType>(opOperand.get().getType())) {
293+
if (!isa<TensorLikeType>(opOperand.get().getType())) {
276294
newOperands.push_back(opOperand.get());
277295
continue;
278296
}
@@ -285,8 +303,8 @@ struct CallOpInterface
285303
Value buffer = *maybeBuffer;
286304

287305
// Caller / callee type mismatch is handled with castOrReallocMemRefValue.
288-
auto memRefType = funcType.getInput(opOperand.getOperandNumber());
289-
if (!isa<BaseMemRefType>(memRefType)) {
306+
auto bufferType = funcType.getInput(opOperand.getOperandNumber());
307+
if (!isa<BufferLikeType>(bufferType)) {
290308
// The called function was not bufferized yet. This can happen when
291309
// there cycles in the function call graph. Compute the bufferized
292310
// result type.
@@ -296,7 +314,7 @@ struct CallOpInterface
296314
state);
297315
if (failed(maybeBufferType))
298316
return failure();
299-
memRefType = *maybeBufferType;
317+
bufferType = *maybeBufferType;
300318
}
301319

302320
// Since we don't yet have a clear layout story, to_buffer may
@@ -305,8 +323,8 @@ struct CallOpInterface
305323
// that will either canonicalize away or fail compilation until we can do
306324
// something better. Insert a reallocation + copy if it cannot be
307325
// statically guaranteed that a direct cast would be valid.
308-
if (buffer.getType() != memRefType) {
309-
auto memrefDstType = dyn_cast<MemRefType>(memRefType);
326+
if (buffer.getType() != bufferType) {
327+
auto memrefDstType = dyn_cast<MemRefType>(bufferType);
310328
assert(memrefDstType &&
311329
"buffer layout not supported on unranked tensors");
312330
FailureOr<Value> replacement = bufferization::castOrReallocMemRefValue(
@@ -370,7 +388,7 @@ struct FuncOpInterface
370388
static bool supportsUnstructuredControlFlow() { return true; }
371389

372390
bool hasTensorSemantics(Operation *op) const {
373-
auto isaTensor = llvm::IsaPred<TensorType>;
391+
auto isaTensor = llvm::IsaPred<TensorLikeType>;
374392

375393
// A function has tensor semantics if it has tensor arguments/results.
376394
auto funcOp = cast<FuncOp>(op);
@@ -406,8 +424,8 @@ struct FuncOpInterface
406424

407425
// Function arguments are special.
408426
if (bbArg.getOwner() == &funcOp.getBody().front())
409-
return cast<BufferLikeType>(
410-
getBufferizedFunctionArgType(funcOp, bbArg.getArgNumber(), options));
427+
return getBufferizedFunctionArgType(funcOp, bbArg.getArgNumber(),
428+
options);
411429

412430
return OpWithUnstructuredControlFlowBufferizableOpInterfaceExternalModel::
413431
getBufferType(op, value, options, state, invocationStack);
@@ -430,7 +448,7 @@ struct FuncOpInterface
430448
SmallVector<Type> argTypes;
431449
for (const auto &it : llvm::enumerate(funcType.getInputs())) {
432450
Type argType = it.value();
433-
if (isa<TensorType>(argType)) {
451+
if (isa<TensorLikeType>(argType)) {
434452
argTypes.push_back(
435453
getBufferizedFunctionArgType(funcOp, it.index(), options));
436454
continue;
@@ -441,9 +459,9 @@ struct FuncOpInterface
441459
// Compute the result types.
442460
SmallVector<Type> retTypes;
443461
for (Type resultType : funcType.getResults()) {
444-
if (auto tensorType = dyn_cast<TensorType>(resultType)) {
445-
BaseMemRefType resultType = options.functionArgTypeConverterFn(
446-
tensorType, *options.defaultMemorySpaceFn(tensorType), funcOp,
462+
if (auto tensorType = dyn_cast<TensorLikeType>(resultType)) {
463+
BufferLikeType resultType = options.functionArgTypeConverterFn(
464+
tensorType, getDefaultMemorySpace(options, tensorType), funcOp,
447465
options);
448466
retTypes.push_back(resultType);
449467
continue;
@@ -473,7 +491,7 @@ struct FuncOpInterface
473491
SmallVector<Value> returnValues;
474492
for (auto [returnVal, bufferizedType] :
475493
llvm::zip_equal(returnOp->getOperands(), retTypes)) {
476-
auto tensorType = dyn_cast<TensorType>(returnVal.getType());
494+
auto tensorType = dyn_cast<TensorLikeType>(returnVal.getType());
477495
rewriter.setInsertionPoint(returnOp);
478496

479497
// If not a tensor type just forward it.

mlir/test/Dialect/Bufferization/Transforms/one-shot-module-bufferize.mlir

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -810,3 +810,59 @@ module @inner_module {
810810
return %t : tensor<5xf32>
811811
}
812812
}
813+
814+
// -----
815+
816+
// CHECK: func.func @custom_types(
817+
// CHECK-SAME: %[[arg:.*]]: !test.test_memref<[4, 4], f64>
818+
// CHECK-SAME: ) -> (!test.test_memref<[4, 8], f64>,
819+
// CHECK-SAME: !test.test_memref<[4, 8], f64>)
820+
func.func @custom_types(%arg: !test.test_tensor<[4, 4], f64>)
821+
-> (!test.test_tensor<[4, 8], f64>, !test.test_tensor<[4, 8], f64>) {
822+
// CHECK: %[[out1:.*]] = "test.dummy_memref_op"(%[[arg]]) :
823+
// CHECK-SAME: (!test.test_memref<[4, 4], f64>) -> !test.test_memref<[4, 8], f64>
824+
%out1 = "test.dummy_tensor_op"(%arg) : (!test.test_tensor<[4, 4], f64>)
825+
-> !test.test_tensor<[4, 8], f64>
826+
827+
// CHECK: %[[alloc:.*]] = "test.create_memref_op"
828+
// CHECK: %[[out2:.*]] = "test.dummy_memref_op"(%[[alloc]])
829+
// CHECK-SAME: (!test.test_memref<[4, 4], f64>) -> !test.test_memref<[4, 8], f64>
830+
%alloc = "test.create_tensor_op"() : () -> !test.test_tensor<[4, 4], f64>
831+
%out2 = "test.dummy_tensor_op"(%alloc) : (!test.test_tensor<[4, 4], f64>)
832+
-> !test.test_tensor<[4, 8], f64>
833+
834+
// CHECK: return %[[out1]], %[[out2]]
835+
return %out1, %out2 :
836+
!test.test_tensor<[4, 8], f64>, !test.test_tensor<[4, 8], f64>
837+
}
838+
839+
// -----
840+
841+
// CHECK: func.func @custom_types_foo(
842+
// CHECK-SAME: %[[arg:.*]]: !test.test_memref<[4, 4], f64>
843+
// CHECK-SAME: ) -> !test.test_memref<[4, 4], f64>
844+
func.func @custom_types_foo(%arg: !test.test_tensor<[4, 4], f64>)
845+
-> !test.test_tensor<[4, 4], f64> {
846+
// CHECK: %[[out:.*]] = "test.dummy_memref_op"(%[[arg]])
847+
%out = "test.dummy_tensor_op"(%arg) : (!test.test_tensor<[4, 4], f64>)
848+
-> !test.test_tensor<[4, 4], f64>
849+
// CHECK: return %[[out]]
850+
return %out : !test.test_tensor<[4, 4], f64>
851+
}
852+
853+
// CHECK: func.func @custom_types_bar(
854+
// CHECK-SAME: %[[arg:.*]]: !test.test_memref<[4, 4], f64>
855+
// CHECK-SAME: ) -> !test.test_memref<[4, 8], f64>
856+
func.func @custom_types_bar(%arg: !test.test_tensor<[4, 4], f64>)
857+
-> !test.test_tensor<[4, 8], f64> {
858+
// CHECK: %[[call:.*]] = call @custom_types_foo(%[[arg]])
859+
%call = func.call @custom_types_foo(%arg) : (!test.test_tensor<[4, 4], f64>)
860+
-> !test.test_tensor<[4, 4], f64>
861+
862+
// CHECK: %[[out:.*]] = "test.dummy_memref_op"(%[[call]])
863+
%out = "test.dummy_tensor_op"(%call) : (!test.test_tensor<[4, 4], f64>)
864+
-> !test.test_tensor<[4, 8], f64>
865+
866+
// CHECK: return %[[out]]
867+
return %out : !test.test_tensor<[4, 8], f64>
868+
}

0 commit comments

Comments
 (0)