MLIR 24.0.0git
LowerVectorContract.cpp
Go to the documentation of this file.
1//===- LowerVectorContract.cpp - Lower 'vector.contract' operation --------===//
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 target-independent rewrites and utilities to lower the
10// 'vector.contract' operation.
11//
12//===----------------------------------------------------------------------===//
13
22#include "mlir/IR/Location.h"
25
26#define DEBUG_TYPE "vector-contract-lowering"
27
28using namespace mlir;
29using namespace mlir::vector;
30
31//===----------------------------------------------------------------------===//
32// Helper functions
33//===----------------------------------------------------------------------===//
34// Helper to find an index in an affine map.
35static std::optional<int64_t> getResultIndex(AffineMap map, int64_t index) {
36 for (int64_t i = 0, e = map.getNumResults(); i < e; ++i) {
37 int64_t idx = map.getDimPosition(i);
38 if (idx == index)
39 return i;
40 }
41 return std::nullopt;
42}
43
44// Helper to construct iterator types with one index removed.
46 int64_t index) {
48 for (const auto &it : llvm::enumerate(iteratorTypes)) {
49 int64_t idx = it.index();
50 if (idx == index)
51 continue;
52 results.push_back(it.value());
53 }
54 return results;
55}
56
57// Helper to construct an affine map with one index removed.
59 PatternRewriter &rewriter) {
60 auto *ctx = rewriter.getContext();
62 for (int64_t i = 0, e = map.getNumResults(); i < e; ++i) {
63 int64_t idx = map.getDimPosition(i);
64 if (idx == index)
65 continue;
66 // Re-insert remaining indices, but renamed when occurring
67 // after the removed index.
68 auto targetExpr = getAffineDimExpr(idx < index ? idx : idx - 1, ctx);
69 results.push_back(targetExpr);
70 }
71 return AffineMap::get(map.getNumDims() - 1, 0, results, ctx);
72}
73
74/// Returns `val` with the dimension at position `index` dropped by indexing
75/// that dimension with `pos`.
76///
77/// If `index == -1`, returns `val` unchanged. If `index == 0`, the result is
78/// a single `vector.extract %val[pos]`.
79///
80/// Example (`index == 0`): extract the sub-vector at `pos` along the leading
81/// dimension.
82/// // val : vector<4x8xf32>, pos = 2
83/// %res = vector.extract %val[2] : vector<8xf32> from vector<4x8xf32>
84///
85/// For `index > 0`, recursively applies the same drop to each sub-vector of
86/// the leading dimension and reassembles the result.
88 PatternRewriter &rewriter) {
89 if (index == -1)
90 return val;
91
92 // At extraction dimension?
93 if (index == 0)
94 return vector::ExtractOp::create(rewriter, loc, val, pos);
95
96 // Unroll leading dimensions.
97 VectorType type = cast<VectorType>(val.getType());
98 VectorType resType = VectorType::Builder(type).dropDim(index);
99 Value result = arith::ConstantOp::create(rewriter, loc, resType,
100 rewriter.getZeroAttr(resType));
101 for (int64_t d = 0, e = resType.getDimSize(0); d < e; d++) {
102 Value ext = vector::ExtractOp::create(rewriter, loc, val, d);
103 Value load = reshapeLoad(loc, ext, index - 1, pos, rewriter);
104 result = vector::InsertOp::create(rewriter, loc, load, result, d);
105 }
106 return result;
107}
108
109/// Inserts `val` into `result` at position `pos` along dimension `index`.
110///
111/// This is the inverse of `reshapeLoad`. If `index == -1`, returns `val`. If
112/// `index == 0`, the result is a single `vector.insert %val, %result [pos]`.
113///
114/// Example (`index == 0`): insert `val` at `pos` along the leading dimension.
115/// // val : vector<4xf32>, acc : vector<2x4xf32>, pos = 1
116/// %res = vector.insert %val, %acc [1] : vector<4xf32> into vector<2x4xf32>
117///
118/// For `index > 0`, recursively applies the same insertion to each sub-vector
119/// of the leading dimension and reassembles the result.
121 int64_t pos, PatternRewriter &rewriter) {
122 // Unmodified?
123 if (index == -1)
124 return val;
125 // At insertion dimension?
126 if (index == 0)
127 return vector::InsertOp::create(rewriter, loc, val, result, pos);
128
129 // Unroll leading dimensions.
130 VectorType type = cast<VectorType>(result.getType());
131 for (int64_t d = 0, e = type.getDimSize(0); d < e; d++) {
132 Value ext = vector::ExtractOp::create(rewriter, loc, result, d);
133 Value ins = vector::ExtractOp::create(rewriter, loc, val, d);
134 Value sto = reshapeStore(loc, ins, ext, index - 1, pos, rewriter);
135 result = vector::InsertOp::create(rewriter, loc, sto, result, d);
136 }
137 return result;
138}
139
140/// Helper to create arithmetic operation associated with a kind of contraction.
141static std::optional<Value>
143 vector::CombiningKind kind, PatternRewriter &rewriter,
144 bool isInt, Value mask = Value(),
145 arith::FastMathFlagsAttr fmf = {}) {
146 using vector::CombiningKind;
147 Value mul;
148
149 if (isInt) {
150 if (kind == CombiningKind::MINNUMF || kind == CombiningKind::MAXNUMF ||
151 kind == CombiningKind::MINIMUMF || kind == CombiningKind::MAXIMUMF)
152 // Only valid for floating point types.
153 return std::nullopt;
154 mul = arith::MulIOp::create(rewriter, loc, x, y);
155 } else {
156 // Float case.
157 if (kind == CombiningKind::AND || kind == CombiningKind::MINUI ||
158 kind == CombiningKind::MINSI || kind == CombiningKind::MAXUI ||
159 kind == CombiningKind::MAXSI || kind == CombiningKind::OR ||
160 kind == CombiningKind::XOR)
161 // Only valid for integer types.
162 return std::nullopt;
163 // Special case for fused multiply-add.
164 if (acc && isa<VectorType>(acc.getType()) && kind == CombiningKind::ADD) {
165 Value fma = vector::FMAOp::create(rewriter, loc, x, y, acc);
166 if (mask)
167 // The fma op doesn't need explicit masking. However, fma ops used in
168 // reductions must preserve previous 'acc' values for masked-out lanes.
169 fma = selectPassthru(rewriter, mask, fma, acc);
170 return fma;
171 }
172 mul = arith::MulFOp::create(rewriter, loc, x, y, fmf);
173 }
174
175 if (!acc)
176 return std::optional<Value>(mul);
177
178 return makeArithReduction(rewriter, loc, kind, mul, acc, fmf, mask);
179}
180
181/// Return the positions of the reductions in the given map.
183 ArrayAttr iteratorTypes) {
184 SmallVector<int64_t> dimsIdx;
185 for (unsigned i = 0, e = map.getNumResults(); i < e; i++) {
186 if (isReductionIterator(iteratorTypes[map.getDimPosition(i)]))
187 dimsIdx.push_back(i);
188 }
189 return dimsIdx;
190}
191
192/// Look for a given dimension in an affine map and return its position. Return
193/// std::nullopt if the dimension is not in the map results.
194static std::optional<unsigned> getDimPosition(AffineMap map, unsigned dim) {
195 for (unsigned i = 0, e = map.getNumResults(); i < e; i++) {
196 if (map.getDimPosition(i) == dim)
197 return i;
198 }
199 return std::nullopt;
200}
201
202/// Creates an AddIOp if `isInt` is true otherwise create an arith::AddFOp using
203/// operands `x` and `y`.
204static Value createAdd(Location loc, Value x, Value y, bool isInt,
205 PatternRewriter &rewriter,
206 arith::FastMathFlagsAttr fmf = {}) {
207 if (isInt)
208 return arith::AddIOp::create(rewriter, loc, x, y);
209 return arith::AddFOp::create(rewriter, loc, x, y, fmf);
210}
211
212/// Creates a MulIOp if `isInt` is true otherwise create an MulFOp using
213/// operands `x and `y`.
214static Value createMul(Location loc, Value x, Value y, bool isInt,
215 PatternRewriter &rewriter,
216 arith::FastMathFlagsAttr fmf = {}) {
217 if (isInt)
218 return arith::MulIOp::create(rewriter, loc, x, y);
219 return arith::MulFOp::create(rewriter, loc, x, y, fmf);
220}
221
222namespace {
223
224/// Progressive lowering of a `vector.contract %a, %b, %c` with row-major matmul
225/// semantics to a reduction_size-unrolled sequence:
226/// ```
227/// %at = vector.transpose %a, [1, 0]
228/// %bRow0 = vector.extract %b[0]
229/// %atRow0 = vector.extract %at[0]
230/// %c0 = vector.outerproduct %atRow0, %bRow0, %c
231/// ...
232/// %bRowK = vector.extract %b[K]
233/// %atRowK = vector.extract %at[K]
234/// %cK = vector.outerproduct %atRowK, %bRowK, %cK-1
235/// ```
236///
237/// This only kicks in when vectorContractLowering is set to OuterProduct and
238/// the vector.contract op is a row-major matrix multiply.
239class ContractionOpToOuterProductOpLowering
240 : public MaskableOpRewritePattern<vector::ContractionOp> {
241public:
242 using MaskableOpRewritePattern::MaskableOpRewritePattern;
243
244 using FilterConstraintType =
245 std::function<LogicalResult(vector::ContractionOp op)>;
246
247 static LogicalResult defaultFilter(vector::ContractionOp op) {
248 return success();
249 }
250
251 ContractionOpToOuterProductOpLowering(
252 vector::VectorContractLowering vectorContractLowering,
253 MLIRContext *context, PatternBenefit benefit = 1,
254 FilterConstraintType constraint = defaultFilter)
255 : MaskableOpRewritePattern<vector::ContractionOp>(context, benefit),
256 vectorContractLowering(vectorContractLowering),
257 filter(std::move(constraint)) {}
258
259 FailureOr<Value>
260 matchAndRewriteMaskableOp(vector::ContractionOp op, MaskingOpInterface maskOp,
261 PatternRewriter &rewriter) const override;
262
263private:
264 /// Options to control the vector patterns.
265 vector::VectorContractLowering vectorContractLowering;
266 FilterConstraintType filter;
267};
268
269/// Progressive lowering of a `vector.contract %a, %b, %c` with row-major matmul
270/// semantics to an output-size-unrolled sequence:
271/// ```
272/// %out = arith.constant ... : vector<MxNxelt_type>
273/// %bt = vector.transpose %b, [1, 0]
274/// %aRow0 = vector.extract %a[0]
275/// %btRow0 = vector.extract %bt[0]
276/// %c00 = vector.reduction %atRow0, %bRow0
277/// %out00 = vector.insert %c00, %out[0, 0]
278/// ...
279/// %aRowLast = vector.extract %at[M-1]
280/// %btRowLast = vector.extract %b[N-1]
281/// %cLastLast = vector.reduction %atRowLast, %bRowLast
282/// %outcLastLast = vector.insert %cLastLast, %out[M-1, N-1]
283/// ```
284///
285/// This only kicks in when VectorTransformsOptions is set to Dot and
286/// the vector.contract op is a row-major matmul or matvec.
287class ContractionOpToDotLowering
288 : public MaskableOpRewritePattern<vector::ContractionOp> {
289public:
290 using MaskableOpRewritePattern::MaskableOpRewritePattern;
291
292 using FilterConstraintType =
293 std::function<LogicalResult(vector::ContractionOp op)>;
294
295 static LogicalResult defaultFilter(vector::ContractionOp op) {
296 return success();
297 }
298
299 ContractionOpToDotLowering(
300 vector::VectorContractLowering vectorContractLowering,
301 MLIRContext *context, PatternBenefit benefit = 1,
302 const FilterConstraintType &constraint = defaultFilter)
303 : MaskableOpRewritePattern<vector::ContractionOp>(context, benefit),
304 vectorContractLowering(vectorContractLowering), filter(defaultFilter) {}
305
306 FailureOr<Value>
307 matchAndRewriteMaskableOp(vector::ContractionOp op, MaskingOpInterface maskOp,
308 PatternRewriter &rewriter) const override;
309
310private:
311 /// Options to control the vector patterns.
312 vector::VectorContractLowering vectorContractLowering;
313 FilterConstraintType filter;
314};
315
316/// Progressive lowering of ContractionOp.
317///
318/// One:
319/// %x = vector.contract with at least one free/batch dimension
320/// is replaced by:
321/// %a = vector.contract with one less free/batch dimension
322/// %b = vector.contract with one less free/batch dimension
323/// ..
324/// %x = combine %a %b ..
325/// until a pure contraction is reached (no free/batch dimensions),
326/// which is replaced by a dot-product.
327///
328/// This only kicks in when either VectorTransformsOptions is set
329/// to Dot or when other contraction patterns fail.
330class ContractionOpLowering
331 : public MaskableOpRewritePattern<vector::ContractionOp> {
332public:
333 using MaskableOpRewritePattern::MaskableOpRewritePattern;
334 using FilterConstraintType =
335 std::function<LogicalResult(vector::ContractionOp op)>;
336
337 static LogicalResult defaultFilter(vector::ContractionOp op) {
338 return success();
339 }
340
341 ContractionOpLowering(
342 vector::VectorContractLowering vectorContractLoweringOption,
343 MLIRContext *context, PatternBenefit benefit = 1,
344 FilterConstraintType constraint = defaultFilter)
345 : MaskableOpRewritePattern<vector::ContractionOp>(context, benefit),
346 vectorContractLoweringOption(vectorContractLoweringOption),
347 filter(std::move(constraint)) {}
348
349 FailureOr<Value>
350 matchAndRewriteMaskableOp(vector::ContractionOp op, MaskingOpInterface maskOp,
351 PatternRewriter &rewriter) const override;
352
353private:
354 /// Options to control the vector patterns.
355 vector::VectorContractLowering vectorContractLoweringOption;
356 FilterConstraintType filter;
357 // Lower one parallel dimension.
358 FailureOr<Value> lowerParallel(PatternRewriter &rewriter,
359 vector::ContractionOp op, int64_t lhsIndex,
360 int64_t rhsIndex, Value mask) const;
361 // Lower one reduction dimension.
362 FailureOr<Value> lowerReduction(PatternRewriter &rewriter,
363 vector::ContractionOp op, Value mask) const;
364};
365
366/// Generate a vector implementation for matmat, matvec and tmatvec.
367/// This unrolls outer-products along the reduction dimension.
368struct UnrolledOuterProductGenerator
369 : public StructuredGenerator<vector::ContractionOp, vector::IteratorType> {
370 UnrolledOuterProductGenerator(RewriterBase &b, vector::ContractionOp op)
371 : StructuredGenerator<vector::ContractionOp, vector::IteratorType>(b, op),
372 kind(op.getKind()), lhs(op.getLhs()), rhs(op.getRhs()),
373 res(op.getAcc()), lhsType(op.getLhsType()) {
374 auto maskableOp = cast<MaskableOpInterface>(op.getOperation());
375 if (maskableOp.isMasked())
376 mask = maskableOp.getMaskingOp().getMask();
377 }
378
379 Value t(Value v, ArrayRef<int64_t> perm = {1, 0}) {
380 if (!v)
381 return v;
382 return vector::TransposeOp::create(rewriter, loc, v, perm);
383 }
384
385 Value promote(Value v, Type dstElementType) {
386 Type elementType = v.getType();
387 auto vecType = dyn_cast<VectorType>(elementType);
388 if (vecType)
389 elementType = vecType.getElementType();
390 if (elementType == dstElementType)
391 return v;
392 Type promotedType = dstElementType;
393 if (vecType)
394 promotedType = vecType.clone(promotedType);
395 if (isa<FloatType>(dstElementType))
396 return arith::ExtFOp::create(rewriter, loc, promotedType, v,
397 /*fastmath=*/{});
398 return arith::ExtSIOp::create(rewriter, loc, promotedType, v);
399 }
400
401 FailureOr<Value> outerProd(Value lhs, Value rhs, Value res,
402 VectorType lhsType, int reductionSize,
403 std::optional<Value> maybeMask = std::nullopt) {
404 // Incremental support for masking.
405 if (mask && !maybeMask.has_value())
406 return failure();
407
408 Type resElementType = cast<VectorType>(res.getType()).getElementType();
409 for (int64_t k = 0; k < reductionSize; ++k) {
410 Value extractA = vector::ExtractOp::create(rewriter, loc, lhs, k);
411 Value extractB = vector::ExtractOp::create(rewriter, loc, rhs, k);
412 extractA = promote(extractA, resElementType);
413 extractB = promote(extractB, resElementType);
414 Value extractMask;
415 if (maybeMask.has_value() && maybeMask.value())
416 extractMask =
417 vector::ExtractOp::create(rewriter, loc, maybeMask.value(), k);
418
419 Operation *outerProdOp = vector::OuterProductOp::create(
420 rewriter, loc, res.getType(), extractA, extractB, res, kind);
421 res = maskOperation(rewriter, outerProdOp, extractMask)->getResult(0);
422 }
423 return res;
424 }
425
426 /// Helper function for `matmat`, `matvec`, `tmatvec`. Returns the size of
427 /// dimension `reductionDim`. If the dimension is a scalable dimension,
428 /// returns "nullopt".
429 std::optional<int64_t> getReductionSize(VectorType vecType,
430 int64_t reductionDim) {
431 // Cannot unroll scalable dimension.
432 if (vecType.getScalableDims()[reductionDim])
433 return std::nullopt;
434 int64_t reductionSize = vecType.getDimSize(reductionDim);
435 assert(reductionSize > 0 &&
436 "Reduction dim must be a known static size to allow unrolling");
437 return reductionSize;
438 }
439
440 /// Two outer parallel, one inner reduction (matmat flavor).
441 FailureOr<Value> matmat() {
442 if (!iters({Par(), Par(), Red()}))
443 return failure();
444 // Set up the parallel/reduction structure in the right form.
445 AffineExpr m, n, k;
446 bindDims(rewriter.getContext(), m, n, k);
447
448 // Classical row-major matmul: Just permute the lhs.
449 if (layout({{m, k}, {k, n}, {m, n}})) {
450 if (auto reductionSize = getReductionSize(lhsType, 1)) {
451 // Note: `t` creates new IR. It must be nested within this `if` check
452 // so that no IR is created when then pattern returns "failure".
453 Value tLhs = t(lhs);
454 Value tMask = t(mask, {2, 0, 1});
455 return outerProd(tLhs, rhs, res, lhsType, *reductionSize, tMask);
456 }
457 }
458 // TODO: may be better to fail and use some vector<k> -> scalar reduction.
459 if (layout({{m, k}, {n, k}, {m, n}})) {
460 if (auto reductionSize = getReductionSize(lhsType, 1)) {
461 Value tLhs = t(lhs);
462 Value tRhs = t(rhs);
463 Value tMask = t(mask, {2, 0, 1});
464 return outerProd(tLhs, tRhs, res, lhsType, *reductionSize, tMask);
465 }
466 }
467 // No need to permute anything.
468 if (layout({{k, m}, {k, n}, {m, n}})) {
469 if (auto reductionSize = getReductionSize(lhsType, 0)) {
470 Value tMask = t(mask, {2, 0, 1});
471 return outerProd(lhs, rhs, res, lhsType, *reductionSize, tMask);
472 }
473 }
474 // Just permute the rhs.
475 if (layout({{k, m}, {n, k}, {m, n}})) {
476 if (auto reductionSize = getReductionSize(lhsType, 0)) {
477 Value tRhs = t(rhs);
478 Value tMask = t(mask, {2, 0, 1});
479 return outerProd(lhs, tRhs, res, lhsType, *reductionSize, tMask);
480 }
481 }
482 // Transposed output: swap RHS and LHS.
483 // Classical row-major matmul: permute the lhs.
484 if (layout({{m, k}, {k, n}, {n, m}})) {
485 if (auto reductionSize = getReductionSize(lhsType, 1)) {
486 Value tLhs = t(lhs);
487 Value tMask = t(mask, {2, 0, 1});
488 return outerProd(rhs, tLhs, res, lhsType, *reductionSize, tMask);
489 }
490 }
491 // TODO: may be better to fail and use some vector<k> -> scalar reduction.
492 if (layout({{m, k}, {n, k}, {n, m}})) {
493 if (auto reductionSize = getReductionSize(lhsType, 1)) {
494 Value tRhs = t(rhs);
495 Value tLhs = t(lhs);
496 Value tMask = t(mask, {2, 0, 1});
497 return outerProd(tRhs, tLhs, res, lhsType, *reductionSize, tMask);
498 }
499 }
500 if (layout({{k, m}, {k, n}, {n, m}})) {
501 if (auto reductionSize = getReductionSize(lhsType, 0)) {
502 Value tMask = t(mask, {2, 0, 1});
503 return outerProd(rhs, lhs, res, lhsType, *reductionSize, tMask);
504 }
505 }
506 if (layout({{k, m}, {n, k}, {n, m}})) {
507 if (auto reductionSize = getReductionSize(lhsType, 0)) {
508 Value tRhs = t(rhs);
509 Value tMask = t(mask, {2, 0, 1});
510 return outerProd(tRhs, lhs, res, lhsType, *reductionSize, tMask);
511 }
512 }
513 return failure();
514 }
515
516 //
517 // One outer parallel, one inner reduction (matvec flavor).
518 // Mask needs to be transposed everywhere to turn the reduction dimension
519 // outermost as required by outerproduct.
520 //
521 FailureOr<Value> matvec() {
522 if (!iters({Par(), Red()}))
523 return failure();
524 AffineExpr m, k;
525 bindDims(rewriter.getContext(), m, k);
526
527 // Case mat-vec: transpose.
528 if (layout({{m, k}, {k}, {m}})) {
529 if (auto reductionSize = getReductionSize(lhsType, 1)) {
530 Value tLhs = t(lhs);
531 Value tMask = t(mask);
532 return outerProd(tLhs, rhs, res, lhsType, *reductionSize, tMask);
533 }
534 }
535 // Case mat-trans-vec: ready to go.
536 if (layout({{k, m}, {k}, {m}})) {
537 if (auto reductionSize = getReductionSize(lhsType, 0)) {
538 Value tMask = t(mask);
539 return outerProd(lhs, rhs, res, lhsType, *reductionSize, tMask);
540 }
541 }
542 // Case vec-mat: swap and transpose.
543 if (layout({{k}, {m, k}, {m}})) {
544 if (auto reductionSize = getReductionSize(lhsType, 0)) {
545 Value tRhs = t(rhs);
546 Value tMask = t(mask);
547 return outerProd(tRhs, lhs, res, lhsType, *reductionSize, tMask);
548 }
549 }
550 // Case vec-mat-trans: swap and ready to go.
551 if (layout({{k}, {k, m}, {m}})) {
552 if (auto reductionSize = getReductionSize(lhsType, 0)) {
553 Value tMask = t(mask);
554 return outerProd(rhs, lhs, res, lhsType, *reductionSize, tMask);
555 }
556 }
557 return failure();
558 }
559
560 //
561 // One outer reduction, one inner parallel (tmatvec flavor).
562 // Mask already has the shape of the outer product.
563 //
564 FailureOr<Value> tmatvec() {
565 if (!iters({Red(), Par()}))
566 return failure();
567 AffineExpr k, m;
568 bindDims(rewriter.getContext(), k, m);
569
570 // Case mat-vec: transpose.
571 if (layout({{m, k}, {k}, {m}}))
572 if (auto reductionSize = getReductionSize(lhsType, 1))
573 return outerProd(t(lhs), rhs, res, lhsType, *reductionSize, mask);
574 // Case mat-trans-vec: ready to go.
575 if (layout({{k, m}, {k}, {m}}))
576 if (auto reductionSize = getReductionSize(lhsType, 0))
577 return outerProd(lhs, rhs, res, lhsType, *reductionSize, mask);
578 // Case vec-mat: swap and transpose.
579 if (layout({{k}, {m, k}, {m}}))
580 if (auto reductionSize = getReductionSize(lhsType, 0))
581 return outerProd(t(rhs), lhs, res, lhsType, *reductionSize, mask);
582 // Case vec-mat-trans: swap and ready to go.
583 if (layout({{k}, {k, m}, {m}}))
584 if (auto reductionSize = getReductionSize(lhsType, 0))
585 return outerProd(rhs, lhs, res, lhsType, *reductionSize, mask);
586 return failure();
587 }
588
589private:
590 vector::CombiningKind kind;
591 Value lhs, rhs, res, mask;
592 VectorType lhsType;
593};
594
595/// Progressively lower a `vector.contract %a, %b, %c` with row-major matmul
596/// semantics to a reduction_size-unrolled sequence:
597/// ```
598/// %at = vector.transpose %a, [1, 0]
599/// %bRow0 = vector.extract %b[0]
600/// %atRow0 = vector.extract %at[0]
601/// %c0 = vector.outerproduct %atRow0, %bRow0, %c
602/// ...
603/// %bRowK = vector.extract %b[K]
604/// %atRowK = vector.extract %at[K]
605/// %cK = vector.outerproduct %atRowK, %bRowK, %cK-1
606/// ```
607///
608/// This only kicks in when vectorContractLowering is set to OuterProduct but
609/// otherwise supports any layout permutation of the matrix-multiply.
610FailureOr<Value>
611ContractionOpToOuterProductOpLowering::matchAndRewriteMaskableOp(
612 vector::ContractionOp op, MaskingOpInterface maskOp,
613 PatternRewriter &rewriter) const {
614 if (vectorContractLowering != vector::VectorContractLowering::OuterProduct)
615 return failure();
616
617 if (failed(filter(op)))
618 return failure();
619
620 UnrolledOuterProductGenerator e(rewriter, op);
621 FailureOr<Value> matmatRes = e.matmat();
622 if (succeeded(matmatRes)) {
623 return matmatRes;
624 }
625 FailureOr<Value> matvecRes = e.matvec();
626 if (succeeded(matvecRes)) {
627 return matvecRes;
628 }
629
630 FailureOr<Value> tmatvecRes = e.tmatvec();
631 return tmatvecRes;
632}
633
634FailureOr<Value> ContractionOpToDotLowering::matchAndRewriteMaskableOp(
635 vector::ContractionOp op, MaskingOpInterface maskOp,
636 PatternRewriter &rewriter) const {
637 // TODO: Support vector.mask.
638 if (maskOp)
639 return failure();
640
641 if (failed(filter(op)))
642 return failure();
643
644 if (vectorContractLowering != vector::VectorContractLowering::Dot)
645 return failure();
646
647 auto iteratorTypes = op.getIteratorTypes().getValue();
648 static constexpr std::array<int64_t, 2> perm = {1, 0};
649 Location loc = op.getLoc();
650 Value lhs = op.getLhs(), rhs = op.getRhs();
651
652 using MapList = ArrayRef<ArrayRef<AffineExpr>>;
653 auto infer = [&](MapList m) {
654 return AffineMap::inferFromExprList(m, op.getContext());
655 };
656 AffineExpr m, n, k;
657 bindDims(rewriter.getContext(), m, n, k);
658 SmallVector<AffineMap> maps = op.getIndexingMapsArray();
659 //
660 // In the following we wish to make the reduction dimension innermost so we
661 // can load vectors and just fmul + reduce into a scalar.
662 //
663 if (isParallelIterator(iteratorTypes[0]) &&
664 isParallelIterator(iteratorTypes[1]) &&
665 isReductionIterator(iteratorTypes[2])) {
666 //
667 // Two outer parallel, one inner reduction (matmat flavor).
668 //
669 if (maps == infer({{m, k}, {k, n}, {m, n}})) {
670 rhs = vector::TransposeOp::create(rewriter, loc, rhs, perm);
671 } else if (maps == infer({{m, k}, {n, k}, {m, n}})) {
672 // No need to permute anything.
673 } else if (maps == infer({{k, m}, {k, n}, {m, n}})) {
674 lhs = vector::TransposeOp::create(rewriter, loc, lhs, perm);
675 rhs = vector::TransposeOp::create(rewriter, loc, rhs, perm);
676 } else if (maps == infer({{k, m}, {n, k}, {m, n}})) {
677 lhs = vector::TransposeOp::create(rewriter, loc, lhs, perm);
678 } else if (maps == infer({{m, k}, {k, n}, {n, m}})) {
679 // This is the classical row-major matmul. Just permute the lhs.
680 Value tmp = lhs;
681 lhs = vector::TransposeOp::create(rewriter, loc, rhs, perm);
682 rhs = tmp;
683 } else if (maps == infer({{m, k}, {n, k}, {n, m}})) {
684 std::swap(lhs, rhs);
685 } else if (maps == infer({{k, m}, {k, n}, {n, m}})) {
686 Value tmp = lhs;
687 lhs = vector::TransposeOp::create(rewriter, loc, rhs, perm);
688 rhs = vector::TransposeOp::create(rewriter, loc, tmp, perm);
689 } else if (maps == infer({{k, m}, {n, k}, {n, m}})) {
690 Value tmp = rhs;
691 rhs = vector::TransposeOp::create(rewriter, loc, lhs, perm);
692 lhs = tmp;
693 } else {
694 return failure();
695 }
696 } else if (isParallelIterator(iteratorTypes[0]) &&
697 isReductionIterator(iteratorTypes[1])) {
698 //
699 // One outer parallel, one inner reduction (matvec flavor)
700 //
701 if (maps == infer({{m, n}, {n}, {m}})) {
702 // No need to permute anything.
703 } else if (maps == infer({{n, m}, {n}, {m}})) {
704 lhs = vector::TransposeOp::create(rewriter, loc, lhs, perm);
705 } else if (maps == infer({{n}, {m, n}, {m}})) {
706 std::swap(lhs, rhs);
707 } else if (maps == infer({{n}, {n, m}, {m}})) {
708 std::swap(lhs, rhs);
709 lhs = vector::TransposeOp::create(rewriter, loc, lhs, perm);
710 } else {
711 return failure();
712 }
713 } else {
714 return failure();
715 }
716
717 VectorType dstType = cast<VectorType>(op.getResultType());
718 assert(dstType.getRank() >= 1 && dstType.getRank() <= 2 &&
719 "Expected dst type of rank 1 or 2");
720
721 unsigned rank = dstType.getRank();
722 unsigned dstRows = dstType.getShape()[0];
723 unsigned dstColumns = rank == 1 ? 1 : dstType.getShape()[1];
724
725 // ExtractOp does not allow dynamic indexing, we must unroll explicitly.
726 Value res = arith::ConstantOp::create(rewriter, loc, dstType,
727 rewriter.getZeroAttr(dstType));
728 bool isInt = isa<IntegerType>(dstType.getElementType());
729 arith::FastMathFlagsAttr fmf = op.getFastmathAttr();
730 llvm::SmallVector<Value> extractedCols;
731 extractedCols.reserve(dstColumns);
732 for (unsigned r = 0; r < dstRows; ++r) {
733 Value rowLhs = vector::ExtractOp::create(rewriter, op.getLoc(), lhs, r);
734 for (unsigned c = 0; c < dstColumns; ++c) {
735 // Extract each respective row and column of the LHS and RHS once to
736 // avoid having duplicate SSA values pointing to the same rows/columns.
737 if (r == 0) {
738 Value colRhs =
739 rank == 1
740 ? rhs
741 : vector::ExtractOp::create(rewriter, op.getLoc(), rhs, c);
742 extractedCols.push_back(colRhs);
743 }
744 Value extractedColRhs = extractedCols[c];
745 Value product =
746 createMul(op.getLoc(), rowLhs, extractedColRhs, isInt, rewriter, fmf);
747 Value sum = vector::ReductionOp::create(rewriter, op.getLoc(),
748 vector::CombiningKind::ADD,
749 product, op.getFastmath());
750
753 res = vector::InsertOp::create(rewriter, op.getLoc(), sum, res, pos);
754 }
755 }
756 if (auto acc = op.getAcc())
757 res = createAdd(op.getLoc(), res, acc, isInt, rewriter, fmf);
758 return res;
759}
760
761/// Lower vector.contract with all size one reduction dimensions to
762/// elementwise ops when possible.
763struct ContractOpToElementwise
764 : public MaskableOpRewritePattern<vector::ContractionOp> {
765 using MaskableOpRewritePattern::MaskableOpRewritePattern;
766 using FilterConstraintType =
767 std::function<LogicalResult(vector::ContractionOp op)>;
768 static LogicalResult defaultFilter(vector::ContractionOp op) {
769 return success();
770 }
771 ContractOpToElementwise(
772 vector::VectorContractLowering vectorContractLowering,
773 MLIRContext *context, PatternBenefit benefit = 1,
774 const FilterConstraintType &constraint = defaultFilter)
775 : MaskableOpRewritePattern<vector::ContractionOp>(context, benefit),
776 vectorContractLowering(vectorContractLowering), filter(defaultFilter) {}
777
778 FailureOr<Value>
779 matchAndRewriteMaskableOp(vector::ContractionOp contractOp,
780 MaskingOpInterface maskOp,
781 PatternRewriter &rewriter) const override {
782 // TODO: Support vector.mask.
783 if (maskOp)
784 return failure();
785
786 if (failed(filter(contractOp)))
787 return failure();
788
789 if (vectorContractLowering != vector::VectorContractLowering::ParallelArith)
790 return failure();
791
792 ArrayRef<int64_t> lhsShape = contractOp.getLhsType().getShape();
793 ArrayRef<int64_t> rhsShape = contractOp.getRhsType().getShape();
794 AffineMap lhsMap = contractOp.getIndexingMapsArray()[0];
795 AffineMap rhsMap = contractOp.getIndexingMapsArray()[1];
796 SmallVector<int64_t> lhsReductionDims =
797 getReductionIndex(lhsMap, contractOp.getIteratorTypes());
798 SmallVector<int64_t> rhsReductionDims =
799 getReductionIndex(rhsMap, contractOp.getIteratorTypes());
800 // All the reduction dimensions must be a size 1.
801 for (int64_t dim : lhsReductionDims) {
802 if (lhsShape[dim] != 1)
803 return failure();
804 }
805 for (int64_t dim : rhsReductionDims) {
806 if (rhsShape[dim] != 1)
807 return failure();
808 }
809 AffineMap accMap = contractOp.getIndexingMapsArray()[2];
810 unsigned numParallelDims = accMap.getNumResults();
811 unsigned numLhsDimToBroadcast =
812 numParallelDims - (lhsMap.getNumResults() - lhsReductionDims.size());
813 unsigned numRhsDimToBroadcast =
814 numParallelDims - (rhsMap.getNumResults() - rhsReductionDims.size());
815 SmallVector<int64_t> lhsDims;
816 SmallVector<int64_t> lhsTranspose;
817 SmallVector<int64_t> rhsDims;
818 SmallVector<int64_t> rhsTranspose;
819 for (int64_t dim : lhsReductionDims)
820 lhsTranspose.push_back(numLhsDimToBroadcast + dim);
821 for (int64_t dim : rhsReductionDims)
822 rhsTranspose.push_back(numRhsDimToBroadcast + dim);
823 // Loop through the parallel dimensions to calculate the dimensions to
824 // broadcast and to permute in order to extract only parallel dimensions.
825 for (unsigned i = 0; i < numParallelDims; i++) {
826 std::optional<unsigned> lhsDim =
827 getDimPosition(lhsMap, accMap.getDimPosition(i));
828 if (lhsDim) {
829 lhsTranspose.push_back(numLhsDimToBroadcast + *lhsDim);
830 } else {
831 // If the parallel dimension doesn't exist we will have to broadcast it.
832 lhsDims.push_back(
833 cast<VectorType>(contractOp.getResultType()).getDimSize(i));
834 lhsTranspose.push_back(lhsDims.size() - 1);
835 }
836 std::optional<unsigned> rhsDim =
837 getDimPosition(rhsMap, accMap.getDimPosition(i));
838 if (rhsDim) {
839 rhsTranspose.push_back(numRhsDimToBroadcast + *rhsDim);
840 } else {
841 // If the parallel dimension doesn't exist we will have to broadcast it.
842 rhsDims.push_back(
843 cast<VectorType>(contractOp.getResultType()).getDimSize(i));
844 rhsTranspose.push_back(rhsDims.size() - 1);
845 }
846 }
847 Value newLhs = contractOp.getLhs();
848 Value newRhs = contractOp.getRhs();
849 Location loc = contractOp.getLoc();
850 if (!lhsDims.empty()) {
851 lhsDims.append(lhsShape.begin(), lhsShape.end());
852 auto expandedType =
853 VectorType::get(lhsDims, contractOp.getLhsType().getElementType());
854 newLhs = vector::BroadcastOp::create(rewriter, loc, expandedType, newLhs);
855 }
856 if (!rhsDims.empty()) {
857 rhsDims.append(rhsShape.begin(), rhsShape.end());
858 auto expandedType =
859 VectorType::get(rhsDims, contractOp.getRhsType().getElementType());
860 newRhs = vector::BroadcastOp::create(rewriter, loc, expandedType, newRhs);
861 }
862 bool isInt = contractOp.getLhsType().getElementType().isIntOrIndex();
863 newLhs = vector::TransposeOp::create(rewriter, loc, newLhs, lhsTranspose);
864 newRhs = vector::TransposeOp::create(rewriter, loc, newRhs, rhsTranspose);
865 SmallVector<int64_t> lhsOffsets(lhsReductionDims.size(), 0);
866 SmallVector<int64_t> rhsOffsets(rhsReductionDims.size(), 0);
867 newLhs = vector::ExtractOp::create(rewriter, loc, newLhs, lhsOffsets);
868 newRhs = vector::ExtractOp::create(rewriter, loc, newRhs, rhsOffsets);
869 std::optional<Value> result =
870 createContractArithOp(loc, newLhs, newRhs, contractOp.getAcc(),
871 contractOp.getKind(), rewriter, isInt,
872 /*mask=*/Value(), contractOp.getFastmathAttr());
873 if (result)
874 return *result;
875
876 return failure();
877 }
878
879private:
880 /// Options to control the vector patterns.
881 vector::VectorContractLowering vectorContractLowering;
882 FilterConstraintType filter;
883};
884
885/// Progressive lowering of ContractionOp.
886/// One:
887/// %x = vector.contract with at least one free/batch dimension
888/// is replaced by:
889/// %a = vector.contract with one less free/batch dimension
890/// %b = vector.contract with one less free/batch dimension
891/// ..
892/// %x = combine %a %b ..
893/// until a pure contraction is reached (no free/batch dimensions),
894/// which is replaced by a dot-product.
895///
896/// This only kicks in when either vectorContractLoweringOption is set
897/// to DOT or when other contraction patterns fail.
898//
899// TODO: break down into transpose/reshape/cast ops
900// when they become available to avoid code dup
901// TODO: investigate lowering order impact on performance
902FailureOr<Value> ContractionOpLowering::matchAndRewriteMaskableOp(
903 vector::ContractionOp op, MaskingOpInterface maskOp,
904 PatternRewriter &rewriter) const {
905 if (failed(filter(op)))
906 return failure();
907
908 // TODO: support mixed mode contract lowering.
909 if (op.getLhsType().getElementType() !=
910 getElementTypeOrSelf(op.getAccType()) ||
911 op.getRhsType().getElementType() != getElementTypeOrSelf(op.getAccType()))
912 return failure();
913
914 // TODO: the code below assumes the default contraction, make sure it supports
915 // other kinds before enabling this lowering.
916 if (op.getKind() != vector::CombiningKind::ADD) {
917 return rewriter.notifyMatchFailure(
918 op, "contractions other than 'add' not supported");
919 }
920
921 // TODO: implement benefits, cost models.
922 MLIRContext *ctx = op.getContext();
923
924 ContractionOpToOuterProductOpLowering pat1(vectorContractLoweringOption, ctx);
925 FailureOr<Value> newVal1 =
926 pat1.matchAndRewriteMaskableOp(op, maskOp, rewriter);
927 if (!failed(newVal1))
928 return newVal1;
929
930 ContractionOpToDotLowering pat2(vectorContractLoweringOption, ctx);
931 FailureOr<Value> newVal2 =
932 pat2.matchAndRewriteMaskableOp(op, maskOp, rewriter);
933 if (!failed(newVal2))
934 return newVal2;
935
936 ContractOpToElementwise pat4(vectorContractLoweringOption, ctx);
937 FailureOr<Value> newVal4 =
938 pat4.matchAndRewriteMaskableOp(op, maskOp, rewriter);
939 if (!failed(newVal4))
940 return newVal4;
941
942 // Vector mask setup.
943
944 Value mask;
945 if (maskOp)
946 mask = maskOp.getMask();
947 // Find first batch dimension in LHS/RHS, and lower when found.
948 std::vector<std::pair<int64_t, int64_t>> batchDimMap = op.getBatchDimMap();
949 if (!batchDimMap.empty()) {
950 int64_t lhsIndex = batchDimMap[0].first;
951 int64_t rhsIndex = batchDimMap[0].second;
952 auto newOp = lowerParallel(rewriter, op, lhsIndex, rhsIndex, mask);
953 if (failed(newOp))
954 return failure();
955 return newOp;
956 }
957
958 // Collect contracting dimensions.
959 std::vector<std::pair<int64_t, int64_t>> contractingDimMap =
960 op.getContractingDimMap();
961 DenseSet<int64_t> lhsContractingDimSet;
962 DenseSet<int64_t> rhsContractingDimSet;
963 for (auto &dimPair : contractingDimMap) {
964 lhsContractingDimSet.insert(dimPair.first);
965 rhsContractingDimSet.insert(dimPair.second);
966 }
967
968 // Find first free dimension in LHS, and lower when found.
969 VectorType lhsType = op.getLhsType();
970 for (int64_t lhsIndex = 0, e = lhsType.getRank(); lhsIndex < e; ++lhsIndex) {
971 if (lhsContractingDimSet.count(lhsIndex) == 0) {
972 auto newOp = lowerParallel(rewriter, op, lhsIndex, /*rhsIndex=*/-1, mask);
973 if (failed(newOp))
974 return failure();
975 return newOp;
976 }
977 }
978
979 // Find first free dimension in RHS, and lower when found.
980 VectorType rhsType = op.getRhsType();
981 for (int64_t rhsIndex = 0, e = rhsType.getRank(); rhsIndex < e; ++rhsIndex) {
982 if (rhsContractingDimSet.count(rhsIndex) == 0) {
983 auto newOp = lowerParallel(rewriter, op, /*lhsIndex=*/-1, rhsIndex, mask);
984 if (failed(newOp))
985 return failure();
986 return newOp;
987 }
988 }
989
990 // Lower the first remaining reduction dimension.
991 if (!contractingDimMap.empty()) {
992 auto newOp = lowerReduction(rewriter, op, mask);
993 if (failed(newOp))
994 return failure();
995 return newOp;
996 }
997
998 return failure();
999}
1000
1001// Lower one parallel dimension.
1002// Incidentally also tolerates unit-size (hence trivial) reduction dimensions.
1003// TODO: consider reusing existing contract unrolling
1004FailureOr<Value> ContractionOpLowering::lowerParallel(PatternRewriter &rewriter,
1005 vector::ContractionOp op,
1006 int64_t lhsIndex,
1007 int64_t rhsIndex,
1008 Value mask) const {
1009 VectorType lhsType = op.getLhsType();
1010 VectorType rhsType = op.getRhsType();
1011 VectorType resType = cast<VectorType>(op.getResultType());
1012 // Find the iterator type index and result index.
1013 SmallVector<AffineMap> iMap = op.getIndexingMapsArray();
1014 int64_t iterIndex = -1;
1015 int64_t dimSize = -1;
1016 if (lhsIndex >= 0) {
1017 iterIndex = iMap[0].getDimPosition(lhsIndex);
1018 if (rhsIndex >= 0 && iterIndex != iMap[1].getDimPosition(rhsIndex))
1019 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
1020 diag << "expected lhsIndex=" << lhsIndex << " and rhsIndex=" << rhsIndex
1021 << " to map to the same dimension";
1022 });
1023 if (lhsType.getScalableDims()[lhsIndex])
1024 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
1025 diag << "Unrolling scalable dimension (lhsIndex=" << lhsIndex
1026 << ") is not supported yet";
1027 });
1028 dimSize = lhsType.getDimSize(lhsIndex);
1029 } else if (rhsIndex >= 0) {
1030 iterIndex = iMap[1].getDimPosition(rhsIndex);
1031 if (rhsType.getScalableDims()[rhsIndex])
1032 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
1033 diag << "Unrolling scalable dimension (rhsIndex=" << rhsIndex
1034 << ") is not supported yet";
1035 });
1036 dimSize = rhsType.getDimSize(rhsIndex);
1037 }
1038 if (iterIndex < 0)
1039 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
1040 diag << "expected either lhsIndex=" << lhsIndex
1041 << " or rhsIndex=" << rhsIndex << " to be nonnegative";
1042 });
1043 // value_or(-1) means that we tolerate a dimension not appearing
1044 // in the result map. That can't happen for actual parallel iterators, but
1045 // the caller ContractionOpLowering::matchAndRewrite is currently calling
1046 // lowerParallel also for the case of unit-size reduction dims appearing only
1047 // on one of LHS or RHS, not both. At the moment, such cases are created by
1048 // CastAwayContractionLeadingOneDim, so we need to either support that or
1049 // modify that pattern.
1050 int64_t resIndex = getResultIndex(iMap[2], iterIndex).value_or(-1);
1051 if (resIndex == -1 && dimSize != 1)
1052 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
1053 diag << "expected the dimension for iterIndex=" << iterIndex
1054 << " to either appear in the result map, or to be a unit dimension";
1055 });
1056
1057 // Construct new iterator types and affine map array attribute.
1058 std::array<AffineMap, 3> lowIndexingMaps = {
1059 adjustMap(iMap[0], iterIndex, rewriter),
1060 adjustMap(iMap[1], iterIndex, rewriter),
1061 adjustMap(iMap[2], iterIndex, rewriter)};
1062 auto lowAffine = rewriter.getAffineMapArrayAttr(lowIndexingMaps);
1063 auto lowIter =
1064 rewriter.getArrayAttr(adjustIter(op.getIteratorTypes(), iterIndex));
1065 // Unroll into a series of lower dimensional vector.contract ops.
1066 Location loc = op.getLoc();
1067 Value result = arith::ConstantOp::create(rewriter, loc, resType,
1068 rewriter.getZeroAttr(resType));
1069
1070 for (int64_t d = 0; d < dimSize; ++d) {
1071 auto lhs = reshapeLoad(loc, op.getLhs(), lhsIndex, d, rewriter);
1072 auto rhs = reshapeLoad(loc, op.getRhs(), rhsIndex, d, rewriter);
1073 auto acc = reshapeLoad(loc, op.getAcc(), resIndex, d, rewriter);
1074
1075 Value lowMask;
1076 if (mask)
1077 lowMask = reshapeLoad(loc, mask, iterIndex, d, rewriter);
1078
1079 Operation *lowContract =
1080 vector::ContractionOp::create(rewriter, loc, lhs, rhs, acc, lowAffine,
1081 lowIter, op.getKind(), op.getFastmath());
1082 lowContract = maskOperation(rewriter, lowContract, lowMask);
1083 result = reshapeStore(loc, lowContract->getResult(0), result, resIndex, d,
1084 rewriter);
1085 }
1086 return result;
1087}
1088
1089// Lower one reduction dimension.
1090FailureOr<Value> ContractionOpLowering::lowerReduction(
1091 PatternRewriter &rewriter, vector::ContractionOp op, Value mask) const {
1092 auto loc = op.getLoc();
1093 VectorType lhsType = op.getLhsType();
1094 VectorType rhsType = op.getRhsType();
1095 Type resType = op.getResultType();
1096 if (isa<VectorType>(resType))
1097 return rewriter.notifyMatchFailure(op,
1098 "did not expect a VectorType result");
1099 bool isInt = isa<IntegerType>(resType);
1100 // Use iterator index 0.
1101 int64_t iterIndex = 0;
1102 SmallVector<AffineMap> iMap = op.getIndexingMapsArray();
1103 std::optional<int64_t> lookupLhs = getResultIndex(iMap[0], iterIndex);
1104 std::optional<int64_t> lookupRhs = getResultIndex(iMap[1], iterIndex);
1105 if (!lookupLhs.has_value())
1106 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
1107 diag << "expected iterIndex=" << iterIndex << "to map to a LHS dimension";
1108 });
1109 if (!lookupRhs.has_value())
1110 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
1111 diag << "expected iterIndex=" << iterIndex << "to map to a RHS dimension";
1112 });
1113 int64_t lhsIndex = *lookupLhs;
1114 int64_t rhsIndex = *lookupRhs;
1115 int64_t dimSize = lhsType.getDimSize(lhsIndex);
1116 if (dimSize != rhsType.getDimSize(rhsIndex))
1117 return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
1118 diag << "expect LHS dimension " << lhsIndex
1119 << " to have the same size as RHS dimension " << rhsIndex;
1120 });
1121 // Base case.
1122 if (lhsType.getRank() == 1) {
1123 if (rhsType.getRank() != 1)
1124 return rewriter.notifyMatchFailure(
1125 op, "When LHS has rank 1, expected also RHS to have rank 1");
1126 arith::FastMathFlagsAttr fmf = op.getFastmathAttr();
1127 Value m = createMul(loc, op.getLhs(), op.getRhs(), isInt, rewriter, fmf);
1128 auto kind = vector::CombiningKind::ADD;
1129
1130 Value acc = op.getAcc();
1131 Operation *reductionOp =
1132 acc ? vector::ReductionOp::create(rewriter, loc, kind, m, acc,
1133 op.getFastmath())
1134 : vector::ReductionOp::create(rewriter, loc, kind, m,
1135 op.getFastmath());
1136 return maskOperation(rewriter, reductionOp, mask)->getResult(0);
1137 }
1138 // Construct new iterator types and affine map array attribute.
1139 std::array<AffineMap, 3> lowIndexingMaps = {
1140 adjustMap(iMap[0], iterIndex, rewriter),
1141 adjustMap(iMap[1], iterIndex, rewriter),
1142 adjustMap(iMap[2], iterIndex, rewriter)};
1143 auto lowAffine = rewriter.getAffineMapArrayAttr(lowIndexingMaps);
1144 auto lowIter =
1145 rewriter.getArrayAttr(adjustIter(op.getIteratorTypes(), iterIndex));
1146 // Unroll into a series of lower dimensional vector.contract ops.
1147 // By feeding the initial accumulator into the first contraction,
1148 // and the result of each contraction into the next, eventually
1149 // the sum of all reductions is computed.
1150 Value result = op.getAcc();
1151 for (int64_t d = 0; d < dimSize; ++d) {
1152 auto lhs = reshapeLoad(loc, op.getLhs(), lhsIndex, d, rewriter);
1153 auto rhs = reshapeLoad(loc, op.getRhs(), rhsIndex, d, rewriter);
1154 Value newMask;
1155 if (mask)
1156 newMask = reshapeLoad(loc, mask, iterIndex, d, rewriter);
1157
1158 Operation *newContract = vector::ContractionOp::create(
1159 rewriter, loc, lhs, rhs, result, lowAffine, lowIter, op.getKind(),
1160 op.getFastmath());
1161 result = maskOperation(rewriter, newContract, newMask)->getResult(0);
1162 }
1163 return result;
1164}
1165
1166/// Progressive lowering of OuterProductOp.
1167/// One:
1168/// %x = vector.outerproduct %lhs, %rhs, %acc
1169/// is replaced by:
1170/// %z = zero-result
1171/// %0 = vector.extract %lhs[0]
1172/// %1 = vector.broadcast %0
1173/// %2 = vector.extract %acc[0]
1174/// %3 = vector.fma %1, %rhs, %2
1175/// %4 = vector.insert %3, %z[0]
1176/// ..
1177/// %x = vector.insert %.., %..[N-1]
1178///
1179class OuterProductOpLowering : public OpRewritePattern<vector::OuterProductOp> {
1180public:
1181 using Base::Base;
1182
1183 LogicalResult matchAndRewrite(vector::OuterProductOp op,
1184 PatternRewriter &rewriter) const override {
1185 VectorType resType = op.getResultVectorType();
1186 if ((resType.getShape().size() >= 2) && resType.allDimsScalable())
1187 return failure();
1188
1189 auto loc = op.getLoc();
1190
1191 VectorType lhsType = op.getOperandVectorTypeLHS();
1192 VectorType rhsType = dyn_cast<VectorType>(op.getOperandTypeRHS());
1193 Type eltType = resType.getElementType();
1194 bool isInt = isa<IntegerType, IndexType>(eltType);
1195 Value acc = op.getAcc();
1196 vector::CombiningKind kind = op.getKind();
1197
1198 // Vector mask setup.
1199 OpBuilder::InsertionGuard guard(rewriter);
1200 auto maskableOp = cast<vector::MaskableOpInterface>(op.getOperation());
1201 Operation *rootOp;
1202 Value mask;
1203 if (maskableOp.isMasked()) {
1204 rewriter.setInsertionPoint(maskableOp.getMaskingOp());
1205 rootOp = maskableOp.getMaskingOp();
1206 mask = maskableOp.getMaskingOp().getMask();
1207 } else {
1208 rootOp = op;
1209 }
1210
1211 if (!rhsType) {
1212 // Special case: AXPY operation.
1213 Value b =
1214 vector::BroadcastOp::create(rewriter, loc, lhsType, op.getRhs());
1215 std::optional<Value> mult = createContractArithOp(
1216 loc, op.getLhs(), b, acc, kind, rewriter, isInt, mask);
1217 if (!mult.has_value())
1218 return failure();
1219 rewriter.replaceOp(rootOp, *mult);
1220 return success();
1221 }
1222
1223 Value result = arith::ConstantOp::create(rewriter, loc, resType,
1224 rewriter.getZeroAttr(resType));
1225 for (int64_t d = 0, e = resType.getDimSize(0); d < e; ++d) {
1226 Value x = vector::ExtractOp::create(rewriter, loc, op.getLhs(), d);
1227 Value a = vector::BroadcastOp::create(rewriter, loc, rhsType, x);
1228 Value r = nullptr;
1229 if (acc)
1230 r = vector::ExtractOp::create(rewriter, loc, acc, d);
1231 Value extrMask;
1232 if (mask)
1233 extrMask = vector::ExtractOp::create(rewriter, loc, mask, d);
1234
1235 std::optional<Value> m = createContractArithOp(
1236 loc, a, op.getRhs(), r, kind, rewriter, isInt, extrMask);
1237 if (!m.has_value())
1238 return failure();
1239 result = vector::InsertOp::create(rewriter, loc, *m, result, d);
1240 }
1241
1242 rewriter.replaceOp(rootOp, result);
1243 return success();
1244 }
1245};
1246
1247} // namespace
1248
1250 RewritePatternSet &patterns,
1251 VectorContractLowering vectorContractLoweringOption, PatternBenefit benefit,
1252 bool disableOuterProductLowering) {
1253 if (!disableOuterProductLowering)
1254 patterns.add<OuterProductOpLowering>(patterns.getContext(), benefit);
1255 patterns.add<ContractionOpLowering, ContractionOpToOuterProductOpLowering>(
1256 vectorContractLoweringOption, patterns.getContext(), benefit);
1257}
1258
1260 RewritePatternSet &patterns, PatternBenefit benefit) {
1261 patterns.add<OuterProductOpLowering>(patterns.getContext(), benefit);
1262}
return success()
static int64_t product(ArrayRef< int64_t > vals)
lhs
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
auto load
static std::optional< int64_t > getResultIndex(AffineMap map, int64_t index)
static SmallVector< int64_t > getReductionIndex(AffineMap map, ArrayAttr iteratorTypes)
Return the positions of the reductions in the given map.
static std::optional< unsigned > getDimPosition(AffineMap map, unsigned dim)
Look for a given dimension in an affine map and return its position.
static Value reshapeStore(Location loc, Value val, Value result, int64_t index, int64_t pos, PatternRewriter &rewriter)
Inserts val into result at position pos along dimension index.
static SmallVector< Attribute > adjustIter(ArrayAttr iteratorTypes, int64_t index)
FailureOr< Value > tmatvec()
static Value createAdd(Location loc, Value x, Value y, bool isInt, PatternRewriter &rewriter, arith::FastMathFlagsAttr fmf={})
Creates an AddIOp if isInt is true otherwise create an arith::AddFOp using operands x and y.
FailureOr< Value > outerProd(Value lhs, Value rhs, Value res, VectorType lhsType, int reductionSize, std::optional< Value > maybeMask=std::nullopt)
FailureOr< Value > matvec()
static AffineMap adjustMap(AffineMap map, int64_t index, PatternRewriter &rewriter)
static Value reshapeLoad(Location loc, Value val, int64_t index, int64_t pos, PatternRewriter &rewriter)
Returns val with the dimension at position index dropped by indexing that dimension with pos.
FailureOr< Value > matmat()
Two outer parallel, one inner reduction (matmat flavor).
static std::optional< Value > createContractArithOp(Location loc, Value x, Value y, Value acc, vector::CombiningKind kind, PatternRewriter &rewriter, bool isInt, Value mask=Value(), arith::FastMathFlagsAttr fmf={})
Helper to create arithmetic operation associated with a kind of contraction.
std::optional< int64_t > getReductionSize(VectorType vecType, int64_t reductionDim)
Helper function for matmat, matvec, tmatvec. Returns the size of dimension reductionDim....
static std::string diag(const llvm::Value &value)
#define mul(a, b)
Base type for affine expression.
Definition AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
unsigned getDimPosition(unsigned idx) const
Extracts the position of the dimensional expression at the given result, when the caller knows it is ...
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
unsigned getNumDims() const
unsigned getNumResults() const
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:275
MLIRContext * getContext() const
Definition Builders.h:56
ArrayAttr getAffineMapArrayAttr(ArrayRef< AffineMap > values)
Definition Builders.cpp:327
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
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:63
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:432
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
Helper StructuredGenerator class to manipulate and rewrite ops with StructuredOpInterface.
bool iters(ArrayRef< IteratorType > its)
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
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
This is a builder type that keeps local references to arguments.
Builder & dropDim(unsigned pos)
Erase a dim from shape @pos.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:732
void promote(RewriterBase &rewriter, scf::ForallOp forallOp)
Promotes the loop body of a scf::ForallOp to its containing block.
Definition SCF.cpp:753
Value makeArithReduction(OpBuilder &b, Location loc, CombiningKind kind, Value v1, Value acc, arith::FastMathFlagsAttr fastmath=nullptr, Value mask=nullptr)
Returns the result value of reducing two scalar/vector values with the corresponding arith operation.
Operation * maskOperation(OpBuilder &builder, Operation *maskableOp, Value mask, Value passthru=Value())
Creates a vector.mask operation around a maskable operation.
bool isReductionIterator(Attribute attr)
Returns true if attr has "reduction" iterator type semantics.
Definition VectorOps.h:156
Value selectPassthru(OpBuilder &builder, Value mask, Value newValue, Value passthru)
Creates a vector select operation that picks values from newValue or passthru for each result vector ...
bool isParallelIterator(Attribute attr)
Returns true if attr has "parallel" iterator type semantics.
Definition VectorOps.h:151
void populateVectorOuterProductLoweringPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Populate the pattern set with the following patterns:
void populateVectorContractLoweringPatterns(RewritePatternSet &patterns, VectorContractLowering vectorContractLoweringOption, PatternBenefit benefit=1, bool disableOuterProductLowering=false)
Populate the pattern set with the following patterns:
Include the generated interface declarations.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition AffineExpr.h:311
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:122
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern Base
Type alias to allow derived classes to inherit constructors with using Base::Base;.
A pattern for ops that implement MaskableOpInterface and that might be masked (i.e.
virtual FailureOr< Value > matchAndRewriteMaskableOp(SourceOp sourceOp, MaskingOpInterface maskingOp, PatternRewriter &rewriter) const =0