MLIR 24.0.0git
LinalgTransformOps.cpp
Go to the documentation of this file.
1//===- LinalgTransformOps.cpp - Implementation of Linalg transform 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
10
41#include "mlir/Support/LLVM.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallVectorExtras.h"
47#include "llvm/ADT/TypeSwitch.h"
48#include "llvm/Support/DebugLog.h"
49#include "llvm/Support/LogicalResult.h"
50#include <type_traits>
51
52using namespace mlir;
53using namespace mlir::linalg;
54using namespace mlir::transform;
55
56#define DEBUG_TYPE "linalg-transforms"
57
58/// Assuming that `ofr` is an index attr or a param of index type
59/// or a transform dialect handle mapped to exactly one op
60/// with one index result, return that value.
62 transform::TransformState &state, TransformOpInterface transformOp,
64 for (OpFoldResult ofr : ofrs) {
65 if (auto attr = dyn_cast<Attribute>(ofr)) {
66 if (!isa<IntegerAttr>(attr))
67 return transformOp.emitDefiniteFailure() << "expected IntegerAttr";
68 result.push_back(ofr);
69 continue;
70 }
71
72 Value transformValue = cast<Value>(ofr);
73 if (isa<TransformParamTypeInterface>(transformValue.getType())) {
74 ArrayRef<Attribute> params = state.getParams(transformValue);
75 if (params.size() != 1)
76 return transformOp.emitDefiniteFailure()
77 << "requires exactly one parameter associated";
78 result.push_back(params[0]);
79 continue;
80 }
81
82 auto payloadOps = state.getPayloadOps(transformValue);
83 if (!llvm::hasSingleElement(payloadOps)) {
85 transformOp.emitSilenceableError()
86 << "handle must be mapped to exactly one payload op";
87 diag.attachNote(transformValue.getLoc())
88 << "mapped to " << llvm::range_size(payloadOps) << " payload ops";
89 return diag;
90 }
91
92 Operation *op = *payloadOps.begin();
93 if (op->getNumResults() != 1 || !op->getResult(0).getType().isIndex()) {
95 transformOp.emitSilenceableError()
96 << "payload op must have exactly 1 index result";
97 diag.attachNote(op->getLoc())
98 << "has " << op->getNumResults() << " results";
99 return diag;
100 }
101 result.push_back(op->getResult(0));
102 }
103
105}
106
107// Given a list of params that are index attrs or a list of OpFoldResults
108// that are either index attrs or op handles, return a list of OpFoldResults
109// of index attrs or a list of OpFoldResults where all op handles are
110// replaced with the first (and only) OpResult of that payload op.
111// (There must be exactly one parameter associated with the AnyParamType or
112// one mapped payload op which must have exactly one index result.)
114 transform::TransformState &state, TransformOpInterface transformOp,
115 SmallVector<OpFoldResult> &result, Value packedHandle) {
116 if (isa<TransformParamTypeInterface>(packedHandle.getType())) {
117 ArrayRef<Attribute> params = state.getParams(packedHandle);
118 for (auto param : params) {
119 if (!isa<IntegerAttr>(param))
120 return transformOp.emitDefiniteFailure()
121 << "expected the parameter to be associated with an integer "
122 "attribute";
123 result.push_back(param);
124 }
126 }
127
128 for (Operation *op : state.getPayloadOps(packedHandle)) {
129 if (op->getNumResults() != 1 || !op->getResult(0).getType().isIndex()) {
131 transformOp.emitSilenceableError()
132 << "payload op must have exactly 1 index result";
133 diag.attachNote(op->getLoc())
134 << "has " << op->getNumResults() << " results";
135 return diag;
136 }
137 result.push_back(op->getResult(0));
138 }
139
141}
142
143/// When possible, converts each `OpFoldResult` in `mixedResult` to
144/// an integer if the value can be statically inferred. If a result
145/// is a `Value` then it must be either a `ParamType` or a handle
146/// to an a constant like op.
148 TransformState &state, TransformOpInterface &transformOp,
149 ArrayRef<OpFoldResult> mixedResults, SmallVectorImpl<int64_t> &reified) {
150 for (OpFoldResult paramOrHandle : mixedResults) {
151 if (auto attr = dyn_cast<Attribute>(paramOrHandle)) {
152 reified.push_back(cast<IntegerAttr>(attr).getInt());
153 continue;
154 }
155 if (isa<TransformParamTypeInterface>(
156 cast<Value>(paramOrHandle).getType())) {
157 ArrayRef<Attribute> params = state.getParams(cast<Value>(paramOrHandle));
158 if (params.size() != 1)
159 return transformOp.emitSilenceableError() << "expected a single param";
160 reified.push_back(
161 cast<IntegerAttr>(params.front()).getValue().getSExtValue());
162 continue;
163 }
164
165 Value handle = cast<Value>(paramOrHandle);
166 if (!isa<TransformHandleTypeInterface>(handle.getType()))
167 return transformOp.emitSilenceableError() << "unexpected value handle";
168 auto payload = state.getPayloadOps(handle);
169 if (!llvm::hasSingleElement(payload))
170 return transformOp.emitSilenceableError()
171 << "requires param or handle that is mapped to 1 payload op";
172
173 Operation *paramOrHandlePayloadOp = *payload.begin();
174 if (paramOrHandlePayloadOp->getNumResults() != 1 ||
175 !paramOrHandlePayloadOp->getResult(0).getType().isIndex()) {
176 return transformOp.emitSilenceableError()
177 << "requires param or handle to be result of op with 1 index "
178 "result";
179 }
180
181 IntegerAttr attr;
182 if (!matchPattern(paramOrHandlePayloadOp->getResult(0), m_Constant(&attr)))
183 return transformOp.emitSilenceableError()
184 << "requires param or handle to be the result of a constant like "
185 "op";
186
187 reified.push_back(attr.getInt());
188 }
190}
191
192//===----------------------------------------------------------------------===//
193// Apply...PatternsOp
194//===----------------------------------------------------------------------===//
195
196void transform::ApplyEraseUnnecessaryInputsPatternsOp::populatePatterns(
197 RewritePatternSet &patterns) {
199}
200
201void transform::ApplyDecomposeTensorPackUnpackPatternsOp::populatePatterns(
202 RewritePatternSet &patterns) {
204}
205
206void transform::ApplyDecomposeTensorPadPatternsOp::populatePatterns(
207 RewritePatternSet &patterns) {
209}
210
211void transform::ApplyFoldUnitExtentDimsViaReshapesPatternsOp::populatePatterns(
212 RewritePatternSet &patterns) {
215}
216
217void transform::ApplyFoldUnitExtentDimsViaSlicesPatternsOp::populatePatterns(
218 RewritePatternSet &patterns) {
220 options.rankReductionStrategy =
223}
224
225void transform::ApplyTilingCanonicalizationPatternsOp::populatePatterns(
226 RewritePatternSet &patterns) {
228}
229
230void transform::ApplyFoldAddIntoDestPatternsOp::populatePatterns(
231 RewritePatternSet &patterns) {
233}
234
235void transform::ApplyPadVectorizationPatternsOp::populatePatterns(
236 RewritePatternSet &patterns) {
238}
239
240void transform::ApplyFoldIntoPackAndUnpackPatternsOp::populatePatterns(
241 RewritePatternSet &patterns) {
243}
244
245void transform::ApplyFoldPackUnpackIntoEmptyPatternsOp::populatePatterns(
246 RewritePatternSet &patterns) {
248}
249
250void transform::ApplyDataLayoutPropagationPatternsOp::populatePatterns(
251 RewritePatternSet &patterns) {
252 linalg::ControlPropagationFn defaultControlFn = [](OpOperand *operand) {
253 return true;
254 };
255 linalg::populateDataLayoutPropagationPatterns(patterns, defaultControlFn,
256 getPoisonPadding());
257}
258
259void transform::ApplyExtractSliceSinkingPatternsOp::populatePatterns(
260 RewritePatternSet &patterns) {
261 linalg::ControlPropagationFn defaultControlFn =
262 [](OpOperand *opOperand) -> bool {
263 Operation *producer = opOperand->get().getDefiningOp();
264 Operation *consumer = opOperand->getOwner();
265 return consumer->getBlock() == producer->getBlock();
266 };
267 linalg::populateExtractSliceSinkingPatterns(patterns, defaultControlFn);
268}
269
270void transform::ApplySwapExtractSliceWithFillPatternsOp::populatePatterns(
271 RewritePatternSet &patterns) {
273}
274
275void transform::ApplyEraseUnusedOperandsAndResultsPatternsOp::populatePatterns(
276 RewritePatternSet &patterns) {
278}
279
280void transform::ApplyFoldReshapeOpsByExpansionPatternsOp::populatePatterns(
281 RewritePatternSet &patterns) {
282 linalg::ControlFusionFn controlFn =
283 [foldSingleUseOnly = getFoldSingleUseOnly()](OpOperand *fusedOperand) {
284 if (!foldSingleUseOnly)
285 return true;
286 Operation *producer = fusedOperand->get().getDefiningOp();
287 return producer && producer->hasOneUse();
288 };
290}
291
292//===----------------------------------------------------------------------===//
293// BufferizeToAllocationOp
294//===----------------------------------------------------------------------===//
295
296namespace {
297class NewOpsListener : public RewriterBase::ForwardingListener {
298public:
300
301 SmallVector<Operation *> getNewOps() const {
302 return SmallVector<Operation *>(newOps.begin(), newOps.end());
303 }
304
305private:
306 void notifyOperationInserted(Operation *op,
307 OpBuilder::InsertPoint previous) override {
308 ForwardingListener::notifyOperationInserted(op, previous);
309 // We only care about newly created ops.
310 if (previous.isSet())
311 return;
312 auto inserted = newOps.insert(op);
313 (void)inserted;
314 assert(inserted.second && "expected newly created op");
315 }
316
317 void notifyOperationErased(Operation *op) override {
318 ForwardingListener::notifyOperationErased(op);
319 op->walk([&](Operation *op) { newOps.erase(op); });
320 }
321
323};
324} // namespace
325
326DiagnosedSilenceableFailure transform::BufferizeToAllocationOp::apply(
329 // Attach listener to keep track of newly created ops.
330 OpBuilder::Listener *previousListener = rewriter.getListener();
331 llvm::scope_exit resetListener(
332 [&]() { rewriter.setListener(previousListener); });
333 NewOpsListener newOpsListener(previousListener);
334 rewriter.setListener(&newOpsListener);
335
337 if (getMemcpyOp() == "bufferization.materialize_in_destination") {
338 options.memcpyOp = linalg::BufferizeToAllocationOptions::MemcpyOp::
339 MaterializeInDestination;
340 } else if (getMemcpyOp() == "memref.copy") {
341 options.memcpyOp =
343 } else if (getMemcpyOp() == "linalg.copy") {
344 options.memcpyOp =
346 } else {
347 llvm_unreachable("invalid memcpy op");
348 }
349 if (getAllocOp() == "memref.alloc") {
350 options.allocOp =
352 } else if (getAllocOp() == "memref.alloca") {
353 options.allocOp =
355 } else {
356 llvm_unreachable("invalid alloc op");
357 }
358 options.bufferizeDestinationOnly = getBufferizeDestinationOnly();
359 options.emitDealloc = getEmitDealloc();
360
361 // Bufferize ops.
362 Attribute memorySpace =
363 getMemorySpace().has_value() ? getMemorySpace().value() : Attribute();
364 SmallVector<Value> allocatedBuffers;
365 for (Operation *op : state.getPayloadOps(getTarget())) {
366 Value buffer =
367 linalg::bufferizeToAllocation(rewriter, options, op, memorySpace);
368 if (!buffer) {
369 DiagnosedSilenceableFailure diag = emitSilenceableError()
370 << "failed to bufferize operation";
371 diag.attachNote(op->getLoc()) << "target payload op";
372 return diag;
373 }
374 allocatedBuffers.push_back(buffer);
375 }
376
377 // Set results.
378 results.setValues(cast<OpResult>(getAllocatedBuffer()), allocatedBuffers);
379 results.set(cast<OpResult>(getNewOps()), newOpsListener.getNewOps());
381}
382
383void transform::BufferizeToAllocationOp::getEffects(
385 if (getBufferizeDestinationOnly()) {
386 // The destination is replaced with a newly allocated buffer, but the op
387 // itself remains in place.
388 onlyReadsHandle(getTargetMutable(), effects);
389 } else {
390 consumesHandle(getTargetMutable(), effects);
391 }
392 producesHandle(getOperation()->getOpResults(), effects);
393 modifiesPayload(effects);
394}
395
396LogicalResult transform::BufferizeToAllocationOp::verify() {
397 if (getMemcpyOp() != "bufferization.materialize_in_destination" &&
398 getMemcpyOp() != "memref.copy" && getMemcpyOp() != "linalg.copy")
399 return emitOpError() << "unsupported memcpy op";
400 if (getAllocOp() != "memref.alloc" && getAllocOp() != "memref.alloca")
401 return emitOpError() << "unsupported alloc op";
402 return success();
403}
404
405//===----------------------------------------------------------------------===//
406// PromoteTensorOp
407//===----------------------------------------------------------------------===//
408
409/// Return true if the operand may be read from by its owner. This is currently
410/// very conservative and only looks inside linalg operations to prevent
411/// unintentional data loss.
412static bool mayBeRead(OpOperand &operand) {
413 auto linalgOp = dyn_cast<linalg::LinalgOp>(operand.getOwner());
414
415 // Be conservative about ops we cannot analyze deeper.
416 if (!linalgOp)
417 return true;
418
419 // Look inside linalg ops.
420 Value blockArgument = linalgOp.getMatchingBlockArgument(&operand);
421 return !blockArgument.use_empty();
422}
423
424/// Return true if the value may be read through any of its uses.
425static bool mayBeRead(Value value) {
426 // If the value has a reference semantics, it
427 // may be read through any alias...
428 if (!isa<TensorType, FloatType, IntegerType>(value.getType()))
429 return true;
430 return llvm::any_of(value.getUses(),
431 static_cast<bool (&)(OpOperand &)>(mayBeRead));
432}
433
435transform::PromoteTensorOp::apply(transform::TransformRewriter &rewriter,
438 SmallVector<Value> promoted;
439 for (Value tensor : state.getPayloadValues(getTensor())) {
440 auto type = dyn_cast<RankedTensorType>(tensor.getType());
441 if (!type) {
442 return emitSilenceableError() << "non-tensor type: " << tensor;
443 }
444
445 Operation *definingOp = tensor.getDefiningOp();
446 if (definingOp)
447 rewriter.setInsertionPointAfter(definingOp);
448 else
449 rewriter.setInsertionPointToStart(cast<BlockArgument>(tensor).getOwner());
450
451 // Check this before we emit operations using this value.
452 bool needsMaterialization = mayBeRead(tensor);
453
454 SmallVector<Value> dynamicDims;
456 for (auto [pos, dim] : llvm::enumerate(type.getShape())) {
457 if (!ShapedType::isDynamic(dim))
458 continue;
459 Value cst =
460 arith::ConstantIndexOp::create(rewriter, tensor.getLoc(), pos);
461 auto dimOp =
462 tensor::DimOp::create(rewriter, tensor.getLoc(), tensor, cst);
463 preservedOps.insert(dimOp);
464 dynamicDims.push_back(dimOp);
465 }
466 auto allocation = bufferization::AllocTensorOp::create(
467 rewriter, tensor.getLoc(), type, dynamicDims);
468 // Set memory space if provided.
469 if (getMemorySpaceAttr())
470 allocation.setMemorySpaceAttr(getMemorySpaceAttr());
471 Value allocated = allocation;
472
473 // Only insert a materialization (typically bufferizes to a copy) when the
474 // value may be read from.
475 if (needsMaterialization) {
476 auto copy = bufferization::MaterializeInDestinationOp::create(
477 rewriter, tensor.getLoc(), tensor, allocated);
478 preservedOps.insert(copy);
479 promoted.push_back(copy.getResult());
480 } else {
481 promoted.push_back(allocated);
482 }
483 rewriter.replaceAllUsesExcept(tensor, promoted.back(), preservedOps);
484 }
485 results.setValues(cast<OpResult>(getPromoted()), promoted);
487}
488
489void transform::PromoteTensorOp::getEffects(
491 transform::onlyReadsHandle(getTensorMutable(), effects);
492 transform::producesHandle(getOperation()->getOpResults(), effects);
494}
495
496//===----------------------------------------------------------------------===//
497// DecomposeOp
498//===----------------------------------------------------------------------===//
499
501transform::DecomposeOp::applyToOne(transform::TransformRewriter &rewriter,
502 LinalgOp target,
505 FailureOr<linalg::LinalgOp> res =
507 if (succeeded(res)) {
508 results.push_back(*res);
510 }
511 return emitDefaultSilenceableFailure(target);
512}
513
514//===----------------------------------------------------------------------===//
515// DecomposeInterfaceOp
516//===----------------------------------------------------------------------===//
517
518// Decompose the target operation if it implements the AggregatedOpInterface.
519// Push the decomposed operations (the ones that replaces the values produced by
520// \p target) in the `results`.
521DiagnosedSilenceableFailure transform::DecomposeInterfaceOp::applyToOne(
525 auto decomposableOp = dyn_cast<AggregatedOpInterface>(target);
526 if (!decomposableOp) {
528 "payload is not a decomposable op");
529 return emitDefaultSilenceableFailure(target);
530 }
531
532 FailureOr<SmallVector<Value>> maybeNewResults =
533 decomposableOp.decomposeOperation(rewriter);
534 if (failed(maybeNewResults))
535 return emitDefaultSilenceableFailure(target);
536
537 rewriter.replaceOp(decomposableOp, *maybeNewResults);
538 for (Value val : *maybeNewResults) {
539 Operation *definition = val.getDefiningOp();
540 if (definition)
541 results.push_back(definition);
542 }
544}
545
546//===----------------------------------------------------------------------===//
547// EliminateLinalgOpAnchoredEmptyTensorsOp
548//===----------------------------------------------------------------------===//
549
550void transform::EliminateLinalgOpAnchoredEmptyTensorsOp::getEffects(
552 onlyReadsHandle(getTargetMutable(), effects);
553 modifiesPayload(effects);
554}
555
557transform::EliminateLinalgOpAnchoredEmptyTensorsOp::apply(
558 transform::TransformRewriter &rewriter, TransformResults &transformResults,
559 TransformState &state) {
561 options.allowReturnAllocsFromLoops = true;
562
563 for (Operation *target : state.getPayloadOps(getTarget())) {
565 if (failed(analyzeOp(target, state)))
566 return mlir::emitSilenceableFailure(target->getLoc())
567 << "failed to analyze op";
569 rewriter, target, state)))
570 return mlir::emitSilenceableFailure(target->getLoc())
571 << "failed to eliminate LinalgOp anchored tensor.empty ops";
572 }
574}
575
576//===----------------------------------------------------------------------===//
577// FuseOp
578//===----------------------------------------------------------------------===//
579
580void transform::FuseOp::build(OpBuilder &builder, OperationState &result,
581 TypeRange loopTypes, Value target,
582 ArrayRef<int64_t> staticTileSizes,
583 ArrayRef<int64_t> staticTileInterchange,
584 bool applyCleanup, bool useForall) {
585 return build(
586 builder, result, loopTypes,
587 /*target=*/target,
588 /*mixedTileSizes=*/
589 getAsOpFoldResult(builder.getI64ArrayAttr(staticTileSizes)),
590 /*mixedTileInterchange=*/
591 getAsOpFoldResult(builder.getI64ArrayAttr(staticTileInterchange)),
592 applyCleanup, useForall);
593}
594
595void transform::FuseOp::build(OpBuilder &builder, OperationState &result,
596 Value target, ArrayRef<int64_t> staticTileSizes,
597 ArrayRef<int64_t> staticTileInterchange,
598 bool applyCleanup, bool useForall) {
599 return build(
600 builder, result,
601 /*target=*/target,
602 /*mixedTileSizes=*/
603 getAsOpFoldResult(builder.getI64ArrayAttr(staticTileSizes)),
604 /*mixedTileInterchange=*/
605 getAsOpFoldResult(builder.getI64ArrayAttr(staticTileInterchange)),
606 applyCleanup, useForall);
607}
608
609void transform::FuseOp::build(OpBuilder &builder, OperationState &result,
611 ArrayRef<OpFoldResult> mixedTileSizes,
612 ArrayRef<OpFoldResult> mixedTileInterchange,
613 bool applyCleanup, bool useForall) {
614 // Loop types are automaticaly splat by the callee, setting up one is
615 // enough.
616 SmallVector<Type> loopTypes(1, builder.getType<transform::AnyOpType>());
617 build(builder, result, loopTypes, target, mixedTileSizes,
618 mixedTileInterchange, applyCleanup, useForall);
619}
620
621void transform::FuseOp::build(OpBuilder &builder, OperationState &result,
622 TypeRange loopTypes, Value target,
623 ArrayRef<OpFoldResult> mixedTileSizes,
624 ArrayRef<OpFoldResult> mixedTileInterchange,
625 bool applyCleanup, bool useForall) {
626 SmallVector<int64_t> staticTileSizes;
627 SmallVector<Value> dynamicTileSizes;
628 dispatchIndexOpFoldResults(mixedTileSizes, dynamicTileSizes, staticTileSizes);
629 SmallVector<int64_t> staticTileInterchange;
630 SmallVector<Value> dynamicTileInterchange;
631 dispatchIndexOpFoldResults(mixedTileInterchange, dynamicTileInterchange,
632 staticTileInterchange);
633 // Call the default builder which sets up the proper operands segment sizes
634 // attributes for multiple variadic operands. In the absence of this,
635 // horrible bugs ensue.
636 auto staticTileSizesAttr = builder.getDenseI64ArrayAttr(staticTileSizes);
637 auto staticTileInterchangeAttr =
638 builder.getDenseI64ArrayAttr(staticTileInterchange);
639 unsigned numExpectedLoops =
640 useForall ? 1 : staticTileSizes.size() - llvm::count(staticTileSizes, 0);
641 SmallVector<Type> resultTypes;
642 resultTypes.reserve(numExpectedLoops);
643 assert((loopTypes.size() == 1 || loopTypes.size() == numExpectedLoops) &&
644 "expected one loop type or as many as loops");
645 if (loopTypes.size() == 1)
646 resultTypes.append(numExpectedLoops, loopTypes[0]);
647 else
648 llvm::append_range(resultTypes, loopTypes);
649 build(builder, result, /*transformed=*/target.getType(),
650 /*loops=*/resultTypes,
651 /*target=*/target,
652 /*tile_sizes=*/dynamicTileSizes,
653 /*tile_interchange=*/dynamicTileInterchange,
654 /*packed_tile_sizes=*/Value(),
655 /*static_tile_sizes=*/staticTileSizesAttr,
656 /*static_tile_interchange=*/staticTileInterchangeAttr,
657 /*inner_tile_alignments=*/ArrayRef<int64_t>{},
658 /*apply_cleanup=*/applyCleanup,
659 /*use_forall=*/useForall);
660}
661
662/// Apply a tiling transformation to all payload ops and store both the
663/// tiled operation as well as the created tile loops.
664template <typename Range>
665static LogicalResult applyTilingToAll(
666 RewriterBase &rewriter, Operation *transformOp, Range &&payloadOps,
667 unsigned numLoops, transform::TransformResults &transformResults,
668 bool packedResults,
669 function_ref<FailureOr<scf::SCFTileAndFuseResult>(TilingInterface)>
670 applyFn) {
671 SmallVector<Operation *> tiledLinalgOps;
672 SmallVector<SmallVector<Operation *>> loopOps(numLoops);
673 size_t numTargets = llvm::range_size(payloadOps);
674
675 for (Operation *target : payloadOps) {
676 auto tilingInterfaceOp = dyn_cast<TilingInterface>(target);
677 if (!tilingInterfaceOp)
678 return transformOp->emitError("only TilingInterface ops are supported");
679
680 rewriter.setInsertionPoint(target);
681 FailureOr<scf::SCFTileAndFuseResult> tiledResults =
682 applyFn(tilingInterfaceOp);
683 if (failed(tiledResults))
684 return failure();
685
686 // Perform the replacement of tiled and fused values.
687 SmallVector<Operation *> opsToReplace{target};
688 llvm::append_range(opsToReplace, tiledResults->fusedProducers);
689 for (Operation *toReplace : opsToReplace) {
690 for (OpResult res : toReplace->getResults())
691 if (auto replacement = tiledResults->replacements.lookup(res))
692 rewriter.replaceAllUsesWith(res, replacement);
693 if (toReplace->use_empty()) {
694 rewriter.eraseOp(toReplace);
695 }
696 }
697
698 // Report back the relevant handles to the transform op.
699 tiledLinalgOps.push_back(tiledResults->tiledAndFusedOps.front());
700 assert(tiledResults->loops.size() == numLoops &&
701 "Mismatched number of loops, tile and fuse transform should have "
702 "failed");
703 for (unsigned int i = 0; i < numLoops; ++i)
704 loopOps[i].push_back(tiledResults->loops[i]);
705 }
706
707 transformResults.set(transformOp->getOpResult(0), tiledLinalgOps);
708 if (packedResults) {
709 // In case of packed results, all created loops are assigned to a single
710 // handle. Loops are returned in order of targets such as:
711 // %loops_handle = {
712 // target0:loop0, ..., target0:loopN,
713 // target1:loop0, ..., target1:loopN,
714 // ... }
715 SmallVector<Operation *> flattenedLoopOps;
716 for (unsigned int idx = 0; idx < numTargets; ++idx)
717 for (unsigned int i = 0; i < numLoops; ++i)
718 flattenedLoopOps.push_back(loopOps[i][idx]);
719 transformResults.set(transformOp->getOpResult(1), flattenedLoopOps);
720 } else {
721 for (unsigned int i = 0; i < numLoops; ++i)
722 transformResults.set(transformOp->getOpResult(i + 1), loopOps[i]);
723 }
724
725 return success();
726}
727
729transform::FuseOp::apply(transform::TransformRewriter &rewriter,
730 mlir::transform::TransformResults &transformResults,
732 auto transformOp = cast<TransformOpInterface>(getOperation());
733
734 SmallVector<OpFoldResult> mixedTileSizes;
736 getPackedTileSizes()
738 state, transformOp, mixedTileSizes, getPackedTileSizes())
740 state, transformOp, mixedTileSizes, getMixedTileSizes());
741 if (!status.succeeded())
742 return status;
743 SmallVector<int64_t> tileInterchange;
745 state, transformOp, getMixedTileInterchange(), tileInterchange);
746 if (!status.succeeded())
747 return status;
748
749 scf::SCFTilingOptions tilingOptions;
750 tilingOptions.interchangeVector = std::move(tileInterchange);
751 bool useForall = getUseForall();
752 tilingOptions.setLoopType(useForall
753 ? scf::SCFTilingOptions::LoopType::ForallOp
754 : scf::SCFTilingOptions::LoopType::ForOp);
755 tilingOptions.setTileSizes(mixedTileSizes);
756 scf::SCFTileAndFuseOptions tileAndFuseOptions;
757 tileAndFuseOptions.tilingOptions = std::move(tilingOptions);
758 // Optional caller-asserted pack/unpack inner-tile alignment (see
759 // InnerTileAlignment).
760 tileAndFuseOptions.tilingOptions.setInnerTileAlignments(
761 convertInnerTileAlignments(getInnerTileAlignments()));
762
763 if (getApplyCleanup()) {
764 MLIRContext *context = rewriter.getContext();
765 RewritePatternSet patterns(context);
766 tensor::ExtractSliceOp::getCanonicalizationPatterns(patterns, context);
769 tileAndFuseOptions.cleanupPatterns = std::move(patterns);
770 }
771
772 size_t numLoops;
773 if (useForall) {
774 numLoops = 1;
775 } else {
776 numLoops = llvm::count_if(mixedTileSizes, [](OpFoldResult ofr) {
777 auto attr = dyn_cast<Attribute>(ofr);
778 if (!attr)
779 return true;
780 return cast<IntegerAttr>(attr).getInt() != 0;
781 });
782 }
783 LogicalResult result = applyTilingToAll(
784 rewriter, getOperation(), state.getPayloadOps(getTarget()), numLoops,
785 transformResults, /*packedResults=*/getPackedTileSizes() != nullptr,
786 [&](TilingInterface tilingInterfaceOp)
787 -> FailureOr<scf::SCFTileAndFuseResult> {
788 return tileConsumerAndFuseProducersUsingSCF(rewriter, tilingInterfaceOp,
789 tileAndFuseOptions);
790 });
793}
794
795LogicalResult transform::FuseOp::verify() {
796 bool hasPackedTiles = getPackedTileSizes() != nullptr;
797 if (!getMixedTileSizes().empty() && hasPackedTiles)
798 return emitOpError(
799 "tile_sizes and packed_tile_sizes are mutually exclusive");
800
801 auto iterspace_rank = getStaticTileSizes().size();
802 ArrayRef<int64_t> permutation = getStaticTileInterchange();
803 if (permutation.size() > iterspace_rank)
804 return emitOpError()
805 << "interchange length exceeds iteration space dimensions ("
806 << iterspace_rank << "), found " << getTileInterchange();
807 SmallVector<bool> seen(iterspace_rank, false);
808 for (int64_t v : permutation) {
809 if (!ShapedType::isDynamic(v)) {
810 if (v < 0 || v >= static_cast<int64_t>(iterspace_rank))
811 return emitOpError() << "expects interchange values to be in range [0, "
812 << iterspace_rank << "), found: " << v;
813 if (seen[v])
814 return emitOpError() << "found duplicate interchange value: " << v;
815 seen[v] = true;
816 }
817 }
818
819 ArrayRef<int64_t> sizes = getStaticTileSizes();
820 size_t numExpectedLoops = getUseForall() || hasPackedTiles
821 ? 1
822 : sizes.size() - llvm::count(sizes, 0);
823 if (numExpectedLoops != getNumResults() - 1)
824 return emitOpError() << "expects " << numExpectedLoops << " loop results";
825
826 return verifyInnerTileAlignments(getOperation(), getInnerTileAlignments());
827}
828
829SmallVector<OpFoldResult> transform::FuseOp::getMixedTileSizes() {
830 return getMixedValues(getStaticTileSizes(), getTileSizes(), getContext());
831}
832
833SmallVector<OpFoldResult> transform::FuseOp::getMixedTileInterchange() {
834 return getMixedValues(getStaticTileInterchange(), getTileInterchange(),
835 getContext());
836}
837
838void transform::FuseOp::getEffects(
840 consumesHandle(getTargetMutable(), effects);
841 onlyReadsHandle(getTileSizesMutable(), effects);
842 onlyReadsHandle(getPackedTileSizesMutable(), effects);
843 onlyReadsHandle(getTileInterchangeMutable(), effects);
844 producesHandle(getOperation()->getOpResults(), effects);
845 modifiesPayload(effects);
846}
847
848//===----------------------------------------------------------------------===//
849// FuseIntoContainingOp
850//===----------------------------------------------------------------------===//
851
852void transform::FuseIntoContainingOp::build(OpBuilder &builder,
854 Value producerOp,
855 Value containingOp) {
856 result.addOperands({producerOp, containingOp});
857 auto resultType = transform::AnyOpType::get(builder.getContext());
858 result.addTypes({resultType, resultType});
859}
860
861/// Add new operands to the forall op for users of the producerOp
862/// that are dominated by the containing scf.forall op.
864 RewriterBase &rewriter, Diagnostic &diag, Operation *producerOp,
865 Operation *containingOp, TilingResult &tileAndFuseResult,
866 int64_t resultNumber, SmallVector<OpFoldResult> &offsets,
868
869 // Count number of users not including the containing op
870 SetVector<Operation *> dominatedUsers;
871 DominanceInfo domInfo(containingOp);
872 for (Operation *user : producerOp->getResult(resultNumber).getUsers()) {
873 if (!containingOp->isAncestor(user) &&
874 (domInfo.dominates(containingOp, user))) {
875 dominatedUsers.insert(user);
876 }
877 }
878 if (dominatedUsers.empty())
879 return nullptr;
880
881 // Create new scf.forall op
882 auto forallOp = cast<scf::ForallOp>(containingOp);
883 OpBuilder::InsertionGuard g(rewriter);
884 rewriter.setInsertionPoint(forallOp);
885
886 // Get new output
887 Location loc = forallOp.getLoc();
888 auto genericOp = dyn_cast<linalg::GenericOp>(producerOp);
889 if (!genericOp)
890 return nullptr;
891 SmallVector<Value> outputs = genericOp.getOutputs();
892 SmallVector<Value> newOuts(forallOp.getOutputs());
893 newOuts.push_back(outputs[resultNumber]);
894
895 // Create new scf.forall op
896 auto newforallOp = scf::ForallOp::create(
897 rewriter, loc, forallOp.getMixedLowerBound(),
898 forallOp.getMixedUpperBound(), forallOp.getMixedStep(), newOuts,
899 forallOp.getMapping());
900 rewriter.eraseBlock(newforallOp.getBody());
901 newforallOp.getRegion().takeBody(forallOp.getRegion());
902
903 // Add additional block argument for new value being returned
904 // and replaces all uses of the new output with corresponding bbArg
905 // inside the scf.forall to enable fusion into this new scf.forall.
906 newforallOp.getBody()->addArgument(newOuts.back().getType(),
907 newOuts.back().getLoc());
908 auto bbArgs = newforallOp.getBody()->getArguments();
909 rewriter.replaceUsesWithIf(newOuts.back(), bbArgs.back(),
910 [&](OpOperand &use) {
911 Operation *op = use.getOwner();
912 return newforallOp->isProperAncestor(op);
913 });
914
915 // Fix terminator
916 scf::InParallelOp terminatorOp = newforallOp.getTerminator();
917 SmallVector<Operation *> yieldingOps = llvm::map_to_vector<4>(
918 terminatorOp.getYieldingOps(), [](Operation &op) { return &op; });
919 Operation *firstYieldOp = yieldingOps.front();
920 rewriter.setInsertionPoint(firstYieldOp);
921 Value src = tileAndFuseResult.tiledValues[0];
922 Value dst = newforallOp.getRegionIterArgs().back();
923 SmallVector<OpFoldResult> strides(offsets.size(), rewriter.getIndexAttr(1));
924 tensor::ParallelInsertSliceOp::create(rewriter, firstYieldOp->getLoc(), src,
925 dst, offsets, sizes, strides);
926
927 for (auto result : llvm::enumerate(forallOp.getResults())) {
928 rewriter.replaceAllUsesWith(result.value(),
929 newforallOp->getResult(result.index()));
930 }
931 rewriter.replaceUsesWithIf(producerOp->getResult(resultNumber),
932 newforallOp->getResults().back(),
933 [&](OpOperand &use) {
934 Operation *user = use.getOwner();
935 return dominatedUsers.contains(user);
936 });
937 return newforallOp;
938}
939
940/// Given two operands coming from a loop iter arg, 'src' and 'dst', return true
941/// if the operand 'src' is equal to 'dst' or equal to a iter arg present in a
942/// outer loop. To determine the second condition, this function iterates
943/// using a worklist over the enclosing loops, trying to find 'src' in any of
944/// the parent loop's iter args.
945static bool sameOrEquivalentIterArg(Value src, Value dst) {
946 // Stack like vector containing possible iterArgs candidates. The first one
947 // is dst, and we will transverse the IR from there.
948 SmallVector<Value> destWorklist;
949 destWorklist.push_back(dst);
950
951 while (!destWorklist.empty()) {
952 Value currentDst = destWorklist.pop_back_val();
953
954 // We have found the same operand in some iter arg in the loop structure,
955 // so src and dst are equivalent.
956 if (src == currentDst)
957 return true;
958
959 // The operands are not equivalent, look for enclosing loops over
960 // currentDst.
961 auto bbArg = dyn_cast<BlockArgument>(currentDst);
962 if (!bbArg)
963 continue;
964
965 Block *parentBlock = bbArg.getOwner();
966 assert(parentBlock && "unlinked block argument");
967
968 Operation *parentOp = parentBlock->getParentOp();
969 assert(parentOp && "expected block argument with parent operation");
970
971 // Check if parent is loop-like. If it's not, do not add it to the worklist.
972 auto parentLoop = dyn_cast<LoopLikeOpInterface>(parentOp);
973 if (!parentLoop)
974 continue;
975
976 for (auto innerIterArg : parentLoop.getRegionIterArgs()) {
977 // No need to check for null as innerIterArg is tied to parentLoop.
978 OpOperand *operand = parentLoop.getTiedLoopInit(innerIterArg);
979 Value loopBlockArgument =
980 parentLoop->getOperand(operand->getOperandNumber());
981 destWorklist.push_back(loopBlockArgument);
982 }
983 }
984
985 return false;
986}
987
988/// Find the first "extract" user of `producerOp` and tile it right before its
989/// use. The tiled op is fused under the `containingOp`.
990/// Return this fused op on success or nullptr if anything fails.
991/// If tiled op has uses that are dominated by `containingOp`, return
992/// a new `containingOp` with results of the fused op appended to
993/// results of the `containingOp` or nullptr if there are no dominated uses.
994static std::tuple<SmallVector<Operation *>, Operation *>
996 Operation *producerOp, Operation *containingOp,
997 ArrayRef<InnerTileAlignment> innerTileAlignments) {
998 LDBG() << "Try to fuse a direct extract use";
999 auto tileableProducer = dyn_cast<TilingInterface>(producerOp);
1000 if (!tileableProducer) {
1001 diag.attachNote(producerOp->getLoc())
1002 << "producer is not a TileableInterface: " << *producerOp;
1003 return {};
1004 }
1005
1006 // Search the producer slices accessed within the containing operation.
1007 // TODO: Generalize to more extract/insert/parallel_insert triples, maybe
1008 // evolve into an interface.
1009 auto it = llvm::find_if(tileableProducer->getUsers(), [&](Operation *user) {
1010 auto sliceOp = dyn_cast<tensor::ExtractSliceOp>(user);
1011 return sliceOp && containingOp->isProperAncestor(sliceOp);
1012 });
1013
1014 // Find a fusion opportunity.
1015 if (it == tileableProducer->getUsers().end()) {
1016 diag.attachNote(tileableProducer->getLoc())
1017 << "could not find fusion opportunity for: " << *tileableProducer;
1018 return {};
1019 }
1020 auto sliceOpToTile = cast<tensor::ExtractSliceOp>(*it);
1021
1022 // Try to fuse the producer in-place.
1023 OpBuilder::InsertionGuard guard(rewriter);
1024 rewriter.setInsertionPoint(sliceOpToTile);
1025
1026 // Clone the producer inside the consumer and try to update the producer init
1027 // operands using the loop bbArgs if applicable. More precisely, if the bbArg
1028 // of the container loop points to a value that it is used by the consumer op,
1029 // then, instead of using such value on the consumer, use the value coming
1030 // from the bbArg instead. This allows to reuse the output tensor (instead of
1031 // creating a new one) of the container when both producer and container write
1032 // to the same output.
1033 if (LoopLikeOpInterface containerLoop =
1034 dyn_cast<LoopLikeOpInterface>(sliceOpToTile->getParentOp())) {
1035 Operation *clone = rewriter.clone(*producerOp);
1036 rewriter.modifyOpInPlace(clone, [&]() {
1037 // Iterate over the outputs of the producer and over the loop bbArgs and
1038 // check if any bbArg points to the same value as the producer output. In
1039 // such case, make the producer output point to the bbArg directly.
1040 auto dpsInterface = dyn_cast<DestinationStyleOpInterface>(clone);
1041 if (!dpsInterface)
1042 return;
1043
1044 for (OpOperand &initOperandPtr : dpsInterface.getDpsInitsMutable()) {
1045 Value producerOperand =
1046 clone->getOperand(initOperandPtr.getOperandNumber());
1047 for (BlockArgument containerIterArg :
1048 containerLoop.getRegionIterArgs()) {
1049 OpOperand *bbArg = containerLoop.getTiedLoopInit(containerIterArg);
1050 Value consumerOperand =
1051 containerLoop->getOperand(bbArg->getOperandNumber());
1052 // The producer has the same init as the loop bbArg, use it.
1053 if (sameOrEquivalentIterArg(producerOperand, consumerOperand)) {
1054 initOperandPtr.set(containerIterArg);
1055 }
1056 }
1057 }
1058 });
1059
1060 tileableProducer = dyn_cast<TilingInterface>(clone);
1061 }
1062
1063 // Tile the producer.
1064 int64_t resultNumber =
1065 cast<OpResult>(sliceOpToTile.getSource()).getResultNumber();
1066 LDBG() << "resultNumber: " << resultNumber;
1067
1068 SmallVector<OpFoldResult> offsets = sliceOpToTile.getMixedOffsets();
1069 SmallVector<OpFoldResult> sizes = sliceOpToTile.getMixedSizes();
1070
1071 FailureOr<TilingResult> tileAndFuseResult =
1072 tileableProducer.generateResultTileValue(rewriter, resultNumber, offsets,
1073 sizes, innerTileAlignments);
1074
1075 if (failed(tileAndFuseResult)) {
1076 diag.attachNote(tileableProducer->getLoc())
1077 << "failed to tile producer op: " << *tileableProducer;
1078 return {};
1079 }
1080
1081#ifndef NDEBUG
1082 for (auto *tiledOp : tileAndFuseResult->tiledOps) {
1083 LDBG() << "tiledProducer: " << *tiledOp;
1084 }
1085#endif
1086
1087 // Replace the extract op.
1088 auto maybeRankReduced = tensor::ExtractSliceOp::rankReduceIfNeeded(
1089 rewriter, sliceOpToTile->getLoc(), tileAndFuseResult->tiledValues[0],
1090 cast<RankedTensorType>(sliceOpToTile->getResult(0).getType()).getShape());
1091 if (failed(maybeRankReduced)) {
1092 diag.attachNote(producerOp->getLoc())
1093 << "shape types don't match (missing canonicalization?):\nTiledOp: "
1094 << tileAndFuseResult->tiledValues[0]
1095 << "\nSliceOp: " << sliceOpToTile.getOperation() << '\n';
1096 return {};
1097 }
1098 rewriter.replaceOp(sliceOpToTile, *maybeRankReduced);
1099
1100 // Add new outputs to containing op, if required
1101 Operation *newContainingOp = replaceForAllWithNewSignature(
1102 rewriter, diag, producerOp, containingOp, *tileAndFuseResult,
1103 resultNumber, offsets, sizes);
1104
1105 // Cleanup clone.
1106 if (isa<LoopLikeOpInterface>(containingOp))
1107 rewriter.eraseOp(tileableProducer);
1108
1109 return std::make_tuple(tileAndFuseResult->tiledOps, newContainingOp);
1110}
1111
1112/// First, find the first "scf::ForallOp" user of `producerOp` and ensure
1113/// it is exactly the `containingOp`, otherwise bail.
1114/// Then, find the first "extract" user of the tied block argument and tile it
1115/// right before its "extract" use. The tiled op is fused under the
1116/// `containingOp`.
1117/// Return this fused op on success or nullptr if anything fails.
1120 RewriterBase &rewriter, Diagnostic &diag, Operation *producerOp,
1121 Operation *containingOp, ArrayRef<InnerTileAlignment> innerTileAlignments) {
1122 LDBG() << "Try to fuse an extract use through block argument";
1123
1124 auto tileableProducer = dyn_cast<TilingInterface>(producerOp);
1125 if (!tileableProducer) {
1126 diag.attachNote(producerOp->getLoc())
1127 << "producer is not a TileableInterface: " << *producerOp;
1128 return {};
1129 }
1130
1131 // Search the first use by a "scf::ForallOp" user.
1132 scf::ForallOp forallOp;
1133 auto itProducerUses =
1134 llvm::find_if(tileableProducer->getUses(), [&](OpOperand &use) {
1135 forallOp = dyn_cast<scf::ForallOp>(use.getOwner());
1136 return forallOp;
1137 });
1138 // If it's not from the containing op, return.
1139 if (!forallOp || forallOp != containingOp) {
1140 diag.attachNote(tileableProducer->getLoc())
1141 << "could not find a use by the containing op: " << *tileableProducer;
1142 return {};
1143 }
1144
1145 // Search the producer slices accessed within the containing
1146 // operation.
1147 // TODO: Generalize to more extract/insert/parallel_insert triples.
1148 // Maybe evolve into an interface.
1149 OpOperand *pUse = &(*itProducerUses);
1150 BlockArgument bbArg = forallOp.getTiedBlockArgument(pUse);
1151
1152 // Search the producer slices accessed within the containing operation.
1153 // TODO: Generalize to more extract/insert/parallel_insert triples, maybe
1154 // evolve into an interface.
1155 auto itBBArgUsers = llvm::find_if(bbArg.getUsers(), [&](Operation *user) {
1156 auto sliceOp = dyn_cast<tensor::ExtractSliceOp>(user);
1157 return sliceOp && containingOp->isProperAncestor(sliceOp);
1158 });
1159
1160 // Find a fusion opportunity.
1161 if (itBBArgUsers == bbArg.getUsers().end()) {
1162 diag.attachNote(containingOp->getLoc())
1163 << "could not find fusion opportunity for bbArg: " << bbArg;
1164 return {};
1165 }
1166 auto sliceOpToTile = cast<tensor::ExtractSliceOp>(*itBBArgUsers);
1167
1168 // Try to fuse the producer in-place.
1169 OpBuilder::InsertionGuard guard(rewriter);
1170 rewriter.setInsertionPoint(sliceOpToTile);
1171
1172 // Replace the use in the tileableProducer before tiling: clone, replace and
1173 // then tile.
1174 int64_t resultNumber = cast<OpResult>(pUse->get()).getResultNumber();
1175 LDBG() << "resultNumber: " << resultNumber;
1176
1177 // Gather destination tensors.
1178 SmallVector<Value> destinationTensors;
1180 rewriter, tileableProducer->getLoc(), tileableProducer,
1181 destinationTensors))) {
1182 diag.attachNote(tileableProducer->getLoc())
1183 << "failed to get destination tensors for: " << *tileableProducer;
1184 return {};
1185 }
1186
1187 IRMapping bvm;
1188 bvm.map(destinationTensors[resultNumber], bbArg);
1189 auto tileableProducerClone =
1190 cast<TilingInterface>(rewriter.clone(*tileableProducer, bvm));
1191 llvm::scope_exit scopeGuard(
1192 [&]() { rewriter.eraseOp(tileableProducerClone); });
1193
1194 // Tile the producer.
1195 FailureOr<TilingResult> tileAndFuseResult =
1196 tileableProducerClone.generateResultTileValue(
1197 rewriter, resultNumber, sliceOpToTile.getMixedOffsets(),
1198 sliceOpToTile.getMixedSizes(), innerTileAlignments);
1199 if (failed(tileAndFuseResult)) {
1200 diag.attachNote(tileableProducer->getLoc())
1201 << "failed to tile producer op: " << *tileableProducer;
1202 return {};
1203 }
1204
1205 // Replace the extract op.
1206 auto maybeRankReduced = tensor::ExtractSliceOp::rankReduceIfNeeded(
1207 rewriter, sliceOpToTile->getLoc(), tileAndFuseResult->tiledValues[0],
1208 cast<RankedTensorType>(sliceOpToTile->getResult(0).getType()).getShape());
1209 assert(succeeded(maybeRankReduced) && "unexpected shape");
1210 rewriter.replaceOp(sliceOpToTile, *maybeRankReduced);
1211
1212 // Replace the use in containingOp.
1213 rewriter.modifyOpInPlace(containingOp, [&]() {
1214 containingOp->setOperand(pUse->getOperandNumber(),
1215 destinationTensors.front());
1216 });
1217
1218 return tileAndFuseResult->tiledOps;
1219}
1220
1222 Operation *producerOp,
1223 Operation *containingOp) {
1224 LDBG() << "Try to fuse an use by cloning";
1225
1226 // Gather all uses inside the containing op.
1228 for (OpResult result : producerOp->getOpResults()) {
1229 for (OpOperand &use : result.getUses()) {
1230 if (containingOp->isProperAncestor(use.getOwner())) {
1231 uses.push_back(&use);
1232 continue;
1233 }
1234 // Cannot clone and fuse if the use is by the containing op itself: fail
1235 // immediately.
1236 if (containingOp == use.getOwner()) {
1237 diag.attachNote(producerOp->getLoc())
1238 << "producer op use by containing op cannot be fused by cloning";
1239 return nullptr;
1240 }
1241 }
1242 }
1243
1244 // Check for a non-empty list of fusion opportunities.
1245 if (uses.empty()) {
1246 diag.attachNote(producerOp->getLoc()) << "no fusion opportunity by cloning";
1247 return nullptr;
1248 }
1249
1250 // Clone and fuse inside the containing op.
1251 Operation *fusedOp = nullptr;
1252 OpOperand *use = uses.front();
1253 // Parallel insert slice is not a valid clone destination.
1254 // TODO: Generalize to other type of ops.
1255 assert(!isa<tensor::ParallelInsertSliceOp>(use->getOwner()) &&
1256 "Parallel insert slice is not a valid clone destination");
1257 unsigned resultNumber = cast<OpResult>(use->get()).getResultNumber();
1258 LDBG() << "resultNumber: " << resultNumber;
1259
1260 OpBuilder::InsertionGuard guard(rewriter);
1261 rewriter.setInsertionPoint(use->getOwner());
1262 fusedOp = rewriter.clone(*producerOp);
1263 rewriter.modifyOpInPlace(
1264 use->getOwner(), [&] { use->set(fusedOp->getOpResult(resultNumber)); });
1265
1266 return fusedOp;
1267}
1268
1269bool transform::FuseIntoContainingOp::allowsRepeatedHandleOperands() {
1270 // Allow repeated handles since we are fusing everything anyway.
1271 return true;
1272}
1273
1274LogicalResult transform::FuseIntoContainingOp::verify() {
1275 return verifyInnerTileAlignments(getOperation(), getInnerTileAlignments());
1276}
1277
1279transform::FuseIntoContainingOp::apply(transform::TransformRewriter &rewriter,
1282 SmallVector<Operation *> fusedOps;
1283 auto producerOps = state.getPayloadOps(getProducerOp());
1284 auto containingOps = state.getPayloadOps(getContainingOp());
1285 if (!llvm::hasSingleElement(containingOps)) {
1286 return emitDefiniteFailure()
1287 << "requires exactly one containing_op handle (got "
1288 << llvm::range_size(containingOps) << ")";
1289 }
1290 Operation *containingOp = *containingOps.begin();
1291
1292 // Forward the optional, caller-asserted alignment of a fused pack/unpack op's
1293 // inner tiles relative to the loop tile sizes (see InnerTileAlignment) to
1294 // each fused producer.
1295 SmallVector<InnerTileAlignment> innerTileAlignments =
1296 convertInnerTileAlignments(getInnerTileAlignments());
1297
1298 // If nothing to fuse, propagate success.
1299 if (std::empty(producerOps)) {
1300 results.set(cast<OpResult>(getFusedOp()), SmallVector<mlir::Operation *>{});
1301 results.set(cast<OpResult>(getNewContainingOp()), {containingOp});
1303 }
1304
1305 // Top-level operations do not share an ancestor region with other producers
1306 // and cannot be fused into a containing operation.
1307 if (llvm::any_of(producerOps, [](Operation *op) {
1308 return op->getParentRegion() == nullptr;
1309 })) {
1310 auto diag = mlir::emitSilenceableFailure(getLoc())
1311 << "cannot fuse a top-level operation";
1312 diag.attachNote(containingOp->getLoc()) << "containing op";
1313 return diag;
1314 }
1315
1316 // Fuse consumers before their producers so that all uses introduced by
1317 // fusing a selected consumer are exposed before its producer is processed.
1318 SetVector<Operation *> sortedProducers =
1319 topologicalSort(SetVector<Operation *>(llvm::from_range, producerOps));
1320 SetVector<Operation *> remainingProducers(llvm::from_range,
1321 llvm::reverse(sortedProducers));
1322 // Find the next producer that has a use inside the containing op.
1323 auto getNextProducer = [&]() -> FailureOr<Operation *> {
1324 for (const auto &it : enumerate(remainingProducers)) {
1325 Operation *producerOp = it.value();
1326 // The containing op may be a user of producerOp: use isAncestor.
1327 int64_t numUsesInContainingOp =
1328 llvm::count_if(producerOp->getUsers(), [&](Operation *op) {
1329 return containingOp->isAncestor(op);
1330 });
1331 if (numUsesInContainingOp > 0) {
1332 if (numUsesInContainingOp == 1)
1333 remainingProducers.erase(remainingProducers.begin() + it.index());
1334 return producerOp;
1335 }
1336 }
1337 return failure();
1338 };
1339
1340 while (!remainingProducers.empty()) {
1341 auto nextProducer = getNextProducer();
1342 if (failed(nextProducer)) {
1343 auto diag = mlir::emitSilenceableFailure(getLoc())
1344 << "could not find next producer to fuse into container";
1345 diag.attachNote(containingOp->getLoc()) << "containing op";
1346 return diag;
1347 }
1348
1349 Operation *producerOp = *nextProducer;
1350
1351 // Default diagnostic, to be complemented with more failure information.
1353 diag << "could not fuse " << *producerOp << " into " << *containingOp;
1354
1355 // TODO: If there are multiple uses of the producer in the containing op,
1356 // we currently tile/clone the op multiple times (once per use). In some
1357 // cases, we can tile/clone once and reuse the value for each use.
1358 auto [tiledOps, newContainingOp] = tileAndFuseFirstExtractUse(
1359 rewriter, diag, producerOp, containingOp, innerTileAlignments);
1360 if (!tiledOps.empty()) {
1361 LDBG() << "\nFused a direct extract use\n" << *containingOp;
1362 fusedOps.append(tiledOps);
1363 if (newContainingOp) {
1364 // Update handles associated with the containing op so we don't need to
1365 // invalidate them. This is a hack to support better composability
1366 // between tiling and fusion while a proper mechanism is being
1367 // investigated.
1368 //
1369 // DO NOT replicate this elsewhere unless you understand what you are
1370 // doing.
1371 LogicalResult replacementStatus =
1372 rewriter.notifyPayloadOperationReplaced(containingOp,
1373 newContainingOp);
1374 (void)replacementStatus;
1375 assert(succeeded(replacementStatus) &&
1376 "unable to update transform state mapping");
1377 rewriter.eraseOp(containingOp);
1378 containingOp = newContainingOp;
1379 }
1380 continue;
1381 }
1382
1383 SmallVector<Operation *> tiledContainingOpOperand =
1385 rewriter, diag, producerOp, containingOp, innerTileAlignments);
1386 if (!tiledContainingOpOperand.empty()) {
1387 LDBG() << "\nFused an extract use through block argument\n"
1388 << *containingOp;
1389 fusedOps.append(tiledContainingOpOperand);
1390 continue;
1391 }
1392
1393 Operation *cloned =
1394 cloneAndFuseFirstUse(rewriter, diag, producerOp, containingOp);
1395 if (cloned) {
1396 LDBG() << "\nFused an use by cloning\n" << *containingOp;
1397 fusedOps.push_back(cloned);
1398 continue;
1399 }
1401 }
1402
1403 results.set(cast<OpResult>(getFusedOp()), fusedOps);
1404 results.set(cast<OpResult>(getNewContainingOp()), {containingOp});
1406}
1407
1408void transform::FuseIntoContainingOp::getEffects(
1410 consumesHandle(getProducerOpMutable(), effects);
1411 onlyReadsHandle(getContainingOpMutable(), effects);
1412 producesHandle(getOperation()->getOpResults(), effects);
1413 modifiesPayload(effects);
1414}
1415
1416//===----------------------------------------------------------------------===//
1417// GeneralizeOp
1418//===----------------------------------------------------------------------===//
1419
1421transform::GeneralizeOp::applyToOne(transform::TransformRewriter &rewriter,
1422 LinalgOp target,
1425 // Exit early if no transformation is needed.
1426 if (isa<GenericOp>(target)) {
1427 results.push_back(target);
1429 }
1430 rewriter.setInsertionPoint(target);
1431 FailureOr<LinalgOp> generic = generalizeNamedOp(rewriter, target);
1432 if (succeeded(generic)) {
1433 results.push_back(generic->getOperation());
1435 }
1436 return emitDefaultSilenceableFailure(target);
1437}
1438
1439//===----------------------------------------------------------------------===//
1440// SpecializeOp
1441//===----------------------------------------------------------------------===/
1442
1444transform::SpecializeOp::applyToOne(transform::TransformRewriter &rewriter,
1445 LinalgOp target,
1448 // Exit early if the operation is not a generic.
1449 if (!isa<GenericOp>(target)) {
1450 results.push_back(target);
1452 }
1453 rewriter.setInsertionPoint(target);
1454 FailureOr<LinalgOp> named =
1455 specializeGenericOp(rewriter, cast<GenericOp>(target), getEmitCategory());
1456 if (succeeded(named)) {
1457 results.push_back(named->getOperation());
1459 }
1460 return emitDefaultSilenceableFailure(target);
1461}
1462
1463//===----------------------------------------------------------------------===//
1464// InterchangeOp
1465//===----------------------------------------------------------------------===//
1466
1468transform::InterchangeOp::applyToOne(transform::TransformRewriter &rewriter,
1469 GenericOp target,
1472 ArrayRef<int64_t> interchangeVector = getIteratorInterchange();
1473 // Exit early if no transformation is needed.
1474 if (interchangeVector.empty()) {
1475 results.push_back(target);
1477 }
1478
1479 unsigned numLoops = cast<LinalgOp>(target.getOperation()).getNumLoops();
1480 if (interchangeVector.size() != numLoops) {
1481 return emitSilenceableError()
1482 << getIteratorInterchangeAttrName() << " has length ("
1483 << interchangeVector.size()
1484 << ") different from the number of loops in the target operation ("
1485 << numLoops << ")";
1486 }
1487 FailureOr<GenericOp> res = interchangeGenericOp(
1488 rewriter, target, SmallVector<unsigned>(interchangeVector));
1489 if (failed(res))
1490 return emitDefiniteFailure() << "failed to apply";
1491 results.push_back(res->getOperation());
1493}
1494
1495LogicalResult transform::InterchangeOp::verify() {
1496 ArrayRef<int64_t> permutation = getIteratorInterchange();
1497 auto sequence = llvm::to_vector(llvm::seq<int64_t>(0, permutation.size()));
1498 if (!std::is_permutation(sequence.begin(), sequence.end(),
1499 permutation.begin(), permutation.end())) {
1500 return emitOpError()
1501 << "expects iterator_interchange to be a permutation, found "
1502 << getIteratorInterchange();
1503 }
1504 return success();
1505}
1506
1507//===----------------------------------------------------------------------===//
1508// LinalgCopyToMemrefOp
1509//===----------------------------------------------------------------------===//
1510
1511DiagnosedSilenceableFailure transform::LinalgCopyToMemrefOp::applyToOne(
1512 transform::TransformRewriter &rewriter, Operation *targetOp,
1515
1516 // Check if the target can be converted.
1517 if (!isa<linalg::CopyOp>(targetOp)) {
1519 emitSilenceableError() << "only linalg.copy target ops are supported";
1520 diag.attachNote(targetOp->getLoc()) << "target op";
1521 return diag;
1522 }
1523
1524 auto copyOp = dyn_cast<linalg::CopyOp>(targetOp);
1525 if (!copyOp.hasPureBufferSemantics()) {
1527 emitSilenceableError()
1528 << "cannot transform a linalg.copy on tensors into a memref.copy";
1529 diag.attachNote(targetOp->getLoc()) << "target op";
1530 return diag;
1531 }
1532
1533 SmallVector<Value> inputs = copyOp.getInputs();
1534 SmallVector<Value> outputs = copyOp.getOutputs();
1535 assert(inputs.size() == 1 && "expected linalg copy op with one input");
1536 assert(outputs.size() == 1 && "expected memref copy op with one output");
1537 Value input = inputs.front();
1538 Value output = outputs.front();
1539
1540 // linalg.copy supports different element types on source/dest whereas
1541 // memref.copy does not, so we must check that the source and dest types can
1542 // be handled by memref.copy and otherwise reject the transformation.
1543 if (!isa<ShapedType>(input.getType())) {
1545 emitSilenceableError()
1546 << "cannot transform a linalg.copy which input has no shape";
1547 diag.attachNote(targetOp->getLoc()) << "target op";
1548 return diag;
1549 }
1550
1551 // linalg.copy destination must be a shaped type.
1552 assert(isa<ShapedType>(output.getType()));
1553
1554 if (cast<ShapedType>(input.getType()).getElementType() !=
1555 cast<ShapedType>(output.getType()).getElementType()) {
1557 emitSilenceableError()
1558 << "cannot transform a linalg.copy with different source and "
1559 "destination element types ";
1560 diag.attachNote(targetOp->getLoc()) << "target op";
1561 return diag;
1562 }
1563
1564 // Target can be converted, do it.
1565 auto memrefCopyOp =
1566 rewriter.replaceOpWithNewOp<memref::CopyOp>(targetOp, input, output);
1567
1568 results.push_back(memrefCopyOp);
1570}
1571
1572//===----------------------------------------------------------------------===//
1573// LowerPackOp
1574//===----------------------------------------------------------------------===//
1575
1576DiagnosedSilenceableFailure transform::LowerPackOp::applyToOne(
1577 transform::TransformRewriter &rewriter, linalg::PackOp target,
1578 transform::ApplyToEachResultList &transformResults,
1580 if (!target.hasPureTensorSemantics()) {
1581 return mlir::emitSilenceableFailure(target->getLoc())
1582 << "lower_pack only supports tensor semantics. The target has "
1583 "memref operands";
1584 }
1585 rewriter.setInsertionPoint(target);
1586 bool lowerPadLikeWithInsertSlice = getLowerPadLikeWithInsertSlice();
1587 FailureOr<LowerPackResult> res =
1588 lowerPack(rewriter, target, lowerPadLikeWithInsertSlice);
1589 if (failed(res)) {
1590 return mlir::emitSilenceableFailure(target->getLoc())
1591 << "cannot lower to pad + expand + transpose";
1592 }
1593 transformResults.push_back(res->padOp);
1594 transformResults.push_back(res->expandShapeOp);
1595 transformResults.push_back(res->transposeOp);
1597}
1598
1599//===----------------------------------------------------------------------===//
1600// LowerUnPackOp
1601//===----------------------------------------------------------------------===//
1602
1603DiagnosedSilenceableFailure transform::LowerUnPackOp::applyToOne(
1604 transform::TransformRewriter &rewriter, linalg::UnPackOp target,
1605 transform::ApplyToEachResultList &transformResults,
1607 if (!target.hasPureTensorSemantics()) {
1609 emitSilenceableError() << "lower_unpack only supports tensor "
1610 "semantics. The target has memref operands";
1611 diag.attachNote(target->getLoc()) << "target payload op";
1612 return diag;
1613 }
1614 rewriter.setInsertionPoint(target);
1615 bool lowerUnpadLikeWithExtractSlice = getLowerUnpadLikeWithExtractSlice();
1616 FailureOr<LowerUnPackOpResult> res =
1617 lowerUnPack(rewriter, target, lowerUnpadLikeWithExtractSlice);
1618 if (failed(res)) {
1620 emitSilenceableError()
1621 << "cannot lower to transpose + collapse + extract";
1622 diag.attachNote(target->getLoc()) << "target payload op";
1623 return diag;
1624 }
1625 transformResults.push_back(res->emptyOp);
1626 transformResults.push_back(res->transposeOp);
1627 transformResults.push_back(res->collapseShapeOp);
1628 transformResults.push_back(res->extractSliceOp);
1629 transformResults.push_back(res->copyOp);
1631}
1632
1633//===---------------------------------------------------------------------===//
1634// MatchOp
1635//===---------------------------------------------------------------------===//
1636
1637void transform::MatchOp::build(OpBuilder &builder, OperationState &result,
1638 Value target, ArrayRef<StringRef> opNames) {
1639 result.addOperands(target);
1640 result.addAttribute(MatchOp::getOpsAttrName(result.name),
1641 builder.getStrArrayAttr(opNames));
1642 result.addTypes(transform::AnyOpType::get(builder.getContext()));
1643}
1644
1645void transform::MatchOp::build(OpBuilder &builder, OperationState &result,
1646 TypeRange resultTypes, Value target,
1647 ArrayRef<StringRef> opNames) {
1648 result.addOperands(target);
1649 result.addAttribute(MatchOp::getOpsAttrName(result.name),
1650 builder.getStrArrayAttr(opNames));
1651 result.addTypes(resultTypes);
1652}
1653
1655transform::MatchOp::apply(transform::TransformRewriter &rewriter,
1658 llvm::StringSet<> strs;
1659 if (getOps().has_value())
1660 strs.insert_range(getOps()->getAsValueRange<StringAttr>());
1661
1662 auto payloadOps = state.getPayloadOps(getTarget());
1663 if (!llvm::hasSingleElement(payloadOps)) {
1664 return emitDefiniteFailure("requires exactly one target handle");
1665 }
1666
1668 bool incorrectNumOperandTypes = false;
1669 auto matchFun = [&](Operation *op) {
1670 if (getOps().has_value() && !strs.contains(op->getName().getStringRef()))
1671 return;
1672
1673 // Interfaces cannot be matched by name, just by ID.
1674 // So we specifically encode the interfaces we care about for this op.
1675 if (getInterface().has_value()) {
1676 auto iface = getInterface().value();
1677 if (iface == transform::MatchInterfaceEnum::LinalgOp &&
1678 !isa<LinalgOp>(op))
1679 return;
1680 if (iface == transform::MatchInterfaceEnum::TilingInterface &&
1681 !isa<TilingInterface>(op))
1682 return;
1683 if (iface == transform::MatchInterfaceEnum::LoopLikeInterface &&
1684 !isa<LoopLikeOpInterface>(op))
1685 return;
1686 }
1687
1688 // Check if all specified attributes match.
1689 if (getOpAttrs().has_value()) {
1690 DictionaryAttr opAttrs = getOpAttrs().value();
1691 for (NamedAttribute attr : opAttrs) {
1692 if (attr.getName() == getInterfaceAttrName() ||
1693 attr.getName() == getOpsAttrName())
1694 continue;
1695 std::optional<Attribute> inherent = op->getInherentAttr(attr.getName());
1696 Attribute actual = inherent.has_value()
1697 ? *inherent
1698 : op->getDiscardableAttr(attr.getName());
1699 if (!actual)
1700 return;
1701 if (actual != attr.getValue())
1702 return;
1703 }
1704 }
1705
1706 if (getFilterResultType().has_value()) {
1707 Type t = getFilterResultType().value();
1708 if (op->getNumResults() != 1 || op->getResultTypes().front() != t)
1709 return;
1710 }
1711
1712 if (getFilterOperandTypes().has_value()) {
1713 mlir::ArrayAttr types = getFilterOperandTypes().value();
1714 auto operandTypes = op->getOperandTypes();
1715
1716 if (types.size() == 1) {
1717 // All the operands must must be equal to the specified type
1718 auto typeattr =
1719 dyn_cast<mlir::TypeAttr>(getFilterOperandTypes().value()[0]);
1720 Type t = cast<::mlir::Type>(typeattr.getValue());
1721 if (!llvm::all_of(op->getOperandTypes(),
1722 [&](Type operandType) { return operandType == t; }))
1723 return;
1724 } else {
1725 // The operand types must match all the types in the list (in the same
1726 // order in with they are specified)
1727 if (types.size() != operandTypes.size()) {
1728 incorrectNumOperandTypes = true;
1729 return;
1730 }
1731
1732 for (auto [attr, operandType] :
1733 llvm::zip_equal(getFilterOperandTypes().value(), operandTypes)) {
1734 auto typeattr = cast<mlir::TypeAttr>(attr);
1735 Type type = cast<::mlir::Type>(typeattr.getValue());
1736
1737 if (type != operandType)
1738 return;
1739 }
1740 }
1741 }
1742
1743 // All constraints are satisfied.
1744 res.push_back(op);
1745 return;
1746 };
1747
1748 (*payloadOps.begin())->walk(matchFun);
1749 if (incorrectNumOperandTypes)
1750 return emitDefiniteFailure("If filter_operand_types contains more than a "
1751 "type, then it must contain as much types as "
1752 "the number of operands in the target ops");
1753 results.set(cast<OpResult>(getResult()), res);
1755}
1756
1757//===---------------------------------------------------------------------===//
1758// MultiTileSizesOp
1759//===---------------------------------------------------------------------===//
1760
1762 Type targetType, Type lowSizeType, Type,
1763 Type) {
1764 printer.printFunctionalType(TypeRange{targetType}, TypeRange{lowSizeType});
1765}
1766
1767static ParseResult parseMultitileSizesTypes(OpAsmParser &parser,
1768 Type &targetType, Type &lowSizeType,
1769 Type &highSizeType,
1770 Type &splitPointType) {
1771 FunctionType funcType;
1772 llvm::SMLoc typeLoc = parser.getCurrentLocation();
1773 if (failed(parser.parseType<FunctionType>(funcType)))
1774 return failure();
1775
1776 if (funcType.getNumInputs() != 1 || funcType.getNumResults() != 1) {
1777 parser.emitError(typeLoc) << "expects a trailing functional type with one "
1778 "argument and one result";
1779 }
1780 targetType = funcType.getInput(0);
1781 lowSizeType = highSizeType = splitPointType = funcType.getResult(0);
1782
1783 return success();
1784}
1785
1786DiagnosedSilenceableFailure transform::MultiTileSizesOp::applyToOne(
1787 transform::TransformRewriter &rewriter, LinalgOp target,
1789 if (isa<TransformParamTypeInterface>(getLowSize().getType())) {
1790 if (target.hasDynamicShape()) {
1791 auto diag = emitSilenceableError()
1792 << "cannot compute parametric tile sizes for dynamically "
1793 "shaped payload op";
1794 diag.attachNote(target->getLoc()) << "payload op";
1795 return diag;
1796 }
1797
1798 FailureOr<StaticMultiSizeSpecification> spec = computeStaticMultiTileSizes(
1799 target, getDimension(), getTargetSize(), getDivisor());
1800 if (failed(spec)) {
1801 return emitSilenceableError()
1802 << "failed to compute multi-size tiling sizes";
1803 }
1804
1805 Builder builder(target.getContext());
1806 results.assign(llvm::map_range(
1807 ArrayRef<int64_t>({spec->lowTileSize, spec->highTileSize,
1808 spec->lowTileSize * spec->lowTripCount}),
1809 [&builder, this](int64_t value) {
1810 return builder.getIntegerAttr(
1811 cast<ParamType>(getLowSize().getType()).getType(), value);
1812 }));
1814 }
1815
1816 OpBuilder builder(target.getContext());
1817 builder.setInsertionPoint(target);
1818 OpFoldResult targetSize = builder.getIndexAttr(getTargetSize());
1819 OpFoldResult divisor = builder.getIndexAttr(getDivisor());
1820 FailureOr<MultiSizeSpecification> spec = computeMultiTileSizes(
1821 builder, target, getDimension(), targetSize, divisor);
1822 if (failed(spec)) {
1823 return emitSilenceableError() << "could not generate tile size computation";
1824 }
1825
1826 AffineExpr s0 = builder.getAffineSymbolExpr(0);
1827 AffineExpr s1 = builder.getAffineSymbolExpr(1);
1828 Operation *splitPoint =
1829 affine::makeComposedAffineApply(builder, target.getLoc(), s0 * s1,
1830 {spec->lowTileSize, spec->lowTripCount});
1831 Operation *lowTileSize = spec->lowTileSize.getDefiningOp();
1832 Operation *highTileSize = spec->highTileSize.getDefiningOp();
1833 assert(lowTileSize && highTileSize && splitPoint &&
1834 "tile sizes are not produced by operations");
1835 results.reserve(results.size() + 3);
1836 results.push_back(lowTileSize);
1837 results.push_back(highTileSize);
1838 results.push_back(splitPoint);
1840}
1841
1842void transform::MultiTileSizesOp::getEffects(
1844 onlyReadsHandle(getTargetMutable(), effects);
1845 producesHandle(getOperation()->getOpResults(), effects);
1846 if (isa<TransformParamTypeInterface>(getLowSize().getType()))
1847 onlyReadsPayload(effects);
1848 else
1849 modifiesPayload(effects);
1850}
1851
1852LogicalResult transform::MultiTileSizesOp::verify() {
1853 if (getLowSize().getType() != getHighSize().getType() ||
1854 getLowSize().getType() != getSplitPoint().getType()) {
1855 return emitOpError() << "expects all results type to be the same";
1856 }
1857 return success();
1858}
1859
1860//===---------------------------------------------------------------------===//
1861// PackOp
1862//===---------------------------------------------------------------------===//
1863
1864void transform::PackOp::build(OpBuilder &builder, OperationState &result,
1865 Value target,
1866 ArrayRef<OpFoldResult> mixedPackedSizes) {
1867 SmallVector<int64_t> staticPackedSizes;
1868 SmallVector<Value> dynamicPackedSizes;
1869 dispatchIndexOpFoldResults(mixedPackedSizes, dynamicPackedSizes,
1870 staticPackedSizes);
1871 // Call the default builder which sets up the proper operands segment sizes
1872 // attributes for multiple variadic operands. In the absence of this, horrible
1873 // bugs ensue.
1874 Type linalgOpHType = transform::OperationType::get(
1875 builder.getContext(), GenericOp::getOperationName());
1876 build(builder, result,
1877 /*resultType=*/linalgOpHType,
1878 /*target=*/target,
1879 /*dynamic_sizes=*/dynamicPackedSizes,
1880 /*static_sizes=*/builder.getDenseI64ArrayAttr(staticPackedSizes));
1881}
1882
1883SmallVector<OpFoldResult> transform::PackOp::getMixedPackedSizes() {
1884 Builder b(getContext());
1885 return getMixedValues(getStaticPackedSizes(), getPackedSizes(), b);
1886}
1887
1889transform::PackOp::apply(transform::TransformRewriter &rewriter,
1890 transform::TransformResults &transformResults,
1892 auto targetOps = state.getPayloadOps(getTarget());
1893 // If nothing to pack, propagate success.
1894 if (std::empty(targetOps)) {
1895 transformResults.set(cast<OpResult>(getPackedOp()),
1898 }
1899 // Fail on multi-op handles.
1900 auto linalgOp = dyn_cast<LinalgOp>(*targetOps.begin());
1901 if (!llvm::hasSingleElement(targetOps) || !linalgOp) {
1902 return emitSilenceableError()
1903 << "requires target to map to exactly 1 LinalgOp (got "
1904 << llvm::range_size(targetOps) << ")";
1905 }
1906 // Fail on memref operands: pack only supports tensor semantics.
1907 if (!linalgOp.hasPureTensorSemantics()) {
1908 return emitSilenceableError()
1909 << "structured.pack only supports tensor semantics. The target has "
1910 "memref operands";
1911 }
1912 // Fail on mismatched number of pack sizes.
1913 if (getMixedPackedSizes().size() != linalgOp.getNumLoops()) {
1914 return emitSilenceableError()
1915 << "requires number of packed sizes match the number of loops ("
1916 << getMixedPackedSizes().size() << " vs " << linalgOp.getNumLoops()
1917 << ")";
1918 }
1919
1920 // Unpack handles to constants or actual SSA index values.
1921 SmallVector<OpFoldResult> packedSizes;
1923 state, *this, packedSizes, getMixedPackedSizes());
1924
1925 rewriter.setInsertionPoint(linalgOp);
1926 FailureOr<PackResult> maybeResult = pack(rewriter, linalgOp, packedSizes);
1927 if (failed(maybeResult))
1928 return emitDefiniteFailure("data tiling failed");
1929
1930 transformResults.set(cast<OpResult>(getPackedOp()),
1931 {maybeResult->packedLinalgOp.getOperation()});
1933}
1934
1935void transform::PackOp::getEffects(
1937 transform::consumesHandle(getTargetMutable(), effects);
1938 transform::onlyReadsHandle(getPackedSizesMutable(), effects);
1939 transform::producesHandle(getOperation()->getOpResults(), effects);
1941}
1942
1943//===---------------------------------------------------------------------===//
1944// PackGreedilyOp.
1945//===---------------------------------------------------------------------===//
1946
1947LogicalResult transform::PackGreedilyOp::verify() {
1948 if (!isPermutationVector(getMatmulInnerDimsOrder())) {
1949 return emitOpError() << getMatmulInnerDimsOrderAttrName()
1950 << " is not a valid permutation";
1951 }
1952 // TODO: relax to allow empty once we have another strategy than just matmul.
1953 if (!getMatmulPaddedSizesNextMultipleOf().empty()) {
1954 for (auto [s, nmo] :
1955 llvm::zip_equal(getMixedMatmulPackedSizes(),
1956 getMatmulPaddedSizesNextMultipleOf())) {
1957 std::optional<int64_t> maybeStaticPackedSize = getConstantIntValue(s);
1958 if (nmo != 0 &&
1959 (!maybeStaticPackedSize.has_value() || *maybeStaticPackedSize != 0)) {
1960 return emitOpError() << "at most one of the packed_size and the "
1961 "padded_sizes_next_multiple_of can be nonzero "
1962 "for the matmul strategy";
1963 }
1964 }
1965 }
1966 return success();
1967}
1968
1970PackGreedilyOp::apply(transform::TransformRewriter &rewriter,
1971 transform::TransformResults &transformResults,
1974 for (auto linalgOp :
1975 llvm::make_isa_range<LinalgOp>(state.getPayloadOps(getTarget()))) {
1976 // linalgOp will be replaced and the insertion point may be invalidated if
1977 // we set it before -> set it after.
1978 rewriter.setInsertionPointAfter(linalgOp);
1979 // Failing to pack greedily is perfectly fine.
1980 // In the future we will want to order packings according to some metric.
1981 FailureOr<PackResult> packResult = packMatmulGreedily(
1982 /*rewriter=*/rewriter,
1983 /*linalgOp=*/linalgOp,
1984 /*mnkPackedSizes=*/getMixedMatmulPackedSizes(),
1985 /*mnkPaddedSizesNextMultipleOf=*/
1986 getMatmulPaddedSizesNextMultipleOf(),
1987 /*mnkOrder=*/getMatmulInnerDimsOrder());
1988 if (succeeded(packResult)) {
1989 results.push_back(packResult->packedLinalgOp);
1990 continue;
1991 }
1992 results.push_back(linalgOp);
1993 }
1994 transformResults.set(cast<OpResult>(getPackedOp()), results);
1996}
1997
1998SmallVector<OpFoldResult> PackGreedilyOp::getMixedMatmulPackedSizes() {
1999 Builder b(getContext());
2000 return getMixedValues(getStaticMatmulPackedSizes(), getMatmulPackedSizes(),
2001 b);
2002}
2003
2004void transform::PackGreedilyOp::getEffects(
2006 transform::consumesHandle(getTargetMutable(), effects);
2007 transform::onlyReadsHandle(getMatmulPackedSizesMutable(), effects);
2008 transform::producesHandle(getOperation()->getOpResults(), effects);
2010}
2011
2012//===---------------------------------------------------------------------===//
2013// PackTransposeOp
2014//===---------------------------------------------------------------------===//
2015
2016LogicalResult transform::PackTransposeOp::verify() {
2017 if (!isPermutationVector(getInnerPerm())) {
2018 return emitOpError() << getInnerPermAttrName()
2019 << " is not a valid permutation";
2020 }
2021 if (!isPermutationVector(getOuterPerm())) {
2022 return emitOpError() << getOuterPermAttrName()
2023 << " is not a valid permutation";
2024 }
2025 if (getInnerPerm().empty() && getOuterPerm().empty()) {
2026 return emitOpError() << " at least one of " << getInnerPermAttrName()
2027 << " or " << getOuterPermAttrName()
2028 << " must be specified";
2029 }
2030 return success();
2031}
2032
2033namespace {
2034enum class OuterOrInnerPerm { Outer = 0, Inner = 1 };
2035} // namespace
2036
2037/// Return true if `permutation` is a valid permutation of the
2038/// `outer_dims_perm` (case OuterOrInnerPerm::Outer) or `inner_dims_pos`
2039/// (OuterOrInnerPerm::Inner) of the `tensor.pack` or `tensor.unpack` `op.
2040/// This is the case when the `permutation` rank matches the rank expected by
2041/// `op` and `permutation` is itself a permutation vector.
2042/// Return true if either `op` or `permutation` are empty to allow a simpler
2043/// polymorphic implementation.
2044template <typename RelayoutOpTy>
2045static bool isValidPackingPermutation(
2046 RelayoutOpTy op, ArrayRef<int64_t> permutation,
2047 OuterOrInnerPerm outerOrInnerPerm = OuterOrInnerPerm::Outer) {
2048 static_assert(
2049 llvm::is_one_of<RelayoutOpTy, linalg::PackOp, linalg::UnPackOp>::value,
2050 "applies to only pack or unpack operations");
2051 if (!op || permutation.empty())
2052 return true;
2053 size_t innerRank = op.getInnerDimsPos().size();
2054 if (outerOrInnerPerm == OuterOrInnerPerm::Inner)
2055 return permutation.size() == innerRank && isPermutationVector(permutation);
2056 // op.getOuterDimsPerm() may be empty, in which case it is identity.
2057 // Don't rely on it.
2058 if (std::is_same<RelayoutOpTy, linalg::PackOp>::value) {
2059 return permutation.size() == op.getSourceRank() &&
2060 isPermutationVector(permutation);
2061 }
2062 return permutation.size() == op.getDestRank() &&
2063 isPermutationVector(permutation);
2064}
2065
2067transform::PackTransposeOp::apply(transform::TransformRewriter &rewriter,
2068 transform::TransformResults &transformResults,
2070 auto packOrUnpackOps = state.getPayloadOps(getTargetPackOrUnPackOp());
2071 auto linalgOps = state.getPayloadOps(getTargetLinalgOp());
2072 // Step 1. If nothing to pack, propagate success.
2073 if (std::empty(packOrUnpackOps)) {
2074 transformResults.set(cast<OpResult>(getPackedOp()), {});
2075 transformResults.set(cast<OpResult>(getPackOp()), {});
2076 transformResults.set(cast<OpResult>(getUnPackOp()), {});
2078 }
2079
2080 // Step 2. Bunch of runtime sanity check and error messages.
2081 // Step 2.1. Fail on multi-op handles.
2082 if (!llvm::hasSingleElement(packOrUnpackOps) ||
2083 !llvm::hasSingleElement(linalgOps)) {
2084 return emitSilenceableError()
2085 << "requires target to map to exactly 1 "
2086 "packing op and 1 packed op ("
2087 << "got " << llvm::range_size(packOrUnpackOps) << " and "
2088 << llvm::range_size(linalgOps) << ")";
2089 }
2090
2091 // Step 2.2. Fail on wrong type.
2092 auto packOp = dyn_cast<linalg::PackOp>(*packOrUnpackOps.begin());
2093 auto unPackOp = dyn_cast<linalg::UnPackOp>(*packOrUnpackOps.begin());
2094 if ((!packOp && !unPackOp)) {
2095 return emitSilenceableError() << "requires target to map to a "
2096 "linalg.pack or linalg.unpack";
2097 }
2098 LinalgOp linalgOpTarget = dyn_cast<LinalgOp>(*linalgOps.begin());
2099 if (!linalgOpTarget)
2100 return emitSilenceableError() << "requires a LinalgOp target";
2101
2102 // Step 2.3. Fail if we can't get the producer / consumer Linalg op.
2103 LinalgOp linalgOp;
2104 if (packOp && packOp.getResult().hasOneUse())
2105 linalgOp = dyn_cast<LinalgOp>(*(packOp.getResult().getUsers().begin()));
2106 else if (unPackOp)
2107 linalgOp = unPackOp.getSource().getDefiningOp<LinalgOp>();
2108 if (linalgOp != linalgOpTarget) {
2109 auto errorMsg =
2110 packOp ? StringLiteral{"not a single use by the LinalgOp target"}
2111 : StringLiteral{"not produced by the LinalgOp target"};
2112 return emitSilenceableError() << errorMsg;
2113 }
2114
2115 // Step 2.4. If we have an UnPackOp, we need to fetch the symmetrical
2116 // PackOp.
2117 if (unPackOp) {
2118 assert(!packOp && "packOp must be null on entry when unPackOp is not null");
2119 OpOperand *packUse = linalgOp.getDpsInitOperand(
2120 cast<OpResult>(unPackOp.getSource()).getResultNumber());
2121 packOp = packUse->get().getDefiningOp<linalg::PackOp>();
2122 if (!packOp || !packOp.getResult().hasOneUse())
2123 return emitSilenceableError() << "could not find matching pack op";
2124 }
2125
2126 // Step 2.5. Fail if any permutation does not validate.
2127 for (auto permType : {OuterOrInnerPerm::Outer, OuterOrInnerPerm::Inner}) {
2128 ArrayRef<int64_t> perm =
2129 (permType == OuterOrInnerPerm::Outer) ? getOuterPerm() : getInnerPerm();
2130 auto errorMsg = (permType == OuterOrInnerPerm::Outer)
2131 ? StringLiteral{"invalid outer_perm"}
2132 : StringLiteral{"invalid inner_perm"};
2133 if (!isValidPackingPermutation(packOp, perm, permType) ||
2134 !isValidPackingPermutation(unPackOp, perm, permType)) {
2135 Operation *packOrUnpackOp =
2136 unPackOp ? unPackOp.getOperation() : packOp.getOperation();
2137 return emitSilenceableError() << errorMsg << ": " << *packOrUnpackOp;
2138 }
2139 }
2140
2141 // From here on, packOp and linalgOp are always present, unPackOp may or may
2142 // not be present.
2143 assert(packOp && linalgOp && "unexpected null op");
2144
2145 // Step 3. Actually transpose the ops.
2146 FailureOr<PackTransposeResult> res = packTranspose(
2147 rewriter, packOp, linalgOp, unPackOp, getOuterPerm(), getInnerPerm());
2148 // Preconditions have been checked, it is an error to fail here.
2149 assert(succeeded(res) && "unexpected packTranspose failure");
2150
2151 // Step 4. Return results.
2152 transformResults.set(cast<OpResult>(getPackOp()), {res->transposedPackOp});
2153 transformResults.set(cast<OpResult>(getPackedOp()),
2154 {res->transposedLinalgOp});
2155 if (unPackOp) {
2156 transformResults.set(cast<OpResult>(getUnPackOp()),
2157 {res->transposedUnPackOp});
2158 } else {
2159 transformResults.set(cast<OpResult>(getUnPackOp()), {});
2160 }
2161
2163}
2164
2165//===---------------------------------------------------------------------===//
2166// PadOp
2167//===---------------------------------------------------------------------===//
2168
2169void transform::PadOp::build(OpBuilder &b, OperationState &result, Value target,
2170 ArrayRef<int64_t> paddingDimensions,
2171 ArrayRef<int64_t> padToMultipleOf,
2172 ArrayRef<int64_t> nofoldFlags,
2173 ArrayRef<Attribute> transposePaddings,
2174 StringRef copyBackOp,
2175 bool usePrescribedTensorShapes) {
2176 auto resultType = transform::AnyOpType::get(b.getContext());
2177 return build(/*odsBuilder=*/b,
2178 /*result=*/result,
2179 /*types=*/TypeRange{resultType, resultType},
2180 /*target=*/target,
2181 /*padding_values=*/ArrayAttr(), // let inference handle this
2182 /*padding_dimensions=*/b.getI64ArrayAttr(paddingDimensions),
2183 /*pad_to_multiple_of=*/ValueRange{},
2184 /*padToMultipleOf=*/
2185 (padToMultipleOf.empty()
2187 : b.getDenseI64ArrayAttr(padToMultipleOf)),
2188 /*nofold_flags=*/b.getI64ArrayAttr(nofoldFlags),
2189 /*transpose_paddings=*/b.getArrayAttr(transposePaddings),
2190 /*copy_back_op=*/b.getStringAttr(copyBackOp),
2191 /*use_prescribed_tensor_shapes=*/
2192 usePrescribedTensorShapes ? b.getUnitAttr() : nullptr);
2193}
2194
2195void transform::PadOp::build(OpBuilder &b, OperationState &result, Value target,
2196 ArrayRef<int64_t> paddingDimensions,
2197 ArrayRef<OpFoldResult> mixedPadToMultipleOf,
2198 ArrayRef<int64_t> nofoldFlags,
2199 ArrayRef<Attribute> transposePaddings,
2200 StringRef copyBackOp,
2201 bool usePrescribedTensorShapes) {
2202 auto resultType = transform::AnyOpType::get(b.getContext());
2203 SmallVector<int64_t> staticPadToMultipleOf;
2204 SmallVector<Value> dynamicPadToMultipleOf;
2205 dispatchIndexOpFoldResults(mixedPadToMultipleOf, dynamicPadToMultipleOf,
2206 staticPadToMultipleOf);
2207 return build(/*odsBuilder=*/b,
2208 /*result=*/result,
2209 /*types=*/TypeRange{resultType, resultType},
2210 /*target=*/target,
2211 /*padding_values=*/ArrayAttr(), // let inference handle this
2212 /*padding_dimensions=*/b.getI64ArrayAttr(paddingDimensions),
2213 /*pad_to_multiple_of=*/dynamicPadToMultipleOf,
2214 /*padToMultipleOf=*/staticPadToMultipleOf,
2215 /*nofold_flags=*/b.getI64ArrayAttr(nofoldFlags),
2216 /*transpose_paddings=*/b.getArrayAttr(transposePaddings),
2217 /*copy_back_op=*/copyBackOp,
2218 /*use_prescribed_tensor_shapes=*/usePrescribedTensorShapes);
2219}
2220
2221void PadOp::getEffects(
2223 consumesHandle(getTargetMutable(), effects);
2224 onlyReadsHandle(getPadToMultipleOfMutable(), effects);
2225 producesHandle(getOperation()->getOpResults(), effects);
2226 modifiesPayload(effects);
2227}
2228
2229SmallVector<OpFoldResult> PadOp::getMixedPadToMultipleOf() {
2230 Builder b(getContext());
2231 return getMixedValues(getStaticPadToMultipleOf(), getPadToMultipleOf(), b);
2232}
2233
2234DiagnosedSilenceableFailure
2235transform::PadOp::apply(transform::TransformRewriter &rewriter,
2236 transform::TransformResults &results,
2237 transform::TransformState &state) {
2238 auto transformOp = cast<TransformOpInterface>(getOperation());
2239 SmallVector<Operation *> paddedOps, padOps, copyBackOps;
2240
2241 for (Operation *target : state.getPayloadOps(getTarget())) {
2242 auto linalgTarget = dyn_cast<LinalgOp>(target);
2243 if (!linalgTarget) {
2244 auto diag = emitSilenceableError() << "expected LinalgOp target";
2245 diag.attachNote(target->getLoc()) << "target op";
2246 return diag;
2247 }
2248
2249 // Convert the integer packing flags to booleans.
2250 SmallVector<bool> nofoldFlags;
2251 for (int64_t packPadding :
2252 extractFromIntegerArrayAttr<int64_t>(getNofoldFlags()))
2253 nofoldFlags.push_back(static_cast<bool>(packPadding));
2254
2255 // Convert the padding values to attributes.
2256 SmallVector<Attribute> paddingValues;
2257 for (auto const &[untypedAttr, elementOrTensorType] :
2258 llvm::zip(getPaddingValues(), linalgTarget->getOperandTypes())) {
2259
2260 if (matchPattern(untypedAttr, ub::m_Poison())) {
2261 paddingValues.push_back(untypedAttr);
2262 continue;
2263 }
2264 auto attr = dyn_cast<TypedAttr>(untypedAttr);
2265 if (!attr) {
2266 emitOpError("expects padding values to be typed attributes or poison");
2268 }
2269 Type elementType = getElementTypeOrSelf(elementOrTensorType);
2270 // Try to parse string attributes to obtain an attribute of element type.
2271 if (auto stringAttr = dyn_cast<StringAttr>(attr)) {
2272 auto parsedAttr = dyn_cast_if_present<TypedAttr>(parseAttribute(
2273 stringAttr, getContext(), elementType,
2274 /*numRead=*/nullptr, /*isKnownNullTerminated=*/true));
2275 if (!parsedAttr || parsedAttr.getType() != elementType) {
2276 auto diag = this->emitOpError("expects a padding that parses to ")
2277 << elementType << ", got " << untypedAttr;
2278 diag.attachNote(linalgTarget.getLoc()) << "when applied to this op";
2280 }
2281 paddingValues.push_back(parsedAttr);
2282 continue;
2283 }
2284 // Otherwise, add the attribute directly.
2285 if (attr.getType() != elementType) {
2286 auto diag = this->emitOpError("expects a padding value of type ")
2287 << elementType << ", got " << attr;
2288 diag.attachNote(linalgTarget.getLoc()) << "when applied to this op";
2290 }
2291 paddingValues.push_back(attr);
2292 }
2293
2294 // Extract the transpose vectors.
2295 SmallVector<SmallVector<int64_t>> transposePaddings;
2296 for (Attribute transposeVector : cast<ArrayAttr>(getTransposePaddings()))
2297 transposePaddings.push_back(extractFromIntegerArrayAttr<int64_t>(
2298 cast<ArrayAttr>(transposeVector)));
2299
2300 LinalgOp paddedOp;
2301 LinalgPaddingOptions options;
2302 options.paddingDimensions =
2303 extractFromIntegerArrayAttr<int64_t>(getPaddingDimensions());
2304
2305 SmallVector<int64_t> padToMultipleOf;
2306 DiagnosedSilenceableFailure status = reifyMixedParamAndHandleResults(
2307 state, transformOp, getMixedPadToMultipleOf(), padToMultipleOf);
2308 if (!status.succeeded())
2309 return status;
2310 if (padToMultipleOf.empty())
2311 padToMultipleOf =
2312 SmallVector<int64_t>(options.paddingDimensions.size(), 1);
2313
2314 options.padToMultipleOf = std::move(padToMultipleOf);
2315 options.paddingValues = std::move(paddingValues);
2316 options.nofoldFlags = std::move(nofoldFlags);
2317 if (getCopyBackOp() ==
2318 bufferization::MaterializeInDestinationOp::getOperationName()) {
2319 options.copyBackOp = LinalgPaddingOptions::CopyBackOp::
2320 BufferizationMaterializeInDestination;
2321 } else if (getCopyBackOp() == linalg::CopyOp::getOperationName()) {
2322 options.copyBackOp = LinalgPaddingOptions::CopyBackOp::LinalgCopy;
2323 } else if (getCopyBackOp() == kCopyOpNone) {
2324 options.copyBackOp = LinalgPaddingOptions::CopyBackOp::None;
2325 } else {
2326 llvm_unreachable("unsupported copy_back op");
2327 }
2328 // Populate `sizeToPadTo` with the dynamic tensor sizes for each operand.
2329 bool irChanged = false;
2330 if (getUsePrescribedTensorShapes() &&
2331 linalgTarget.hasPureTensorSemantics()) {
2332 OpBuilder::InsertionGuard g(rewriter);
2333 rewriter.setInsertionPoint(linalgTarget);
2334 for (OpOperand &operand : linalgTarget->getOpOperands()) {
2335 for (auto [i, dim] : llvm::enumerate(linalgTarget.getShape(&operand))) {
2336 if (ShapedType::isStatic(dim))
2337 continue;
2338 options.setSizeToPadTo(operand.getOperandNumber(), i,
2339 tensor::getMixedSize(rewriter,
2340 operand.get().getLoc(),
2341 operand.get(), i));
2342 irChanged = true;
2343 }
2344 }
2345 }
2346
2347 SmallVector<Value> replacements;
2348 SmallVector<tensor::PadOp> newPadOps;
2349 if (failed(rewriteAsPaddedOp(rewriter, linalgTarget, options, paddedOp,
2350 replacements, newPadOps))) {
2351 if (irChanged) {
2352 auto diag = emitDefiniteFailure() << "failed to pad op";
2353 diag.attachNote(target->getLoc()) << "target op";
2354 return diag;
2355 }
2356 auto diag = emitSilenceableError() << "failed to pad op";
2357 diag.attachNote(target->getLoc()) << "target op";
2358 return diag;
2359 }
2360
2361 // We need to perform our own replacement here because this API is still
2362 // used in patterns that "pad and hoist", for which the replacement values
2363 // need to be different.
2364 // TODO: clean this up and stop "pad and hoist" behavior more globally now
2365 // that we have more composable abstractions.
2366 rewriter.replaceOp(linalgTarget, replacements);
2367 paddedOps.push_back(paddedOp);
2368 padOps.append(newPadOps.begin(), newPadOps.end());
2369 if (options.copyBackOp != LinalgPaddingOptions::CopyBackOp::None) {
2370 for (Value v : replacements) {
2371 Operation *copyBackOp = v.getDefiningOp();
2372 if (!llvm::is_contained(copyBackOps, copyBackOp))
2373 copyBackOps.push_back(copyBackOp);
2374 }
2375 }
2376 }
2377
2378 results.set(cast<OpResult>(getPadded()), paddedOps);
2379 results.set(cast<OpResult>(getPad()), padOps);
2380 results.set(cast<OpResult>(getCopy()), copyBackOps);
2382}
2383
2384LogicalResult transform::PadOp::verify() {
2385 SmallVector<int64_t> nofoldFlags =
2386 extractFromIntegerArrayAttr<int64_t>(getNofoldFlags());
2387 if (any_of(nofoldFlags, [](int64_t packPadding) {
2388 return packPadding != 0 && packPadding != 1;
2389 })) {
2390 return emitOpError()
2391 << "expects nofold_flags to contain booleans (0/1), found "
2392 << getNofoldFlags();
2393 }
2394
2395 SmallVector<int64_t> paddingDimensions =
2396 extractFromIntegerArrayAttr<int64_t>(getPaddingDimensions());
2397 if (any_of(paddingDimensions,
2398 [](int64_t paddingDimension) { return paddingDimension < 0; })) {
2399 return emitOpError() << "expects padding_dimensions to contain positive "
2400 "integers, found "
2401 << getPaddingDimensions();
2402 }
2403 if (!getMixedPadToMultipleOf().empty()) {
2404 if (getMixedPadToMultipleOf().size() != paddingDimensions.size()) {
2405 return emitOpError() << "expects as many multiples as padding_dimensions";
2406 }
2407 }
2408 ArrayAttr transposes = getTransposePaddings();
2409 for (Attribute attr : transposes) {
2410 SmallVector<int64_t> transpose = extractFromIntegerArrayAttr<int64_t>(attr);
2411 auto sequence = llvm::to_vector(llvm::seq<int64_t>(0, transpose.size()));
2412 if (!std::is_permutation(sequence.begin(), sequence.end(),
2413 transpose.begin(), transpose.end())) {
2414 return emitOpError()
2415 << "expects transpose_paddings to be a permutation, found "
2416 << attr;
2417 }
2418 }
2419 if (getCopyBackOp() !=
2420 bufferization::MaterializeInDestinationOp::getOperationName() &&
2421 getCopyBackOp() != linalg::CopyOp::getOperationName() &&
2422 getCopyBackOp() != kCopyOpNone)
2423 return emitOpError() << "invalid copy_back_op";
2424 return success();
2425}
2426
2427//===---------------------------------------------------------------------===//
2428// PadTilingInterfaceOp
2429//===---------------------------------------------------------------------===//
2430
2431void transform::PadTilingInterfaceOp::build(OpBuilder &b,
2432 OperationState &result,
2433 Value target,
2434 ArrayRef<int64_t> paddingSizes,
2435 bool padToMultipleOf) {
2436 auto resultType = transform::AnyOpType::get(b.getContext());
2437 return build(/*odsBuilder=*/b,
2438 /*result=*/result,
2439 /*types=*/TypeRange{resultType, resultType},
2440 /*target=*/target,
2441 /*padding_values=*/ArrayAttr(), // let inference handle this
2442 /*padding_sizes=*/ValueRange{},
2443 /*paddingSizes=*/
2444 (paddingSizes.empty() ? DenseI64ArrayAttr()
2445 : b.getDenseI64ArrayAttr(paddingSizes)),
2446 /*pad_to_multiple_of=*/
2447 padToMultipleOf ? b.getUnitAttr() : nullptr);
2448}
2449
2450void transform::PadTilingInterfaceOp::build(
2451 OpBuilder &b, OperationState &result, Value target,
2452 ArrayRef<OpFoldResult> mixedPaddingSizes, bool padToMultipleOf) {
2453 auto resultType = transform::AnyOpType::get(b.getContext());
2454 SmallVector<int64_t> staticPaddingSizes;
2455 SmallVector<Value> dynamicPaddingSizes;
2456 dispatchIndexOpFoldResults(mixedPaddingSizes, dynamicPaddingSizes,
2457 staticPaddingSizes);
2458 return build(/*odsBuilder=*/b,
2459 /*result=*/result,
2460 /*types=*/TypeRange{resultType, resultType},
2461 /*target=*/target,
2462 /*padding_values=*/ArrayAttr(), // let inference handle this
2463 /*padding_sizes=*/dynamicPaddingSizes,
2464 /*paddingSizes=*/staticPaddingSizes,
2465 /*usePrescribedTensorShapes=*/padToMultipleOf);
2466}
2467
2468void transform::PadTilingInterfaceOp::getEffects(
2469 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
2470 consumesHandle(getTargetMutable(), effects);
2471 onlyReadsHandle(getPaddingSizesMutable(), effects);
2472 producesHandle(getOperation()->getOpResults(), effects);
2473 modifiesPayload(effects);
2474}
2475
2476SmallVector<OpFoldResult>
2477transform::PadTilingInterfaceOp::getMixedPaddingSizes() {
2478 Builder b(getContext());
2479 return getMixedValues(getStaticPaddingSizes(), getPaddingSizes(), b);
2480}
2481
2482DiagnosedSilenceableFailure
2483transform::PadTilingInterfaceOp::apply(transform::TransformRewriter &rewriter,
2484 transform::TransformResults &results,
2485 transform::TransformState &state) {
2486 SmallVector<Operation *> paddedOps, padOps;
2487
2488 for (Operation *target : state.getPayloadOps(getTarget())) {
2489 auto targetOp = dyn_cast<TilingInterface>(target);
2490 if (!targetOp) {
2491 auto diag = emitSilenceableError() << "expected TilingInterface target";
2492 diag.attachNote(target->getLoc()) << "target op";
2493 return diag;
2494 }
2495
2496 // Only IndexingMapOpInterface ops for now, until TilingInterface exposes a
2497 // loopsToOperand map / C++ APIs to compute the effect of padding on
2498 // operands.
2499 if (!isa<IndexingMapOpInterface>(targetOp.getOperation())) {
2500 auto diag = emitSilenceableError() << "only IndexingMapOpInterface ops "
2501 "supported atm";
2502 diag.attachNote(target->getLoc()) << "target op";
2503 return diag;
2504 }
2505
2506 // Convert the padding values to attributes.
2507 SmallVector<Attribute> paddingValues;
2508 for (auto const &[untypedAttr, elementOrTensorType] :
2509 llvm::zip(getPaddingValues(), targetOp->getOperandTypes())) {
2510 auto attr = dyn_cast<TypedAttr>(untypedAttr);
2511 Type elementType = getElementTypeOrSelf(elementOrTensorType);
2512
2513 if (matchPattern(untypedAttr, ub::m_Poison())) {
2514 paddingValues.push_back(untypedAttr);
2515 continue;
2516 }
2517 if (!attr) {
2518 emitOpError("expects padding values to be typed attributes or poison");
2520 }
2521 // Try to parse string attributes to obtain an attribute of element type.
2522 if (auto stringAttr = dyn_cast<StringAttr>(attr)) {
2523 auto parsedAttr = dyn_cast_if_present<TypedAttr>(parseAttribute(
2524 stringAttr, getContext(), elementType,
2525 /*numRead=*/nullptr, /*isKnownNullTerminated=*/true));
2526 if (!parsedAttr || parsedAttr.getType() != elementType) {
2527 auto diag = this->emitOpError("expects a padding that parses to ")
2528 << elementType << ", got " << attr;
2529 diag.attachNote(targetOp.getLoc()) << "when applied to this op";
2531 }
2532 paddingValues.push_back(parsedAttr);
2533 continue;
2534 }
2535 // Otherwise, add the attribute directly.
2536 if (attr.getType() != elementType) {
2537 auto diag = this->emitOpError("expects a padding value of type ")
2538 << elementType << ", got " << attr;
2539 diag.attachNote(targetOp.getLoc()) << "when applied to this op";
2541 }
2542 paddingValues.push_back(attr);
2543 }
2544
2545 // Set options.
2546 PadTilingInterfaceOptions options;
2547 options.paddingValues = std::move(paddingValues);
2548 options.setPaddingSizes(getMixedPaddingSizes())
2549 .setPadToMultipleOf(getPadToMultipleOf());
2550
2551 OpBuilder::InsertionGuard g(rewriter);
2552 rewriter.setInsertionPointAfter(targetOp);
2553 auto maybePadOps = rewriteAsPaddedOp(
2554 rewriter, cast<TilingInterface>(targetOp.getOperation()),
2555 std::move(options));
2556 if (failed(maybePadOps)) {
2557 auto diag = emitSilenceableError() << "failed to pad op";
2558 diag.attachNote(target->getLoc()) << "target op";
2559 return diag;
2560 }
2561 const auto &[paddedOperands, paddedOp, slicedResults] = maybePadOps.value();
2562
2563 // Set transform results.
2564 paddedOps.push_back(paddedOp);
2565 padOps.append(paddedOperands.begin(), paddedOperands.end());
2566 rewriter.replaceOp(targetOp.getOperation(), slicedResults);
2567 }
2568
2569 results.set(cast<OpResult>(getPadded()), paddedOps);
2570 results.set(cast<OpResult>(getPad()), padOps);
2572}
2573
2574LogicalResult transform::PadTilingInterfaceOp::verify() { return success(); }
2575
2576//===---------------------------------------------------------------------===//
2577// HoistPadOp
2578//===---------------------------------------------------------------------===//
2579
2580DiagnosedSilenceableFailure transform::HoistPadBuildPackingLoopNestOp::apply(
2581 transform::TransformRewriter &rewriter,
2582 transform::TransformResults &transformResults,
2583 transform::TransformState &state) {
2584 auto targetOps = state.getPayloadOps(getTarget());
2585 auto loopOps = state.getPayloadOps(getLoop());
2586 if (!llvm::hasSingleElement(targetOps) || !llvm::hasSingleElement(loopOps)) {
2587 return emitDefiniteFailure()
2588 << "requires exactly one target and one loop handle (got "
2589 << llvm::range_size(targetOps) << " and "
2590 << llvm::range_size(loopOps) << ")";
2591 }
2592
2593 auto padOp = dyn_cast_or_null<tensor::PadOp>(*targetOps.begin());
2594 auto loopOp = dyn_cast_or_null<scf::ForOp>(*loopOps.begin());
2595 if (!padOp || !loopOp)
2596 return emitDefiniteFailure() << "requires exactly 2 non-null handles";
2597
2598 FailureOr<linalg::detail::PackingResult> result =
2599 linalg::detail::buildPackingLoopNest(rewriter, padOp, loopOp,
2600 getTranspose());
2601 if (failed(result))
2602 return emitDefiniteFailure() << "could not build packing loop nest";
2603
2604 if (result->clonedLoopIvs.empty()) {
2605 transformResults.set(cast<OpResult>(getPackingLoop()),
2606 {result->hoistedPadOp.getOperation()});
2608 }
2609 auto outerPackedLoop =
2610 scf::getForInductionVarOwner(result->clonedLoopIvs.front());
2611 transformResults.set(cast<OpResult>(getPackingLoop()),
2612 {outerPackedLoop.getOperation()});
2614}
2615
2616LogicalResult transform::HoistPadBuildPackingLoopNestOp::verify() {
2617 ArrayRef<int64_t> transpose = getTranspose();
2618 auto sequence = llvm::to_vector(llvm::seq<int64_t>(0, transpose.size()));
2619 if (!std::is_permutation(sequence.begin(), sequence.end(), transpose.begin(),
2620 transpose.end())) {
2621 return emitOpError() << "expects transpose to be a permutation, found "
2622 << getTranspose();
2623 }
2624 return success();
2625}
2626
2627void transform::HoistPadBuildPackingLoopNestOp::getEffects(
2628 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
2629 transform::onlyReadsHandle(getTargetMutable(), effects);
2630 transform::onlyReadsHandle(getLoopMutable(), effects);
2631 transform::producesHandle(getOperation()->getOpResults(), effects);
2633}
2634
2635DiagnosedSilenceableFailure
2636transform::HoistPadOp::applyToOne(transform::TransformRewriter &rewriter,
2637 tensor::PadOp target,
2638 transform::ApplyToEachResultList &results,
2639 transform::TransformState &state) {
2640 tensor::PadOp hoistedPadOp;
2641 SmallVector<TransposeOp> transposeOps;
2642 FailureOr<Value> result =
2643 hoistPaddingOnTensors(rewriter, target, getNumLoops(), getTranspose(),
2644 hoistedPadOp, transposeOps);
2645 if (succeeded(result)) {
2646 // We need to perform our own replacement here because this API is still
2647 // used in patterns that "pad and hoist", for which the replacement values
2648 // need to be different.
2649 // TODO: clean this up and stop "pad and hoist" behavior more globally now
2650 // that we have more composable abstractions.
2651 rewriter.replaceOp(target, *result);
2652 results.push_back(hoistedPadOp);
2654 }
2655 return emitDefaultSilenceableFailure(target);
2656}
2657
2658LogicalResult transform::HoistPadOp::verify() {
2659 ArrayRef<int64_t> transpose = getTranspose();
2660 auto sequence = llvm::to_vector(llvm::seq<int64_t>(0, transpose.size()));
2661 if (!std::is_permutation(sequence.begin(), sequence.end(), transpose.begin(),
2662 transpose.end())) {
2663 return emitOpError() << "expects transpose to be a permutation, found "
2664 << getTranspose();
2665 }
2666 return success();
2667}
2668
2669//===----------------------------------------------------------------------===//
2670// PromoteOp
2671//===----------------------------------------------------------------------===//
2672
2673DiagnosedSilenceableFailure
2674transform::PromoteOp::applyToOne(transform::TransformRewriter &rewriter,
2675 LinalgOp target,
2676 transform::ApplyToEachResultList &results,
2677 transform::TransformState &state) {
2678 LinalgPromotionOptions promotionOptions;
2679 if (!getOperandsToPromote().empty())
2680 promotionOptions = promotionOptions.setOperandsToPromote(
2681 extractFromIntegerArrayAttr<int64_t>(getOperandsToPromote()));
2682 if (getUseFullTilesByDefault())
2683 promotionOptions = promotionOptions.setUseFullTileBuffersByDefault(
2684 getUseFullTilesByDefault());
2685 if (getUseOriginalSubviewSize())
2686 promotionOptions =
2687 promotionOptions.setUseOriginalSubviewSize(getUseOriginalSubviewSize());
2688 if (getUseAlloca())
2689 promotionOptions = promotionOptions.setUseAlloca(getUseAlloca());
2690 if (!getUseFullTileBuffers().empty())
2691 promotionOptions = promotionOptions.setUseFullTileBuffers(
2692 llvm::to_vector(getUseFullTileBuffers().getAsValueRange<BoolAttr>()));
2693 if (getAlignment().has_value())
2694 promotionOptions = promotionOptions.setAlignment(*getAlignment());
2695 if (getMemorySpace().has_value())
2696 promotionOptions = promotionOptions.setMemorySpace(*getMemorySpace());
2697
2698 if (getMapping().has_value()) {
2699 // The mapping should only contain an element
2700 auto mapping = *getMapping();
2701 if (mapping.size() > 1)
2702 return emitDefaultDefiniteFailure(target);
2703
2704 auto addressSpace = cast<mlir::gpu::GPUMemorySpaceMappingAttr>(mapping[0]);
2705
2706 if (addressSpace.getAddressSpace() ==
2707 mlir::gpu::GPUDialect::getWorkgroupAddressSpace()) {
2708 promotionOptions =
2709 promotionOptions
2713 .setUseFullTileBuffers({false, false});
2714 } else if (addressSpace.getAddressSpace() ==
2715 mlir::gpu::GPUDialect::getPrivateAddressSpace()) {
2716 promotionOptions =
2717 promotionOptions
2721 .setUseFullTileBuffers({false, false});
2722 } else {
2723 return emitDefaultDefiniteFailure(target);
2724 }
2725 }
2726
2727 if (failed(promoteSubviewsPrecondition(target, promotionOptions)))
2728 return emitDefaultDefiniteFailure(target);
2729
2730 rewriter.setInsertionPoint(target);
2731 FailureOr<LinalgOp> res = promoteSubViews(rewriter, target, promotionOptions);
2732 if (failed(res))
2733 return emitDefaultDefiniteFailure(target);
2734 results.push_back(target);
2736}
2737
2738//===----------------------------------------------------------------------===//
2739// ReplaceOp
2740//===----------------------------------------------------------------------===//
2741
2742DiagnosedSilenceableFailure
2743transform::ReplaceOp::apply(transform::TransformRewriter &rewriter,
2744 TransformResults &transformResults,
2745 TransformState &state) {
2746 auto payload = state.getPayloadOps(getTarget());
2747
2748 // Check for invalid targets.
2749 for (Operation *target : payload) {
2750 if (target->getNumOperands() > 0)
2751 return emitDefiniteFailure() << "expected target without operands";
2752 if (!target->hasTrait<OpTrait::IsIsolatedFromAbove>() &&
2753 target->getNumRegions() > 0)
2754 return emitDefiniteFailure()
2755 << "expected target that is isolated from above";
2756 }
2757
2758 // Clone and replace.
2759 Operation *pattern = &getBodyRegion().front().front();
2760 SmallVector<Operation *> replacements;
2761 for (Operation *target : payload) {
2762 if (getOperation()->isAncestor(target))
2763 continue;
2764 rewriter.setInsertionPoint(target);
2765 Operation *replacement = rewriter.clone(*pattern);
2766 rewriter.replaceOp(target, replacement->getResults());
2767 replacements.push_back(replacement);
2768 }
2769 transformResults.set(cast<OpResult>(getReplacement()), replacements);
2771}
2772
2773void transform::ReplaceOp::getEffects(
2774 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
2775 consumesHandle(getTargetMutable(), effects);
2776 producesHandle(getOperation()->getOpResults(), effects);
2777 modifiesPayload(effects);
2778}
2779
2780LogicalResult transform::ReplaceOp::verify() {
2781 if (!getBodyRegion().hasOneBlock())
2782 return emitOpError() << "expected one block";
2783 if (std::distance(getBodyRegion().front().begin(),
2784 getBodyRegion().front().end()) != 1)
2785 return emitOpError() << "expected one operation in block";
2786 Operation *replacement = &getBodyRegion().front().front();
2787 if (replacement->getNumOperands() > 0)
2788 return replacement->emitOpError()
2789 << "expected replacement without operands";
2790 if (!replacement->hasTrait<OpTrait::IsIsolatedFromAbove>() &&
2791 replacement->getNumRegions() > 0)
2792 return replacement->emitOpError()
2793 << "expect op that is isolated from above";
2794 return success();
2795}
2796
2797//===----------------------------------------------------------------------===//
2798// ScalarizeOp
2799//===----------------------------------------------------------------------===//
2800
2801DiagnosedSilenceableFailure
2802transform::ScalarizeOp::applyToOne(transform::TransformRewriter &rewriter,
2803 LinalgOp target,
2804 transform::ApplyToEachResultList &results,
2805 transform::TransformState &state) {
2806 scf::SCFTilingOptions tilingOptions;
2807 tilingOptions.setTileSizeComputationFunction([&](OpBuilder &b, Operation *) {
2808 SmallVector<OpFoldResult> tileSizes;
2809 Location loc = target.getLoc();
2810 SmallVector<OpFoldResult> allShapeSizes =
2811 target.createFlatListOfOperandDims(b, loc);
2812 AffineMap map = target.getShapesToLoopsMap();
2813 if (!map)
2814 return tileSizes;
2815 SmallVector<OpFoldResult> shapeSizes =
2817 allShapeSizes);
2818 // If the shape size is dynamic, tile by 1.
2819 // Otherwise, do not tile (i.e. tile size 0).
2820 for (OpFoldResult shapeSize : shapeSizes) {
2821 tileSizes.push_back(getConstantIntValue(shapeSize) ? b.getIndexAttr(0)
2822 : b.getIndexAttr(1));
2823 }
2824 return tileSizes;
2825 });
2826 rewriter.setInsertionPoint(target);
2827 FailureOr<scf::SCFTilingResult> maybeTilingResult = tileUsingSCF(
2828 rewriter, cast<TilingInterface>(target.getOperation()), tilingOptions);
2829 if (failed(maybeTilingResult))
2830 return emitDefaultDefiniteFailure(target);
2831
2832 if (target->getNumResults())
2833 rewriter.replaceOp(target, maybeTilingResult->replacements);
2834 else
2835 rewriter.eraseOp(target);
2836
2837 results.reserve(maybeTilingResult->tiledOps.size());
2838 for (Operation *tiled : maybeTilingResult->tiledOps)
2839 results.push_back(tiled);
2841}
2842
2843//===----------------------------------------------------------------------===//
2844// ConvertToLoopsOp
2845//===----------------------------------------------------------------------===//
2846
2847DiagnosedSilenceableFailure
2848transform::ConvertToLoopsOp::apply(transform::TransformRewriter &rewriter,
2849 transform::TransformResults &results,
2850 transform::TransformState &state) {
2851 SmallVector<Operation *> loops;
2852 for (Operation *target : state.getPayloadOps(getTarget())) {
2853 auto tilingOp = dyn_cast<TilingInterface>(*target);
2854 if (!tilingOp) {
2855 DiagnosedSilenceableFailure diag =
2856 emitSilenceableError()
2857 << "expected the payload to implement TilingInterface";
2858 diag.attachNote(target->getLoc()) << "payload op";
2859 return diag;
2860 }
2861 rewriter.setInsertionPoint(target);
2862 FailureOr<SmallVector<scf::ForOp>> generatedLoops =
2863 scf::lowerToLoopsUsingSCFForOp(rewriter, tilingOp);
2864 if (failed(generatedLoops))
2865 return emitDefaultDefiniteFailure(target);
2866 for (scf::ForOp &loop : *generatedLoops) {
2867 loops.push_back(loop.getOperation());
2868 }
2869 rewriter.eraseOp(target);
2870 }
2871 results.set(cast<OpResult>(getResult()), loops);
2873}
2874
2875//===----------------------------------------------------------------------===//
2876// RewriteInDestinationPassingStyleOp
2877//===----------------------------------------------------------------------===//
2878
2879DiagnosedSilenceableFailure
2880transform::RewriteInDestinationPassingStyleOp::applyToOne(
2881 transform::TransformRewriter &rewriter, Operation *target,
2882 transform::ApplyToEachResultList &results,
2883 transform::TransformState &state) {
2884 rewriter.setInsertionPoint(target);
2885 FailureOr<Operation *> maybeResult =
2887 .Case<DestinationStyleOpInterface>([](auto op) { return op; })
2888 .Case<tensor::FromElementsOp, tensor::GenerateOp, tensor::PadOp>(
2889 [&rewriter](auto op) {
2890 return rewriteInDestinationPassingStyle(rewriter, op);
2891 });
2892 if (failed(maybeResult))
2893 return emitDefaultSilenceableFailure(target);
2894 results.push_back(*maybeResult);
2896}
2897
2898//===----------------------------------------------------------------------===//
2899// SplitOp
2900//===----------------------------------------------------------------------===//
2901
2902DiagnosedSilenceableFailure
2903SplitOp::apply(transform::TransformRewriter &rewriter,
2904 TransformResults &results, TransformState &state) {
2905 // Collect the dynamic split points if provided.
2906 SmallVector<Operation *> payload =
2907 llvm::to_vector(state.getPayloadOps(getTarget()));
2908
2909 bool isMultiwaySplit = getMultiway();
2910
2911 if (isMultiwaySplit && !llvm::hasSingleElement(payload)) {
2912 return mlir::emitSilenceableFailure(getLoc())
2913 << "requires exactly one target when "
2914 "multiway split is enabled (got "
2915 << llvm::range_size(payload) << ")";
2916 }
2917
2918 SmallVector<OpFoldResult> chunkSizes;
2919
2920 if (!isMultiwaySplit)
2921 chunkSizes.reserve(payload.size());
2922
2923 if (getDynamicChunkSizes()) {
2925 if (isa<TransformHandleTypeInterface>(getDynamicChunkSizes().getType())) {
2926 chunkSizes = llvm::map_to_vector(
2927 state.getPayloadOps(getDynamicChunkSizes()), [&](Operation *op) {
2928 if (op->getNumResults() != 1 ||
2929 !op->getResult(0).getType().isIndex()) {
2930 diag = emitSilenceableError()
2931 << "expected dynamic split point handle to point to a "
2932 "single-result index-typed op";
2933 diag.attachNote(op->getLoc()) << "dynamic split point";
2934 }
2935 return OpFoldResult(op->getResult(0));
2936 });
2937 } else {
2938 chunkSizes = llvm::map_to_vector(
2939 state.getParams(getDynamicChunkSizes()),
2940 [](Attribute attr) { return OpFoldResult(attr); });
2941 }
2942 if (diag.isSilenceableFailure())
2943 return diag;
2944
2945 // For multiway split, a single payload is expected to have multiple
2946 // split points.
2947 if (!isMultiwaySplit && chunkSizes.size() != payload.size()) {
2948 return emitDefiniteFailure()
2949 << "expected the dynamic split point handle to point to as "
2950 "many operations ("
2951 << chunkSizes.size() << ") as the target handle ("
2952 << payload.size() << ")";
2953 }
2954 } else {
2955 chunkSizes.resize(payload.size(),
2956 rewriter.getIndexAttr(getStaticChunkSizes()));
2957 }
2958
2959 auto checkStructuredOpAndDimensions =
2960 [&](LinalgOp linalgOp, Location loc) -> DiagnosedSilenceableFailure {
2961 if (!linalgOp) {
2962 auto diag = emitSilenceableError() << "only applies to structured ops";
2963 diag.attachNote(loc) << "target op";
2964 return diag;
2965 }
2966
2967 if (getDimension() >= linalgOp.getNumLoops()) {
2968 auto diag = emitSilenceableError() << "dimension " << getDimension()
2969 << " does not exist in target op";
2970 diag.attachNote(loc) << "target op";
2971 return diag;
2972 }
2974 };
2975
2976 auto checkFailureInSplitting =
2977 [&](bool hasFailed, Location loc) -> DiagnosedSilenceableFailure {
2978 if (hasFailed) {
2979 auto diag = emitDefiniteFailure() << "internal failure in splitting";
2980 diag.attachNote(loc) << "target op";
2981 return diag;
2982 }
2984 };
2985
2986 SmallVector<Operation *> opList;
2987 if (isMultiwaySplit) {
2988
2989 // Split a single target operation at multiple points.
2990 TilingInterface head, tail;
2991 Operation *target = payload.front();
2992
2993 LinalgOp linalgOp = dyn_cast<LinalgOp>(target);
2994
2995 // Check that the target is a valid LinalgOp with correct dimensions.
2996 DiagnosedSilenceableFailure diag =
2997 checkStructuredOpAndDimensions(linalgOp, target->getLoc());
2998 if (diag.isSilenceableFailure())
2999 return diag;
3000
3001 for (auto &&[idx, chunkSize] : llvm::enumerate(chunkSizes)) {
3002
3003 if (idx > 0)
3004 target = tail.getOperation();
3005
3006 if (!target)
3007 break;
3008
3009 linalgOp = cast<LinalgOp>(target);
3010 Location loc = target->getLoc();
3011
3012 rewriter.setInsertionPoint(linalgOp);
3013 std::tie(head, tail) = linalg::splitOp(
3014 rewriter, cast<TilingInterface>(linalgOp.getOperation()),
3015 getDimension(), chunkSize);
3016
3017 // Propagate errors.
3018 DiagnosedSilenceableFailure diag =
3019 checkFailureInSplitting(!head && !tail, loc);
3020 if (diag.isDefiniteFailure())
3021 return diag;
3022
3023 opList.push_back(head.getOperation());
3024 }
3025
3026 // Append any leftover parts to the end of the result list.
3027 if (tail)
3028 opList.push_back(tail.getOperation());
3029
3030 } else {
3031 // Split each target operation.
3032 SmallVector<Operation *> first, second;
3033 Operation *noSecondPart = nullptr;
3034 for (const auto &pair : llvm::zip(payload, chunkSizes)) {
3035 Operation *target = std::get<0>(pair);
3036 Location loc = target->getLoc();
3037 LinalgOp linalgOp = dyn_cast<LinalgOp>(target);
3038 DiagnosedSilenceableFailure diag =
3039 checkStructuredOpAndDimensions(linalgOp, target->getLoc());
3040
3041 if (diag.isSilenceableFailure())
3042 return diag;
3043
3044 rewriter.setInsertionPoint(linalgOp);
3045 std::tie(first.emplace_back(), second.emplace_back()) = linalg::splitOp(
3046 rewriter, cast<TilingInterface>(linalgOp.getOperation()),
3047 getDimension(), std::get<1>(pair));
3048
3049 // Propagate errors.
3050 DiagnosedSilenceableFailure diagSplit =
3051 checkFailureInSplitting(!first.back() && !second.back(), loc);
3052 if (diagSplit.isDefiniteFailure())
3053 return diag;
3054
3055 // Do not add null second parts.
3056 if (!second.back()) {
3057 noSecondPart = target;
3058 second.pop_back();
3059 }
3060 }
3061
3062 if (second.size() != first.size() && !second.empty()) {
3063 auto diag = emitSilenceableError()
3064 << "splitting does not produce the second part for a subset "
3065 "of targets";
3066 diag.attachNote()
3067 << "expected splitting to produce the second part of all "
3068 "or none of the targets";
3069 diag.attachNote(noSecondPart->getLoc())
3070 << "first target with no second part";
3071 return diag;
3072 }
3073
3074 opList.append(first);
3075 if (!second.empty())
3076 opList.append(second);
3077 }
3078 results.set(cast<OpResult>(getSplitList()), opList);
3080}
3081
3082void SplitOp::getEffects(
3083 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
3084 consumesHandle(getTargetMutable(), effects);
3085 if (getDynamicChunkSizes())
3086 onlyReadsHandle(getDynamicChunkSizesMutable(), effects);
3087 producesHandle(getOperation()->getOpResults(), effects);
3088 modifiesPayload(effects);
3089}
3090
3091ParseResult SplitOp::parse(OpAsmParser &parser, OperationState &result) {
3092 OpAsmParser::UnresolvedOperand target, dynamicChunkSizes;
3093 IntegerAttr staticChunkSizes;
3094 if (parser.parseOperand(target) || parser.parseKeyword("after"))
3095 return failure();
3096
3097 OptionalParseResult dynamicPointParseResult =
3098 parser.parseOptionalOperand(dynamicChunkSizes);
3099 if (!dynamicPointParseResult.has_value()) {
3100 int64_t staticChunkSizesValue;
3101 if (failed(parser.parseInteger(staticChunkSizesValue)))
3102 return failure();
3103
3104 staticChunkSizes =
3105 parser.getBuilder().getI64IntegerAttr(staticChunkSizesValue);
3106 }
3107
3108 Type targetType;
3109 if (parser.parseOptionalAttrDict(result.attributes) ||
3110 parser.parseColonType(targetType) ||
3111 parser.resolveOperand(target, targetType, result.operands)) {
3112 return failure();
3113 }
3114 if (dynamicPointParseResult.has_value()) {
3115 Type chunkSizesType;
3116 if (failed(*dynamicPointParseResult) || parser.parseComma() ||
3117 parser.parseType(chunkSizesType) ||
3118 parser.resolveOperand(dynamicChunkSizes, chunkSizesType,
3119 result.operands)) {
3120 return failure();
3121 }
3122
3123 staticChunkSizes =
3124 parser.getBuilder().getI64IntegerAttr(ShapedType::kDynamic);
3125 }
3126
3127 result.addAttribute(
3128 SplitOp::getStaticChunkSizesAttrName(result.name).getValue(),
3129 staticChunkSizes);
3130 result.addTypes(targetType);
3131 return success();
3132}
3133
3134void SplitOp::print(OpAsmPrinter &printer) {
3135 printer << " " << getTarget() << " after ";
3136 int64_t staticChunkSize = static_cast<int64_t>(getStaticChunkSizes());
3137 if (staticChunkSize != ShapedType::kDynamic)
3138 printer << staticChunkSize;
3139 else
3140 printer << getDynamicChunkSizes();
3141 printer << " ";
3142 NamedAttrList attrs(getOperation()->getDiscardableAttrDictionary());
3143 attrs.append(getDimensionAttrName(), getDimensionAttr());
3144 if (UnitAttr multiway = getMultiwayAttr())
3145 attrs.append(getMultiwayAttrName(), multiway);
3146 printer.printOptionalAttrDict(attrs, {getStaticChunkSizesAttrName()});
3147 printer << " : " << getTarget().getType();
3148 if (staticChunkSize == ShapedType::kDynamic)
3149 printer << ", " << getDynamicChunkSizes().getType();
3150}
3151
3152LogicalResult SplitOp::verify() {
3153 if ((static_cast<int64_t>(getStaticChunkSizes()) != ShapedType::kDynamic) ^
3154 (getDynamicChunkSizes() == nullptr)) {
3155 return emitOpError() << "expects either a dynamic or a static split "
3156 "point to be provided";
3157 }
3158 return success();
3159}
3160
3161//===----------------------------------------------------------------------===//
3162// SplitReductionOp
3163//===----------------------------------------------------------------------===//
3164
3165void transform::SplitReductionOp::build(
3166 OpBuilder &builder, OperationState &result, Value target,
3167 int64_t splitFactor, int64_t insertSplitDimension, bool innerParallel,
3168 bool useScalingAlgorithm, bool useAlloc) {
3169 MLIRContext *ctx = builder.getContext();
3170 result.addOperands(target);
3171 result.addAttribute(SplitReductionOp::getSplitFactorAttrName(result.name),
3172 builder.getI64IntegerAttr(splitFactor));
3173 result.addAttribute(
3174 SplitReductionOp::getInsertSplitDimensionAttrName(result.name),
3175 builder.getI64IntegerAttr(insertSplitDimension));
3176 if (innerParallel) {
3177 result.addAttribute(SplitReductionOp::getInnerParallelAttrName(result.name),
3178 builder.getUnitAttr());
3179 }
3180 if (useScalingAlgorithm) {
3181 result.addAttribute(
3182 SplitReductionOp::getUseScalingAlgorithmAttrName(result.name),
3183 builder.getUnitAttr());
3184 }
3185 if (useAlloc) {
3186 result.addAttribute(SplitReductionOp::getUseAllocAttrName(result.name),
3187 builder.getUnitAttr());
3188 }
3189 auto resultType = transform::AnyOpType::get(ctx);
3190 result.addTypes({resultType, resultType, resultType, resultType});
3191}
3192
3193DiagnosedSilenceableFailure transform::SplitReductionOp::applyToOne(
3194 transform::TransformRewriter &rewriter, LinalgOp target,
3195 transform::ApplyToEachResultList &results,
3196 transform::TransformState &state) {
3197 ControlSplitReductionFn splitFn = [&](LinalgOp) {
3198 return linalg::SplitReductionOptions{int64_t(getSplitFactor()),
3199 unsigned(getInsertSplitDimension()),
3200 bool(getInnerParallel())};
3201 };
3202 rewriter.setInsertionPoint(target);
3203 FailureOr<SplitReductionResult> splitResult =
3204 (getUseScalingAlgorithm())
3205 ? splitReductionByScaling(rewriter, target, splitFn, getUseAlloc())
3206 : splitReduction(rewriter, target, splitFn, getUseAlloc());
3207 if (failed(splitResult))
3208 return emitDefaultDefiniteFailure(target);
3209
3210 results.push_back(splitResult->initOrAlloc);
3211 results.push_back(splitResult->fillOp);
3212 results.push_back(splitResult->splitLinalgOp);
3213 results.push_back(splitResult->resultCombiningLinalgOp);
3215}
3216
3217//===----------------------------------------------------------------------===//
3218// TileReductionUsingForOp
3219//===----------------------------------------------------------------------===//
3220
3221void transform::TileReductionUsingForOp::build(
3222 OpBuilder &builder, OperationState &result, Value target,
3223 ArrayRef<int64_t> staticTileSizes) {
3224 // Call the default builder.
3225 // This is future-proof re mixed static-dynamic and setting up the proper
3226 // operands segment sizes attributes for multiple variadic operands.
3227 // In the absence of this, horrible bugs ensue.
3228 // TODO: support mixed static-dynamic (see TileUsingForallOp).
3229 MLIRContext *ctx = builder.getContext();
3230 auto opTy = transform::AnyOpType::get(ctx);
3231 auto staticTileSizesAttr = builder.getI64ArrayAttr(staticTileSizes);
3232 build(builder, result,
3233 /*resultTypes=*/TypeRange{opTy, opTy, opTy, opTy},
3234 /*target=*/target,
3235 /*reduction_dims=*/nullptr,
3236 /*tile_sizes=*/staticTileSizesAttr);
3237}
3238
3239DiagnosedSilenceableFailure transform::TileReductionUsingForOp::applyToOne(
3240 transform::TransformRewriter &rewriter, Operation *target,
3241 transform::ApplyToEachResultList &results,
3242 transform::TransformState &state) {
3243 rewriter.setInsertionPoint(target);
3244
3245 auto partialReductionOp = dyn_cast<PartialReductionOpInterface>(target);
3246 if (!partialReductionOp) {
3248 target->getLoc(),
3249 "Operation should implement PartialReductionOpInterface");
3250 }
3251
3252 SmallVector<unsigned> reductionDims =
3253 extractFromIntegerArrayAttr<unsigned>(getReductionDims());
3254 if (reductionDims.empty()) {
3255 for (auto [idx, iteratorType] :
3256 llvm::enumerate(partialReductionOp.getLoopIteratorTypes())) {
3257 if (iteratorType == utils::IteratorType::reduction)
3258 reductionDims.push_back(idx);
3259 }
3260 }
3261
3262 scf::SCFTilingOptions options;
3263 options.setLoopType(scf::SCFTilingOptions::LoopType::ForOp);
3264 options.setReductionTilingStrategy(
3266 options.setTileSizes(getAsOpFoldResult(getTileSizesAttr()));
3267 options.setReductionDims(reductionDims);
3268 FailureOr<scf::SCFTilingResult> result =
3269 scf::tileUsingSCF(rewriter, partialReductionOp, options);
3270
3271 if (failed(result)) {
3272 return emitSilenceableFailure(getLoc(),
3273 "failed to tile using partial reduction");
3274 }
3275 rewriter.replaceOp(target, result->replacements);
3276 for (Value initValue : result->initialValues)
3277 results.push_back(initValue.getDefiningOp());
3278 for (auto *parallelTiledOp : result->tiledOps)
3279 results.push_back(parallelTiledOp);
3280 for (auto *mergeOp : result->mergeOps)
3281 results.push_back(mergeOp);
3282 results.push_back(result->loops.front());
3284}
3285
3286//===----------------------------------------------------------------------===//
3287// TileReductionUsingForallOp
3288//===----------------------------------------------------------------------===//
3289
3290void transform::TileReductionUsingForallOp::build(
3291 OpBuilder &builder, OperationState &result, Value target,
3292 ArrayRef<int64_t> staticNumThreads, ArrayRef<int64_t> staticTileSizes,
3293 ArrayAttr mapping) {
3294 // Call the default builder.
3295 // This is future-proof re mixed static-dynamic and setting up the proper
3296 // operands segment sizes attributes for multiple variadic operands.
3297 // In the absence of this, horrible bugs ensue.
3298 // TODO: support mixed static-dynamic (see TileUsingForallOp).
3299 MLIRContext *ctx = builder.getContext();
3300 auto opTy = transform::AnyOpType::get(ctx);
3301 auto staticNumThreadsAttr = builder.getDenseI64ArrayAttr(staticNumThreads);
3302 auto staticTileSizesAttr = builder.getDenseI64ArrayAttr(staticTileSizes);
3303 build(builder, result,
3304 /*resultTypes=*/TypeRange{opTy, opTy, opTy, opTy},
3305 /*target=*/target,
3306 /*reduction_dims=*/{},
3307 /*num_threads=*/staticNumThreadsAttr,
3308 /*tile_sizes=*/staticTileSizesAttr,
3309 /*mapping=*/mapping);
3310}
3311
3312DiagnosedSilenceableFailure transform::TileReductionUsingForallOp::applyToOne(
3313 transform::TransformRewriter &rewriter, Operation *target,
3314 transform::ApplyToEachResultList &results,
3315 transform::TransformState &state) {
3316 rewriter.setInsertionPoint(target);
3317
3318 auto partialReductionOp = dyn_cast<PartialReductionOpInterface>(target);
3319 if (!partialReductionOp) {
3321 target->getLoc(),
3322 "Operation should implement PartialReductionOpInterface");
3323 }
3324 SmallVector<OpFoldResult> numThreads =
3325 getAsOpFoldResult(rewriter.getI64ArrayAttr(getNumThreads()));
3326 SmallVector<OpFoldResult> tileSizes =
3328
3329 scf::SCFTilingOptions options;
3330 options.setLoopType(scf::SCFTilingOptions::LoopType::ForallOp);
3331 options.setReductionTilingStrategy(
3333 if (!getNumThreads().empty()) {
3334 options.setNumThreads(numThreads);
3335 } else {
3336 options.setTileSizes(tileSizes);
3337 }
3338 if (auto mapping = getMapping()) {
3339 options.setMapping(mapping.value().getValue());
3340 }
3341 SmallVector<unsigned> reductionDims =
3342 extractFromIntegerArrayAttr<unsigned>(getReductionDims());
3343 if (reductionDims.empty()) {
3344 for (auto [idx, iteratorType] :
3345 llvm::enumerate(partialReductionOp.getLoopIteratorTypes())) {
3346 if (iteratorType == utils::IteratorType::reduction)
3347 reductionDims.push_back(idx);
3348 }
3349 }
3350 options.setReductionDims(reductionDims);
3351 FailureOr<scf::SCFTilingResult> result =
3352 scf::tileUsingSCF(rewriter, partialReductionOp, options);
3353
3354 if (failed(result)) {
3355 auto diag = emitSilenceableError() << "could not tile reduction";
3356 return diag;
3357 }
3358 rewriter.replaceOp(target, result->replacements);
3359
3360 for (Value initValue : result->initialValues)
3361 results.push_back(initValue.getDefiningOp());
3362 for (auto *parallelTiledOp : result->tiledOps)
3363 results.push_back(parallelTiledOp);
3364 for (auto *mergeOp : result->mergeOps)
3365 results.push_back(mergeOp);
3366 results.push_back(result->loops.front());
3368}
3369
3370//===----------------------------------------------------------------------===//
3371// ContinuousTileSizesOp
3372//===----------------------------------------------------------------------===//
3373
3374DiagnosedSilenceableFailure
3375transform::ContinuousTileSizesOp::apply(transform::TransformRewriter &rewriter,
3376 TransformResults &transformResults,
3377 TransformState &state) {
3378
3379 SmallVector<Operation *> targetOps =
3380 llvm::to_vector(state.getPayloadOps(getTarget()));
3381
3382 if (!llvm::hasSingleElement(targetOps)) {
3383 return mlir::emitSilenceableFailure(getLoc())
3384 << "requires exactly one target (got " << llvm::range_size(targetOps)
3385 << ")";
3386 }
3387
3388 Operation *target = *targetOps.begin();
3389 auto linalgOp = dyn_cast<LinalgOp>(target);
3390 auto tileableOp = dyn_cast<TilingInterface>(target);
3391
3392 if (!linalgOp)
3393 return emitDefiniteFailure() << "expected Linalg Op";
3394
3395 OpBuilder builder(linalgOp.getContext());
3396
3397 if (isa<TransformParamTypeInterface>(getChunkSizes().getType())) {
3398 if (linalgOp.hasDynamicShape()) {
3399 auto diag = emitSilenceableError()
3400 << "cannot compute parametric tile sizes for dynamically "
3401 "shaped payload op";
3402 diag.attachNote(linalgOp->getLoc()) << "payload op";
3403 return diag;
3404 }
3405
3406 FailureOr<StaticContinuousTileSizeSpecification> spec =
3407 computeStaticContinuousTileSizes(linalgOp, getDimension(),
3408 getTargetSize());
3409 if (failed(spec)) {
3410 return emitSilenceableError()
3411 << "failed to compute multi-size tiling sizes";
3412 }
3413
3414 SmallVector<int64_t> chunkSizes;
3415
3416 for (auto &&[tileSize, tripCount] :
3417 llvm::zip_equal(spec->tileSizes, spec->tripCounts))
3418 chunkSizes.push_back(tileSize * tripCount);
3419
3420 auto getI64AttrsFromI64 = [&](ArrayRef<int64_t> values) {
3421 return llvm::map_to_vector(values, [&](int64_t value) -> Attribute {
3422 return builder.getI64IntegerAttr(value);
3423 });
3424 };
3425 transformResults.setParams(cast<OpResult>(getTileSizes()),
3426 getI64AttrsFromI64(spec->tileSizes));
3427 transformResults.setParams(cast<OpResult>(getChunkSizes()),
3428 getI64AttrsFromI64(chunkSizes));
3429
3431 }
3432
3433 builder.setInsertionPoint(linalgOp);
3434
3435 OpFoldResult targetSize = builder.getIndexAttr(getTargetSize());
3436 unsigned dimension = getDimension();
3437
3438 FailureOr<ContinuousTileSizeSpecification> spec = computeContinuousTileSizes(
3439 builder, tileableOp, dimension, targetSize, true);
3440 if (failed(spec)) {
3441 return emitSilenceableError() << "could not generate tile size computation";
3442 }
3443
3444 AffineExpr s0 = builder.getAffineSymbolExpr(0);
3445 AffineExpr s1 = builder.getAffineSymbolExpr(1);
3446 auto apply = [&](AffineExpr expr, ArrayRef<OpFoldResult> ofrs) -> Value {
3447 return affine::makeComposedAffineApply(builder, linalgOp->getLoc(), expr,
3448 ofrs);
3449 };
3450
3451 SmallVector<Value> chunkSizes;
3452 Value splitPoint;
3453 for (auto &&[tileSize, tripCount] :
3454 llvm::zip_equal(spec->tileSizes, spec->tripCounts)) {
3455 splitPoint = apply(s0 * s1, {tileSize, tripCount});
3456 chunkSizes.push_back(splitPoint);
3457 }
3458
3459 auto getDefiningOps = [&](ArrayRef<Value> values) {
3460 return llvm::map_to_vector(values, [&](Value value) -> Operation * {
3461 return value.getDefiningOp();
3462 });
3463 };
3464
3465 transformResults.set(cast<OpResult>(getTileSizes()),
3466 getDefiningOps(spec->tileSizes));
3467 transformResults.set(cast<OpResult>(getChunkSizes()),
3468 getDefiningOps(chunkSizes));
3469
3471}
3472
3473LogicalResult transform::ContinuousTileSizesOp::verify() {
3474
3475 if (getTileSizes().getType() != getChunkSizes().getType()) {
3476 return emitOpError() << "expects all results type to be the same";
3477 }
3478
3479 return success();
3480}
3481
3482void transform::ContinuousTileSizesOp::getEffects(
3483 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
3484 if (isa<TransformParamTypeInterface>(getTileSizes().getType()))
3485 onlyReadsPayload(effects);
3486 else
3487 modifiesPayload(effects);
3488 onlyReadsHandle(getTargetMutable(), effects);
3489 producesHandle(getOperation()->getOpResults(), effects);
3490}
3491
3493 Type targetType, Type tileSizes,
3494 Type) {
3495 printer.printFunctionalType(TypeRange{targetType}, TypeRange{tileSizes});
3496}
3497
3499 Type &targetType,
3500 Type &tileSizesType,
3501 Type &chunkSizesType) {
3502 FunctionType funcType;
3503 llvm::SMLoc typeLoc = parser.getCurrentLocation();
3504 if (failed(parser.parseType<FunctionType>(funcType)))
3505 return failure();
3506
3507 if (funcType.getNumInputs() != 1 || funcType.getNumResults() != 1) {
3508 parser.emitError(typeLoc) << "expects a trailing functional type with one "
3509 "argument and one result";
3510 }
3511 targetType = funcType.getInput(0);
3512 tileSizesType = chunkSizesType = funcType.getResult(0);
3513
3514 return success();
3515}
3516
3517//===----------------------------------------------------------------------===//
3518// TileUsingForOp
3519//===----------------------------------------------------------------------===//
3520
3521void transform::TileUsingForOp::build(
3522 OpBuilder &builder, OperationState &result, TypeRange loopTypes,
3523 Value target, ArrayRef<int64_t> staticTileSizes,
3524 ArrayRef<int64_t> interchange,
3525 std::optional<ArrayRef<bool>> scalableSizes) {
3526 return build(builder, result, loopTypes,
3527 /*target=*/target,
3528 /*mixedTileSizes=*/
3529 getAsOpFoldResult(builder.getI64ArrayAttr(staticTileSizes)),
3530 interchange, scalableSizes);
3531}
3532
3533void transform::TileUsingForOp::build(
3534 OpBuilder &builder, OperationState &result, Value target,
3535 ArrayRef<int64_t> staticTileSizes, ArrayRef<int64_t> interchange,
3536 std::optional<ArrayRef<bool>> scalableSizes) {
3537 build(builder, result, target,
3538 getAsOpFoldResult(builder.getI64ArrayAttr(staticTileSizes)),
3539 interchange, scalableSizes);
3540}
3541
3542void transform::TileUsingForOp::build(
3543 OpBuilder &builder, OperationState &result, Value target,
3544 ArrayRef<OpFoldResult> mixedTileSizes, ArrayRef<int64_t> interchange,
3545 std::optional<ArrayRef<bool>> scalableSizes) {
3546 // Loop types are automaticaly splat by the callee, setting up one is
3547 // enough.
3548 SmallVector<Type> loopTypes(1, builder.getType<transform::AnyOpType>());
3549 build(builder, result, loopTypes, target, mixedTileSizes, interchange,
3550 scalableSizes);
3551}
3552
3553void transform::TileUsingForOp::build(
3554 OpBuilder &builder, OperationState &result, Value target,
3555 ArrayRef<OpFoldResult> mixedTileSizes,
3556 ArrayRef<OpFoldResult> mixedInterchange,
3557 std::optional<ArrayRef<bool>> scalableSizes) {
3558 // Loop types are automaticaly splat by the callee, setting up one is
3559 // enough.
3560 SmallVector<Type> loopTypes(1, builder.getType<transform::AnyOpType>());
3561 build(builder, result, loopTypes, target, mixedTileSizes, mixedInterchange,
3562 scalableSizes);
3563}
3564
3565void transform::TileUsingForOp::build(
3566 OpBuilder &builder, OperationState &result, TypeRange loopTypes,
3567 Value target, ArrayRef<OpFoldResult> mixedTileSizes,
3568 ArrayRef<int64_t> interchange,
3569 std::optional<ArrayRef<bool>> scalableSizes) {
3570 SmallVector<OpFoldResult> mixedInterchange =
3571 getAsOpFoldResult(builder.getI64ArrayAttr(interchange));
3572 build(builder, result, loopTypes, target, mixedTileSizes, mixedInterchange,
3573 scalableSizes);
3574}
3575
3576void transform::TileUsingForOp::build(
3577 OpBuilder &builder, OperationState &result, TypeRange loopTypes,
3578 Value target, ArrayRef<OpFoldResult> mixedTileSizes,
3579 ArrayRef<OpFoldResult> mixedInterchange,
3580 std::optional<ArrayRef<bool>> scalableSizes) {
3581 SmallVector<int64_t> staticTileSizes;
3582 SmallVector<Value> dynamicTileSizes;
3583 SmallVector<int64_t> staticInterchange;
3584 SmallVector<Value> dynamicInterchange;
3585 dispatchIndexOpFoldResults(mixedTileSizes, dynamicTileSizes, staticTileSizes);
3586 dispatchIndexOpFoldResults(mixedInterchange, dynamicInterchange,
3587 staticInterchange);
3588 // Call the default builder which sets up the proper operands segment sizes
3589 // attributes for multiple variadic operands. In the absence of this,
3590 // horrible bugs ensue.
3591 auto staticTileSizesAttr = builder.getDenseI64ArrayAttr(staticTileSizes);
3592 auto staticInterchangeAttr = builder.getDenseI64ArrayAttr(staticInterchange);
3593 unsigned numExpectedLoops =
3594 staticTileSizes.size() - llvm::count(staticTileSizes, 0);
3595 SmallVector<Type> resultTypes;
3596 resultTypes.reserve(numExpectedLoops);
3597 assert((loopTypes.size() == 1 || loopTypes.size() == numExpectedLoops) &&
3598 "expected one loop type or as many as loops");
3599 if (loopTypes.size() == 1)
3600 resultTypes.append(numExpectedLoops, loopTypes[0]);
3601 else
3602 llvm::append_range(resultTypes, loopTypes);
3603 SmallVector<bool> expandedScalableSizes(mixedTileSizes.size(), false);
3604 if (scalableSizes.has_value())
3605 expandedScalableSizes.assign(scalableSizes->begin(), scalableSizes->end());
3606 Value packedTileSizes;
3607 build(builder, result, /*tiled_linalg_op=*/target.getType(),
3608 /*loops=*/resultTypes,
3609 /*target=*/target,
3610 /*dynamic_sizes=*/dynamicTileSizes,
3611 /*interchange=*/dynamicInterchange,
3612 /*packed_tile_sizes=*/packedTileSizes,
3613 /*packed_interchange=*/Value(),
3614 /*static_sizes=*/staticTileSizesAttr,
3615 /*static_interchange=*/staticInterchangeAttr,
3616 /*scalable_sizes=*/expandedScalableSizes);
3617}
3618
3619LogicalResult transform::TileUsingForOp::verify() {
3620 bool hasPackedTiles = getPackedTileSizes() != Value();
3621 bool hasPackedInterchange = getPackedInterchange() != Value();
3622 if (!getMixedSizes().empty() && hasPackedTiles)
3623 return emitOpError(
3624 "tile_sizes and packed_tile_sizes are mutually exclusive");
3625 if (!getMixedInterchange().empty() && hasPackedInterchange)
3626 return emitOpError(
3627 "interchange and packed_interchange are mutually exclusive");
3628 if (hasPackedTiles && !getScalableSizes().empty())
3629 return emitOpError(
3630 "scalable tile_sizes are not supported with packed_tile_sizes");
3631
3632 if (getMixedSizes().size() != getScalableSizes().size())
3633 return emitOpError("expected same number of sizes (")
3634 << getMixedSizes().size() << ") and scalable sizes ("
3635 << getScalableSizes().size() << ")";
3636
3637 auto iterspaceRank = getStaticSizes().size();
3638 ArrayRef<int64_t> permutation = getStaticInterchange();
3639 if (permutation.size() > iterspaceRank)
3640 return emitOpError()
3641 << "interchange length exceeds iteration space dimensions ("
3642 << iterspaceRank << "), found " << getInterchange();
3643 SmallVector<bool> seen(iterspaceRank, false);
3644 for (int64_t v : permutation) {
3645 if (!ShapedType::isDynamic(v)) {
3646 if (v < 0 || v >= static_cast<int64_t>(iterspaceRank))
3647 return emitOpError() << "expects interchange values to be in range [0, "
3648 << iterspaceRank << "), found: " << v;
3649 if (seen[v])
3650 return emitOpError() << "found duplicate interchange value: " << v;
3651 seen[v] = true;
3652 }
3653 }
3654
3655 ArrayRef<int64_t> staticSizes = getStaticSizes();
3656 unsigned numExpectedLoops =
3657 hasPackedTiles ? 1 : staticSizes.size() - llvm::count(staticSizes, 0);
3658 if (getLoops().size() != numExpectedLoops)
3659 return emitOpError("expected number of loops to tile (")
3660 << numExpectedLoops << ") to match number of `loops` results ("
3661 << getLoops().size() << ")";
3662 return verifyInnerTileAlignments(getOperation(), getInnerTileAlignments());
3663}
3664
3665DiagnosedSilenceableFailure
3666transform::TileUsingForOp::apply(transform::TransformRewriter &rewriter,
3667 TransformResults &transformResults,
3668 TransformState &state) {
3669 ArrayRef<int64_t> tileSizes = getStaticSizes();
3670 bool hasPackedTiles = getPackedTileSizes() != Value();
3671 bool hasPackedInterchange = getPackedInterchange() != Value();
3672 auto transformOp = cast<TransformOpInterface>(getOperation());
3673
3674 SmallVector<OpFoldResult> mixedInterchange;
3675 if (hasPackedInterchange) {
3676 DiagnosedSilenceableFailure status =
3678 state, transformOp, mixedInterchange, getPackedInterchange());
3679 if (!status.succeeded())
3680 return status;
3681 } else {
3682 mixedInterchange = getMixedInterchange();
3683 }
3684 SmallVector<int64_t> tileInterchange;
3685 DiagnosedSilenceableFailure status = reifyMixedParamAndHandleResults(
3686 state, transformOp, mixedInterchange, tileInterchange);
3687 if (!status.succeeded())
3688 return status;
3689
3690 SmallVector<Operation *> targets =
3691 llvm::to_vector(state.getPayloadOps(getTarget()));
3692 SmallVector<SmallVector<Operation *>> dynamicSizeProducers;
3693 SmallVector<SmallVector<int64_t>> paramSizes;
3694 SmallVector<OpFoldResult> mixedTileSizes;
3695 if (hasPackedTiles) {
3697 state, transformOp, mixedTileSizes, getPackedTileSizes());
3698 if (!status.succeeded())
3699 return status;
3700 tileSizes = {};
3701 } else {
3702 dynamicSizeProducers.reserve(getDynamicSizes().size());
3703 paramSizes.reserve(getDynamicSizes().size());
3704 for (Value transformValue : getDynamicSizes()) {
3705 if (isa<TransformParamTypeInterface>(transformValue.getType())) {
3706 dynamicSizeProducers.push_back({});
3707 ArrayRef<Attribute> params = state.getParams(transformValue);
3708 paramSizes.push_back(llvm::map_to_vector(params, [](Attribute attr) {
3709 return cast<IntegerAttr>(attr).getValue().getSExtValue();
3710 }));
3711
3712 if (paramSizes.back().size() != targets.size()) {
3713 DiagnosedSilenceableFailure diag =
3714 emitSilenceableError()
3715 << "expected as many parameter values ("
3716 << dynamicSizeProducers.back().size() << ") as target ops ("
3717 << targets.size() << ")";
3718 diag.attachNote(transformValue.getLoc()) << "for this parameter";
3719 return diag;
3720 }
3721
3722 continue;
3723 }
3724 paramSizes.push_back({});
3725 dynamicSizeProducers.push_back(
3726 llvm::to_vector(state.getPayloadOps(transformValue)));
3727
3728 if (dynamicSizeProducers.back().size() != targets.size()) {
3729 DiagnosedSilenceableFailure diag =
3730 emitSilenceableError()
3731 << "expected as many dynamic size-producing operations ("
3732 << dynamicSizeProducers.back().size() << ") as target ops ("
3733 << targets.size() << ")";
3734 diag.attachNote(transformValue.getLoc()) << "for this handle";
3735 return diag;
3736 }
3737
3738 for (Operation *op : dynamicSizeProducers.back()) {
3739 if (op->getNumResults() == 1 &&
3740 isa<IndexType>(op->getResult(0).getType())) {
3741 continue;
3742 }
3743
3744 DiagnosedSilenceableFailure diag =
3745 emitSilenceableError() << "expected sizes to be produced by ops "
3746 "with a single index-type result";
3747 diag.attachNote(op->getLoc()) << "size producer op";
3748 diag.attachNote(transformValue.getLoc()) << "for this handle";
3749 return diag;
3750 }
3751 }
3752 }
3753
3754 SmallVector<Operation *> tiled;
3755 SmallVector<SmallVector<Operation *, 4>, 4> loops;
3756 size_t numLoops =
3757 hasPackedTiles
3758 ? llvm::count_if(mixedTileSizes,
3759 [](OpFoldResult ofr) {
3760 if (auto attr = dyn_cast<Attribute>(ofr))
3761 return cast<IntegerAttr>(attr).getInt() != 0;
3762 return true;
3763 })
3764 : getLoops().size();
3765 loops.resize(numLoops);
3766 auto scalableSizes = getScalableSizes();
3767 for (auto [i, op] : llvm::enumerate(targets)) {
3768 auto tilingInterface = dyn_cast<TilingInterface>(op);
3769 if (!tilingInterface) {
3770 DiagnosedSilenceableFailure diag =
3771 emitSilenceableError()
3772 << "only ops implementing TilingInterface are supported";
3773 diag.attachNote(op->getLoc()) << "target op";
3774 return diag;
3775 }
3776 if (isa<linalg::RelayoutOpInterface>(op) &&
3777 !cast<DestinationStyleOpInterface>(op).hasPureTensorSemantics()) {
3778 DiagnosedSilenceableFailure diag =
3779 emitSilenceableError()
3780 << "tiling only supports tensor semantics for linalg.pack / "
3781 "linalg.unpack. The target has memref operands";
3782 diag.attachNote(op->getLoc()) << "target op";
3783 return diag;
3784 }
3785
3786 int64_t iterspaceRank = tilingInterface.getLoopIteratorTypes().size();
3787 if (tileInterchange.size() > static_cast<size_t>(iterspaceRank)) {
3788 return emitSilenceableError()
3789 << "interchange length exceeds iteration space dimensions ("
3790 << iterspaceRank << ")";
3791 }
3792 SmallVector<bool> seen(iterspaceRank, false);
3793 for (int64_t v : tileInterchange) {
3794 if (v < 0 || v >= iterspaceRank) {
3795 return emitSilenceableError()
3796 << "expects interchange values to be in range [0, "
3797 << iterspaceRank << "), found: " << v;
3798 }
3799 if (seen[v]) {
3800 return emitSilenceableError()
3801 << "found duplicate interchange value: " << v;
3802 }
3803 seen[v] = true;
3804 }
3805
3806 if (tileSizes.size() > tilingInterface.getLoopIteratorTypes().size()) {
3807 DiagnosedSilenceableFailure diag =
3808 emitSilenceableError()
3809 << "too many tiles provided, expected at most "
3810 << tilingInterface.getLoopIteratorTypes().size() << " found "
3811 << tileSizes.size();
3812 diag.attachNote(op->getLoc()) << "target op";
3813 return diag;
3814 }
3815
3816 scf::SCFTilingOptions tilingOptions;
3817 if (!hasPackedTiles && tileSizes.empty()) {
3818 tilingOptions.setTileSizeComputationFunction(
3819 [](OpBuilder &, Operation *) -> SmallVector<OpFoldResult> {
3820 return {};
3821 });
3822 } else if (hasPackedTiles) {
3823 tilingOptions.setTileSizes(mixedTileSizes);
3824 } else {
3825 tilingOptions.setTileSizeComputationFunction([&, index = i](OpBuilder &b,
3826 Operation *) {
3827 SmallVector<OpFoldResult> sizes;
3828 sizes.reserve(tileSizes.size());
3829 unsigned dynamicIdx = 0;
3830
3831 for (auto [ofrIdx, ofr] : llvm::enumerate(getMixedSizes())) {
3832 if (auto attr = llvm::dyn_cast_if_present<Attribute>(ofr)) {
3833 if (scalableSizes[ofrIdx]) {
3835 b, getLoc(), cast<IntegerAttr>(attr).getInt());
3836 Value vscale =
3837 vector::VectorScaleOp::create(b, getLoc(), b.getIndexType());
3838 sizes.push_back(
3839 arith::MulIOp::create(b, getLoc(), val, vscale).getResult());
3840 } else {
3841 sizes.push_back(attr);
3842 }
3843 continue;
3844 }
3845 ArrayRef<Operation *> dynamicSizes = dynamicSizeProducers[dynamicIdx];
3846 ArrayRef<int64_t> params = paramSizes[dynamicIdx];
3847 ++dynamicIdx;
3848 assert((dynamicSizes.empty() ^ params.empty()) &&
3849 "expected either dynamic sizes or parameters");
3850 if (!params.empty()) {
3851 sizes.push_back(b.getIndexAttr(params[index]));
3852 } else {
3853 sizes.push_back(dynamicSizes[index]->getResult(0));
3854 }
3855 }
3856 return sizes;
3857 });
3858 }
3859
3860 tilingOptions.setInterchange(tileInterchange);
3861 tilingOptions.setInnerTileAlignments(
3862 convertInnerTileAlignments(getInnerTileAlignments()));
3863 FailureOr<scf::SCFTilingResult> maybeTilingResult =
3864 tileUsingSCF(rewriter, tilingInterface, tilingOptions);
3865 if (failed(maybeTilingResult))
3867
3868 rewriter.replaceOp(op, maybeTilingResult->replacements);
3869
3870 tiled.append(maybeTilingResult->tiledOps);
3871 for (const auto &en2 : llvm::enumerate(maybeTilingResult->loops))
3872 loops[en2.index()].push_back(en2.value());
3873 }
3874
3875 transformResults.set(cast<OpResult>(getTiledLinalgOp()), tiled);
3876 if (hasPackedTiles) {
3877 // For packed sizes all created loops are assigned to a single handle.
3878 SmallVector<Operation *> flattenedLoops;
3879 for (auto [targetIdx, _] : llvm::enumerate(targets))
3880 for (auto [loopIdx, __] : llvm::enumerate(loops))
3881 flattenedLoops.push_back(loops[loopIdx][targetIdx]);
3882 transformResults.set(cast<OpResult>(getLoops().front()), flattenedLoops);
3883 } else {
3884 for (const auto &en : llvm::enumerate(loops))
3885 transformResults.set(cast<OpResult>(getLoops()[en.index()]), en.value());
3886 }
3887
3889}
3890
3891SmallVector<OpFoldResult> transform::TileUsingForOp::getMixedSizes() {
3892 ValueRange dynamic = getDynamicSizes();
3893 ArrayRef<int64_t> tileSizes = getStaticSizes();
3894 SmallVector<OpFoldResult> results;
3895 results.reserve(tileSizes.size());
3896 unsigned dynamicPos = 0;
3897 Builder builder(getContext());
3898 for (int64_t size : tileSizes) {
3899 if (size == ShapedType::kDynamic) {
3900 results.push_back(dynamic[dynamicPos++]);
3901 } else {
3902 results.push_back(builder.getIndexAttr(size));
3903 }
3904 }
3905 return results;
3906}
3907
3908SmallVector<OpFoldResult> transform::TileUsingForOp::getMixedInterchange() {
3909 return getMixedValues(getStaticInterchange(), getInterchange(), getContext());
3910}
3911
3912void transform::TileUsingForOp::getEffects(
3913 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
3914 consumesHandle(getTargetMutable(), effects);
3915 onlyReadsHandle(getDynamicSizesMutable(), effects);
3916 onlyReadsHandle(getInterchangeMutable(), effects);
3917 onlyReadsHandle(getPackedTileSizesMutable(), effects);
3918 onlyReadsHandle(getPackedInterchangeMutable(), effects);
3919 producesHandle(getOperation()->getOpResults(), effects);
3920 modifiesPayload(effects);
3921}
3922
3923//===----------------------------------------------------------------------===//
3924// TileUsingForallOp
3925//===----------------------------------------------------------------------===//
3926
3927void transform::TileUsingForallOp::build(OpBuilder &builder,
3928 OperationState &result, Value target,
3929 ArrayRef<int64_t> staticTileSizes,
3930 transform::TileSizesSpec,
3931 ArrayAttr mapping,
3932 ArrayRef<bool> scalableSizes) {
3933 return build(builder, result,
3934 /*target=*/target,
3935 /*mixedTileSizes=*/
3936 getAsOpFoldResult(builder.getI64ArrayAttr(staticTileSizes)),
3937 /*_=*/TileSizesSpec(),
3938 /*mapping=*/mapping, scalableSizes);
3939}
3940
3941void transform::TileUsingForallOp::build(OpBuilder &builder,
3942 OperationState &result, Value target,
3943 ArrayRef<OpFoldResult> mixedTileSizes,
3944 transform::TileSizesSpec,
3945 ArrayAttr mapping,
3946 ArrayRef<bool> scalableSizes) {
3947 SmallVector<int64_t> staticTileSizes;
3948 SmallVector<Value> dynamicTileSizes;
3949 dispatchIndexOpFoldResults(mixedTileSizes, dynamicTileSizes, staticTileSizes);
3950 // Call the default builder which sets up the proper operands segment sizes
3951 // attributes for multiple variadic operands. In the absence of this,
3952 // horrible bugs ensue.
3953 MLIRContext *ctx = builder.getContext();
3954 auto operationType = transform::AnyOpType::get(ctx);
3955 auto staticTileSizesAttr = builder.getDenseI64ArrayAttr(staticTileSizes);
3956 build(builder, result,
3957 /*resultTypes=*/TypeRange{operationType, operationType},
3958 /*target=*/target,
3959 /*num_threads=*/ValueRange{},
3960 /*tile_sizes=*/dynamicTileSizes,
3961 /*packed_num_threads=*/Value(),
3962 /*packed_tile_sizes=*/Value(),
3963 /*static_num_threads=*/builder.getDenseI64ArrayAttr({}),
3964 /*static_tile_sizes=*/staticTileSizesAttr,
3965 /*scalable_sizes=*/builder.getDenseBoolArrayAttr(scalableSizes),
3966 /*mapping=*/mapping);
3967}
3968
3969void transform::TileUsingForallOp::build(OpBuilder &builder,
3970 OperationState &result, Value target,
3971 ArrayRef<int64_t> staticNumThreads,
3972 transform::NumThreadsSpec,
3973 ArrayAttr mapping) {
3974 return build(builder, result, target,
3975 getAsOpFoldResult(builder.getI64ArrayAttr(staticNumThreads)),
3976 NumThreadsSpec(), mapping);
3977}
3978
3979void transform::TileUsingForallOp::build(OpBuilder &builder,
3980 OperationState &result, Value target,
3981 ArrayRef<OpFoldResult> mixedNumThreads,
3982 transform::NumThreadsSpec,
3983 ArrayAttr mapping) {
3984 SmallVector<int64_t> staticNumThreads;
3985 SmallVector<Value> dynamicNumThreads;
3986 dispatchIndexOpFoldResults(mixedNumThreads, dynamicNumThreads,
3987 staticNumThreads);
3988 // Call the default builder which sets up the proper operands segment sizes
3989 // attributes for multiple variadic operands. In the absence of this,
3990 // horrible bugs ensue.
3991 MLIRContext *ctx = builder.getContext();
3992 auto operationType = transform::AnyOpType::get(ctx);
3993 auto staticNumThreadsAttr = builder.getDenseI64ArrayAttr(staticNumThreads);
3994 build(builder, result,
3995 /*resultTypes=*/TypeRange{operationType, operationType},
3996 /*target=*/target,
3997 /*num_threads=*/dynamicNumThreads,
3998 /*tile_sizes=*/ValueRange{},
3999 /*packed_num_threads=*/Value(),
4000 /*packed_tile_sizes=*/Value(),
4001 /*static_num_threads=*/staticNumThreadsAttr,
4002 /*static_tile_sizes=*/builder.getDenseI64ArrayAttr({}),
4003 /*scalable_sizes=*/builder.getDenseBoolArrayAttr({}),
4004 /*mapping=*/mapping);
4005}
4006
4007/// Given `lbs`, `ubs` and `steps` of loops, return (for each loop), the
4008/// normalized upper bound.
4009static SmallVector<OpFoldResult>
4012 ArrayRef<OpFoldResult> steps) {
4013 AffineExpr s0, s1, s2;
4014 bindSymbols(rewriter.getContext(), s0, s1, s2);
4015 AffineExpr normalizedUbExpr = (s1 - s0).ceilDiv(s2);
4016 SmallVector<OpFoldResult> normalizedUbs;
4017 for (auto [lb, ub, step] : llvm::zip_equal(lbs, ubs, steps)) {
4019 rewriter, loc, normalizedUbExpr, {lb, ub, step});
4020 normalizedUbs.push_back(normalizedUb);
4021 }
4022 return normalizedUbs;
4023}
4024
4025/// When a loop is normalized, the uses of the induction variable within the
4026/// loop need to replaced with `original_lb + old_iv * original_step`.
4028 Location loc, ValueRange ivs,
4030 ArrayRef<OpFoldResult> steps) {
4031 AffineExpr s0, s1;
4032 AffineExpr d0;
4033 bindSymbols(rewriter.getContext(), s0, s1);
4034 bindDims(rewriter.getContext(), d0);
4035 AffineExpr denormExpr = s0 + d0 * s1;
4036 SmallVector<Value> denormalizedIvs;
4037
4038 for (auto [iv, lb, step] : llvm::zip_equal(ivs, lbs, steps)) {
4040 rewriter, loc, denormExpr, ArrayRef<OpFoldResult>{iv, lb, step});
4041 denormalizedIvs.push_back(
4042 getValueOrCreateConstantIndexOp(rewriter, loc, denormValue));
4043 }
4044 return denormalizedIvs;
4045}
4046
4047/// Given a `scf.forall` loop return a loop op with the loop bounds
4048/// normalized.
4049/// TODO: Replace this with a general utility to normalize `scf.forall`.
4050/// At the time of writing, this wasnt done since adding this to `scf`
4051/// dialect would disallow using of `affine.apply` operations due
4052/// to cyclic dependencies. To avoid churn in lit tests
4053/// with the change this was added with, defer that to a follow up.
4054static scf::ForallOp normalizeForallLoopOp(RewriterBase &rewriter,
4055 scf::ForallOp loop) {
4056 SmallVector<OpFoldResult> lbs = loop.getMixedLowerBound();
4057 SmallVector<OpFoldResult> ubs = loop.getMixedUpperBound();
4058 SmallVector<OpFoldResult> steps = loop.getMixedStep();
4059
4060 if (llvm::all_of(lbs, isZeroInteger) && llvm::all_of(steps, isOneInteger)) {
4061 return loop;
4062 }
4063
4064 Location loc = loop.getLoc();
4065 SmallVector<OpFoldResult> normalizedUbs =
4066 normalizeUpperBounds(rewriter, loc, lbs, ubs, steps);
4067 SmallVector<OpFoldResult> normalizedLbs(normalizedUbs.size(),
4068 rewriter.getIndexAttr(0));
4069 SmallVector<OpFoldResult> normalizedSteps(normalizedUbs.size(),
4070 rewriter.getIndexAttr(1));
4071
4072 auto normalizedForallOp = scf::ForallOp::create(
4073 rewriter, loc, normalizedLbs, normalizedUbs, normalizedSteps,
4074 loop.getOutputs(), loop.getMapping(),
4075 [](OpBuilder &, Location, ValueRange) {});
4076
4077 auto normalizedLoopIvs = normalizedForallOp.getInductionVars();
4078 OpBuilder::InsertionGuard g(rewriter);
4079 Block *normalizedLoopBlock = normalizedForallOp.getBody();
4080 rewriter.setInsertionPointToStart(normalizedLoopBlock);
4081
4082 SmallVector<Value> argValues =
4083 denormalizeIndVar(rewriter, loc, normalizedLoopIvs, lbs, steps);
4084 argValues.append(normalizedForallOp.getRegionIterArgs().begin(),
4085 normalizedForallOp.getRegionIterArgs().end());
4086 Block *origLoopBlock = loop.getBody();
4087 rewriter.mergeBlocks(origLoopBlock, normalizedLoopBlock, argValues);
4088
4089 rewriter.replaceOp(loop, normalizedForallOp);
4090 return normalizedForallOp;
4091}
4092
4094 RewriterBase &rewriter, transform::TransformState &state,
4095 TransformOpInterface transformOp, Operation *target,
4096 ArrayRef<OpFoldResult> mixedNumThreads,
4097 ArrayRef<OpFoldResult> mixedTileSizes, std::optional<ArrayAttr> mapping,
4098 scf::SCFTilingResult &tilingResult, ArrayRef<bool> scalableSizes) {
4099 // Transform all targets one by one.
4100 auto tileableOp = dyn_cast<TilingInterface>(target);
4101 if (!tileableOp) {
4103 transformOp.emitSilenceableError()
4104 << "only TilingInterface ops are supported";
4105 diag.attachNote(target->getLoc()) << "target op";
4106 return diag;
4107 }
4108 if (isa<linalg::RelayoutOpInterface>(target) &&
4109 !cast<DestinationStyleOpInterface>(target).hasPureTensorSemantics()) {
4111 transformOp.emitSilenceableError()
4112 << "tiling only supports tensor semantics for linalg.pack / "
4113 "linalg.unpack. The target has memref operands";
4114 diag.attachNote(target->getLoc()) << "target op";
4115 return diag;
4116 }
4117 rewriter.setInsertionPoint(tileableOp);
4118 scf::SCFTilingOptions options;
4119 options.setLoopType(scf::SCFTilingOptions::LoopType::ForallOp);
4120 if (!mixedNumThreads.empty()) {
4121 options.setNumThreads(mixedNumThreads);
4122 } else {
4123 // Materialize scalable sizes only after checking the target's
4124 // preconditions. The tiler invokes this callback in each target's scope.
4125 options.setTileSizeComputationFunction(
4126 [mixedTileSizes, scalableSizes](OpBuilder &builder, Operation *op) {
4127 SmallVector<OpFoldResult> tileSizes(mixedTileSizes);
4128 Value vscale;
4129 for (auto [i, scalable] : llvm::enumerate(scalableSizes)) {
4130 if (!scalable || isZeroInteger(tileSizes[i]))
4131 continue;
4132 Location loc = op->getLoc();
4133 if (!vscale)
4134 vscale = vector::VectorScaleOp::create(builder, loc,
4135 builder.getIndexType());
4136 Value factor =
4137 getValueOrCreateConstantIndexOp(builder, loc, tileSizes[i]);
4138 tileSizes[i] =
4139 arith::MulIOp::create(builder, loc, factor, vscale).getResult();
4140 }
4141 return tileSizes;
4142 });
4143 }
4144 if (mapping) {
4145 options.setMapping(mapping.value().getValue());
4146 }
4147 FailureOr<scf::SCFTilingResult> maybeTilingResult =
4148 scf::tileUsingSCF(rewriter, tileableOp, options);
4149
4150 if (failed(maybeTilingResult))
4151 return transformOp.emitDefaultSilenceableFailure(tileableOp);
4152
4153 rewriter.replaceOp(tileableOp, maybeTilingResult->replacements);
4154
4155 tilingResult = *maybeTilingResult;
4156
4157 // Rank-0 ops produce no loops; skip normalization when there is nothing
4158 // to normalize.
4159 if (mixedNumThreads.empty() && !tilingResult.loops.empty()) {
4160 auto generatedForallOp = cast<scf::ForallOp>(tilingResult.loops.front());
4161 OpBuilder::InsertionGuard g(rewriter);
4162 rewriter.setInsertionPoint(generatedForallOp);
4163 scf::ForallOp normalizedForallOp =
4164 normalizeForallLoopOp(rewriter, generatedForallOp);
4165 tilingResult.loops.front() = normalizedForallOp;
4166 }
4167
4169}
4170
4171DiagnosedSilenceableFailure transform::TileUsingForallOp::apply(
4173 transform::TransformResults &transformResults,
4175 auto transformOp = cast<TransformOpInterface>(getOperation());
4176
4177 // Result payload ops.
4179 SmallVector<Operation *> tiledOps;
4180
4181 // Unpack handles.
4182 SmallVector<OpFoldResult> mixedNumThreads;
4184 getPackedNumThreads()
4186 state, transformOp, mixedNumThreads, getPackedNumThreads())
4188 state, transformOp, mixedNumThreads, getMixedNumThreads());
4189 if (!status.succeeded())
4190 return status;
4191 SmallVector<OpFoldResult> mixedTileSizes;
4192 status = getPackedTileSizes()
4194 state, transformOp, mixedTileSizes, getPackedTileSizes())
4196 state, transformOp, mixedTileSizes, getMixedTileSizes());
4197 if (!status.succeeded())
4198 return status;
4199
4200 for (Operation *target : state.getPayloadOps(getTarget())) {
4201 scf::SCFTilingResult tilingResult;
4203 rewriter, state, transformOp, target, mixedNumThreads, mixedTileSizes,
4204 getMapping(), tilingResult, getScalableSizes());
4205 if (!diag.succeeded())
4206 return diag;
4207 if (!tilingResult.loops.empty())
4208 tileOps.push_back(tilingResult.loops.front());
4209 tiledOps.append(tilingResult.tiledOps);
4210 }
4211
4212 transformResults.set(cast<OpResult>(getForallOp()), tileOps);
4213 transformResults.set(cast<OpResult>(getTiledOp()), tiledOps);
4214
4216}
4217
4218void transform::TileUsingForallOp::getEffects(
4219 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
4220 consumesHandle(getTargetMutable(), effects);
4221 onlyReadsHandle(getTileSizesMutable(), effects);
4222 onlyReadsHandle(getNumThreadsMutable(), effects);
4223 onlyReadsHandle(getPackedNumThreadsMutable(), effects);
4224 onlyReadsHandle(getPackedTileSizesMutable(), effects);
4225 producesHandle(getOperation()->getOpResults(), effects);
4226 modifiesPayload(effects);
4227}
4228
4229SmallVector<OpFoldResult> TileUsingForallOp::getMixedNumThreads() {
4230 Builder b(getContext());
4231 return getMixedValues(getStaticNumThreads(), getNumThreads(), b);
4232}
4233
4234SmallVector<OpFoldResult> TileUsingForallOp::getMixedTileSizes() {
4235 Builder b(getContext());
4236 return getMixedValues(getStaticTileSizes(), getTileSizes(), b);
4237}
4238
4239LogicalResult TileUsingForallOp::verify() {
4240 ArrayRef<bool> scalableSizes = getScalableSizes();
4241 if (!scalableSizes.empty() &&
4242 scalableSizes.size() != getStaticTileSizes().size())
4243 return emitOpError(
4244 "expected as many scalable size flags as static tile sizes");
4245 for (auto [size, scalable] : llvm::zip(getStaticTileSizes(), scalableSizes)) {
4246 if (scalable && (ShapedType::isDynamic(size) || size < 0))
4247 return emitOpError(
4248 "scalable tile sizes must be non-negative static integers");
4249 }
4250 int numThreadsSpec = static_cast<int>(!getMixedNumThreads().empty()) +
4251 static_cast<int>(getPackedNumThreads() != Value());
4252 if (numThreadsSpec > 1)
4253 return emitOpError(
4254 "num_threads and packed_num_threads are mutually exclusive");
4255 int tileSizesSpec = static_cast<int>(!getMixedTileSizes().empty()) +
4256 static_cast<int>(getPackedTileSizes() != Value());
4257 if (tileSizesSpec > 1)
4258 return emitOpError(
4259 "tile_sizes and packed_tile_sizes are mutually exclusive");
4260 if (numThreadsSpec == 0 && tileSizesSpec == 0)
4261 return emitOpError("either (packed_)num_threads or (packed_)tile_sizes "
4262 "must be specified");
4263 if (numThreadsSpec != 0 && llvm::is_contained(scalableSizes, true))
4264 return emitOpError("scalable tile sizes cannot be used with num_threads");
4265 return success();
4266}
4267
4268//===----------------------------------------------------------------------===//
4269// VectorizeChildrenAndApplyPatternsOp
4270//===----------------------------------------------------------------------===//
4271
4272void transform::VectorizeChildrenAndApplyPatternsOp::build(
4273 OpBuilder &builder, OperationState &result, Value target,
4274 bool foldTypeExtensionsIntoContract, bool vectorizePadding,
4275 bool vectorizeExtract, bool flatten1DDepthwiseConv) {
4276 result.addOperands(target);
4277 if (foldTypeExtensionsIntoContract) {
4278 result.addAttribute(
4279 VectorizeChildrenAndApplyPatternsOp::
4280 getFoldTypeExtensionsIntoContractAttrName(result.name),
4281 builder.getUnitAttr());
4282 }
4283 if (vectorizePadding) {
4284 result.addAttribute(
4285 VectorizeChildrenAndApplyPatternsOp::getVectorizePaddingAttrName(
4286 result.name),
4287 builder.getUnitAttr());
4288 }
4289 if (vectorizeExtract) {
4290 result.addAttribute(
4291 VectorizeChildrenAndApplyPatternsOp::getVectorizeNdExtractAttrName(
4292 result.name),
4293 builder.getUnitAttr());
4294 }
4295 if (flatten1DDepthwiseConv) {
4296 result.addAttribute(
4297 VectorizeChildrenAndApplyPatternsOp::getFlatten_1dDepthwiseConvAttrName(
4298 result.name),
4299 builder.getUnitAttr());
4300 }
4301 result.addTypes(transform::AnyOpType::get(builder.getContext()));
4302}
4303
4304namespace {
4305/// This is an helper only to call vectorize via a pattern inside of
4306/// VectorizeChildrenAndApplyPatternsOp::applyToOne.
4307struct VectorizationPattern : public RewritePattern {
4308 explicit VectorizationPattern(MLIRContext *context,
4309 bool vectorizeExtract = false,
4310 bool flattenConv = false)
4311 : RewritePattern(MatchAnyOpTypeTag(), /*benefit=*/1, context),
4312 vectorizeNDExtract(vectorizeExtract),
4313 flatten1DDepthwiseConv(flattenConv) {}
4314 LogicalResult matchAndRewrite(Operation *op,
4315 PatternRewriter &rewriter) const override {
4317 return rewriter.notifyMatchFailure(op,
4318 "Unsupported Op, cannot vectorize");
4319 FailureOr<VectorizationResult> vectorResults =
4320 vectorize(rewriter, op, /*inputVectorSizes=*/{},
4321 /*inputScalableVecDims=*/{}, vectorizeNDExtract,
4322 flatten1DDepthwiseConv);
4323 if (failed(vectorResults))
4324 return failure();
4325 rewriter.replaceOp(op, vectorResults->replacements);
4326 return success();
4327 }
4328
4329private:
4330 /// Controls whether to vectorize `tensor.extract` when the input tensor is
4331 /// rank >= 2.
4332 bool vectorizeNDExtract = false;
4333 /// Controls whether to "flatten" the channel dimension when vectorising 1D
4334 /// depthwise convolutions. This should lead to bette vectorization for
4335 /// tensors with a low number of channel dimensions.
4336 bool flatten1DDepthwiseConv = false;
4337};
4338} // namespace
4339
4340DiagnosedSilenceableFailure
4341transform::VectorizeChildrenAndApplyPatternsOp::applyToOne(
4342 transform::TransformRewriter &rewriter, Operation *target,
4343 transform::ApplyToEachResultList &results,
4344 transform::TransformState &state) {
4345 if (!target->hasTrait<OpTrait::IsIsolatedFromAbove>()) {
4346 auto diag = this->emitOpError("requires isolated-from-above targets");
4347 diag.attachNote(target->getLoc()) << "non-isolated target";
4349 }
4350
4351 MLIRContext *ctx = getContext();
4352 RewritePatternSet patterns(ctx);
4353 patterns.add<VectorizationPattern>(ctx, getVectorizeNdExtract(),
4354 getFlatten_1dDepthwiseConv());
4355
4356 if (!getDisableTransferPermutationMapLoweringPatterns())
4358
4359 if (!getDisableMultiReductionToContractPatterns())
4361
4363
4364 patterns.add<linalg::LinalgCopyVTRForwardingPattern,
4365 linalg::LinalgCopyVTWForwardingPattern>(ctx,
4366 /*benefit=*/2);
4367 vector::TransferReadOp::getCanonicalizationPatterns(patterns, ctx);
4368 vector::TransferWriteOp::getCanonicalizationPatterns(patterns, ctx);
4370
4371 patterns.add<CopyVectorizationPattern>(ctx);
4372
4373 if (getFoldTypeExtensionsIntoContract())
4375
4376 if (getVectorizePadding()) {
4378 // This creates an alternative path for lowering tensor.pad - by
4379 // decomposing it into e.g. linalg.fill.
4381 }
4383
4384 TrackingListener listener(state, *this);
4385 if (failed(
4386 applyPatternsGreedily(target, std::move(patterns),
4387 GreedyRewriteConfig().setListener(&listener))))
4388 return emitDefaultDefiniteFailure(target);
4389
4390 results.push_back(target);
4392}
4393
4394//===----------------------------------------------------------------------===//
4395// VectorizeOp
4396//===----------------------------------------------------------------------===//
4397
4398DiagnosedSilenceableFailure transform::VectorizeOp::apply(
4399 transform::TransformRewriter &rewriter,
4400 mlir::transform::TransformResults &transformResults,
4401 mlir::transform::TransformState &state) {
4402 auto targets = state.getPayloadOps(getTarget());
4403 if (std::empty(targets))
4405 auto transformOp = cast<TransformOpInterface>(getOperation());
4406 SmallVector<int64_t> vectorSizes;
4407 DiagnosedSilenceableFailure status = reifyMixedParamAndHandleResults(
4408 state, transformOp, getMixedVectorSizes(), vectorSizes);
4409 if (!status.succeeded())
4410 return status;
4411
4412 // TODO: Check that the correct number of vectorSizes was provided.
4413 for (Operation *target : targets) {
4415 return mlir::emitSilenceableFailure(target->getLoc())
4416 << "Unsupported Op, cannot vectorize";
4417 }
4418 FailureOr<VectorizationResult> vectorResults =
4419 linalg::vectorize(rewriter, target, vectorSizes, getScalableSizes(),
4420 getVectorizeNdExtract().value_or(false),
4421 /*flatten1DDepthwiseConv=*/false,
4422 getAssumeDynamicDimsMatchVecSizes().value_or(false),
4423 getCreateNamedContraction().value_or(false));
4424 if (failed(vectorResults)) {
4425 return mlir::emitSilenceableFailure(target->getLoc())
4426 << "Attempted to vectorize, but failed";
4427 }
4428 rewriter.replaceOp(target, vectorResults->replacements);
4429 }
4430
4432}
4433
4434void transform::VectorizeOp::getEffects(
4435 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
4436 consumesHandle(getTargetMutable(), effects);
4437 onlyReadsHandle(getVectorSizesMutable(), effects);
4438 modifiesPayload(effects);
4439}
4440
4441SmallVector<OpFoldResult> VectorizeOp::getMixedVectorSizes() {
4442 OpBuilder b(getContext());
4443 return getMixedValues(getStaticVectorSizes(), getVectorSizes(), b);
4444}
4445
4446LogicalResult transform::VectorizeOp::verify() {
4447 if (getStaticVectorSizes().size() != getScalableSizes().size())
4448 return emitOpError("expected same number of vector sizes (")
4449 << getStaticVectorSizes().size() << ") and scalable sizes ("
4450 << getScalableSizes().size() << ")";
4451 return success();
4452}
4453
4454//===----------------------------------------------------------------------===//
4455// HoistRedundantVectorTransfersOp
4456//===----------------------------------------------------------------------===//
4457
4458DiagnosedSilenceableFailure
4459transform::HoistRedundantVectorTransfersOp::applyToOne(
4460 transform::TransformRewriter &rewriter, func::FuncOp target,
4461 transform::ApplyToEachResultList &results,
4462 transform::TransformState &state) {
4463 // WARNING: This hoisting does not model parallelism and is generally
4464 // incorrect when used on distributed loops with memref semantics!
4465 // TODO: obsolete and should be retired.
4466 linalg::hoistRedundantVectorTransfers(target, getVerifyNonZeroTrip());
4467 results.push_back(target);
4469}
4470
4471//===----------------------------------------------------------------------===//
4472// HoistRedundantVectorBroadcastsOp
4473//===----------------------------------------------------------------------===//
4474
4475DiagnosedSilenceableFailure
4476transform::HoistRedundantVectorBroadcastsOp::applyToOne(
4477 transform::TransformRewriter &rewriter, mlir::Operation *target,
4478 transform::ApplyToEachResultList &results,
4479 transform::TransformState &state) {
4480 rewriter.setInsertionPoint(target);
4482 results.push_back(target);
4484}
4485
4486//===----------------------------------------------------------------------===//
4487// ConvertConv2DToImg2ColOp.
4488//===----------------------------------------------------------------------===//
4489
4490DiagnosedSilenceableFailure transform::ConvertConv2DToImg2ColOp::applyToOne(
4491 transform::TransformRewriter &rewriter, linalg::LinalgOp target,
4492 transform::ApplyToEachResultList &results,
4493 transform::TransformState &state) {
4494 rewriter.setInsertionPoint(target);
4495 auto maybeTransformed =
4497 target)
4498 .Case([&](linalg::Conv2DNhwcHwcfOp op) {
4499 return rewriteInIm2Col(rewriter, op);
4500 })
4501 .Case([&](linalg::Conv2DNhwcFhwcOp op) {
4502 return rewriteInIm2Col(rewriter, op);
4503 })
4504 .Case([&](linalg::DepthwiseConv2DNhwcHwcOp op) {
4505 return rewriteInIm2Col(rewriter, op);
4506 })
4507 .Case([&](linalg::Conv2DNchwFchwOp op) {
4508 return rewriteInIm2Col(rewriter, op);
4509 })
4510 .Default([&](Operation *op) {
4511 return rewriter.notifyMatchFailure(op, "not supported");
4512 });
4513 if (failed(maybeTransformed))
4514 return emitDefaultSilenceableFailure(target);
4515 // Handle to the operation producing the img2col tensor.
4516 results.push_back(maybeTransformed->first);
4517 // Handle to the operation that replaces the original convolution.
4518 results.push_back(maybeTransformed->second);
4520}
4521
4522//===----------------------------------------------------------------------===//
4523// FlattenElementwiseLinalgOp.
4524//===----------------------------------------------------------------------===//
4525
4526DiagnosedSilenceableFailure transform::FlattenElementwiseLinalgOp::applyToOne(
4527 transform::TransformRewriter &rewriter, linalg::LinalgOp target,
4528 transform::ApplyToEachResultList &results,
4529 transform::TransformState &state) {
4530 rewriter.setInsertionPoint(target);
4531 if (!isElementwise(target))
4532 return mlir::emitSilenceableFailure(target->getLoc())
4533 << "only elementwise flattening is supported";
4534
4535 if (!llvm::all_of(target.getIndexingMapsArray(), [](AffineMap m) {
4536 return m.isPermutation() || m.getNumResults() == 0;
4537 })) {
4538 results.push_back(target);
4539 return mlir::emitSilenceableFailure(target->getLoc())
4540 << "broadcasting of non scalar operands is not supported";
4541 }
4542
4543 // If rank <= 1, do nothing
4544 if (target.getNumLoops() <= 1) {
4545 results.push_back(target);
4547 }
4548
4549 // Only broadcasts with a 0-D input are handled; leave anything else
4550 // unchanged.
4551 if (auto broadcastOp = dyn_cast<linalg::BroadcastOp>(target.getOperation());
4552 broadcastOp && broadcastOp.getInput().getType().getRank() != 0) {
4553 results.push_back(target);
4555 }
4556
4557 // Attempt to flatten all dims to one.
4558 ReassociationIndices reassociation(target.getNumLoops());
4559 std::iota(reassociation.begin(), reassociation.end(), 0);
4560 auto maybeFlattened =
4561 collapseOpIterationDims(target, reassociation, rewriter);
4562 if (failed(maybeFlattened))
4563 return mlir::emitSilenceableFailure(target->getLoc())
4564 << "attempted to flatten, but failed";
4565 results.push_back(maybeFlattened->collapsedOp);
4566 rewriter.replaceOp(target, maybeFlattened->results);
4568}
4569
4570//===----------------------------------------------------------------------===//
4571// TransposeConv2DOp
4572//===----------------------------------------------------------------------===//
4573
4574DiagnosedSilenceableFailure transform::TransposeConv2DOp::applyToOne(
4575 transform::TransformRewriter &rewriter, linalg::LinalgOp target,
4576 transform::ApplyToEachResultList &results,
4577 transform::TransformState &state) {
4578 rewriter.setInsertionPoint(target);
4579 auto maybeTransformed =
4581 .Case([&](linalg::Conv2DNhwcFhwcOp op) {
4582 return transposeConv2D(rewriter, op);
4583 })
4584 .Case([&](linalg::Conv2DNhwcFhwcQOp op) {
4585 return transposeConv2D(rewriter, op);
4586 })
4587 .Default([&](Operation *op) {
4588 return rewriter.notifyMatchFailure(op, "not supported");
4589 });
4590 if (failed(maybeTransformed))
4591 return emitDefaultSilenceableFailure(target);
4592 // Handle to the new Conv2D operation with transposed filters
4593 results.push_back(*maybeTransformed);
4595}
4596
4597//===----------------------------------------------------------------------===//
4598// TransposeMatmulOp
4599//===----------------------------------------------------------------------===//
4600
4601DiagnosedSilenceableFailure transform::TransposeMatmulOp::applyToOne(
4602 transform::TransformRewriter &rewriter, linalg::LinalgOp target,
4603 transform::ApplyToEachResultList &results,
4604 transform::TransformState &state) {
4605 rewriter.setInsertionPoint(target);
4606 bool transposeLHS = getInputToTranspose() == TransposeMatmulInput::lhs;
4607 auto maybeTransformed =
4609 .Case([&](linalg::MatmulOp op) {
4610 return transposeMatmul(rewriter, op, transposeLHS);
4611 })
4612 .Case([&](linalg::BatchMatmulOp op) {
4613 return transposeBatchMatmul(rewriter, op, transposeLHS);
4614 })
4615 .Default(failure());
4616 if (failed(maybeTransformed))
4617 return emitSilenceableFailure(target->getLoc()) << "not supported";
4618 // Handle to the new Matmul operation with transposed filters
4619 results.push_back(*maybeTransformed);
4621}
4622
4623//===----------------------------------------------------------------------===//
4624// InsertSliceToCopyOp
4625//===----------------------------------------------------------------------===//
4626template <typename OpTy>
4627static DiagnosedSilenceableFailure
4628doit(RewriterBase &rewriter, OpTy target,
4631 static_assert(llvm::is_one_of<OpTy, tensor::InsertSliceOp,
4632 tensor::ParallelInsertSliceOp>() &&
4633 "wrong op type");
4634
4635 if (auto copySource =
4636 target.getSource().template getDefiningOp<linalg::CopyOp>()) {
4637 results.push_back(copySource);
4639 }
4640
4641 // If we are inside a `ParallelCombiningOp` region, temporarily set the
4642 // insertion point outside: only ops implementing ParallelCombiningOpInterface
4643 // are allowed in there.
4644 if (isa<mlir::ParallelCombiningOpInterface>(target.getOperation()))
4645 rewriter.setInsertionPoint(target->getParentOp());
4646
4647 Value extracted = tensor::ExtractSliceOp::create(
4648 rewriter, target.getLoc(), target.getDest(), target.getMixedOffsets(),
4649 target.getMixedSizes(), target.getMixedStrides());
4650 Value copied = linalg::CopyOp::create(rewriter, target.getLoc(),
4651 target.getSource(), extracted)
4652 .getResult(0);
4653 // Reset the insertion point.
4654 rewriter.setInsertionPoint(target);
4655 rewriter.replaceOpWithNewOp<OpTy>(
4656 target, copied, target.getDest(), target.getMixedOffsets(),
4657 target.getMixedSizes(), target.getMixedStrides());
4658
4659 results.push_back(copied.getDefiningOp());
4661}
4662
4663DiagnosedSilenceableFailure transform::InsertSliceToCopyOp::applyToOne(
4664 transform::TransformRewriter &rewriter, Operation *targetOp,
4665 transform::ApplyToEachResultList &results,
4666 transform::TransformState &state) {
4667
4668 rewriter.setInsertionPoint(targetOp);
4669 if (auto target = dyn_cast<tensor::InsertSliceOp>(targetOp))
4670 return doit(rewriter, target, results, state);
4671 if (auto target = dyn_cast<tensor::ParallelInsertSliceOp>(targetOp))
4672 return doit(rewriter, target, results, state);
4673
4674 DiagnosedSilenceableFailure diag =
4675 emitSilenceableError()
4676 << "only InsertSliceOp and ParallelInsertSliceOp ops are supported";
4677 diag.attachNote(targetOp->getLoc()) << "target op";
4678 return diag;
4679}
4680
4681//===----------------------------------------------------------------------===//
4682// MapCopyToThreadsOp
4683//===----------------------------------------------------------------------===//
4684
4685DiagnosedSilenceableFailure transform::MapCopyToThreadsOp::applyToOne(
4686 transform::TransformRewriter &rewriter, Operation *target,
4687 transform::ApplyToEachResultList &results,
4688 transform::TransformState &state) {
4689 // Check if the op is supported.
4690 if (!isa<linalg::CopyOp, tensor::PadOp>(target)) {
4691 DiagnosedSilenceableFailure diag =
4692 emitSilenceableError()
4693 << "only linalg.copy and tensor.pad target ops are supported";
4694 diag.attachNote(target->getLoc()) << "target op";
4695 return diag;
4696 }
4697 assert(target->getNumResults() == 1 && "expected single result");
4698 auto resultShapedType = cast<ShapedType>(target->getResult(0).getType());
4699 if (!resultShapedType.hasStaticShape()) {
4700 DiagnosedSilenceableFailure diag =
4701 emitSilenceableError()
4702 << "only statically sized ops of rank <= 3 are supported";
4703 diag.attachNote(target->getLoc()) << "target op";
4704 return diag;
4705 }
4706
4707 // Conservatively set the minimum viable desired bitwidth alignment.
4708 int64_t desiredBitAlignment = getDesiredBitAlignment();
4709 int64_t eltBitwidth =
4710 resultShapedType.getElementType().getIntOrFloatBitWidth();
4711 if (desiredBitAlignment % eltBitwidth != 0) {
4712 desiredBitAlignment = eltBitwidth;
4713 }
4714
4715 gpu::CopyMappingInfo mapping(
4716 /*ctx=*/getContext(),
4717 /*totalNumThreads=*/getTotalNumThreads(),
4718 /*alignment=*/desiredBitAlignment,
4719 /*sizes=*/resultShapedType.getShape(),
4720 /*favorPredication=*/false,
4721 /*elementalBitwidth=*/
4722 resultShapedType.getElementType().getIntOrFloatBitWidth());
4723 if (mapping.status == gpu::CopyMappingInfo::Status::Invalid) {
4724 DiagnosedSilenceableFailure diag =
4725 emitSilenceableError()
4726 << "too few threads to map copy op to threads on the most minor "
4727 "dimension, given alignment and vector size constraints, try "
4728 "smaller tile size of mapping to more threads";
4729 diag.attachNote(target->getLoc()) << "target op";
4730 return diag;
4731 }
4732
4733 // OpBuilder only used to compute attributes.
4734 OpBuilder b(getContext());
4735 scf::SCFTilingResult tilingResult;
4736 DiagnosedSilenceableFailure diag = tileToForallOpImpl(
4737 /*rewriter=*/rewriter,
4738 /*state=*/state,
4739 /*transformOp=*/*this,
4740 /*target=*/target,
4741 /*mixedNumThreads=*/getMixedValues(mapping.numThreads, {}, b),
4742 /*mixedTileSizes=*/ArrayRef<OpFoldResult>{},
4743 /*mapping=*/b.getArrayAttr(mapping.threadMapping),
4744 /*tilingResult=*/tilingResult);
4745 if (!diag.succeeded())
4746 return diag;
4747
4748 results.push_back(tilingResult.loops.front());
4749 for (auto *op : tilingResult.tiledOps)
4750 results.push_back(op);
4752}
4753
4754//===----------------------------------------------------------------------===//
4755// WinogradConv2DOp
4756//===----------------------------------------------------------------------===//
4757
4758DiagnosedSilenceableFailure transform::WinogradConv2DOp::applyToOne(
4759 transform::TransformRewriter &rewriter, linalg::LinalgOp target,
4760 transform::ApplyToEachResultList &results,
4761 transform::TransformState &state) {
4762 rewriter.setInsertionPoint(target);
4763 FailureOr<Operation *> maybeTransformed = failure();
4764 bool supported = TypeSwitch<Operation *, bool>(target)
4765 .Case([&](linalg::Conv2DNhwcFhwcOp op) {
4766 maybeTransformed =
4767 winogradConv2D(rewriter, op, getFmr());
4768 return true;
4769 })
4770 .Default([&](Operation *op) { return false; });
4771
4772 if (!supported) {
4773 return emitSilenceableError()
4774 << "this operation is not supported to convert to Winograd Conv2D";
4775 }
4776
4777 if (failed(maybeTransformed)) {
4778 return emitSilenceableError() << "apply Winograd Conv2D failed";
4779 }
4780
4781 results.push_back(*maybeTransformed);
4783}
4784
4785DiagnosedSilenceableFailure transform::DecomposeWinogradOp::applyToOne(
4786 transform::TransformRewriter &rewriter, Operation *target,
4787 transform::ApplyToEachResultList &results,
4788 transform::TransformState &state) {
4789 rewriter.setInsertionPoint(target);
4790 FailureOr<Operation *> maybeTransformed = failure();
4791 bool supported =
4793 .Case([&](linalg::WinogradFilterTransformOp op) {
4794 maybeTransformed = decomposeWinogradFilterTransformOp(rewriter, op);
4795 return true;
4796 })
4797 .Case([&](linalg::WinogradInputTransformOp op) {
4798 maybeTransformed = decomposeWinogradInputTransformOp(rewriter, op);
4799 return true;
4800 })
4801 .Case([&](linalg::WinogradOutputTransformOp op) {
4802 maybeTransformed = decomposeWinogradOutputTransformOp(rewriter, op);
4803 return true;
4804 })
4805 .Default(false);
4806
4807 if (!supported) {
4808 DiagnosedSilenceableFailure diag =
4809 emitSilenceableError()
4810 << "this operation is not supported to decompose into other operations";
4811 diag.attachNote(target->getLoc()) << "target op";
4812 return diag;
4813 }
4814
4815 if (failed(maybeTransformed)) {
4816 DiagnosedSilenceableFailure diag =
4817 emitSilenceableError() << "decompose Winograd operations failed";
4818 diag.attachNote(target->getLoc()) << "target op";
4819 return diag;
4820 }
4821
4822 results.push_back(*maybeTransformed);
4824}
4825
4826#include "mlir/Dialect/Linalg/TransformOps/LinalgTransformOpsEnums.cpp.inc"
4827
4828#define GET_OP_CLASSES
4829#include "mlir/Dialect/Linalg/TransformOps/LinalgTransformOps.cpp.inc"
for(Operation *op :ops)
return success()
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
static SmallVector< Value > denormalizeIndVar(RewriterBase &rewriter, Location loc, ValueRange ivs, ArrayRef< OpFoldResult > lbs, ArrayRef< OpFoldResult > steps)
When a loop is normalized, the uses of the induction variable within the loop need to replaced with o...
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static LogicalResult applyTilingToAll(RewriterBase &rewriter, Operation *transformOp, Range &&payloadOps, unsigned numLoops, transform::TransformResults &transformResults, bool packedResults, function_ref< FailureOr< scf::SCFTileAndFuseResult >(TilingInterface)> applyFn)
Apply a tiling transformation to all payload ops and store both the tiled operation as well as the cr...
static Operation * cloneAndFuseFirstUse(RewriterBase &rewriter, Diagnostic &diag, Operation *producerOp, Operation *containingOp)
static DiagnosedSilenceableFailure reifyMixedParamAndHandleResults(TransformState &state, TransformOpInterface &transformOp, ArrayRef< OpFoldResult > mixedResults, SmallVectorImpl< int64_t > &reified)
When possible, converts each OpFoldResult in mixedResult to an integer if the value can be statically...
static DiagnosedSilenceableFailure unpackSingleIndexResultPayloadOperations(transform::TransformState &state, TransformOpInterface transformOp, SmallVector< OpFoldResult > &result, ArrayRef< OpFoldResult > ofrs)
Assuming that ofr is an index attr or a param of index type or a transform dialect handle mapped to e...
static SmallVector< OpFoldResult > normalizeUpperBounds(RewriterBase &rewriter, Location loc, ArrayRef< OpFoldResult > lbs, ArrayRef< OpFoldResult > ubs, ArrayRef< OpFoldResult > steps)
Given lbs, ubs and steps of loops, return (for each loop), the normalized upper bound.
static scf::ForallOp normalizeForallLoopOp(RewriterBase &rewriter, scf::ForallOp loop)
Given a scf.forall loop return a loop op with the loop bounds normalized. TODO: Replace this with a g...
ArrayAttr()
static bool mayBeRead(OpOperand &operand)
Return true if the operand may be read from by its owner.
static void printMultitileSizesTypes(OpAsmPrinter &printer, Operation *op, Type targetType, Type lowSizeType, Type, Type)
static bool sameOrEquivalentIterArg(Value src, Value dst)
Given two operands coming from a loop iter arg, 'src' and 'dst', return true if the operand 'src' is ...
static SmallVector< Operation * > tileAndFuseFirstExtractUseThroughContainingOpBlockArgument(RewriterBase &rewriter, Diagnostic &diag, Operation *producerOp, Operation *containingOp, ArrayRef< InnerTileAlignment > innerTileAlignments)
First, find the first "scf::ForallOp" user of producerOp and ensure it is exactly the containingOp,...
static ParseResult parseContinuousTileSizeTypes(OpAsmParser &parser, Type &targetType, Type &tileSizesType, Type &chunkSizesType)
static Operation * replaceForAllWithNewSignature(RewriterBase &rewriter, Diagnostic &diag, Operation *producerOp, Operation *containingOp, TilingResult &tileAndFuseResult, int64_t resultNumber, SmallVector< OpFoldResult > &offsets, SmallVector< OpFoldResult > &sizes)
Add new operands to the forall op for users of the producerOp that are dominated by the containing sc...
static ParseResult parseMultitileSizesTypes(OpAsmParser &parser, Type &targetType, Type &lowSizeType, Type &highSizeType, Type &splitPointType)
static void printContinuousTileSizeTypes(OpAsmPrinter &printer, Operation *op, Type targetType, Type tileSizes, Type)
static DiagnosedSilenceableFailure doit(RewriterBase &rewriter, OpTy target, transform::ApplyToEachResultList &results, transform::TransformState &state)
static std::tuple< SmallVector< Operation * >, Operation * > tileAndFuseFirstExtractUse(RewriterBase &rewriter, Diagnostic &diag, Operation *producerOp, Operation *containingOp, ArrayRef< InnerTileAlignment > innerTileAlignments)
Find the first "extract" user of producerOp and tile it right before its use.
b getContext())
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
memberIdxs push_back(ArrayAttr::get(parser.getContext(), values))
static llvm::ManagedStatic< PassManagerOptions > options
static void getDynamicSizes(RankedTensorType tp, ValueRange sizes, SmallVectorImpl< Value > &dynSizes)
Collects the dynamic dimension sizes for tp with the assumption that sizes are the dimension sizes fo...
static SmallVector< Value > getTileSizes(Location loc, x86::amx::TileType tType, RewriterBase &rewriter)
Maps the 2-dim vector shape to the two 16-bit tile sizes.
Base type for affine expression.
Definition AffineExpr.h:68
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
UnitAttr getUnitAttr()
Definition Builders.cpp:106
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:175
AffineExpr getAffineSymbolExpr(unsigned position)
Definition Builders.cpp:377
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:120
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition Builders.h:94
MLIRContext * getContext() const
Definition Builders.h:56
DenseBoolArrayAttr getDenseBoolArrayAttr(ArrayRef< bool > values)
Tensor-typed DenseArrayAttr getters.
Definition Builders.cpp:159
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:290
IndexType getIndexType()
Definition Builders.cpp:59
ArrayAttr getStrArrayAttr(ArrayRef< StringRef > values)
Definition Builders.cpp:315
The result of a transform IR operation application.
static DiagnosedSilenceableFailure success()
Constructs a DiagnosedSilenceableFailure in the success state.
bool isDefiniteFailure() const
Returns true if this is a definite failure.
Diagnostic & attachNote(std::optional< Location > loc=std::nullopt)
Attaches a note to the last diagnostic.
static DiagnosedSilenceableFailure silenceableFailure(Diagnostic &&diag)
Constructs a DiagnosedSilenceableFailure in the silenceable failure state, ready to emit the given di...
bool succeeded() const
Returns true if this is a success.
static DiagnosedSilenceableFailure definiteFailure()
Constructs a DiagnosedSilenceableFailure in the failure state.
bool isSilenceableFailure() const
Returns true if this is a silenceable failure.
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
A class for computing basic dominance information.
Definition Dominance.h:143
bool dominates(Operation *a, Operation *b) const
Return true if operation A dominates operation B, i.e.
Definition Dominance.h:161
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
IRValueT get() const
Return the current value being used by this operand.
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:71
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
virtual OptionalParseResult parseOptionalOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single operand if present.
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
void printFunctionalType(Operation *op)
Print the complete type of an operation in functional form.
bool isSet() const
Returns true if this insert point is set.
Definition Builders.h:340
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:581
void setListener(Listener *newListener)
Sets the listener of this builder to the one provided.
Definition Builders.h:319
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
Definition Builders.h:323
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
This class represents a single result from folding an operation.
This class represents an operand of an operation.
Definition Value.h:256
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
Definition Value.cpp:231
This is a value defined by a result of an operation.
Definition Value.h:456
StringRef getStringRef() const
Return the name of this operation. This always succeeds.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns a null Attribute if the discardable attribute does no...
Definition Operation.h:487
OpResult getOpResult(unsigned idx)
Definition Operation.h:448
void setOperand(unsigned idx, Value value)
Definition Operation.h:378
bool hasOneUse()
Returns true if this operation has exactly one use.
Definition Operation.h:903
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
std::optional< Attribute > getInherentAttr(StringRef name)
Access an inherent attribute by name: returns an empty optional if there is no inherent attribute wit...
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
operand_type_range getOperandTypes()
Definition Operation.h:424
result_type_range getResultTypes()
Definition Operation.h:455
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
Definition Operation.h:288
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
user_range getUsers()
Returns a range of all users.
Definition Operation.h:927
result_range getOpResults()
Definition Operation.h:447
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:247
bool isProperAncestor(Operation *other)
Return true if this operation is a proper ancestor of the other operation.
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
bool has_value() const
Returns true if we contain a valid ParseResult value.
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 eraseBlock(Block *block)
This method erases all operations in a block.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void replaceAllUsesExcept(Value from, Value to, Operation *exceptedUser)
Find uses of from and replace them with to except if the user is exceptedUser.
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
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,...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
virtual bool replaceUsesWithIf(Value from, Value to, function_ref< bool(OpOperand &)> functor, bool *allUsesReplaced=nullptr)
Find uses of from and replace them with to if the functor returns true.
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIndex() const
Definition Types.cpp:56
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
Type front()
Return first type in the range.
Definition TypeRange.h:164
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
bool use_empty() const
Returns true if this value has no uses.
Definition Value.h:208
Type getType() const
Return the type of this value.
Definition Value.h:105
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition Value.h:188
user_range getUsers() const
Definition Value.h:218
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:436
State for analysis-enabled bufferization.
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
A list of results of applying a transform op with ApplyEachOpTrait to a single payload operation,...
void assign(unsigned size, std::nullptr_t)
Sets the list of results to size null pointers.
void reserve(unsigned size)
Reserves space for size elements in the list.
size_t size() const
Returns the number of elements in the list.
void push_back(Operation *op)
Appends an element to the list.
Local mapping between values defined by a specific op implementing the TransformOpInterface and the p...
void setValues(OpResult handle, Range &&values)
Indicates that the result of the transform IR op at the given position corresponds to the given range...
void setParams(OpResult value, ArrayRef< TransformState::Param > params)
Indicates that the result of the transform IR op at the given position corresponds to the given list ...
void set(OpResult value, Range &&ops)
Indicates that the result of the transform IR op at the given position corresponds to the given list ...
This is a special rewriter to be used in transform op implementations, providing additional helper fu...
LogicalResult notifyPayloadOperationReplaced(Operation *op, Operation *replacement)
Notify the transform dialect interpreter that the given op has been replaced with another op and that...
The state maintained across applications of various ops implementing the TransformOpInterface.
auto getPayloadOps(Value value) const
Returns an iterator that enumerates all ops that the given transform IR value corresponds to.
auto getPayloadValues(Value handleValue) const
Returns an iterator that enumerates all payload IR values that the given transform IR value correspon...
ArrayRef< Attribute > getParams(Value value) const
Returns the list of parameters that the given transform IR value corresponds to.
AffineApplyOp makeComposedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Returns a composed AffineApplyOp by composing map and operands with other AffineApplyOps supplying th...
SmallVector< OpFoldResult > makeComposedFoldedMultiResultAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Variant of makeComposedFoldedAffineApply suitable for multi-result maps.
OpFoldResult makeComposedFoldedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Constructs an AffineApplyOp that applies map to operands after composing the map with the maps of any...
LogicalResult analyzeOp(Operation *op, OneShotAnalysisState &state, BufferizationStatistics *statistics=nullptr)
Analyze op and its nested ops.
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition Matchers.h:344
FailureOr< PackingResult > buildPackingLoopNest(RewriterBase &rewriter, tensor::PadOp opToHoist, scf::ForOp outermostEnclosingForOp, ArrayRef< int64_t > transposeVector)
Build the packing loop nest required to hoist opToHoist above outermostEnclosingForOp.
void populateDataLayoutPropagationPatterns(RewritePatternSet &patterns, const ControlPropagationFn &controlPackUnPackPropagation, bool PoisonPaddingOk=false)
Patterns to bubble up or down data layout ops across other operations.
LogicalResult rewriteAsPaddedOp(RewriterBase &rewriter, LinalgOp opToPad, const LinalgPaddingOptions &options, LinalgOp &paddedOp, SmallVector< Value > &replacements, SmallVector< tensor::PadOp > &padOps)
Pad the iterator dimensions options.paddingDimensions of all opToPad operands to a static bounding bo...
Definition Padding.cpp:244
FailureOr< std::pair< Operation *, Operation * > > rewriteInIm2Col(RewriterBase &rewriter, linalg::Conv2DNhwcHwcfOp convOp)
Convert linalg.conv_2d_nhwc_hwcf into linalg.generic (for img2col packing) and linalg....
bool hasVectorizationImpl(Operation *)
Return true if there's dedicated logic in the Linalg Vectorizer to vectorize this Op,...
void populateExtractSliceSinkingPatterns(RewritePatternSet &patterns, const ControlPropagationFn &controlPackUnPackPropagation)
Patterns to sink extract slice across other operations.
FailureOr< Operation * > decomposeWinogradFilterTransformOp(RewriterBase &rewriter, linalg::WinogradFilterTransformOp op)
Rewrite linalg.winograd_filter_transform.
std::optional< Value > allocateWorkgroupMemory(OpBuilder &builder, memref::SubViewOp subview, ArrayRef< Value > sizeBounds, DataLayout &)
Allocate the subview in the GPU workgroup memory.
FailureOr< PackTransposeResult > packTranspose(RewriterBase &rewriter, linalg::PackOp packOp, linalg::LinalgOp linalgOp, linalg::UnPackOp maybeUnPackOp, ArrayRef< int64_t > outerPerm, ArrayRef< int64_t > innerPerm)
Transpose a single PackOp -> LinalgOp -> UnPackOp chain and return the transposed PackOp -> LinalgOp ...
Value bufferizeToAllocation(RewriterBase &rewriter, const BufferizeToAllocationOptions &options, tensor::PadOp padOp, Attribute memorySpace={}, Operation *insertionPoint=nullptr)
Materialize a buffer allocation for the given tensor.pad op and lower the op to linalg....
FailureOr< VectorizationResult > vectorize(RewriterBase &rewriter, Operation *op, ArrayRef< int64_t > inputVectorSizes={}, ArrayRef< bool > inputScalableVecDims={}, bool vectorizeNDExtract=false, bool flatten1DDepthwiseConv=false, bool assumeDynamicDimsMatchVecSizes=false, bool createNamedContraction=false)
Returns a VectorizationResult containing the results of the vectorized op, or failure if the transfor...
FailureOr< Value > hoistPaddingOnTensors(RewriterBase &rewriter, tensor::PadOp opToHoist, int64_t numLoops, ArrayRef< int64_t > transposeVector, tensor::PadOp &hoistedOp, SmallVectorImpl< TransposeOp > &transposeOps)
Mechanically hoist padding operations on tensors by numLoops into a new, generally larger tensor.
FailureOr< LowerUnPackOpResult > lowerUnPack(RewriterBase &rewriter, linalg::UnPackOp unPackOp, bool lowerUnpadLikeWithExtractSlice=true)
Rewrite pack as empty + transpose + reshape + extract_slice + copy.
void populatePadOpVectorizationPatterns(RewritePatternSet &patterns, PatternBenefit baseBenefit=1)
Populates patterns with patterns that vectorize tensor.pad.
void populateLinalgTilingCanonicalizationPatterns(RewritePatternSet &patterns)
Canonicalization patterns relevant to apply after tiling patterns.
Definition Tiling.cpp:866
LogicalResult deallocateGPUPrivateMemory(OpBuilder &, Value)
In case of GPU private memory there is no need to deallocate since the memory is freed when going out...
FailureOr< Operation * > decomposeWinogradOutputTransformOp(RewriterBase &rewriter, linalg::WinogradOutputTransformOp op)
Rewrite linalg.winograd_output_transform.
std::function< SplitReductionOptions(LinalgOp op)> ControlSplitReductionFn
Function signature to control reduction splitting.
Definition Transforms.h:489
std::optional< Value > allocateGPUPrivateMemory(OpBuilder &builder, memref::SubViewOp subview, ArrayRef< Value > sizeBounds, DataLayout &)
Allocate the subview in the GPU private memory.
FailureOr< Operation * > rewriteInDestinationPassingStyle(RewriterBase &rewriter, tensor::FromElementsOp fromElementsOp)
Rewrite tensor.from_elements to linalg.generic.
FailureOr< Operation * > winogradConv2D(RewriterBase &rewriter, linalg::Conv2DNhwcFhwcOp op, WinogradConv2DFmr fmr)
Convert linalg.conv_2d_nhwc_fhwc to Winograd Conv2D algorithm F(m x m, r x r).
FailureOr< Operation * > transposeConv2D(RewriterBase &rewriter, linalg::Conv2DNhwcFhwcOp op)
Convert linalg.conv_2d_nhwc_fhwc(_q) to linalg.conv_2d_nhwc_hwcf(_q) by materializing transpose.
void populateFoldUnitExtentDimsPatterns(RewritePatternSet &patterns, ControlDropUnitDims &options)
Patterns to fold unit-extent dimensions in operands/results of linalg ops on tensors and memref.
LogicalResult copyToWorkgroupMemory(OpBuilder &b, Value src, Value dst)
Create Memref copy operations and add gpu barrier guards before and after the copy operation to ensur...
FailureOr< LinalgOp > generalizeNamedOp(RewriterBase &rewriter, LinalgOp linalgOp, bool emitCategoryOps=false)
Create a GenericOp or CategoryOp from the given named operation linalgOp and replace the given linalg...
LogicalResult linalgOpAnchoredEmptyTensorEliminationStep(RewriterBase &rewriter, Operation *op, bufferization::OneShotAnalysisState &state)
Try to eliminate tensor::EmptyOps inside op that are anchored on a LinalgOp.
FailureOr< Operation * > transposeBatchMatmul(RewriterBase &rewriter, linalg::BatchMatmulOp op, bool transposeLHS=true)
Pattern to replace.
FailureOr< LinalgOp > specializeGenericOp(RewriterBase &rewriter, GenericOp genericOp, bool emitCategoryOps=false)
Replace the given GenericOp with a namedOp or categoryOp.
LogicalResult promoteSubviewsPrecondition(Operation *op, LinalgPromotionOptions options)
Promote memref.subviews feeding linalg-on-buffers operations.
LogicalResult copyToGPUPrivateMemory(OpBuilder &b, Value src, Value dst)
Normal copy to between src and dst.
bool isElementwise(LinalgOp op)
Check if a LinalgOp is an element-wise operation.
Definition Utils.cpp:217
FailureOr< GenericOp > interchangeGenericOp(RewriterBase &rewriter, GenericOp genericOp, ArrayRef< unsigned > interchangeVector)
Interchange the iterator_types and iterator_maps dimensions and adapts the index accesses of op.
FailureOr< StaticMultiSizeSpecification > computeStaticMultiTileSizes(LinalgOp op, unsigned dimension, int64_t targetSize, int64_t divisor)
Definition Tiling.cpp:236
void populateDecomposePackUnpackPatterns(RewritePatternSet &patterns)
Populates patterns to decompose linalg.pack and linalg.unpack Ops into e.g.
void populateEraseUnusedOperandsAndResultsPatterns(RewritePatternSet &patterns)
Pattern to remove dead operands and results of linalg.generic operations.
std::function< bool(OpOperand *fusedOperand)> ControlFusionFn
Function type which is used to control when to stop fusion.
FailureOr< ContinuousTileSizeSpecification > computeContinuousTileSizes(OpBuilder &builder, TilingInterface op, unsigned dimension, OpFoldResult targetSize, bool emitAssertions)
Definition Tiling.cpp:156
FailureOr< StaticContinuousTileSizeSpecification > computeStaticContinuousTileSizes(LinalgOp op, unsigned dimension, unsigned targetSize)
Definition Tiling.cpp:106
FailureOr< SplitReductionResult > splitReduction(RewriterBase &b, LinalgOp op, const ControlSplitReductionFn &controlSplitReductionFn, bool useAlloc=false)
void populateFoldPackUnpackIntoTensorEmptyPatterns(RewritePatternSet &patterns)
Populates patterns with patterns that fold operations like linalg.pack and linalg....
void populateFoldIntoPackAndUnpackPatterns(RewritePatternSet &patterns, const ControlFoldIntoPackUnpackFn &controlFn=nullptr)
Populates patterns with patterns that fold operations like tensor.pad and tensor.extract_slice into t...
void hoistRedundantVectorBroadcasts(RewriterBase &rewriter, Operation *root)
Hoist vector.extract/vector.broadcast pairs out of immediately enclosing scf::ForOp iteratively,...
Definition Hoisting.cpp:91
FailureOr< PackResult > packMatmulGreedily(RewriterBase &rewriter, LinalgOp linalgOp, ArrayRef< OpFoldResult > mnkPackedSizes, ArrayRef< int64_t > mnkPaddedSizesNextMultipleOf, ArrayRef< int64_t > mnkOrder)
Pack a LinalgOp by greedily inferring matmul dimensions (m, n, k) where m and n are proper parallel d...
FailureOr< PackResult > pack(RewriterBase &rewriter, linalg::LinalgOp linalgOp, ArrayRef< OpFoldResult > packedSizes)
Implement packing of a single LinalgOp by packedSizes.
void populateEraseUnnecessaryInputsPatterns(RewritePatternSet &patterns)
Patterns to promote inputs to outputs and remove unused inputs of linalg.generic ops.
void populateFoldReshapeOpsByExpansionPatterns(RewritePatternSet &patterns, const ControlFusionFn &controlFoldingReshapes)
Patterns to fold an expanding (collapsing) tensor_reshape operation with its producer (consumer) gene...
std::function< bool(OpOperand *opOperand)> ControlPropagationFn
Function type which is used to control propagation of linalg.pack/unpack ops.
void populateSwapExtractSliceWithFillPatterns(RewritePatternSet &patterns)
Adds patterns that waps tensor.extract_slice(linalg.fill(cst, init)) into linalg.fill(cst,...
FailureOr< LinalgOp > promoteSubViews(OpBuilder &b, LinalgOp op, const LinalgPromotionOptions &options)
Promote the subViews into a new buffer allocated at the insertion point b.
LogicalResult deallocateWorkgroupMemory(OpBuilder &, Value)
In case of GPU group memory there is no need to deallocate.
FailureOr< Operation * > transposeMatmul(RewriterBase &rewriter, linalg::MatmulOp op, bool transposeLHS=true)
Convert Linalg matmul ops to transposed variants.
FailureOr< CollapseResult > collapseOpIterationDims(LinalgOp op, ArrayRef< ReassociationIndices > foldedIterationDims, RewriterBase &rewriter)
Collapses dimensions of linalg.generic/linalg.copy operation.
void hoistRedundantVectorTransfers(Operation *root, bool verifyNonZeroTrip=false)
Hoist vector.transfer_read/vector.transfer_write on buffers pairs out of immediately enclosing scf::F...
Definition Hoisting.cpp:166
FailureOr< Operation * > decomposeWinogradInputTransformOp(RewriterBase &rewriter, linalg::WinogradInputTransformOp op)
Rewrite linalg.winograd_input_transform.
void populateDecomposePadPatterns(RewritePatternSet &patterns)
Populates patterns to decompose tensor.pad into e.g.
void populateFoldAddIntoDestPatterns(RewritePatternSet &patterns)
Pattern to replace linalg.add when destination passing on a contraction op suffices for achieving the...
std::pair< TilingInterface, TilingInterface > splitOp(RewriterBase &rewriter, TilingInterface op, unsigned dimension, OpFoldResult splitPoint)
Split the given op into two parts along the given iteration space dimension at the specified splitPoi...
Definition Split.cpp:68
FailureOr< SplitReductionResult > splitReductionByScaling(RewriterBase &b, LinalgOp op, const ControlSplitReductionFn &controlSplitReductionFn, bool useAlloc=false)
Scaling-based implementation of the split reduction transformation.
FailureOr< MultiSizeSpecification > computeMultiTileSizes(OpBuilder &builder, LinalgOp op, unsigned dimension, OpFoldResult targetSize, OpFoldResult divisor, bool emitAssertions=true)
Emits the IR computing the multi-sized tiling specification with two tile sizes not exceeding targetS...
Definition Tiling.cpp:262
FailureOr< LinalgOp > downscaleSizeOneWindowedConvolution(RewriterBase &rewriter, LinalgOp op)
Rewrite convolution/pooling/depthwise ops with size-1 window dimensions into lower-dimensional ops.
FailureOr< LowerPackResult > lowerPack(RewriterBase &rewriter, linalg::PackOp packOp, bool lowerPadLikeWithInsertSlice=true)
Rewrite pack as pad + reshape + transpose.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
ForOp getForInductionVarOwner(Value val)
Returns the loop parent of an induction variable.
Definition SCF.cpp:678
void populateMergeConsecutiveInsertExtractSlicePatterns(RewritePatternSet &patterns)
Collects patterns to merge consecutive tensor.insert_slice/extract_slice into one.
void populateBubbleUpExtractSliceOpPatterns(RewritePatternSet &patterns)
Appends patterns that are used to bubble up tensor.extract slice op above its producer.
OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value, int64_t dim)
Return the dimension of the given tensor value.
Definition TensorOps.cpp:82
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Definition TensorOps.cpp:91
LogicalResult getOrCreateDestinations(OpBuilder &b, Location loc, Operation *op, SmallVector< Value > &result)
This is a helper function for DestinationStyleOpInterface.
void populateFoldTensorSubsetIntoVectorTransferPatterns(RewritePatternSet &patterns)
Appends patterns for folding tensor subset ops into vector transfer ops.
void onlyReadsPayload(SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
void producesHandle(ResultRange handles, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
DiagnosedSilenceableFailure tileToForallOpImpl(RewriterBase &rewriter, transform::TransformState &state, TransformOpInterface transformOp, Operation *target, ArrayRef< OpFoldResult > mixedNumThreads, ArrayRef< OpFoldResult > mixedTileSizes, std::optional< ArrayAttr > mapping, scf::SCFTilingResult &tilingResult, ArrayRef< bool > scalableSizes={})
Implementation of tiling operations using scf.forall.
void consumesHandle(MutableArrayRef< OpOperand > handles, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Populates effects with the memory effects indicating the operation on the given handle value:
void onlyReadsHandle(MutableArrayRef< OpOperand > handles, SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
void modifiesPayload(SmallVectorImpl< MemoryEffects::EffectInstance > &effects)
Populates effects with the memory effects indicating the access to payload IR resource.
detail::poison_attr_matcher m_Poison()
Matches a poison constant (any attribute implementing PoisonAttrInterface).
Definition UBMatchers.h:46
void populateVectorTransferPermutationMapLoweringPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Collect a set of transfer read/write lowering patterns that simplify the permutation map (e....
void populateVectorReductionToContractPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1, bool allowFastMathFlagLoss=true)
Collect patterns to convert reduction op to vector.contract and fold transpose/broadcast ops into the...
void populateFoldArithExtensionPatterns(RewritePatternSet &patterns)
Collect a set of patterns that fold arithmetic extension on floating point into vector contract for t...
void populateSinkVectorOpsPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Patterns that remove redundant Vector Ops by re-ordering them with e.g.
void populateVectorStepLoweringPatterns(RewritePatternSet &patterns, unsigned indexBitwidth=64, PatternBenefit benefit=1)
Populate the pattern set with the following patterns:
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
SmallVector< OpFoldResult > getMixedValues(ArrayRef< int64_t > staticValues, ValueRange dynamicValues, MLIRContext *context)
Return a vector of OpFoldResults with the same size a staticValues, but all elements for which Shaped...
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
SmallVector< InnerTileAlignment > convertInnerTileAlignments(ArrayRef< int64_t > alignments)
Maps a validated inner_tile_alignments integer array onto the per-dimension InnerTileAlignment hints ...
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition AffineExpr.h:313
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...
DiagnosedSilenceableFailure emitSilenceableFailure(Location loc, const Twine &message={})
Emits a silenceable failure with the given message.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
Attribute parseAttribute(llvm::StringRef attrStr, MLIRContext *context, Type type={}, size_t *numRead=nullptr, bool isKnownNullTerminated=false)
This parses a single MLIR attribute to an MLIR context if it was valid.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
DiagnosedDefiniteFailure emitDefiniteFailure(Location loc, const Twine &message={})
Emits a definite failure with the given message.
LogicalResult verifyInnerTileAlignments(Operation *op, ArrayRef< int64_t > alignments)
Verifies that every entry of a raw inner_tile_alignments integer array is a valid InnerTileAlignment,...
FailureOr< SCFTileAndFuseResult > tileConsumerAndFuseProducersUsingSCF(RewriterBase &rewriter, TilingInterface consumer, const SCFTileAndFuseOptions &options)
Method to tile and fuse a sequence of operations, by tiling the consumer and fusing its producers.
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
bool isZeroInteger(OpFoldResult v)
Return "true" if v is an integer value/attribute with constant value 0.
void bindSymbols(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to SymbolExpr at positions: [0 .
Definition AffineExpr.h:327
void dispatchIndexOpFoldResults(ArrayRef< OpFoldResult > ofrs, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch multiple OpFoldResults according to the behavior of dispatchIndexOpFoldRe...
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:114
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
SmallVector< int64_t, 2 > ReassociationIndices
Definition Utils.h:27
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
SmallVector< IntTy > extractFromIntegerArrayAttr(Attribute attr)
Extract integer values from the assumed ArrayAttr of IntegerAttr.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
bool isPermutationVector(ArrayRef< int64_t > interchange)
Method to check if an interchange vector is a permutation.
bool isOneInteger(OpFoldResult v)
Return true if v is an IntegerAttr with value 1.
FailureOr< SCFTilingResult > tileUsingSCF(RewriterBase &rewriter, TilingInterface op, const SCFTilingOptions &options)
Method to tile an op that implements the TilingInterface using scf.for for iterating over the tiles.
SetVector< Operation * > topologicalSort(const SetVector< Operation * > &toSort)
Sorts all operations in toSort topologically while also considering region semantics.
This class represents a listener that may be used to hook into various actions within an OpBuilder.
Definition Builders.h:288
This represents an operation in an abstracted form, suitable for use with the builder APIs.
Represents a range (offset, size, and stride) where each element of the triple may be dynamic or stat...
A listener that forwards all notifications to another listener.
ForwardingListener(OpBuilder::Listener *listener)
Container for result values of tiling.
SmallVector< Value > tiledValues
Options for analysis-enabled bufferization.
Transformation to drop unit-extent dimensions from linalg.generic operations.
Definition Transforms.h:521
LinalgPromotionOptions & setUseFullTileBuffers(ArrayRef< bool > useFullTiles)
Definition Transforms.h:409
LinalgPromotionOptions & setAllocationDeallocationFns(AllocBufferCallbackFn const &allocFn, DeallocBufferCallbackFn const &deallocFn)
Definition Transforms.h:456
LinalgPromotionOptions & setAlignment(unsigned align)
Definition Transforms.h:433
LinalgPromotionOptions & setMemorySpace(Attribute memorySpc)
Definition Transforms.h:440
LinalgPromotionOptions & setOperandsToPromote(ArrayRef< int64_t > operands)
Definition Transforms.h:398
LinalgPromotionOptions & setUseFullTileBuffersByDefault(bool use)
Definition Transforms.h:420
LinalgPromotionOptions & setUseOriginalSubviewSize(bool originalSize)
Definition Transforms.h:427
LinalgPromotionOptions & setUseAlloca(bool use)
Definition Transforms.h:446
LinalgPromotionOptions & setCopyInOutFns(CopyCallbackFn const &copyIn, CopyCallbackFn const &copyOut)
Definition Transforms.h:466