24 for (
Block &
b : funcOp.getBody())
25 if (
auto returnOp = dyn_cast<func::ReturnOp>(
b.getTerminator()))
26 result.push_back(returnOp);
36 auto createdAliasingResults =
42 (
void)createdAliasingResults;
45 (
void)createdWritable;
47 assert(createdEquiv.second &&
"equivalence info exists already");
48 assert(createdAliasingResults.second &&
"aliasing info exists already");
49 assert(createdRead.second &&
"bbarg access info exists already");
50 assert(createdWritten.second &&
"bbarg access info exists already");
51 assert(createdWritable.second &&
52 "return value writability info exists already");
59static FailureOr<Attribute>
63 dyn_cast<TensorLikeType>(funcOp.getFunctionType().getResult(
index));
64 assert(type &&
"expected TensorLikeType");
66 auto memorySpace =
options.defaultMemorySpaceFn(type);
68 return funcOp.emitError(
"could not infer memory space for result #")
78static FailureOr<BufferLikeType>
82 dyn_cast<TensorLikeType>(funcOp.getFunctionType().getInput(
index));
83 assert(type &&
"expected TensorLikeType");
85 auto memorySpace =
options.defaultMemorySpaceFn(type);
87 return funcOp.emitError(
"could not infer memory space for argument #")
89 BufferLikeType bufferType =
90 options.functionArgTypeConverterFn(type, *memorySpace, funcOp,
options);
93 if (isa<TensorType>(type)) {
94 auto layoutAttr = funcOp.getArgAttrOfType<MemRefLayoutAttrInterface>(
95 index, BufferizationDialect::kBufferLayoutAttrName);
99 auto rankedMemrefType = dyn_cast<MemRefType>(bufferType);
100 assert(rankedMemrefType &&
101 "buffer layout not supported on unranked tensors");
102 return cast<BufferLikeType>(MemRefType::get(
103 rankedMemrefType.getShape(), rankedMemrefType.getElementType(),
104 layoutAttr, rankedMemrefType.getMemorySpace()));
113 return dyn_cast_or_null<FuncOp>(callOp.resolveCallableInTable(&symbolTables));
119 if (isa<OneShotAnalysisState>(state)) {
120 auto &oneShotAnalysisState =
122 if (
auto *funcAnalysisState =
134static const FuncAnalysisState &
136 assert(isa<OneShotAnalysisState>(state) &&
"expected OneShotAnalysisState");
138 .getExtension<FuncAnalysisState>();
139 assert(
result &&
"FuncAnalysisState does not exist");
146 if (!isa<OneShotAnalysisState>(state))
149 .getExtension<FuncAnalysisState>();
152 const auto &analyzedFuncOps = funcState->analyzedFuncOps;
153 auto it = analyzedFuncOps.find(funcOp);
154 if (it == analyzedFuncOps.end())
161static std::optional<int64_t>
169 auto retValIt = funcOpIt->getSecond().find(returnValIdx);
170 if (retValIt == funcOpIt->getSecond().end())
174 return retValIt->getSecond();
178 :
public BufferizableOpInterface::ExternalModel<CallOpInterface,
182 func::CallOp callOp = cast<func::CallOp>(op);
184 assert(funcOp &&
"expected CallOp to a FuncOp");
191 return funcState.
readBbArgs.lookup(funcOp).contains(
197 func::CallOp callOp = cast<func::CallOp>(op);
199 assert(funcOp &&
"expected CallOp to a FuncOp");
212 func::CallOp callOp = cast<func::CallOp>(op);
214 assert(funcOp &&
"expected CallOp to a FuncOp");
217 return detail::unknownGetAliasingValues(opOperand);
221 auto aliasingReturnVals =
226 std::optional<int64_t> equivalent = {};
227 if (aliasingReturnVals.size() == 1) {
229 aliasingReturnVals.front());
230 assert((!equivalent.has_value() ||
232 "inconsistent analysis state");
235 for (
int64_t resultIdx : aliasingReturnVals)
236 result.addAlias({callOp->getOpResult(resultIdx),
237 equivalent.has_value() ? BufferRelation::Equivalent
238 : BufferRelation::Unknown,
239 equivalent.has_value()});
245 auto callOp = cast<func::CallOp>(op);
247 assert(funcOp &&
"expected CallOp to a FuncOp");
255 cast<OpResult>(value).getResultNumber());
258 FailureOr<BufferLikeType>
260 const BufferizationState &state,
262 auto callOp = cast<func::CallOp>(op);
266 assert(funcOp &&
"expected CallOp to a FuncOp");
267 int64_t resultIdx = cast<OpResult>(value).getResultNumber();
271 FunctionType funcType = funcOp.getFunctionType();
272 Type resultType = funcType.getResult(resultIdx);
273 if (
auto bufferizedType = dyn_cast<BufferLikeType>(resultType))
274 return bufferizedType;
277 auto tensorType = cast<TensorLikeType>(resultType);
279 if (failed(memorySpace))
281 return options.functionArgTypeConverterFn(tensorType, *memorySpace, funcOp,
289 BufferizationState &state)
const {
290 func::CallOp callOp = cast<func::CallOp>(op);
296 if (!isa<TensorLikeType>(returnType)) {
298 resultTypes.push_back(returnType);
303 FailureOr<BufferLikeType> resultType =
305 if (failed(resultType))
307 resultTypes.push_back(*resultType);
315 assert(funcOp &&
"expected CallOp to a FuncOp");
316 FunctionType funcType = funcOp.getFunctionType();
318 for (
OpOperand &opOperand : callOp->getOpOperands()) {
320 if (!isa<TensorLikeType>(opOperand.get().getType())) {
321 newOperands.push_back(opOperand.get());
326 FailureOr<Value> maybeBuffer =
327 getBuffer(rewriter, opOperand.get(),
options, state);
328 if (failed(maybeBuffer))
330 Value buffer = *maybeBuffer;
333 auto bufferType = funcType.getInput(opOperand.getOperandNumber());
334 if (!isa<BufferLikeType>(bufferType)) {
338 FailureOr<BufferLikeType> maybeBufferType =
339 bufferization::getBufferType(
340 funcOp.getArgument(opOperand.getOperandNumber()),
options,
342 if (failed(maybeBufferType))
344 bufferType = *maybeBufferType;
353 if (buffer.
getType() != bufferType) {
354 auto memrefDstType = dyn_cast<MemRefType>(bufferType);
355 assert(memrefDstType &&
356 "buffer layout not supported on unranked tensors");
364 newOperands.push_back(buffer);
368 func::CallOp newCallOp =
369 func::CallOp::create(rewriter, callOp.getLoc(), resultTypes,
370 newOperands, callOp.getProperties(),
371 callOp->getDiscardableAttrDictionary().getValue());
374 replaceOpWithBufferizedValues(rewriter, callOp, newCallOp->getResults());
381 :
public BufferizableOpInterface::ExternalModel<ReturnOpInterface,
400 BufferizationState &state)
const {
402 auto returnOp = cast<func::ReturnOp>(op);
403 assert(isa<FuncOp>(returnOp->getParentOp()) &&
404 "only support FuncOp parent for ReturnOp");
414 FuncOpInterface, FuncOp> {
419 auto isaTensor = llvm::IsaPred<TensorLikeType>;
422 auto funcOp = cast<FuncOp>(op);
423 bool hasTensorArg = any_of(funcOp.getArgumentTypes(),
isaTensor);
424 bool hasTensorResult = any_of(funcOp.getResultTypes(),
isaTensor);
425 if (hasTensorArg || hasTensorResult)
433 for (
Block &block : funcOp.getBody())
434 if (any_of(block.getArgumentTypes(),
isaTensor))
440 AliasingOpOperandList
446 FailureOr<BufferLikeType>
448 const BufferizationState &state,
450 auto funcOp = cast<FuncOp>(op);
451 auto bbArg = cast<BlockArgument>(value);
454 if (bbArg.getOwner() == &funcOp.getBody().front())
471 BufferizationState &state)
const {
472 auto funcOp = cast<FuncOp>(op);
473 FunctionType funcType = funcOp.getFunctionType();
477 for (
const auto &it : llvm::enumerate(funcType.getInputs())) {
478 Type argType = it.value();
479 if (isa<TensorLikeType>(argType)) {
480 auto bufferizedArgType =
482 if (failed(bufferizedArgType))
484 argTypes.push_back(*bufferizedArgType);
487 argTypes.push_back(argType);
492 for (
auto [
index, resultType] : llvm::enumerate(funcType.getResults())) {
493 if (
auto tensorType = dyn_cast<TensorLikeType>(resultType)) {
495 if (failed(memorySpace))
497 BufferLikeType resultType =
options.functionArgTypeConverterFn(
498 tensorType, *memorySpace, funcOp,
options);
499 retTypes.push_back(resultType);
502 retTypes.push_back(resultType);
506 auto newFuncType = FunctionType::get(op->
getContext(), argTypes, retTypes);
509 if (funcOp.isExternal()) {
510 funcOp.setType(newFuncType);
515 for (
Block &block : funcOp.getBody())
522 assert(returnOp->getNumOperands() == retTypes.size() &&
523 "incorrect number of return values");
525 for (
auto [returnVal, bufferizedType] :
526 llvm::zip_equal(returnOp->getOperands(), retTypes)) {
527 auto tensorType = dyn_cast<TensorLikeType>(returnVal.getType());
532 returnValues.push_back(returnVal);
538 Value toBufferOp = bufferization::ToBufferOp::create(
539 rewriter, returnOp.getLoc(), bufferizedType, returnVal);
540 returnValues.push_back(toBufferOp);
543 returnOp.getOperandsMutable().assign(returnValues);
547 funcOp.setType(newFuncType);
554 auto funcOp = cast<FuncOp>(op);
556 assert(bbArg &&
"expected BlockArgument");
566 bbArg.
getArgNumber(), BufferizationDialect::kWritableAttrName))
567 return writable.getValue();
581 func::CallOp::attachInterface<func_ext::CallOpInterface>(*ctx);
582 func::FuncOp::attachInterface<func_ext::FuncOpInterface>(*ctx);
583 func::ReturnOp::attachInterface<func_ext::ReturnOpInterface>(*ctx);
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
static bool isaTensor(Type t)
static llvm::ManagedStatic< PassManagerOptions > options
Base class for generic analysis states.
This class represents an argument of a Block.
unsigned getArgNumber() const
Returns the number of this argument.
Block * getOwner() const
Returns the block that owns this argument.
Block represents an ordered list of Operations.
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
MLIRContext is the top-level object for a collection of MLIR operations.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
This class represents an operand of an operation.
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
Operation is the basic unit of execution within MLIR.
MLIRContext * getContext()
Return the context this operation is associated with.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
This class represents a collection of SymbolTables.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
State for analysis-enabled bufferization.
static FailureOr< Attribute > getFunctionResultMemorySpace(FuncOp funcOp, int64_t index, const BufferizationOptions &options)
Return the memory space for the index-th function result.
FuncOpAnalysisState
The state of analysis of a FuncOp.
void registerBufferizableOpInterfaceExternalModels(DialectRegistry ®istry)
static FuncOp getCalledFunction(CallOpInterface callOp, SymbolTableCollection &symbolTables)
Return the FuncOp called by callOp.
static std::optional< int64_t > getEquivalentFuncArgIdx(FuncOp funcOp, const FuncAnalysisState &state, int64_t returnValIdx)
Return the index of the bbArg in the given FuncOp that is equivalent to the specified return value (i...
static FuncOpAnalysisState getFuncOpAnalysisState(const AnalysisState &state, FuncOp funcOp)
Return the state (phase) of analysis of the FuncOp.
static const FuncAnalysisState & getFuncAnalysisState(const AnalysisState &state)
Get FuncAnalysisState.
static FailureOr< BufferLikeType > getBufferizedFunctionArgType(FuncOp funcOp, int64_t index, const BufferizationOptions &options)
Return the index-th bufferized function argument type.
FailureOr< Value > castOrReallocMemRefValue(OpBuilder &b, Value value, MemRefType type, const BufferizationOptions &options)
Try to cast the given ranked MemRef-typed value to the given ranked MemRef type.
SmallVector< func::ReturnOp > getReturnOps(func::FuncOp funcOp)
Helper function that returns all func.return ops in the given function.
LogicalResult bufferizeBlockSignature(Block *block, RewriterBase &rewriter, const BufferizationOptions &options, BufferizationState &state)
Bufferize the signature of block and its callers (i.e., ops that have the given block as a successor)...
Include the generated interface declarations.
A template that provides a default implementation of getAliasingOpOperands for ops that support unstr...
AliasingOpOperandList getAliasingBranchOpOperands(Operation *op, BlockArgument bbArg, const AnalysisState &state) const
FailureOr< BufferLikeType > getBufferType(Operation *op, Value value, const BufferizationOptions &options, const BufferizationState &state, SmallVector< Value > &invocationStack) const
FailureOr< BufferLikeType > getBufferType(Operation *op, Value value, const BufferizationOptions &options, const BufferizationState &state, SmallVector< Value > &invocationStack) const
AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand, const AnalysisState &state) const
LogicalResult bufferize(Operation *op, RewriterBase &rewriter, const BufferizationOptions &options, BufferizationState &state) const
All function arguments are writable.
bool isWritable(Operation *op, Value value, const AnalysisState &state) const
bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand, const AnalysisState &state) const
bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand, const AnalysisState &state) const
Extra analysis state that is required for bufferization of function boundaries.
DenseMap< FuncOp, IndexMapping > equivalentFuncArgs
A mapping of ReturnOp OpOperand indices to equivalent FuncOp BBArg indices.
DenseMap< int64_t, SmallVector< int64_t > > IndexToIndexListMapping
A mapping of indices to a list of indices.
DenseMap< FuncOp, IndexToIndexListMapping > aliasingReturnVals
A mapping of FuncOp BBArg indices to aliasing ReturnOp OpOperand indices.
DenseMap< FuncOp, BbArgIndexSet > readBbArgs
A set of all read BlockArguments of FuncOps.
DenseMap< FuncOp, DenseSet< int64_t > > writableReturnVals
Indices of tensor return values whose buffers are writable at every func.return, including all aliase...
DenseSet< int64_t > BbArgIndexSet
A set of block argument indices.
DenseMap< FuncOp, BbArgIndexSet > writtenBbArgs
A set of all written-to BlockArguments of FuncOps.
DenseMap< FuncOp, FuncOpAnalysisState > analyzedFuncOps
Keep track of which FuncOps are fully analyzed or currently being analyzed.
void startFunctionAnalysis(FuncOp funcOp)
This function is called right before analyzing the given FuncOp.
DenseMap< int64_t, int64_t > IndexMapping
A mapping of indices to indices.
FailureOr< BufferLikeType > getBufferType(Operation *op, Value value, const BufferizationOptions &options, const BufferizationState &state, SmallVector< Value > &invocationStack) const
AliasingOpOperandList getAliasingOpOperands(Operation *op, Value value, const AnalysisState &state) const
bool isWritable(Operation *op, Value value, const AnalysisState &state) const
Return true if the given function argument is writable.
static bool supportsUnstructuredControlFlow()
bool hasTensorSemantics(Operation *op) const
LogicalResult bufferize(Operation *op, RewriterBase &rewriter, const BufferizationOptions &options, BufferizationState &state) const
Rewrite function bbArgs and return values into buffer form.
AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand, const AnalysisState &state) const
bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand, const AnalysisState &state) const
bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand, const AnalysisState &state) const
LogicalResult bufferize(Operation *op, RewriterBase &rewriter, const BufferizationOptions &options, BufferizationState &state) const