MLIR  21.0.0git
BufferizableOpInterfaceImpl.cpp
Go to the documentation of this file.
1 //===- BufferizableOpInterfaceImpl.cpp - Impl. of BufferizableOpInterface -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
14 #include "mlir/IR/Attributes.h"
15 #include "mlir/IR/Dialect.h"
16 #include "mlir/IR/Operation.h"
17 
18 using namespace mlir;
19 using namespace mlir::bufferization;
20 
21 namespace {
22 /// Bufferization of arith.constant. Replace with memref.get_global.
23 struct ConstantOpInterface
24  : public BufferizableOpInterface::ExternalModel<ConstantOpInterface,
25  arith::ConstantOp> {
26  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
28  BufferizationState &state) const {
29  auto constantOp = cast<arith::ConstantOp>(op);
30  auto type = dyn_cast<RankedTensorType>(constantOp.getType());
31 
32  // Only ranked tensors are supported.
33  if (!type)
34  return failure();
35 
36  Attribute memorySpace;
37  if (auto memSpace = options.defaultMemorySpaceFn(type))
38  memorySpace = *memSpace;
39  else
40  return constantOp->emitError("could not infer memory space");
41 
42  // Only constants inside a module are supported.
43  auto moduleOp = constantOp->getParentOfType<ModuleOp>();
44  if (!moduleOp)
45  return failure();
46 
47  // Create global memory segment and replace tensor with memref pointing to
48  // that memory segment.
49  FailureOr<memref::GlobalOp> globalOp =
50  getGlobalFor(constantOp, state.getSymbolTables(),
51  options.bufferAlignment, memorySpace);
52  if (failed(globalOp))
53  return failure();
54  memref::GlobalOp globalMemref = *globalOp;
55  replaceOpWithNewBufferizedOp<memref::GetGlobalOp>(
56  rewriter, op, globalMemref.getType(), globalMemref.getName());
57 
58  return success();
59  }
60 
61  bool isWritable(Operation *op, Value value,
62  const AnalysisState &state) const {
63  // Memory locations returned by memref::GetGlobalOp may not be written to.
64  assert(isa<OpResult>(value));
65  return false;
66  }
67 };
68 
69 struct IndexCastOpInterface
70  : public BufferizableOpInterface::ExternalModel<IndexCastOpInterface,
71  arith::IndexCastOp> {
72  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
73  const AnalysisState &state) const {
74  return false;
75  }
76 
77  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
78  const AnalysisState &state) const {
79  return false;
80  }
81 
82  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
83  const AnalysisState &state) const {
84  return {{op->getResult(0), BufferRelation::Equivalent}};
85  }
86 
87  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
89  BufferizationState &state) const {
90  auto castOp = cast<arith::IndexCastOp>(op);
91  auto resultTensorType = cast<TensorType>(castOp.getType());
92 
93  FailureOr<Value> source =
94  getBuffer(rewriter, castOp.getIn(), options, state);
95  if (failed(source))
96  return failure();
97  auto sourceType = cast<BaseMemRefType>(source->getType());
98 
99  // Result type should have same layout and address space as the source type.
100  BaseMemRefType resultType;
101  if (auto rankedMemRefType = dyn_cast<MemRefType>(sourceType)) {
102  resultType = MemRefType::get(
103  rankedMemRefType.getShape(), resultTensorType.getElementType(),
104  rankedMemRefType.getLayout(), rankedMemRefType.getMemorySpace());
105  } else {
106  auto unrankedMemrefType = cast<UnrankedMemRefType>(sourceType);
107  resultType = UnrankedMemRefType::get(resultTensorType.getElementType(),
108  unrankedMemrefType.getMemorySpace());
109  }
110 
111  replaceOpWithNewBufferizedOp<arith::IndexCastOp>(rewriter, op, resultType,
112  *source);
113  return success();
114  }
115 };
116 
117 /// Bufferization of arith.select. Just replace the operands.
118 struct SelectOpInterface
119  : public BufferizableOpInterface::ExternalModel<SelectOpInterface,
120  arith::SelectOp> {
121  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
122  const AnalysisState &state) const {
123  return false;
124  }
125 
126  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
127  const AnalysisState &state) const {
128  return false;
129  }
130 
131  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
132  const AnalysisState &state) const {
133  return {{op->getOpResult(0) /*result*/, BufferRelation::Equivalent,
134  /*isDefinite=*/false}};
135  }
136 
137  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
139  BufferizationState &state) const {
140  auto selectOp = cast<arith::SelectOp>(op);
141  Location loc = selectOp.getLoc();
142 
143  // Elementwise conditions are not supported yet. To bufferize such an op,
144  // it could be lowered to an elementwise "linalg.generic" with a new
145  // "tensor.empty" out tensor, followed by "empty tensor elimination". Such
146  // IR will bufferize.
147  if (!selectOp.getCondition().getType().isInteger(1))
148  return op->emitOpError("only i1 condition values are supported");
149 
150  // TODO: It would be more efficient to copy the result of the `select` op
151  // instead of its OpOperands. In the worst case, 2 copies are inserted at
152  // the moment (one for each tensor). When copying the op result, only one
153  // copy would be needed.
154  FailureOr<Value> maybeTrueBuffer =
155  getBuffer(rewriter, selectOp.getTrueValue(), options, state);
156  FailureOr<Value> maybeFalseBuffer =
157  getBuffer(rewriter, selectOp.getFalseValue(), options, state);
158  if (failed(maybeTrueBuffer) || failed(maybeFalseBuffer))
159  return failure();
160  Value trueBuffer = *maybeTrueBuffer;
161  Value falseBuffer = *maybeFalseBuffer;
162 
163  // The "true" and the "false" operands must have the same type. If the
164  // buffers have different types, they differ only in their layout map. Cast
165  // both of them to the most dynamic MemRef type.
166  if (trueBuffer.getType() != falseBuffer.getType()) {
167  auto targetType =
168  bufferization::getBufferType(selectOp.getResult(), options, state);
169  if (failed(targetType))
170  return failure();
171  if (trueBuffer.getType() != *targetType)
172  trueBuffer =
173  rewriter.create<memref::CastOp>(loc, *targetType, trueBuffer);
174  if (falseBuffer.getType() != *targetType)
175  falseBuffer =
176  rewriter.create<memref::CastOp>(loc, *targetType, falseBuffer);
177  }
178 
179  replaceOpWithNewBufferizedOp<arith::SelectOp>(
180  rewriter, op, selectOp.getCondition(), trueBuffer, falseBuffer);
181  return success();
182  }
183 
184  FailureOr<BaseMemRefType>
186  const BufferizationState &state,
187  SmallVector<Value> &invocationStack) const {
188  auto selectOp = cast<arith::SelectOp>(op);
189  assert(value == selectOp.getResult() && "invalid value");
190  auto trueType = bufferization::getBufferType(
191  selectOp.getTrueValue(), options, state, invocationStack);
192  auto falseType = bufferization::getBufferType(
193  selectOp.getFalseValue(), options, state, invocationStack);
194  if (failed(trueType) || failed(falseType))
195  return failure();
196  if (*trueType == *falseType)
197  return *trueType;
198  if (trueType->getMemorySpace() != falseType->getMemorySpace())
199  return op->emitError("inconsistent memory space on true/false operands");
200 
201  // If the buffers have different types, they differ only in their layout
202  // map.
203  auto memrefType = llvm::cast<MemRefType>(*trueType);
205  RankedTensorType::get(memrefType.getShape(),
206  memrefType.getElementType()),
207  memrefType.getMemorySpace());
208  }
209 };
210 
211 } // namespace
212 
214  DialectRegistry &registry) {
215  registry.addExtension(+[](MLIRContext *ctx, ArithDialect *dialect) {
216  ConstantOp::attachInterface<ConstantOpInterface>(*ctx);
217  IndexCastOp::attachInterface<IndexCastOpInterface>(*ctx);
218  SelectOp::attachInterface<SelectOpInterface>(*ctx);
219  });
220 }
static llvm::ManagedStatic< PassManagerOptions > options
Base class for generic analysis states.
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class provides a shared interface for ranked and unranked memref types.
Definition: BuiltinTypes.h:102
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.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:453
This class represents an operand of an operation.
Definition: Value.h:257
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
OpResult getOpResult(unsigned idx)
Definition: Operation.h:421
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition: Operation.h:407
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
Definition: Operation.cpp:268
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Definition: Operation.cpp:673
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:358
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:105
BufferizationState provides information about the state of the IR during the bufferization process.
void registerBufferizableOpInterfaceExternalModels(DialectRegistry &registry)
FailureOr< BaseMemRefType > getBufferType(Value value, const BufferizationOptions &options, const BufferizationState &state)
Return the buffer type for a given Value (tensor) after bufferization without bufferizing any IR.
FailureOr< Value > getBuffer(RewriterBase &rewriter, Value value, const BufferizationOptions &options, const BufferizationState &state)
Lookup the buffer for the given value.
FailureOr< memref::GlobalOp > getGlobalFor(arith::ConstantOp constantOp, SymbolTableCollection &symbolTables, uint64_t alignment, Attribute memorySpace={})
BaseMemRefType getMemRefTypeWithFullyDynamicLayout(TensorType tensorType, Attribute memorySpace=nullptr)
Return a MemRef type with fully dynamic layout.
Include the generated interface declarations.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
Options for BufferizableOpInterface-based bufferization.