MLIR 23.0.0git
ConstantFold.cpp
Go to the documentation of this file.
1//===- ConstantFold.cpp - Implementation of constant folding on Linalg ops ===//
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//
9// This file implements constant folding on Linalg operations.
10//
11//===----------------------------------------------------------------------===//
12
15#include "mlir/IR/Matchers.h"
17#include "mlir/Support/LLVM.h"
18#include "llvm/ADT/SmallVectorExtras.h"
19#include <optional>
20
21using namespace mlir;
22using namespace mlir::linalg;
23
24namespace {
25/// Base class for constant folding linalg structured ops with N inputs, 1
26/// output, and permutation indexing maps.
27///
28/// `ConcreteType` should provide methods with signatures
29///
30/// ```c++
31/// bool matchIndexingMaps(LinalgOp linalgOp) const;
32/// RegionComputationFn getRegionComputeFn(LinalgOp) const;
33/// ```
34///
35/// The latter inspects the region and returns the computation inside as a
36/// functor. The functor will be invoked with constant elements for all inputs
37/// and should return the corresponding computed constant element for output.
38template <typename ConcreteType>
39class FoldConstantBase : public OpInterfaceRewritePattern<LinalgOp> {
40public:
41 struct APIntOrFloat {
42 std::optional<APInt> apInt;
43 std::optional<APFloat> apFloat;
44 };
45 struct APIntOrFloatArray {
46 SmallVector<APInt> apInts;
47 SmallVector<APFloat> apFloats;
48 };
49 using RegionComputationFn =
50 std::function<APIntOrFloat(const APIntOrFloatArray &)>;
51
52 FoldConstantBase(MLIRContext *context, const ControlFusionFn &controlFn,
53 PatternBenefit benefit = 1)
54 : OpInterfaceRewritePattern<LinalgOp>(context, benefit),
55 controlFn(controlFn) {}
56
57 LogicalResult matchAndRewrite(LinalgOp linalgOp,
58 PatternRewriter &rewriter) const override {
59 // Mixed and buffer sematics aren't supported.
60 if (!linalgOp.hasPureTensorSemantics())
61 return failure();
62
63 // Only support ops generating one output for now.
64 if (linalgOp.getNumDpsInits() != 1)
65 return failure();
66
67 auto outputType = dyn_cast<ShapedType>(linalgOp->getResultTypes().front());
68 // Require the output types to be static given that we are generating
69 // constants.
70 if (!outputType || !outputType.hasStaticShape())
71 return failure();
72
73 if (!llvm::all_of(linalgOp.getDpsInputs(), [](Value input) {
74 return isa<ShapedType>(input.getType());
75 }))
76 return failure();
77
78 // Make sure all element types are the same.
79 auto getOperandElementType = [](Value value) {
80 return cast<ShapedType>(value.getType()).getElementType();
81 };
82 if (!llvm::all_equal(
83 llvm::map_range(linalgOp->getOperands(), getOperandElementType)))
84 return failure();
85
86 // We can only handle the case where we have int/float elements.
87 auto elementType = outputType.getElementType();
88 if (!elementType.isIntOrFloat())
89 return failure();
90
91 // Require all indexing maps to be permutations for now. This is common and
92 // it simplifies input/output access greatly: we can do the data shuffling
93 // entirely in the compiler, without needing to turn all indices into
94 // Values, and then do affine apply on them, and then match back the
95 // constant again.
96 if (!llvm::all_of(linalgOp.getIndexingMapsArray(),
97 [](AffineMap map) { return map.isPermutation(); }))
98 return failure();
99
100 for (OpOperand &operand : linalgOp.getDpsInitsMutable()) {
101 if (linalgOp.payloadUsesValueFromOperand(&operand))
102 return failure();
103 }
104
105 // Further check the indexing maps are okay for the ConcreteType.
106 if (!static_cast<const ConcreteType *>(this)->matchIndexingMaps(linalgOp))
107 return failure();
108
109 // Defer to the concrete type to check the region and discover the
110 // computation inside.
111 RegionComputationFn computeFn =
112 static_cast<const ConcreteType *>(this)->getRegionComputeFn(linalgOp);
113 if (!computeFn)
114 return failure();
115
116 // All inputs should be constants.
117 int numInputs = linalgOp.getNumDpsInputs();
118 SmallVector<DenseIntOrFPElementsAttr> inputValues(numInputs);
119 for (const auto &en : llvm::enumerate(linalgOp.getDpsInputOperands())) {
120 if (!matchPattern(en.value()->get(),
121 m_Constant(&inputValues[en.index()])))
122 return failure();
123 }
124
125 // Identified this as a potential candidate for folding. Now check the
126 // policy to see whether we are allowed to proceed.
127 for (OpOperand *operand : linalgOp.getDpsInputOperands()) {
128 if (!controlFn(operand))
129 return failure();
130 }
131
132 SmallVector<int64_t, 4> loopBounds = linalgOp.getStaticLoopRanges();
133 int64_t numElements = outputType.getNumElements();
134
135 // Use APInt/APFloat instead of Attribute here for constructing the output.
136 // This helps to avoid blowing up compiler memory usage: Attributes would
137 // unify the following cases but they have lifetime as the MLIRContext.
138 SmallVector<APInt> intOutputValues;
139 SmallVector<APFloat> fpOutputValues;
140 if (isa<FloatType>(elementType))
141 fpOutputValues.resize(numElements, APFloat(0.f));
142 else
143 intOutputValues.resize(numElements);
144
145 // Return the constant dim positions from the given permutation map.
146 auto getDimPositions = [](AffineMap map) {
147 SmallVector<unsigned> dims;
148 dims.reserve(map.getNumResults());
149 for (AffineExpr result : map.getResults()) {
150 dims.push_back(cast<AffineDimExpr>(result).getPosition());
151 }
152 return dims;
153 };
154
155 SmallVector<SmallVector<unsigned>> inputDims;
156 for (int i = 0; i < numInputs; ++i)
157 inputDims.push_back(getDimPositions(linalgOp.getIndexingMapsArray()[i]));
158 auto outputDims = getDimPositions(linalgOp.getIndexingMapsArray().back());
159 auto outputShape = outputType.getShape();
160
161 // Allocate small vectors for index delinearization. Initial values do not
162 // matter here as they will be overwritten later.
163 SmallVector<uint64_t> indices(loopBounds.size(), 0);
164 SmallVector<uint64_t> dstIndices(loopBounds.size(), 0);
165 SmallVector<SmallVector<uint64_t>> srcIndices(
166 numInputs, SmallVector<uint64_t>(loopBounds.size(), 0));
167 SmallVector<uint64_t> srcLinearIndices(numInputs, 0);
168 uint64_t dstLinearIndex = 0;
169
170 // Allocate spaces for compute function inputs. Initial values do not matter
171 // here as they will be overwritten later.
172 APIntOrFloatArray computeFnInputs;
173
174 auto inputShapes =
175 llvm::map_to_vector<4>(linalgOp.getDpsInputs(), [](Value value) {
176 return cast<ShapedType>(value.getType()).getShape();
177 });
178
179 // Given a `linearIndex`, remap it to a linear index to access linalg op
180 // inputs/ouputs. This mutates `indices`, `srcIndices`, `dstIndices`,
181 // `srcLinearIndices`, `dstLinearIndex` in place.
182 auto computeRemappedLinearIndex = [&](int linearIndex) {
183 int totalCount = linearIndex;
184 for (int dim = loopBounds.size() - 1; dim >= 0; --dim) {
185 indices[dim] = totalCount % loopBounds[dim];
186 totalCount /= loopBounds[dim];
187 }
188
189 for (int dim = loopBounds.size() - 1; dim >= 0; --dim) {
190 for (int i = 0; i < numInputs; ++i)
191 srcIndices[i][dim] = indices[inputDims[i][dim]];
192 dstIndices[dim] = indices[outputDims[dim]];
193 }
194
195 dstLinearIndex = dstIndices.front();
196 for (int i = 0; i < numInputs; ++i)
197 srcLinearIndices[i] = srcIndices[i].front();
198
199 for (int dim = 1; dim < outputType.getRank(); ++dim) {
200 dstLinearIndex = dstLinearIndex * outputShape[dim] + dstIndices[dim];
201 for (int i = 0; i < numInputs; ++i)
202 srcLinearIndices[i] =
203 srcLinearIndices[i] * inputShapes[i][dim] + srcIndices[i][dim];
204 }
205 };
206
207 bool isFloat = isa<FloatType>(elementType);
208 if (isFloat) {
209 SmallVector<DenseElementsAttr::iterator_range<APFloat>> inFpRanges;
210 for (int i = 0; i < numInputs; ++i)
211 inFpRanges.push_back(inputValues[i].getValues<APFloat>());
212
213 computeFnInputs.apFloats.resize(numInputs, APFloat(0.f));
214
215 // Transpose the input constant. Because we don't know its rank in
216 // advance, we need to loop over the range [0, element count) and
217 // delinearize the index.
218 for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) {
219 computeRemappedLinearIndex(linearIndex);
220
221 // Collect constant elements for all inputs at this loop iteration.
222 for (int i = 0; i < numInputs; ++i)
223 computeFnInputs.apFloats[i] = inFpRanges[i][srcLinearIndices[i]];
224
225 // Invoke the computation to get the corresponding constant output
226 // element.
227 fpOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apFloat;
228 }
229 } else {
230 SmallVector<DenseElementsAttr::iterator_range<APInt>> inIntRanges;
231 for (int i = 0; i < numInputs; ++i)
232 inIntRanges.push_back(inputValues[i].getValues<APInt>());
233
234 computeFnInputs.apInts.resize(numInputs);
235
236 // Transpose the input constant. Because we don't know its rank in
237 // advance, we need to loop over the range [0, element count) and
238 // delinearize the index.
239 for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) {
240 computeRemappedLinearIndex(linearIndex);
241
242 // Collect constant elements for all inputs at this loop iteration.
243 for (int i = 0; i < numInputs; ++i)
244 computeFnInputs.apInts[i] = inIntRanges[i][srcLinearIndices[i]];
245
246 // Invoke the computation to get the corresponding constant output
247 // element.
248 intOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apInt;
249 }
250 }
251
252 DenseElementsAttr outputAttr =
253 isFloat ? DenseElementsAttr::get(outputType, fpOutputValues)
254 : DenseElementsAttr::get(outputType, intOutputValues);
255
256 rewriter.replaceOpWithNewOp<arith::ConstantOp>(linalgOp, outputAttr);
257 return success();
258 }
259
260private:
261 ControlFusionFn controlFn;
262};
263
264// Folds linalg.transpose (and linalg.generic ops that are actually transposes)
265// on constant values.
266struct FoldConstantTranspose : public FoldConstantBase<FoldConstantTranspose> {
267
268 using FoldConstantBase::FoldConstantBase;
269
270 bool matchIndexingMaps(LinalgOp linalgOp) const {
271 // We should have one input and one output.
272 return linalgOp.getIndexingMapsArray().size() == 2;
273 }
274
275 RegionComputationFn getRegionComputeFn(LinalgOp linalgOp) const {
276 // Make sure the region only contains a yield op.
277 Block &body = linalgOp->getRegion(0).front();
278 if (!llvm::hasSingleElement(body))
279 return nullptr;
280 auto yieldOp = dyn_cast<linalg::YieldOp>(body.getTerminator());
281 if (!yieldOp)
282 return nullptr;
283
284 // The yield op should return the block argument corresponds to the input.
285 for (Value yieldVal : yieldOp.getValues()) {
286 auto yieldArg = dyn_cast<BlockArgument>(yieldVal);
287 if (!yieldArg || yieldArg.getOwner() != &body)
288 return nullptr;
289 if (yieldArg.getArgNumber() != 0)
290 return nullptr;
291 }
292
293 // No computation; just return the orginal value.
294 return [](const APIntOrFloatArray &inputs) {
295 if (inputs.apFloats.empty())
296 return APIntOrFloat{inputs.apInts.front(), std::nullopt};
297 return APIntOrFloat{std::nullopt, inputs.apFloats.front()};
298 };
299 }
300
301 ControlFusionFn controlFn;
302};
303} // namespace
304
306 RewritePatternSet &patterns, const ControlFusionFn &controlFn) {
307 MLIRContext *context = patterns.getContext();
308 patterns.insert<FoldConstantTranspose>(context, controlFn);
309}
return success()
ArrayRef< AffineExpr > getResults() const
unsigned getNumResults() const
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
std::function< bool(OpOperand *fusedOperand)> ControlFusionFn
Function type which is used to control when to stop fusion.
void populateConstantFoldLinalgOperations(RewritePatternSet &patterns, const ControlFusionFn &controlFn)
Patterns to constant fold Linalg operations.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
const FrozenRewritePatternSet & patterns
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
OpInterfaceRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting a...