MLIR 23.0.0git
Specialize.cpp
Go to the documentation of this file.
1//===- Specialize.cpp - linalg generic ops to named 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 a method to specialize generic operations to named
10// operations. Conceptually it is the opposite of generalize.cpp.
11//
12//===----------------------------------------------------------------------===//
13
23
24namespace mlir {
25#define GEN_PASS_DEF_LINALGSPECIALIZEGENERICOPSPASS
26#include "mlir/Dialect/Linalg/Passes.h.inc"
27} // namespace mlir
28
29#define DEBUG_TYPE "linalg-specialization"
30
31using namespace mlir;
32using namespace mlir::linalg;
33
34//===----------------------------------------------------------------------===//
35// Specialize linalg generic to elementwise ops.
36//===----------------------------------------------------------------------===//
37
38// Given an elementwise single binary linalg generic op, checks whether the
39// binary op accesses operands as swapped. e.g.
40// this differentiates between a linalg-generic body that contains:
41// ^bb0(%a: f32, %b: f32, %c : f32):
42// %0 = arith.subf %a, %b : f32
43// linalg.yield %0: f32
44// against:
45// ^bb0(%a: f32, %b: f32, %c : f32):
46// %0 = arith.subf %b, %a : f32
47// linalg.yield %0: f32
48// Former is linalg.sub(a,b), latter is linalg.sub(b,a).
49static bool areBinOpsSwapped(GenericOp genericOp) {
50 Block *body = genericOp.getBody();
51 Operation *op = &body->front();
52 bool swapped = false;
53 if (op->getOpOperand(0).get() != body->getArgument(0)) {
54 swapped = true;
55 assert(op->getOpOperand(0).get() == body->getArgument(1) &&
56 op->getOpOperand(1).get() == body->getArgument(0) &&
57 "binary op uses just one block arg");
58 }
59 return swapped;
60}
61
62// Given an elementwise single unary linalg generic op whose body operation is a
63// binary operation, check if one of its operands is a scalar value defined
64// outside the generic op, set its index, and return true. Otherwise return
65// false. The index is unique because the block argument is used at
66// least by one operand, as checked in `isaElemwiseSingleUnaryOpInterface`.
67//
68// Example:
69// %cst = arith.constant 3.14 : f32
70// %0 = linalg.generic { indexing_maps = [#mapA, #mapRes], ... }
71// ins(%A : tensor<?xf32>) outs(...) {
72// ^bb0(%a: f32, %out : f32):
73// %0 = arith.mulf %a, %cst : f32
74// linalg.yield %0: f32
75// } -> tensor<?xf32>
76// Here, the returned index is 1, and the generic op can be represented as
77// %0 = linalg.elementwise kind=#linalg.elementwise_kind<mul>
78// indexing_maps = [#mapA, affine_map<(d0) -> ()>, #mapRes]
79// ins(%A, %cst : tensor<?xf32>, f32) outs(...) -> tensor<?xf32>
80static bool findIndexOfScalarOperand(GenericOp genericOp, int &index) {
81 Block *body = genericOp.getBody();
82 Operation *op = &body->front();
83 for (auto [i, v] : llvm::enumerate(op->getOperands())) {
84 if (auto blockArg = dyn_cast<BlockArgument>(v);
85 blockArg && blockArg.getOwner() == body)
86 continue; // not an outside value...
87 index = i;
88 return true;
89 }
90 return false;
91}
92
93// Attempt to specialize unary or binary linalg.generic ops to named elementwise
94// ops or linalg.elementwise.
95//
96// Example:
97// %0 = linalg.generic {
98// indexing_maps = [affine_map<(d0, d1) -> (d0, d1)>,
99// affine_map<(d0, d1) -> (d0, d1)>],
100// iterator_types = ["parallel", "parallel"]
101// } ins(%In : tensor<?x?xf32>) outs(%Out : tensor<?x?xf32>) {
102// ^bb0(%in: f32, %out: f32):
103// %1 = math.exp %in : f32
104// linalg.yield %1 : f32
105// } -> tensor<?x?xf32>
106//
107// is specialized to either
108// linalg.exp ins(...) outs(...) -> ...
109// or
110// linalg.elementwise kind=#linalg.elementwise_kind<exp> ...
111//
112// Only the category op can carry non-identity indexing maps; these are
113// transferred verbatim from the `genericOp`.
114//
115// In addition to the canonical forms used by the generalization path, this
116// function can handle the following variations:
117//
118// 1) Swapped operands in binary ops (see the `areBinOpsSwapped` helper)
119// 2) Unary generic ops with a binary body op (see the
120// `findIndexOfScalarOperand` helper)
121static FailureOr<LinalgOp> specializeLinalgElementwise(RewriterBase &rewriter,
122 GenericOp genericOp,
123 bool emitCategoryOp) {
124 bool hasNonIdentityMaps =
125 !llvm::all_of(genericOp.getIndexingMapsArray(),
126 [](AffineMap map) { return map.isIdentity(); });
127
128 // Early exit: Named ops cannot carry user-defined maps.
129 if (hasNonIdentityMaps && !emitCategoryOp)
130 return rewriter.notifyMatchFailure(
131 genericOp,
132 "non-identity indexing maps prevent specialization to named op");
133
134 // Classify the generic op.
135 bool isUnary = genericOp.getNumDpsInputs() == 1;
136 bool isBinary = genericOp.getNumDpsInputs() == 2;
137
138 // Will inspect the body operation to determine named op or elementwise kind.
139 Operation *op = &genericOp.getBody()->front();
140
141 // Detect variations from canonical forms.
142 bool hasSwappedOperands = isBinary && areBinOpsSwapped(genericOp);
143 int scalarOprIdx = -1;
144 bool hasScalarOperand = isUnary && op->getNumOperands() == 2 &&
145 findIndexOfScalarOperand(genericOp, scalarOprIdx);
146
147 // Helper to dispatch between named op and `linalg.elementwise`.
148 // Lambdas with explicit template parameter list are a C++20 feature, hence
149 // the dummy op object.
150 auto replaceOp = [&](auto namedOp, ElementwiseKind kind,
151 bool mayHoistScalarOperand = true) -> LinalgOp {
152 SmallVector<Value> inputs = genericOp.getDpsInputs();
153 if (hasSwappedOperands)
154 std::swap(inputs[0], inputs[1]);
155
156 LinalgOp newOp;
157 if (!emitCategoryOp) {
158 using NamedOpTy = decltype(namedOp);
159 if constexpr (!std::is_null_pointer_v<NamedOpTy>)
160 newOp = NamedOpTy::create(rewriter, genericOp.getLoc(), inputs,
161 genericOp.getDpsInits(),
163 else
164 llvm_unreachable("Missing named op type");
165 } else {
166 SmallVector<AffineMap> indexingMaps = genericOp.getIndexingMapsArray();
167 // Swap indexing maps, too.
168 if (hasSwappedOperands)
169 std::swap(indexingMaps[0], indexingMaps[1]);
170
171 // Represent unary generic op as a binary `linalg.elementwise` with a
172 // scalar operand and broadcasting map.
173 if (hasScalarOperand && mayHoistScalarOperand) {
174 // Adjust inputs and indexing maps accordingly.
175 inputs.insert(inputs.begin() + scalarOprIdx,
176 op->getOperand(scalarOprIdx));
177 auto scalarBroadcastMap =
178 AffineMap::get(genericOp.getNumParallelLoops(), /*symbolCount=*/0,
179 rewriter.getContext());
180 indexingMaps.insert(indexingMaps.begin() + scalarOprIdx,
181 scalarBroadcastMap);
182 }
183 newOp = ElementwiseOp::create(
184 rewriter, genericOp.getLoc(), inputs, genericOp.getDpsInits(),
185 ElementwiseKindAttr::get(rewriter.getContext(), kind),
186 rewriter.getAffineMapArrayAttr(indexingMaps));
187 }
188
189 rewriter.replaceOp(genericOp, newOp);
190 return newOp;
191 };
192
193 if (isUnary) {
194 if (isa<math::ExpOp>(op))
195 return replaceOp(ExpOp{}, ElementwiseKind::exp);
196 if (isa<math::LogOp>(op))
197 return replaceOp(LogOp{}, ElementwiseKind::log);
198 if (isa<math::AbsFOp>(op))
199 return replaceOp(AbsOp{}, ElementwiseKind::abs);
200 if (isa<math::CeilOp>(op))
201 return replaceOp(CeilOp{}, ElementwiseKind::ceil);
202 if (isa<math::FloorOp>(op))
203 return replaceOp(FloorOp{}, ElementwiseKind::floor);
204 if (isa<arith::NegFOp>(op))
205 return replaceOp(NegFOp{}, ElementwiseKind::negf);
206 if (auto divOp = dyn_cast<arith::DivFOp>(op)) {
207 if (auto constOp = dyn_cast_if_present<arith::ConstantOp>(
208 divOp.getLhs().getDefiningOp()))
209 if (cast<FloatAttr>(constOp.getValue()).getValue().isExactlyValue(1.0))
210 return replaceOp(ReciprocalOp{}, ElementwiseKind::reciprocal,
211 /*mayHoistScalarOperand=*/false);
212 }
213 if (isa<math::RoundOp>(op))
214 return replaceOp(RoundOp{}, ElementwiseKind::round);
215 if (isa<math::SqrtOp>(op))
216 return replaceOp(SqrtOp{}, ElementwiseKind::sqrt);
217 if (isa<math::RsqrtOp>(op))
218 return replaceOp(RsqrtOp{}, ElementwiseKind::rsqrt);
219 if (auto mulOp = dyn_cast<arith::MulFOp>(op);
220 mulOp && mulOp.getLhs() == mulOp.getRhs())
221 return replaceOp(SquareOp{}, ElementwiseKind::square);
222 if (isa<math::TanhOp>(op))
223 return replaceOp(TanhOp{}, ElementwiseKind::tanh);
224 if (isa<math::ErfOp>(op))
225 return replaceOp(ErfOp{}, ElementwiseKind::erf);
226
227 // At this point, we exhaustively checked the available unary named ops. The
228 // 1-input generic op might be representable as a `linalg.elementwise` that
229 // broadcasts a scalar operand. But if we can't emit the category op or
230 // don't have a scalar operand, exit now.
231 if (!emitCategoryOp || !hasScalarOperand)
232 return rewriter.notifyMatchFailure(
233 genericOp, "unary elementwise operation cannot be specialized to "
234 "named or category op");
235 }
236
237 // Boolean-typed `linalg.add` and `linalg.mul` require special handling.
238 bool allBool = llvm::all_of(op->getOperands(),
239 [](Value v) { return v.getType().isInteger(1); });
240
241 if (isa<arith::AddIOp, arith::AddFOp, complex::AddOp>(op) ||
242 (allBool && isa<arith::OrIOp>(op)))
243 return replaceOp(AddOp{}, ElementwiseKind::add);
244 if (isa<arith::SubIOp, arith::SubFOp, complex::SubOp>(op))
245 return replaceOp(SubOp{}, ElementwiseKind::sub);
246 if (isa<arith::MulIOp, arith::MulFOp, complex::MulOp>(op) ||
247 (allBool && isa<arith::AndIOp>(op)))
248 return replaceOp(MulOp{}, ElementwiseKind::mul);
249 if (isa<arith::DivSIOp, arith::DivFOp, complex::DivOp>(op))
250 return replaceOp(DivOp{}, ElementwiseKind::div);
251 if (isa<arith::DivUIOp>(op))
252 return replaceOp(DivUnsignedOp{}, ElementwiseKind::div_unsigned);
253 if (isa<arith::MaxSIOp, arith::MaximumFOp>(op))
254 return replaceOp(MaxOp{}, ElementwiseKind::max_signed);
255 if (isa<arith::MinSIOp, arith::MinimumFOp>(op))
256 return replaceOp(MinOp{}, ElementwiseKind::min_signed);
257 if (emitCategoryOp) {
258 // No named ops for unsigned maximum/minimum.
259 if (isa<arith::MaxUIOp>(op))
260 return replaceOp(nullptr, ElementwiseKind::max_unsigned);
261 if (isa<arith::MinUIOp>(op))
262 return replaceOp(nullptr, ElementwiseKind::min_unsigned);
263 }
264 if (isa<math::PowFOp>(op))
265 return replaceOp(PowFOp{}, ElementwiseKind::powf);
266
267 return rewriter.notifyMatchFailure(
268 genericOp,
269 "elementwise operation cannot be specialized to named or category op");
270}
271
272//===----------------------------------------------------------------------===//
273// Specialize linalg generic to matmul variants.
274//===----------------------------------------------------------------------===//
275/// Identifies linalg.generic that is essentially named op of the form:
276// ` linalg.{batch_}?matmul{_transpose_a | _transpose_b}? `
277//
278// It is possible that a linalg.generic may be implementing a matmul but not
279// in a straight-forward way e.g. below is matrix multiply over some slice
280// ```
281// %0 = linalg.generic {
282// indexing_maps = [affine_map<(d0, d1, d2) -> (3, d1, d0)>,
283// affine_map<(d0, d1, d2) -> (d0, 5, d2)>,
284// affine_map<(d0, d1, d2) -> (d2, d1, 13)>],
285// iterator_types = ["parallel", "parallel", "parallel"]}
286// ins(%A, %B : tensor<20x20x20xf32>, tensor<20x20x20xf32>)
287// outs(%C : tensor<20x20x20xf32>) {
288// ^bb0(%a: f32, %b: f32, %c : f32):
289// %mul = arith.mulf %a, %b : f32
290// %add = arith.addf %mul, %c : f32
291// linalg.yield %add : f32
292// } -> tensor<20x20x20xf32>
293// ```
294// It is not possible to represent above as named op.
295// e.g. linalg.batch_matmul(%A, %B : tensor<20x20x20xf32>, ...) is
296// not the same as linalg.generic above.
297namespace {
298enum class IndexMatchResult {
299 Match = 0, // identity map.
300 Transposed, // transposed map.
301 Mismatch // none of the above.
302};
303
304// Checks whether the input Affine `map` contains two consecutive dims that
305// can be interpreted as accessing a 2D matrix. It is assumed that the row
306// column dimension are adjacent axis (in this order) and start at
307// `rowDimIdx` in the input map.
308//
309// e.g. consider A matrix in `C[M,N] = A[M,K] * B[K,N]`. We will check
310// whether the map of A is identity (match), transposed, or something
311// completely different (mis-match). Similar for B and C.
312static IndexMatchResult matchOperandMap(AffineMap map, unsigned rowDimIdx,
313 unsigned expectedPosOfRowDim,
314 unsigned expectedPosOfColDim) {
315 // Get the matrix multiply indices. They are past the batch indices.
316 auto exprOfRowDim = map.getResults()[rowDimIdx];
317 auto exprOfColDim = map.getResults()[rowDimIdx + 1];
318
319 // They should be pure dimension ids.
320 if (exprOfRowDim.getKind() != AffineExprKind::DimId ||
321 exprOfColDim.getKind() != AffineExprKind::DimId)
322 return IndexMatchResult::Mismatch;
323
324 auto posRowDim = cast<AffineDimExpr>(exprOfRowDim).getPosition();
325 auto posColDim = cast<AffineDimExpr>(exprOfColDim).getPosition();
326
327 if (expectedPosOfRowDim == posRowDim && expectedPosOfColDim == posColDim)
328 return IndexMatchResult::Match;
329
330 if (expectedPosOfRowDim == posColDim && expectedPosOfColDim == posRowDim)
331 return IndexMatchResult::Transposed;
332
333 return IndexMatchResult::Mismatch;
334}
335
336// Replaces genericOp with `NamedOpTy` op, supplied as a template arg.
337// All the variants expressed as pseudo regular expression:
338// `linalg.{batch_}?matmul` have same number of ins/out, so it's easy to
339// stamp different versions.
340// `castTy` is an optional type function that indicates whether (and which) cast
341// attribute is needed for the named matmul op variant.
342template <typename NamedOpTy>
343static LinalgOp replaceWithMatmulVariant(RewriterBase &rewriter, GenericOp op,
344 std::optional<TypeFn> castTy,
345 ArrayRef<AffineMap> indexingMaps) {
347 // Only explicitly specify the cast attribute for unsigned cast; signed is
348 // the default for linalg.matmul/linalg.batch_matmul.
349 if (castTy.has_value() && *castTy == TypeFn::cast_unsigned) {
350 auto castAttr = rewriter.getNamedAttr(
351 "cast", TypeFnAttr::get(rewriter.getContext(), *castTy));
352 attributes.push_back(castAttr);
353 }
354
355 // Set the original generic's maps to preserve operand indexing semantics like
356 // transposition.
357 SmallVector<Attribute, 3> indexingMapsAttrVal =
358 llvm::map_to_vector(indexingMaps, [](AffineMap map) -> Attribute {
359 return AffineMapAttr::get(map);
360 });
361 auto indexingMapsAttr = rewriter.getNamedAttr(
362 "indexing_maps", rewriter.getArrayAttr(indexingMapsAttrVal));
363 attributes.push_back(indexingMapsAttr);
364
365 LinalgOp namedOp = rewriter.replaceOpWithNewOp<NamedOpTy>(
366 op, ValueRange{op.getDpsInputs()[0], op.getDpsInputs()[1]},
367 ValueRange{op.getDpsInits()[0]}, attributes);
368
369 return namedOp;
370}
371
372// Returns the cast type to use for a matmul-like named op. If the generic
373// contains casts that cannot be represented (e.g. output casts or mixed
374// signedness), return std::nullopt.
375static std::optional<TypeFn> getCastTypeForMatmulLikeOp(GenericOp genericOp) {
376 bool foundCastForMatmulOutput = false;
377 SmallVector<TypeFn> castTyFns;
378 genericOp.getBody()->walk([&](CastOpInterface castOp) {
379 // Collect forward slice of the cast op to check if it is for the matmul
380 // output.
381 SetVector<Operation *> forwardSlice;
382 getForwardSlice(castOp, &forwardSlice);
383
384 // If there is no multiplication op in the forward slice, then this cast
385 // op is for the matmul output. Cast ops on matmul output cannot be
386 // expressed by the matmul op variant.
387 if (!llvm::any_of(forwardSlice, [](Operation *op) {
388 // We check explicitly for these multiplication ops in
389 // `specializeLinalgContractions()` to infer matmul-like ops.
390 return isa<arith::MulIOp, arith::MulFOp, complex::MulOp>(op);
391 })) {
392 foundCastForMatmulOutput = true;
393 return WalkResult::interrupt();
394 }
395
396 // Determine the cast type.
397 if (isa<arith::ExtUIOp, arith::UIToFPOp, arith::FPToUIOp>(castOp))
398 castTyFns.push_back(TypeFn::cast_unsigned);
399 else if (isa<arith::ExtSIOp, arith::SIToFPOp, arith::FPToSIOp>(castOp))
400 castTyFns.push_back(TypeFn::cast_signed);
401
402 return WalkResult::advance();
403 });
404
405 if (foundCastForMatmulOutput)
406 return std::nullopt;
407
408 if (!castTyFns.empty()) {
409 // If there were multiple different cast types found, then we can't express
410 // them using matmul-like ops. They only allow a single cast type for all
411 // inputs.
412 if (!llvm::all_equal(castTyFns))
413 return std::nullopt;
414 return castTyFns.front();
415 }
416
417 // Default to signed cast for matmul-like ops.
418 return TypeFn::cast_signed;
419}
420
421static FailureOr<LinalgOp> specializeLinalgMmt4D(RewriterBase &rewriter,
422 GenericOp genericOp,
423 std::optional<TypeFn> castTy,
424 ContractionDimensions &dims) {
425 // Should all be rank 4 and dim 6
426 auto indexingMaps = genericOp.getIndexingMapsArray();
427 if (llvm::any_of(indexingMaps, [](AffineMap m) {
428 return m.getResults().size() != 4 || m.getNumDims() != 6;
429 }))
430 return failure();
431
432 auto aOuter = matchOperandMap(indexingMaps[0], 0, dims.m[0], dims.k[0]);
433 auto aInner = matchOperandMap(indexingMaps[0], 2, dims.m[1], dims.k[1]);
434
435 auto bOuter = matchOperandMap(indexingMaps[1], 0, dims.k[0], dims.n[0]);
436 auto bInner = matchOperandMap(indexingMaps[1], 2, dims.k[1], dims.n[1]);
437
438 auto cOuter = matchOperandMap(indexingMaps[2], 0, dims.m[0], dims.n[0]);
439 auto cInner = matchOperandMap(indexingMaps[2], 2, dims.m[1], dims.n[1]);
440
441 if (llvm::is_contained({aOuter, bOuter, cOuter}, IndexMatchResult::Mismatch))
442 return failure();
443 if (llvm::is_contained({aInner, bInner, cInner}, IndexMatchResult::Mismatch))
444 return failure();
445
446 SmallVector<AffineMap> namedOpMaps = {indexingMaps[0], indexingMaps[1],
447 indexingMaps[2]};
448
449 return replaceWithMatmulVariant<Mmt4DOp>(rewriter, genericOp, castTy,
450 namedOpMaps);
451}
452
453// Converts linalg.generic to named linalg.*matmul* where possible.
454static FailureOr<LinalgOp> specializeLinalgContractions(RewriterBase &rewriter,
455 GenericOp genericOp,
456 bool emitCategoryOp) {
457 if (genericOp.getNumDpsInputs() != 2 || genericOp.getNumDpsInits() != 1)
458 return failure();
459
460 // Early exit if not projected permutations.
461 auto mapRange = genericOp.getIndexingMapsArray();
462 if (llvm::any_of(mapRange,
463 [](AffineMap m) { return !m.isProjectedPermutation(); }))
464 return failure();
465
466 // Only mul+add contraction is supported.
467 // Currently, there is no way to control the contraction body type in named
468 // and category ops which all default to mul+add only.
470 *genericOp.getBlock(), [](Operation *first, Operation *second) {
471 return (isa<arith::MulFOp>(first) && isa<arith::AddFOp>(second)) ||
472 (isa<arith::MulIOp>(first) && isa<arith::AddIOp>(second)) ||
473 (isa<complex::MulOp>(first) && isa<complex::AddOp>(second));
474 }))
475 return failure();
476
477 // Determine the cast type for the named matmul op, or bail out if casts
478 // cannot be represented by the named op.
479 std::optional<TypeFn> castTy = getCastTypeForMatmulLikeOp(genericOp);
480 if (!castTy)
481 return rewriter.notifyMatchFailure(
482 genericOp, "contains invalid cast ops for the named matmul op");
483
484 // In case of category op, wider range of variants is supported.
485 if (emitCategoryOp)
486 return replaceWithMatmulVariant<ContractOp>(
487 rewriter, genericOp, castTy, genericOp.getIndexingMapsArray());
488
489 // Further checks for named variants.
490 //
491 // Linalg generic contraction can be across multiple axis e.g.
492 // ```
493 // linalg.generic
494 // {indexing_maps = [affine_map<(m, n, k1, k2) -> (m, k1, k2)>,
495 // affine_map<(m, n, k1, k2) -> (k2, k1, n)>,
496 // affine_map<(m, n, k1, k2) -> (m, n)>],
497 // iterator_types = ["parallel", "parallel",
498 // "reduction", "reduction"]}
499 // ins(%A, %B : tensor<10x20x30xf32>, tensor<30x20x40xf32>)
500 // outs(%C : tensor<10x40xf32>) {
501 // ^bb0(%a: f32, %b: f32, %c: f32):
502 // %1 = arith.mulf %a, %b : f32
503 // %2 = arith.addf %c, %1 : f32
504 // linalg.yield %2 : f32
505 // } -> tensor<10x40xf32>
506 // ```
507 // In above contraction, there are two reduction dimensions {k1, k2}
508 // and although a valid linalg contraction, it is not a named-op
509 // matrix multiply kind. Therefore, reject multi-dim reduction.
510 auto res = inferContractionDims(genericOp);
511 if (!succeeded(res))
512 return failure();
513 auto dims = *res;
514 if (dims.m.size() == 2 && dims.n.size() == 2 && dims.k.size() == 2)
515 return specializeLinalgMmt4D(rewriter, genericOp, castTy, dims);
516 if (dims.m.size() != 1 || dims.n.size() != 1 || dims.k.size() != 1)
517 return failure();
518
519 // Check rank of operands
520 auto indexingMaps = genericOp.getIndexingMapsArray();
521 if (llvm::any_of(indexingMaps, [&dims](AffineMap m) {
522 return m.getResults().size() !=
523 dims.batch.size() + 2 /* any two of {m,n,k} */;
524 }))
525 return failure();
526
527 auto numOfBatchDims = dims.batch.size();
528 if (indexingMaps[0].getNumDims() != numOfBatchDims + 3)
529 return failure();
530
531 if (numOfBatchDims) {
532 // Each operand in a linalg generic contraction could express different
533 // permutations for its batch dimension. But for named op it must be
534 // identity since separate maps are not specified.
535 if (llvm::any_of(indexingMaps, [numOfBatchDims](AffineMap m) {
536 for (unsigned i = 0; i < numOfBatchDims; ++i) {
537 auto expr = m.getResults()[i];
538 if (expr.getKind() != AffineExprKind::DimId ||
539 cast<AffineDimExpr>(expr).getPosition() != i)
540 return true;
541 }
542 return false;
543 }))
544 return failure();
545 }
546
547 auto a =
548 matchOperandMap(indexingMaps[0], numOfBatchDims, dims.m[0], dims.k[0]);
549 auto b =
550 matchOperandMap(indexingMaps[1], numOfBatchDims, dims.k[0], dims.n[0]);
551 auto c =
552 matchOperandMap(indexingMaps[2], numOfBatchDims, dims.m[0], dims.n[0]);
553
554 if (llvm::is_contained({a, b, c}, IndexMatchResult::Mismatch))
555 return failure();
556
557 // Build indexing maps for the named op in its canonical dimension ordering
558 auto *ctx = genericOp.getContext();
559 unsigned numLoopDims = numOfBatchDims + 3;
560 unsigned mIdx = numOfBatchDims;
561 unsigned nIdx = mIdx + 1;
562 unsigned kIdx = mIdx + 2;
563
564 // TODO: add support for indexing_maps with broadcasts.
565 auto makeMap = [&](IndexMatchResult match, unsigned rowIdx, unsigned colIdx) {
566 SmallVector<unsigned> tensorDims;
567 for (unsigned i = 0; i < numOfBatchDims; ++i)
568 tensorDims.push_back(i);
569 if (match == IndexMatchResult::Transposed)
570 llvm::append_values(tensorDims, colIdx, rowIdx);
571 else
572 llvm::append_values(tensorDims, rowIdx, colIdx);
573 return AffineMap::getMultiDimMapWithTargets(numLoopDims, tensorDims, ctx);
574 };
575
576 auto mapA = makeMap(a, mIdx, kIdx);
577 auto mapB = makeMap(b, kIdx, nIdx);
578 auto mapC = makeMap(c, mIdx, nIdx);
579
580 SmallVector<AffineMap> namedOpMaps = {mapA, mapB, mapC};
581
582 // Codegen the different matmul variants.
583 if (numOfBatchDims) {
584 return replaceWithMatmulVariant<BatchMatmulOp>(rewriter, genericOp, castTy,
585 namedOpMaps);
586 }
587 return replaceWithMatmulVariant<MatmulOp>(rewriter, genericOp, castTy,
588 namedOpMaps);
589}
590
591/// Utility to specialize a `genericOp` with a convolution op of type `ConvOpTy`
592/// with `dilations` and `strides`.
593template <typename ConvOpTy>
594static FailureOr<LinalgOp>
595specializeToConvOp(RewriterBase &rewriter, GenericOp genericOp,
596 ArrayRef<int64_t> dilations, ArrayRef<int64_t> strides) {
597 SmallVector<Value> inputs = genericOp.getDpsInputs();
598 ValueRange outputs = genericOp.getDpsInits();
599 SmallVector<Type> resultTypes = genericOp.hasPureTensorSemantics()
600 ? TypeRange(ValueRange(outputs))
601 : TypeRange{};
602 LinalgOp namedOp;
603 // Ops with no dilations and no strides.
604 if constexpr (std::is_same_v<ConvOpTy, linalg::Conv1DOp> ||
605 std::is_same_v<ConvOpTy, linalg::Conv2DOp> ||
606 std::is_same_v<ConvOpTy, linalg::Conv3DOp>) {
607 namedOp = rewriter.replaceOpWithNewOp<ConvOpTy>(genericOp, resultTypes,
608 inputs, outputs);
609 } else {
610 Attribute stridesAttr = rewriter.getI64TensorAttr(strides);
611 Attribute dilationsAttr = rewriter.getI64TensorAttr(dilations);
612 namedOp = rewriter.replaceOpWithNewOp<ConvOpTy>(
613 genericOp, resultTypes, inputs, outputs, stridesAttr, dilationsAttr);
614 }
615 return namedOp;
616}
617
618/// Converts linalg.generic to named linalg.*conv/pooling* where possible.
619static FailureOr<LinalgOp> specializeLinalgConvolutions(RewriterBase &rewriter,
620 GenericOp genericOp) {
621#define CONV_OP_SPECIALIZER(ConvOpTy) \
622 if (std::optional<DilationsAndStrides> convParams = \
623 matchConvolutionOpOfType<ConvOpTy>(genericOp)) \
624 return specializeToConvOp<ConvOpTy>( \
625 rewriter, genericOp, convParams->dilations, convParams->strides); \
626 // -----------------------------
627 // Convolution ops.
628 // -----------------------------
629 CONV_OP_SPECIALIZER(linalg::Conv1DOp);
630 CONV_OP_SPECIALIZER(linalg::Conv1DNwcWcfOp);
631 CONV_OP_SPECIALIZER(linalg::Conv1DNcwFcwOp);
632 CONV_OP_SPECIALIZER(linalg::Conv2DOp);
633 CONV_OP_SPECIALIZER(linalg::Conv2DNhwcHwcfOp);
634 CONV_OP_SPECIALIZER(linalg::Conv2DNhwcHwcfQOp);
635 CONV_OP_SPECIALIZER(linalg::Conv2DNhwcFhwcOp);
636 CONV_OP_SPECIALIZER(linalg::Conv2DNhwcFhwcQOp);
637 CONV_OP_SPECIALIZER(linalg::Conv2DNchwFchwOp);
638 CONV_OP_SPECIALIZER(linalg::Conv2DNchwFchwQOp);
639 CONV_OP_SPECIALIZER(linalg::Conv2DNgchwFgchwOp);
640 CONV_OP_SPECIALIZER(linalg::Conv2DNgchwGfchwOp);
641 CONV_OP_SPECIALIZER(linalg::Conv2DNgchwGfchwQOp);
642 CONV_OP_SPECIALIZER(linalg::Conv2DNhwgcGfhwcOp);
643 CONV_OP_SPECIALIZER(linalg::Conv2DNhwgcGfhwcQOp);
644 CONV_OP_SPECIALIZER(linalg::Conv3DOp);
645 CONV_OP_SPECIALIZER(linalg::Conv3DNdhwcDhwcfOp);
646 CONV_OP_SPECIALIZER(linalg::Conv3DNdhwcDhwcfQOp);
647 CONV_OP_SPECIALIZER(linalg::Conv3DNcdhwFcdhwOp);
648 // -----------------------------
649 // Depthwise Convolution ops.
650 // -----------------------------
651 CONV_OP_SPECIALIZER(linalg::DepthwiseConv1DNcwCwOp);
652 CONV_OP_SPECIALIZER(linalg::DepthwiseConv1DNwcWcOp);
653 CONV_OP_SPECIALIZER(linalg::DepthwiseConv1DNwcWcmOp);
654 CONV_OP_SPECIALIZER(linalg::DepthwiseConv2DNchwChwOp);
655 CONV_OP_SPECIALIZER(linalg::DepthwiseConv2DNhwcHwcOp);
656 CONV_OP_SPECIALIZER(linalg::DepthwiseConv2DNhwcHwcQOp);
657 CONV_OP_SPECIALIZER(linalg::DepthwiseConv2DNhwcHwcmOp);
658 CONV_OP_SPECIALIZER(linalg::DepthwiseConv2DNhwcHwcmQOp);
659 CONV_OP_SPECIALIZER(linalg::DepthwiseConv3DNdhwcDhwcOp);
660 CONV_OP_SPECIALIZER(linalg::DepthwiseConv3DNcdhwCdhwOp);
661 CONV_OP_SPECIALIZER(linalg::DepthwiseConv3DNdhwcDhwcmOp);
662 // -----------------------------
663 // Pooling ops.
664 // -----------------------------
665 CONV_OP_SPECIALIZER(linalg::PoolingNhwcMaxOp);
666 CONV_OP_SPECIALIZER(linalg::PoolingNhwcMinOp);
667 CONV_OP_SPECIALIZER(linalg::PoolingNhwcSumOp);
668 CONV_OP_SPECIALIZER(linalg::PoolingNhwcMaxUnsignedOp);
669 CONV_OP_SPECIALIZER(linalg::PoolingNhwcMinUnsignedOp);
670 CONV_OP_SPECIALIZER(linalg::PoolingNchwSumOp);
671 CONV_OP_SPECIALIZER(linalg::PoolingNchwMaxOp);
672 CONV_OP_SPECIALIZER(linalg::PoolingNwcSumOp);
673 CONV_OP_SPECIALIZER(linalg::PoolingNcwSumOp);
674 CONV_OP_SPECIALIZER(linalg::PoolingNwcMaxOp);
675 CONV_OP_SPECIALIZER(linalg::PoolingNwcMaxUnsignedOp);
676 CONV_OP_SPECIALIZER(linalg::PoolingNcwMaxOp);
677 CONV_OP_SPECIALIZER(linalg::PoolingNwcMinOp);
678 CONV_OP_SPECIALIZER(linalg::PoolingNwcMinUnsignedOp);
679 CONV_OP_SPECIALIZER(linalg::PoolingNdhwcSumOp);
680 CONV_OP_SPECIALIZER(linalg::PoolingNdhwcMaxOp);
681 CONV_OP_SPECIALIZER(linalg::PoolingNdhwcMinOp);
682#undef CONV_OP_SPECIALIZER
683 return failure();
684}
685
686} // namespace
687
688//===----------------------------------------------------------------------===//
689// Categorize linalg generic to named op where possible.
690//===----------------------------------------------------------------------===//
692 RewriterBase &rewriter, GenericOp genericOp,
694 // Elementwise - e.g. exp, add
695 if (isaElemwiseSingleUnaryOpInterface(genericOp, options.emitCategoryOps) ||
696 isaElemwiseSingleBinaryOpInterface(genericOp, options.emitCategoryOps)) {
697 return specializeLinalgElementwise(rewriter, genericOp,
698 options.emitCategoryOps);
699 }
700
701 // Contraction - e.g. matmul
702 if (isaContractionOpInterface(genericOp)) {
703 return specializeLinalgContractions(rewriter, genericOp,
704 options.emitCategoryOps);
705 }
706
707 // Early exit in case of category specialization.
708 // TODO: Remove when matches for other ops account for both named and
709 // category.
710 if (options.emitCategoryOps)
711 return rewriter.notifyMatchFailure(
712 genericOp, "no matching category op specialization");
713
714 // Copy
715 if (isaCopyOpInterface(genericOp)) {
716 LinalgOp namedOp = rewriter.replaceOpWithNewOp<CopyOp>(
717 genericOp, genericOp.getDpsInputs()[0], genericOp.getDpsInits()[0]);
718 return namedOp;
719 }
720
721 // Fill
722 if (std::optional<Value> fillValue = isaFillOpInterface(genericOp)) {
723 // Always use the detected fill value, regardless of pattern
724 LinalgOp namedOp = rewriter.replaceOpWithNewOp<FillOp>(
725 genericOp, *fillValue, genericOp.getDpsInits()[0]);
726 return namedOp;
727 }
728
729 // Broadcast
730 std::optional<SmallVector<int64_t>> equivalentToBroadcast =
731 isaBroadcastOpInterface(genericOp);
732 if (equivalentToBroadcast) {
733 auto dims = *equivalentToBroadcast;
734 LinalgOp namedOp = rewriter.replaceOpWithNewOp<BroadcastOp>(
735 genericOp, genericOp.getDpsInputs()[0], genericOp.getDpsInits()[0],
736 dims);
737 return namedOp;
738 }
739
740 // Transpose
741 std::optional<SmallVector<int64_t>> equivalentToTranspose =
742 isaTransposeOpInterface(genericOp);
743 if (equivalentToTranspose) {
744 auto permutation = *equivalentToTranspose;
745 LinalgOp namedOp = rewriter.replaceOpWithNewOp<TransposeOp>(
746 genericOp, genericOp.getDpsInputs()[0], genericOp.getDpsInits()[0],
747 permutation);
748 return namedOp;
749 }
750
751 // Convolution - e.g. *conv/pooling*
752 if (isaConvolutionOpInterface(genericOp))
753 return specializeLinalgConvolutions(rewriter, genericOp);
754
755 return rewriter.notifyMatchFailure(genericOp,
756 "no matching named op specialization");
757}
758
759namespace {
760struct LinalgSpecializeGenericOpsPass
762 LinalgSpecializeGenericOpsPass> {
763
765 LinalgSpecializeGenericOpsPass>::LinalgSpecializeGenericOpsPassBase;
766 void runOnOperation() override;
767};
768} // namespace
769
770void LinalgSpecializeGenericOpsPass::runOnOperation() {
771 RewritePatternSet patterns(&getContext());
774
775 if (failed(applyPatternsGreedily(getOperation(), std::move(patterns))))
776 signalPassFailure();
777}
778
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
b getContext())
static llvm::ManagedStatic< PassManagerOptions > options
static bool findIndexOfScalarOperand(GenericOp genericOp, int &index)
#define CONV_OP_SPECIALIZER(ConvOpTy)
static bool areBinOpsSwapped(GenericOp genericOp)
static FailureOr< LinalgOp > specializeLinalgElementwise(RewriterBase &rewriter, GenericOp genericOp, bool emitCategoryOp)
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
bool isProjectedPermutation(bool allowZeroInResults=false) const
Returns true if the AffineMap represents a subset (i.e.
unsigned getNumDims() const
ArrayRef< AffineExpr > getResults() const
static AffineMap getMultiDimMapWithTargets(unsigned numDims, ArrayRef< unsigned > targets, MLIRContext *context)
Returns an affine map with numDims input dimensions and results specified by targets.
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:33
BlockArgument getArgument(unsigned i)
Definition Block.h:139
Operation & front()
Definition Block.h:163
DenseIntElementsAttr getI64TensorAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:190
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:271
MLIRContext * getContext() const
Definition Builders.h:56
NamedAttribute getNamedAttr(StringRef name, Attribute val)
Definition Builders.cpp:98
ArrayAttr getAffineMapArrayAttr(ArrayRef< AffineMap > values)
Definition Builders.cpp:323
IRValueT get() const
Return the current value being used by this operand.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:375
unsigned getNumOperands()
Definition Operation.h:371
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:403
OpOperand & getOpOperand(unsigned idx)
Definition Operation.h:413
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.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
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,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:389
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
bool isContractionBody(Block &block, function_ref< bool(Operation *, Operation *)> isaPair, llvm::raw_ostream &errs=mlir::thread_safe_nulls())
Returns true if the block contains a contraction of the following form:
std::optional< SmallVector< int64_t > > isaTransposeOpInterface(GenericOp genericOp)
Checks whether genericOp is semantically equivalent to a linalg.transpose.
bool isaCopyOpInterface(LinalgOp linalgOp)
Checks whether linalgOp is semantically equivalent to a linalg.copyOp.
bool isaElemwiseSingleBinaryOpInterface(GenericOp genericOp, bool allowNonIdentityMaps=false)
Checks whether genericOp is semantically equivalent to a single linalg elementwise binary op e....
void populateDecomposeProjectedPermutationPatterns(RewritePatternSet &patterns)
Add patterns to make explicit broadcasts and transforms in the input operands of a genericOp.
FailureOr< LinalgOp > specializeGenericOp(RewriterBase &rewriter, GenericOp genericOp, const GenericOpSpecializationOptions &options={})
Replace the given GenericOp with a namedOp or categoryOp.
bool isaConvolutionOpInterface(LinalgOp linalgOp, bool allowEmptyConvolvedDims=false)
Checks whether linalgOp conforms to ConvolutionOpInterface.
std::optional< SmallVector< int64_t > > isaBroadcastOpInterface(LinalgOp linalgOp)
Checks whether linalgOp is semantically equivalent to a broadcast operation.
FailureOr< ContractionDimensions > inferContractionDims(LinalgOp linalgOp)
Find at least 2 parallel (m and n) and 1 reduction (k) dimension candidates that form a matmul subcom...
bool isaContractionOpInterface(LinalgOp linalgOp)
Checks whether linalgOp conforms to ContractionOpInterface.
bool isaElemwiseSingleUnaryOpInterface(GenericOp genericOp, bool allowNonIdentityMaps=false)
Checks whether a given genericOp is semantically equivalent to a single linalg elementwise unary op,...
std::optional< Value > isaFillOpInterface(GenericOp genericOp)
Checks whether genericOp is semantically equivalent to a linalg.fill.
void populateLinalgGenericOpsSpecializationPatterns(RewritePatternSet &patterns, const GenericOpSpecializationOptions &options={})
Populates patterns with patterns to convert linalg.generic ops to named or category ops where possibl...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:717
Include the generated interface declarations.
LogicalResult applyPatternsGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
@ DimId
Dimensional identifier.
Definition AffineExpr.h:59
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:125
void getForwardSlice(Operation *op, SetVector< Operation * > *forwardSlice, const ForwardSliceOptions &options={})
Fills forwardSlice with the computed forward slice (i.e.
Positions of a Linalg op loops that correspond to different kinds of a contraction dimension.
SmallVector< unsigned, 2 > batch