76#include "llvm/ADT/MapVector.h"
77#include "llvm/ADT/SmallVectorExtras.h"
98static void annotateEquivalentReturnBbArg(
OpOperand &returnVal,
100 const char *kEquivalentArgsAttr =
"__equivalent_func_args__";
106 equivBbArgs = llvm::map_to_vector<4>(attr, [](
Attribute a) {
107 return cast<IntegerAttr>(a).getValue().getSExtValue();
123 if (funcOp.getBody().empty()) {
126 FunctionType type = funcOp.getFunctionType();
127 for (
const auto &inputIt : llvm::enumerate(type.getInputs())) {
128 if (!isa<TensorLikeType>(inputIt.value()))
130 for (
const auto &resultIt : llvm::enumerate(type.getResults())) {
131 if (!isa<TensorLikeType>(resultIt.value()))
133 int64_t returnIdx = resultIt.index();
134 int64_t bbArgIdx = inputIt.index();
145 if (returnOps.empty()) {
146 return funcOp.emitError(
"cannot bufferize func.func without func.return");
151 if (isa<TensorLikeType>(bbArg.
getType())) {
155 for (func::ReturnOp returnOp : returnOps) {
156 for (
OpOperand &returnVal : returnOp->getOpOperands()) {
157 if (isa<TensorLikeType>(returnVal.
get().
getType())) {
160 aliases.insert(returnIdx);
173 auto findEquivalentBlockArgIdx =
174 [&](
OpOperand &opOperand) -> std::optional<int64_t> {
175 Value v = opOperand.get();
176 if (!isa<TensorLikeType>(v.
getType()))
179 if (isa<TensorLikeType>(bbArg.
getType())) {
182 annotateEquivalentReturnBbArg(opOperand, bbArg);
190 int64_t numResults = returnOps.front()->getNumOperands();
191 for (
int64_t i = 0; i < numResults; ++i) {
194 std::optional<int64_t> maybeEquiv =
195 findEquivalentBlockArgIdx(returnOps.front()->getOpOperand(i));
196 if (!maybeEquiv.has_value())
198 int64_t bbArgIdx = *maybeEquiv;
199 bool allEquiv =
true;
205 for (func::ReturnOp returnOp :
ArrayRef(returnOps).drop_front()) {
206 std::optional<int64_t> maybeEquiv =
207 findEquivalentBlockArgIdx(returnOp->getOpOperand(i));
208 if (maybeEquiv != bbArgIdx) {
223static void annotateFuncArgAccess(func::FuncOp funcOp,
int64_t idx,
bool isRead,
227 if (isRead && isWritten) {
228 accessType =
b.getStringAttr(
"read-write");
230 accessType =
b.getStringAttr(
"read");
231 }
else if (isWritten) {
232 accessType =
b.getStringAttr(
"write");
234 accessType =
b.getStringAttr(
"none");
236 funcOp.setArgAttr(idx, BufferizationDialect::kBufferAccessAttrName,
246 for (
int64_t idx = 0, e = funcOp.getFunctionType().getNumInputs(); idx < e;
249 if (!isa<TensorLikeType>(funcOp.getFunctionType().getInput(idx)))
253 if (
auto accessAttr = funcOp.getArgAttrOfType<StringAttr>(
254 idx, BufferizationDialect::kBufferAccessAttrName)) {
256 StringRef str = accessAttr.getValue();
257 isRead = str ==
"read" || str ==
"read-write";
258 isWritten = str ==
"write" || str ==
"read-write";
259 }
else if (funcOp.getBody().empty()) {
267 isRead = state.isValueRead(bbArg);
272 annotateFuncArgAccess(funcOp, idx, isRead, isWritten);
283static void funcOpReturnValueWritabilityAnalysis(FuncOp funcOp,
287 if (funcOp.isExternal())
291 for (
auto [
index, type] : llvm::enumerate(funcOp.getResultTypes())) {
292 if (!isa<TensorLikeType>(type))
294 bool isWritable =
true;
295 for (func::ReturnOp returnOp : returnOps) {
299 isWritable &= state.isWritable(alias);
312 BufferizationDialect::kBufferLayoutAttrName);
314 BufferizationDialect::kWritableAttrName);
321 return dyn_cast_or_null<func::FuncOp>(
322 callOp.resolveCallableInTable(&symbolTable));
327 return llvm::any_of(funcOp.getFunctionType().getInputs(),
328 llvm::IsaPred<TensorLikeType>) ||
329 llvm::any_of(funcOp.getFunctionType().getResults(),
330 llvm::IsaPred<TensorLikeType>);
353 for (func::FuncOp funcOp : block.getOps<func::FuncOp>()) {
355 numberCallOpsContainedInFuncOp[funcOp] = 0;
358 assert(calledFunction &&
"could not retrieved called func::FuncOp");
364 callerMap[calledFunction].insert(callOp);
365 if (calledBy[calledFunction].insert(funcOp)) {
366 numberCallOpsContainedInFuncOp[funcOp]++;
370 if (res.wasInterrupted())
380 for (
const auto &entry : numberCallOpsContainedInFuncOp) {
381 if (entry.second == 0)
382 worklist.push_back(entry.first);
385 while (!worklist.empty()) {
386 func::FuncOp
func = worklist.pop_back_val();
387 orderedFuncOps.push_back(
func);
389 for (func::FuncOp caller : calledBy[
func]) {
390 auto &count = numberCallOpsContainedInFuncOp[caller];
393 worklist.push_back(caller);
396 numberCallOpsContainedInFuncOp.erase(
func);
401 for (
auto it : numberCallOpsContainedInFuncOp)
402 remainingFuncOps.push_back(it.first);
418 if (isa<UnrankedMemRefType>(castOp.getSource().getType()) &&
421 return castOp.getSource();
429 assert(!returnOps.empty() &&
"expected at least one ReturnOp");
430 int numOperands = returnOps.front()->getNumOperands();
436 for (
int i = 0; i < numOperands; ++i) {
438 Type t = getSourceType(returnOps.front()->getOperand(i));
441 for (
int j = 1; j < static_cast<int>(returnOps.size()); ++
j)
442 if (getSourceType(returnOps[
j]->getOperand(i)) != t)
460 if (funcOp.getBody().empty())
468 if (returnOps.empty())
473 for (func::ReturnOp returnOp : returnOps) {
474 for (
OpOperand &operand : returnOp->getOpOperands()) {
476 if (resultTypes[operand.getOperandNumber()]) {
484 for (
int i = 0; i < static_cast<int>(resultTypes.size()); ++i) {
487 resultTypes[i] = funcOp.getFunctionType().getResult(i);
491 auto newFuncType = FunctionType::get(
492 funcOp.getContext(), funcOp.getFunctionType().getInputs(), resultTypes);
493 funcOp.setType(newFuncType);
500 assert(state.
getOptions().bufferizeFunctionBoundaries &&
501 "expected that function boundary bufferization is activated");
516 remainingFuncOps, callerMap,
522 for (func::FuncOp funcOp : orderedFuncOps) {
530 if (failed(
analyzeOp(funcOp, state, statistics)))
534 if (failed(aliasingFuncOpBBArgsAnalysis(funcOp, state, funcState)) ||
535 failed(funcOpBbArgReadWriteAnalysis(funcOp, state, funcState)))
537 funcOpReturnValueWritabilityAnalysis(funcOp, state, funcState);
544 for (func::FuncOp funcOp : remainingFuncOps) {
549 if (failed(
analyzeOp(funcOp, state, statistics)))
566 for (func::FuncOp funcOp : block.getOps<func::FuncOp>()) {
577 assert(
options.bufferizeFunctionBoundaries &&
578 "expected that function boundary bufferization is activated");
598 remainingFuncOps, callerMap,
599 state.getSymbolTables())))
601 llvm::append_range(orderedFuncOps, remainingFuncOps);
604 for (func::FuncOp funcOp : orderedFuncOps) {
608 if (llvm::is_contained(
options.noAnalysisFuncFilter, funcOp.getSymName())) {
612 updatedOptions.copyBeforeWrite =
true;
613 if (failed(
bufferizeOp(funcOp, updatedOptions, state, statistics)))
621 if (
options.inferFunctionResultLayout)
629 llvm::make_early_inc_range(block.getOperations())) {
648 assert(
options.bufferizeFunctionBoundaries &&
649 "expected that function boundary bufferization is activated");
651 "invalid combination of bufferization flags");
652 if (!
options.copyBeforeWrite) {
653 if (
options.noAnalysisFuncFilter.empty()) {
659 OpFilter::Entry::FilterFn analysisFilterFn = [=](
Operation *op) {
660 auto func = dyn_cast<func::FuncOp>(op);
664 return llvm::is_contained(
options.noAnalysisFuncFilter,
669 updatedOptions.opFilter.denyOperation(analysisFilterFn);
DenseMap< func::FuncOp, DenseSet< Operation * > > FuncCallerMap
A mapping of FuncOps to their callers.
static SmallVector< Type > getReturnTypes(SmallVector< func::ReturnOp > returnOps)
Helper function that returns the return types (skipping casts) of the given func.return ops.
static FuncAnalysisState & getOrCreateFuncAnalysisState(OneShotAnalysisState &state)
Get or create FuncAnalysisState.
static bool hasTensorSignature(func::FuncOp funcOp)
Return "true" if the given function signature has tensor semantics.
static void removeBufferizationAttributes(BlockArgument bbArg)
Remove bufferization attributes on FuncOp arguments.
static void foldMemRefCasts(func::FuncOp funcOp)
Fold return values that are memref casts and update function return types.
static Value unpackCast(Value v)
Helper function that extracts the source from a memref.cast.
static LogicalResult getFuncOpsOrderedByCalls(Operation *moduleOp, SmallVectorImpl< func::FuncOp > &orderedFuncOps, SmallVectorImpl< func::FuncOp > &remainingFuncOps, FuncCallerMap &callerMap, SymbolTableCollection &symbolTables)
Store all functions of the moduleOp in orderedFuncOps, sorted by callee-caller order (i....
static llvm::ManagedStatic< PassManagerOptions > options
Attributes are known-constant values of operations.
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.
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
IRValueT get() const
Return the current value being used by this operand.
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
This class helps build Operations.
This class represents an operand of an operation.
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
A trait used to provide symbol table functionalities to a region operation.
Operation is the basic unit of execution within MLIR.
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns a null Attribute if the discardable attribute does no...
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
unsigned getNumOperands()
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
bool hasDiscardableAttr(StringRef name)
Return true if this operation has a discardable attribute with the provided name.
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
MLIRContext * getContext()
Return the context this operation is associated with.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
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.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
A utility result that is used to signal how to proceed with an ongoing walk:
static WalkResult advance()
State for analysis-enabled bufferization.
bool isValueWritten(Value value) const
Return true if the buffer of the given tensor value is written to.
Ty & addExtension(Args &&...args)
Adds a new Extension of the type specified as template parameter, constructing it with the arguments ...
const OneShotBufferizationOptions & getOptions() const
Return a reference to the BufferizationOptions.
Ty * getExtension()
Returns the extension of the specified type.
void applyOnAliases(Value v, function_ref< void(Value)> fun) const
Apply fun to all aliases of v.
bool areEquivalentBufferizedValues(Value v1, Value v2) const override
Return true if v1 and v2 bufferize to equivalent buffers.
bool areAliasingBufferizedValues(Value v1, Value v2) const override
Return true if v1 and v2 may bufferize to aliasing buffers.
Operation * getOwner() const
Return the owner of this operand.
static FuncOp getCalledFunction(CallOpInterface callOp, SymbolTableCollection &symbolTables)
Return the FuncOp called by callOp.
LogicalResult bufferizeOp(Operation *op, const BufferizationOptions &options, BufferizationState &bufferizationState, BufferizationStatistics *statistics=nullptr)
Bufferize op and its nested ops that implement BufferizableOpInterface.
llvm::LogicalResult bufferizeModuleOp(Operation *moduleOp, const OneShotBufferizationOptions &options, BufferizationState &state, BufferizationStatistics *statistics=nullptr)
Bufferize an ops nested ops that implement BufferizableOpInterface.
void removeBufferizationAttributesInModule(Operation *moduleOp)
Remove bufferization attributes on every FuncOp arguments in the SymbolTable op.
LogicalResult analyzeOp(Operation *op, OneShotAnalysisState &state, BufferizationStatistics *statistics=nullptr)
Analyze op and its nested ops.
SmallVector< func::ReturnOp > getReturnOps(func::FuncOp funcOp)
Helper function that returns all func.return ops in the given function.
LogicalResult insertTensorCopies(Operation *op, const OneShotBufferizationOptions &options, const BufferizationState &bufferizationState, BufferizationStatistics *statistics=nullptr)
Resolve RaW and other conflicts by inserting bufferization.alloc_tensor ops.
llvm::LogicalResult analyzeModuleOp(Operation *moduleOp, OneShotAnalysisState &state, BufferizationStatistics *statistics=nullptr)
Analyze moduleOp and its nested ops.
llvm::LogicalResult runOneShotModuleBufferize(Operation *moduleOp, const bufferization::OneShotBufferizationOptions &options, BufferizationState &state, BufferizationStatistics *statistics=nullptr)
Run One-Shot Module Bufferization on the given SymbolTable.
Include the generated interface declarations.
llvm::SetVector< T, Vector, Set, N > SetVector
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Bufferization statistics for debugging.
Options for analysis-enabled bufferization.
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< FuncOp, IndexToIndexListMapping > aliasingReturnVals
A mapping of FuncOp BBArg indices to aliasing ReturnOp OpOperand indices.
SymbolTableCollection symbolTables
A collection of cached SymbolTables used for faster function lookup.
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...
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.
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.