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"
56#define DEBUG_TYPE "linalg-transforms"
65 if (
auto attr = dyn_cast<Attribute>(ofr)) {
66 if (!isa<IntegerAttr>(attr))
67 return transformOp.emitDefiniteFailure() <<
"expected IntegerAttr";
72 Value transformValue = cast<Value>(ofr);
73 if (isa<TransformParamTypeInterface>(transformValue.
getType())) {
75 if (params.size() != 1)
76 return transformOp.emitDefiniteFailure()
77 <<
"requires exactly one parameter associated";
78 result.push_back(params[0]);
83 if (!llvm::hasSingleElement(payloadOps)) {
85 transformOp.emitSilenceableError()
86 <<
"handle must be mapped to exactly one payload op";
88 <<
"mapped to " << llvm::range_size(payloadOps) <<
" payload ops";
95 transformOp.emitSilenceableError()
96 <<
"payload op must have exactly 1 index result";
116 if (isa<TransformParamTypeInterface>(packedHandle.
getType())) {
118 for (
auto param : params) {
119 if (!isa<IntegerAttr>(param))
120 return transformOp.emitDefiniteFailure()
121 <<
"expected the parameter to be associated with an integer "
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";
137 result.push_back(op->getResult(0));
151 if (
auto attr = dyn_cast<Attribute>(paramOrHandle)) {
152 reified.push_back(cast<IntegerAttr>(attr).getInt());
155 if (isa<TransformParamTypeInterface>(
156 cast<Value>(paramOrHandle).
getType())) {
158 if (params.size() != 1)
159 return transformOp.emitSilenceableError() <<
"expected a single param";
161 cast<IntegerAttr>(params.front()).getValue().getSExtValue());
165 Value handle = cast<Value>(paramOrHandle);
166 if (!isa<TransformHandleTypeInterface>(handle.getType()))
167 return transformOp.emitSilenceableError() <<
"unexpected value handle";
169 if (!llvm::hasSingleElement(payload))
170 return transformOp.emitSilenceableError()
171 <<
"requires param or handle that is mapped to 1 payload op";
173 Operation *paramOrHandlePayloadOp = *payload.begin();
176 return transformOp.emitSilenceableError()
177 <<
"requires param or handle to be result of op with 1 index "
183 return transformOp.emitSilenceableError()
184 <<
"requires param or handle to be the result of a constant like "
187 reified.push_back(attr.getInt());
196void transform::ApplyEraseUnnecessaryInputsPatternsOp::populatePatterns(
201void transform::ApplyDecomposeTensorPackUnpackPatternsOp::populatePatterns(
206void transform::ApplyDecomposeTensorPadPatternsOp::populatePatterns(
211void transform::ApplyFoldUnitExtentDimsViaReshapesPatternsOp::populatePatterns(
217void transform::ApplyFoldUnitExtentDimsViaSlicesPatternsOp::populatePatterns(
220 options.rankReductionStrategy =
225void transform::ApplyTilingCanonicalizationPatternsOp::populatePatterns(
230void transform::ApplyFoldAddIntoDestPatternsOp::populatePatterns(
235void transform::ApplyPadVectorizationPatternsOp::populatePatterns(
240void transform::ApplyFoldIntoPackAndUnpackPatternsOp::populatePatterns(
245void transform::ApplyFoldPackUnpackIntoEmptyPatternsOp::populatePatterns(
250void transform::ApplyDataLayoutPropagationPatternsOp::populatePatterns(
259void transform::ApplyExtractSliceSinkingPatternsOp::populatePatterns(
263 Operation *producer = opOperand->get().getDefiningOp();
264 Operation *consumer = opOperand->getOwner();
270void transform::ApplySwapExtractSliceWithFillPatternsOp::populatePatterns(
275void transform::ApplyEraseUnusedOperandsAndResultsPatternsOp::populatePatterns(
280void transform::ApplyFoldReshapeOpsByExpansionPatternsOp::populatePatterns(
283 [foldSingleUseOnly = getFoldSingleUseOnly()](
OpOperand *fusedOperand) {
284 if (!foldSingleUseOnly)
286 Operation *producer = fusedOperand->get().getDefiningOp();
287 return producer && producer->
hasOneUse();
301 SmallVector<Operation *> getNewOps()
const {
302 return SmallVector<Operation *>(newOps.begin(), newOps.end());
306 void notifyOperationInserted(Operation *op,
307 OpBuilder::InsertPoint previous)
override {
308 ForwardingListener::notifyOperationInserted(op, previous);
310 if (previous.
isSet())
314 assert(
inserted.second &&
"expected newly created op");
317 void notifyOperationErased(Operation *op)
override {
318 ForwardingListener::notifyOperationErased(op);
319 op->
walk([&](Operation *op) { newOps.erase(op); });
331 llvm::scope_exit resetListener(
332 [&]() { rewriter.
setListener(previousListener); });
333 NewOpsListener newOpsListener(previousListener);
337 if (getMemcpyOp() ==
"bufferization.materialize_in_destination") {
338 options.memcpyOp = linalg::BufferizeToAllocationOptions::MemcpyOp::
339 MaterializeInDestination;
340 }
else if (getMemcpyOp() ==
"memref.copy") {
343 }
else if (getMemcpyOp() ==
"linalg.copy") {
347 llvm_unreachable(
"invalid memcpy op");
349 if (getAllocOp() ==
"memref.alloc") {
352 }
else if (getAllocOp() ==
"memref.alloca") {
356 llvm_unreachable(
"invalid alloc op");
358 options.bufferizeDestinationOnly = getBufferizeDestinationOnly();
359 options.emitDealloc = getEmitDealloc();
363 getMemorySpace().has_value() ? getMemorySpace().value() :
Attribute();
370 <<
"failed to bufferize operation";
371 diag.attachNote(op->
getLoc()) <<
"target payload op";
374 allocatedBuffers.push_back(buffer);
378 results.
setValues(cast<OpResult>(getAllocatedBuffer()), allocatedBuffers);
379 results.
set(cast<OpResult>(getNewOps()), newOpsListener.getNewOps());
383void transform::BufferizeToAllocationOp::getEffects(
385 if (getBufferizeDestinationOnly()) {
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";
413 auto linalgOp = dyn_cast<linalg::LinalgOp>(operand.
getOwner());
420 Value blockArgument = linalgOp.getMatchingBlockArgument(&operand);
428 if (!isa<TensorType, FloatType, IntegerType>(value.
getType()))
430 return llvm::any_of(value.
getUses(),
440 auto type = dyn_cast<RankedTensorType>(
tensor.getType());
442 return emitSilenceableError() <<
"non-tensor type: " <<
tensor;
456 for (
auto [pos, dim] : llvm::enumerate(type.getShape())) {
457 if (!ShapedType::isDynamic(dim))
462 tensor::DimOp::create(rewriter,
tensor.getLoc(),
tensor, cst);
463 preservedOps.insert(dimOp);
464 dynamicDims.push_back(dimOp);
466 auto allocation = bufferization::AllocTensorOp::create(
467 rewriter,
tensor.getLoc(), type, dynamicDims);
469 if (getMemorySpaceAttr())
470 allocation.setMemorySpaceAttr(getMemorySpaceAttr());
471 Value allocated = allocation;
475 if (needsMaterialization) {
476 auto copy = bufferization::MaterializeInDestinationOp::create(
478 preservedOps.insert(
copy);
479 promoted.push_back(
copy.getResult());
481 promoted.push_back(allocated);
485 results.
setValues(cast<OpResult>(getPromoted()), promoted);
489void transform::PromoteTensorOp::getEffects(
505 FailureOr<linalg::LinalgOp> res =
507 if (succeeded(res)) {
511 return emitDefaultSilenceableFailure(
target);
525 auto decomposableOp = dyn_cast<AggregatedOpInterface>(
target);
526 if (!decomposableOp) {
528 "payload is not a decomposable op");
529 return emitDefaultSilenceableFailure(
target);
532 FailureOr<SmallVector<Value>> maybeNewResults =
533 decomposableOp.decomposeOperation(rewriter);
534 if (
failed(maybeNewResults))
535 return emitDefaultSilenceableFailure(
target);
537 rewriter.
replaceOp(decomposableOp, *maybeNewResults);
538 for (
Value val : *maybeNewResults) {
539 Operation *definition = val.getDefiningOp();
550void transform::EliminateLinalgOpAnchoredEmptyTensorsOp::getEffects(
557transform::EliminateLinalgOpAnchoredEmptyTensorsOp::apply(
561 options.allowReturnAllocsFromLoops =
true;
567 <<
"failed to analyze op";
569 rewriter,
target, state)))
571 <<
"failed to eliminate LinalgOp anchored tensor.empty ops";
584 bool applyCleanup,
bool useForall) {
586 builder,
result, loopTypes,
592 applyCleanup, useForall);
598 bool applyCleanup,
bool useForall) {
606 applyCleanup, useForall);
613 bool applyCleanup,
bool useForall) {
617 build(builder,
result, loopTypes,
target, mixedTileSizes,
618 mixedTileInterchange, applyCleanup, useForall);
625 bool applyCleanup,
bool useForall) {
632 staticTileInterchange);
637 auto staticTileInterchangeAttr =
639 unsigned numExpectedLoops =
640 useForall ? 1 : staticTileSizes.size() - llvm::count(staticTileSizes, 0);
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]);
648 llvm::append_range(resultTypes, loopTypes);
653 dynamicTileInterchange,
656 staticTileInterchangeAttr,
664template <
typename Range>
669 function_ref<FailureOr<scf::SCFTileAndFuseResult>(TilingInterface)>
673 size_t numTargets = llvm::range_size(payloadOps);
676 auto tilingInterfaceOp = dyn_cast<TilingInterface>(
target);
677 if (!tilingInterfaceOp)
678 return transformOp->
emitError(
"only TilingInterface ops are supported");
681 FailureOr<scf::SCFTileAndFuseResult> tiledResults =
682 applyFn(tilingInterfaceOp);
683 if (failed(tiledResults))
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))
693 if (toReplace->use_empty()) {
699 tiledLinalgOps.push_back(tiledResults->tiledAndFusedOps.front());
700 assert(tiledResults->loops.size() == numLoops &&
701 "Mismatched number of loops, tile and fuse transform should have "
703 for (
unsigned int i = 0; i < numLoops; ++i)
704 loopOps[i].
push_back(tiledResults->loops[i]);
707 transformResults.
set(transformOp->
getOpResult(0), tiledLinalgOps);
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);
721 for (
unsigned int i = 0; i < numLoops; ++i)
722 transformResults.
set(transformOp->
getOpResult(i + 1), loopOps[i]);
732 auto transformOp = cast<TransformOpInterface>(getOperation());
738 state, transformOp, mixedTileSizes, getPackedTileSizes())
740 state, transformOp, mixedTileSizes, getMixedTileSizes());
745 state, transformOp, getMixedTileInterchange(), tileInterchange);
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);
760 tileAndFuseOptions.tilingOptions.setInnerTileAlignments(
763 if (getApplyCleanup()) {
766 tensor::ExtractSliceOp::getCanonicalizationPatterns(patterns, context);
769 tileAndFuseOptions.cleanupPatterns = std::move(patterns);
776 numLoops = llvm::count_if(mixedTileSizes, [](
OpFoldResult ofr) {
777 auto attr = dyn_cast<Attribute>(ofr);
780 return cast<IntegerAttr>(attr).getInt() != 0;
784 rewriter, getOperation(), state.
getPayloadOps(getTarget()), numLoops,
785 transformResults, getPackedTileSizes() !=
nullptr,
786 [&](TilingInterface tilingInterfaceOp)
787 -> FailureOr<scf::SCFTileAndFuseResult> {
795LogicalResult transform::FuseOp::verify() {
796 bool hasPackedTiles = getPackedTileSizes() !=
nullptr;
797 if (!getMixedTileSizes().empty() && hasPackedTiles)
799 "tile_sizes and packed_tile_sizes are mutually exclusive");
801 auto iterspace_rank = getStaticTileSizes().size();
803 if (permutation.size() > iterspace_rank)
805 <<
"interchange length exceeds iteration space dimensions ("
806 << iterspace_rank <<
"), found " << getTileInterchange();
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;
814 return emitOpError() <<
"found duplicate interchange value: " << v;
820 size_t numExpectedLoops = getUseForall() || hasPackedTiles
822 : sizes.size() - llvm::count(sizes, 0);
823 if (numExpectedLoops != getNumResults() - 1)
824 return emitOpError() <<
"expects " << numExpectedLoops <<
" loop results";
834 return getMixedValues(getStaticTileInterchange(), getTileInterchange(),
838void transform::FuseOp::getEffects(
852void transform::FuseIntoContainingOp::build(
OpBuilder &builder,
855 Value containingOp) {
856 result.addOperands({producerOp, containingOp});
857 auto resultType = transform::AnyOpType::get(builder.
getContext());
858 result.addTypes({resultType, resultType});
874 (domInfo.
dominates(containingOp, user))) {
875 dominatedUsers.insert(user);
878 if (dominatedUsers.empty())
882 auto forallOp = cast<scf::ForallOp>(containingOp);
888 auto genericOp = dyn_cast<linalg::GenericOp>(producerOp);
893 newOuts.push_back(outputs[resultNumber]);
896 auto newforallOp = scf::ForallOp::create(
897 rewriter, loc, forallOp.getMixedLowerBound(),
898 forallOp.getMixedUpperBound(), forallOp.getMixedStep(), newOuts,
899 forallOp.getMapping());
901 newforallOp.getRegion().takeBody(forallOp.getRegion());
906 newforallOp.getBody()->addArgument(newOuts.back().getType(),
907 newOuts.back().getLoc());
908 auto bbArgs = newforallOp.getBody()->getArguments();
911 Operation *op = use.getOwner();
912 return newforallOp->isProperAncestor(op);
916 scf::InParallelOp terminatorOp = newforallOp.getTerminator();
918 terminatorOp.getYieldingOps(), [](
Operation &op) { return &op; });
919 Operation *firstYieldOp = yieldingOps.front();
922 Value dst = newforallOp.getRegionIterArgs().back();
924 tensor::ParallelInsertSliceOp::create(rewriter, firstYieldOp->
getLoc(), src,
925 dst, offsets, sizes, strides);
927 for (
auto result : llvm::enumerate(forallOp.getResults())) {
929 newforallOp->getResult(
result.index()));
932 newforallOp->getResults().back(),
934 Operation *user = use.getOwner();
935 return dominatedUsers.contains(user);
949 destWorklist.push_back(dst);
951 while (!destWorklist.empty()) {
952 Value currentDst = destWorklist.pop_back_val();
956 if (src == currentDst)
961 auto bbArg = dyn_cast<BlockArgument>(currentDst);
965 Block *parentBlock = bbArg.getOwner();
966 assert(parentBlock &&
"unlinked block argument");
969 assert(parentOp &&
"expected block argument with parent operation");
972 auto parentLoop = dyn_cast<LoopLikeOpInterface>(parentOp);
976 for (
auto innerIterArg : parentLoop.getRegionIterArgs()) {
978 OpOperand *operand = parentLoop.getTiedLoopInit(innerIterArg);
979 Value loopBlockArgument =
981 destWorklist.push_back(loopBlockArgument);
994static std::tuple<SmallVector<Operation *>,
Operation *>
998 LDBG() <<
"Try to fuse a direct extract use";
999 auto tileableProducer = dyn_cast<TilingInterface>(producerOp);
1000 if (!tileableProducer) {
1002 <<
"producer is not a TileableInterface: " << *producerOp;
1009 auto it = llvm::find_if(tileableProducer->getUsers(), [&](
Operation *user) {
1010 auto sliceOp = dyn_cast<tensor::ExtractSliceOp>(user);
1011 return sliceOp && containingOp->isProperAncestor(sliceOp);
1015 if (it == tileableProducer->getUsers().end()) {
1016 diag.attachNote(tileableProducer->getLoc())
1017 <<
"could not find fusion opportunity for: " << *tileableProducer;
1020 auto sliceOpToTile = cast<tensor::ExtractSliceOp>(*it);
1033 if (LoopLikeOpInterface containerLoop =
1034 dyn_cast<LoopLikeOpInterface>(sliceOpToTile->getParentOp())) {
1040 auto dpsInterface = dyn_cast<DestinationStyleOpInterface>(
clone);
1044 for (
OpOperand &initOperandPtr : dpsInterface.getDpsInitsMutable()) {
1045 Value producerOperand =
1046 clone->getOperand(initOperandPtr.getOperandNumber());
1048 containerLoop.getRegionIterArgs()) {
1049 OpOperand *bbArg = containerLoop.getTiedLoopInit(containerIterArg);
1050 Value consumerOperand =
1054 initOperandPtr.set(containerIterArg);
1060 tileableProducer = dyn_cast<TilingInterface>(
clone);
1065 cast<OpResult>(sliceOpToTile.getSource()).getResultNumber();
1066 LDBG() <<
"resultNumber: " << resultNumber;
1071 FailureOr<TilingResult> tileAndFuseResult =
1072 tileableProducer.generateResultTileValue(rewriter, resultNumber, offsets,
1073 sizes, innerTileAlignments);
1075 if (failed(tileAndFuseResult)) {
1076 diag.attachNote(tileableProducer->getLoc())
1077 <<
"failed to tile producer op: " << *tileableProducer;
1082 for (
auto *tiledOp : tileAndFuseResult->tiledOps) {
1083 LDBG() <<
"tiledProducer: " << *tiledOp;
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)) {
1093 <<
"shape types don't match (missing canonicalization?):\nTiledOp: "
1094 << tileAndFuseResult->tiledValues[0]
1095 <<
"\nSliceOp: " << sliceOpToTile.getOperation() <<
'\n';
1098 rewriter.
replaceOp(sliceOpToTile, *maybeRankReduced);
1102 rewriter,
diag, producerOp, containingOp, *tileAndFuseResult,
1103 resultNumber, offsets, sizes);
1106 if (isa<LoopLikeOpInterface>(containingOp))
1107 rewriter.
eraseOp(tileableProducer);
1109 return std::make_tuple(tileAndFuseResult->tiledOps, newContainingOp);
1122 LDBG() <<
"Try to fuse an extract use through block argument";
1124 auto tileableProducer = dyn_cast<TilingInterface>(producerOp);
1125 if (!tileableProducer) {
1127 <<
"producer is not a TileableInterface: " << *producerOp;
1132 scf::ForallOp forallOp;
1133 auto itProducerUses =
1134 llvm::find_if(tileableProducer->getUses(), [&](
OpOperand &use) {
1135 forallOp = dyn_cast<scf::ForallOp>(use.getOwner());
1139 if (!forallOp || forallOp != containingOp) {
1140 diag.attachNote(tileableProducer->getLoc())
1141 <<
"could not find a use by the containing op: " << *tileableProducer;
1156 auto sliceOp = dyn_cast<tensor::ExtractSliceOp>(user);
1157 return sliceOp && containingOp->isProperAncestor(sliceOp);
1161 if (itBBArgUsers == bbArg.
getUsers().end()) {
1163 <<
"could not find fusion opportunity for bbArg: " << bbArg;
1166 auto sliceOpToTile = cast<tensor::ExtractSliceOp>(*itBBArgUsers);
1174 int64_t resultNumber = cast<OpResult>(pUse->
get()).getResultNumber();
1175 LDBG() <<
"resultNumber: " << resultNumber;
1180 rewriter, tileableProducer->getLoc(), tileableProducer,
1181 destinationTensors))) {
1182 diag.attachNote(tileableProducer->getLoc())
1183 <<
"failed to get destination tensors for: " << *tileableProducer;
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); });
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;
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);
1215 destinationTensors.front());
1218 return tileAndFuseResult->tiledOps;
1224 LDBG() <<
"Try to fuse an use by cloning";
1231 uses.push_back(&use);
1236 if (containingOp == use.getOwner()) {
1238 <<
"producer op use by containing op cannot be fused by cloning";
1246 diag.attachNote(producerOp->
getLoc()) <<
"no fusion opportunity by cloning";
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;
1262 fusedOp = rewriter.
clone(*producerOp);
1264 use->
getOwner(), [&] { use->set(fusedOp->getOpResult(resultNumber)); });
1269bool transform::FuseIntoContainingOp::allowsRepeatedHandleOperands() {
1274LogicalResult transform::FuseIntoContainingOp::verify() {
1284 auto containingOps = state.
getPayloadOps(getContainingOp());
1285 if (!llvm::hasSingleElement(containingOps)) {
1287 <<
"requires exactly one containing_op handle (got "
1288 << llvm::range_size(containingOps) <<
")";
1290 Operation *containingOp = *containingOps.begin();
1299 if (std::empty(producerOps)) {
1301 results.
set(cast<OpResult>(getNewContainingOp()), {containingOp});
1307 if (llvm::any_of(producerOps, [](
Operation *op) {
1311 <<
"cannot fuse a top-level operation";
1312 diag.attachNote(containingOp->
getLoc()) <<
"containing op";
1321 llvm::reverse(sortedProducers));
1323 auto getNextProducer = [&]() -> FailureOr<Operation *> {
1324 for (
const auto &it :
enumerate(remainingProducers)) {
1327 int64_t numUsesInContainingOp =
1329 return containingOp->isAncestor(op);
1331 if (numUsesInContainingOp > 0) {
1332 if (numUsesInContainingOp == 1)
1333 remainingProducers.erase(remainingProducers.begin() + it.index());
1340 while (!remainingProducers.empty()) {
1341 auto nextProducer = getNextProducer();
1342 if (
failed(nextProducer)) {
1344 <<
"could not find next producer to fuse into container";
1345 diag.attachNote(containingOp->
getLoc()) <<
"containing op";
1353 diag <<
"could not fuse " << *producerOp <<
" into " << *containingOp;
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) {
1371 LogicalResult replacementStatus =
1374 (
void)replacementStatus;
1375 assert(succeeded(replacementStatus) &&
1376 "unable to update transform state mapping");
1377 rewriter.
eraseOp(containingOp);
1378 containingOp = newContainingOp;
1385 rewriter,
diag, producerOp, containingOp, innerTileAlignments);
1386 if (!tiledContainingOpOperand.empty()) {
1387 LDBG() <<
"\nFused an extract use through block argument\n"
1389 fusedOps.append(tiledContainingOpOperand);
1396 LDBG() <<
"\nFused an use by cloning\n" << *containingOp;
1397 fusedOps.push_back(cloned);
1403 results.
set(cast<OpResult>(getFusedOp()), fusedOps);
1404 results.
set(cast<OpResult>(getNewContainingOp()), {containingOp});
1408void transform::FuseIntoContainingOp::getEffects(
1426 if (isa<GenericOp>(
target)) {
1432 if (succeeded(generic)) {
1433 results.
push_back(generic->getOperation());
1436 return emitDefaultSilenceableFailure(
target);
1449 if (!isa<GenericOp>(
target)) {
1454 FailureOr<LinalgOp> named =
1456 if (succeeded(named)) {
1457 results.
push_back(named->getOperation());
1460 return emitDefaultSilenceableFailure(
target);
1474 if (interchangeVector.empty()) {
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 ("
1495LogicalResult transform::InterchangeOp::verify() {
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();
1517 if (!isa<linalg::CopyOp>(targetOp)) {
1519 emitSilenceableError() <<
"only linalg.copy target ops are supported";
1520 diag.attachNote(targetOp->
getLoc()) <<
"target op";
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";
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();
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";
1552 assert(isa<ShapedType>(output.
getType()));
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";
1580 if (!
target.hasPureTensorSemantics()) {
1582 <<
"lower_pack only supports tensor semantics. The target has "
1586 bool lowerPadLikeWithInsertSlice = getLowerPadLikeWithInsertSlice();
1587 FailureOr<LowerPackResult> res =
1591 <<
"cannot lower to pad + expand + transpose";
1594 transformResults.
push_back(res->expandShapeOp);
1595 transformResults.
push_back(res->transposeOp);
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";
1615 bool lowerUnpadLikeWithExtractSlice = getLowerUnpadLikeWithExtractSlice();
1616 FailureOr<LowerUnPackOpResult> res =
1620 emitSilenceableError()
1621 <<
"cannot lower to transpose + collapse + extract";
1622 diag.attachNote(
target->getLoc()) <<
"target payload op";
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);
1640 result.addAttribute(MatchOp::getOpsAttrName(
result.name),
1649 result.addAttribute(MatchOp::getOpsAttrName(
result.name),
1651 result.addTypes(resultTypes);
1659 if (getOps().has_value())
1660 strs.insert_range(getOps()->getAsValueRange<StringAttr>());
1663 if (!llvm::hasSingleElement(payloadOps)) {
1668 bool incorrectNumOperandTypes =
false;
1675 if (getInterface().has_value()) {
1676 auto iface = getInterface().value();
1677 if (iface == transform::MatchInterfaceEnum::LinalgOp &&
1680 if (iface == transform::MatchInterfaceEnum::TilingInterface &&
1681 !isa<TilingInterface>(op))
1683 if (iface == transform::MatchInterfaceEnum::LoopLikeInterface &&
1684 !isa<LoopLikeOpInterface>(op))
1689 if (getOpAttrs().has_value()) {
1690 DictionaryAttr opAttrs = getOpAttrs().value();
1692 if (attr.getName() == getInterfaceAttrName() ||
1693 attr.getName() == getOpsAttrName())
1695 std::optional<Attribute> inherent = op->
getInherentAttr(attr.getName());
1701 if (actual != attr.getValue())
1706 if (getFilterResultType().has_value()) {
1707 Type t = getFilterResultType().value();
1712 if (getFilterOperandTypes().has_value()) {
1713 mlir::ArrayAttr types = getFilterOperandTypes().value();
1716 if (types.size() == 1) {
1719 dyn_cast<mlir::TypeAttr>(getFilterOperandTypes().value()[0]);
1720 Type t = cast<::mlir::Type>(typeattr.getValue());
1722 [&](
Type operandType) { return operandType == t; }))
1727 if (types.size() != operandTypes.size()) {
1728 incorrectNumOperandTypes =
true;
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());
1737 if (type != operandType)
1748 (*payloadOps.begin())->walk(matchFun);
1749 if (incorrectNumOperandTypes)
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);
1768 Type &targetType,
Type &lowSizeType,
1770 Type &splitPointType) {
1771 FunctionType funcType;
1773 if (failed(parser.
parseType<FunctionType>(funcType)))
1776 if (funcType.getNumInputs() != 1 || funcType.getNumResults() != 1) {
1777 parser.
emitError(typeLoc) <<
"expects a trailing functional type with one "
1778 "argument and one result";
1780 targetType = funcType.getInput(0);
1781 lowSizeType = highSizeType = splitPointType = funcType.getResult(0);
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";
1799 target, getDimension(), getTargetSize(), getDivisor());
1801 return emitSilenceableError()
1802 <<
"failed to compute multi-size tiling sizes";
1806 results.
assign(llvm::map_range(
1808 spec->lowTileSize * spec->lowTripCount}),
1809 [&builder,
this](
int64_t value) {
1821 builder,
target, getDimension(), targetSize, divisor);
1823 return emitSilenceableError() <<
"could not generate tile size computation";
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");
1842void transform::MultiTileSizesOp::getEffects(
1846 if (isa<TransformParamTypeInterface>(getLowSize().
getType()))
1852LogicalResult transform::MultiTileSizesOp::verify() {
1855 return emitOpError() <<
"expects all results type to be the same";
1874 Type linalgOpHType = transform::OperationType::get(
1875 builder.
getContext(), GenericOp::getOperationName());
1894 if (std::empty(targetOps)) {
1895 transformResults.
set(cast<OpResult>(getPackedOp()),
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) <<
")";
1907 if (!linalgOp.hasPureTensorSemantics()) {
1908 return emitSilenceableError()
1909 <<
"structured.pack only supports tensor semantics. The target has "
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()
1923 state, *
this, packedSizes, getMixedPackedSizes());
1926 FailureOr<PackResult> maybeResult =
pack(rewriter, linalgOp, packedSizes);
1930 transformResults.
set(cast<OpResult>(getPackedOp()),
1931 {maybeResult->packedLinalgOp.getOperation()});
1935void transform::PackOp::getEffects(
1947LogicalResult transform::PackGreedilyOp::verify() {
1949 return emitOpError() << getMatmulInnerDimsOrderAttrName()
1950 <<
" is not a valid permutation";
1953 if (!getMatmulPaddedSizesNextMultipleOf().empty()) {
1954 for (
auto [s, nmo] :
1955 llvm::zip_equal(getMixedMatmulPackedSizes(),
1956 getMatmulPaddedSizesNextMultipleOf())) {
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";
1974 for (
auto linalgOp :
1975 llvm::make_isa_range<LinalgOp>(state.
getPayloadOps(getTarget()))) {
1984 getMixedMatmulPackedSizes(),
1986 getMatmulPaddedSizesNextMultipleOf(),
1987 getMatmulInnerDimsOrder());
1988 if (succeeded(packResult)) {
1989 results.push_back(packResult->packedLinalgOp);
1992 results.push_back(linalgOp);
1994 transformResults.
set(cast<OpResult>(getPackedOp()), results);
2000 return getMixedValues(getStaticMatmulPackedSizes(), getMatmulPackedSizes(),
2004void transform::PackGreedilyOp::getEffects(
2016LogicalResult transform::PackTransposeOp::verify() {
2018 return emitOpError() << getInnerPermAttrName()
2019 <<
" is not a valid permutation";
2022 return emitOpError() << getOuterPermAttrName()
2023 <<
" is not a valid permutation";
2025 if (getInnerPerm().empty() && getOuterPerm().empty()) {
2026 return emitOpError() <<
" at least one of " << getInnerPermAttrName()
2027 <<
" or " << getOuterPermAttrName()
2028 <<
" must be specified";
2034enum class OuterOrInnerPerm { Outer = 0, Inner = 1 };
2044template <
typename RelayoutOpTy>
2045static bool isValidPackingPermutation(
2047 OuterOrInnerPerm outerOrInnerPerm = OuterOrInnerPerm::Outer) {
2049 llvm::is_one_of<RelayoutOpTy, linalg::PackOp, linalg::UnPackOp>::value,
2050 "applies to only pack or unpack operations");
2051 if (!op || permutation.empty())
2053 size_t innerRank = op.getInnerDimsPos().size();
2054 if (outerOrInnerPerm == OuterOrInnerPerm::Inner)
2058 if (std::is_same<RelayoutOpTy, linalg::PackOp>::value) {
2059 return permutation.size() == op.getSourceRank() &&
2062 return permutation.size() == op.getDestRank() &&
2070 auto packOrUnpackOps = state.
getPayloadOps(getTargetPackOrUnPackOp());
2073 if (std::empty(packOrUnpackOps)) {
2074 transformResults.
set(cast<OpResult>(getPackedOp()), {});
2075 transformResults.
set(cast<OpResult>(getPackOp()), {});
2076 transformResults.
set(cast<OpResult>(getUnPackOp()), {});
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) <<
")";
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";
2098 LinalgOp linalgOpTarget = dyn_cast<LinalgOp>(*linalgOps.begin());
2099 if (!linalgOpTarget)
2100 return emitSilenceableError() <<
"requires a LinalgOp target";
2104 if (packOp && packOp.getResult().hasOneUse())
2105 linalgOp = dyn_cast<LinalgOp>(*(packOp.getResult().getUsers().begin()));
2107 linalgOp = unPackOp.getSource().getDefiningOp<LinalgOp>();
2108 if (linalgOp != linalgOpTarget) {
2110 packOp ? StringLiteral{
"not a single use by the LinalgOp target"}
2111 : StringLiteral{
"not produced by the LinalgOp target"};
2112 return emitSilenceableError() << errorMsg;
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());
2122 if (!packOp || !packOp.getResult().hasOneUse())
2123 return emitSilenceableError() <<
"could not find matching pack op";
2127 for (
auto permType : {OuterOrInnerPerm::Outer, OuterOrInnerPerm::Inner}) {
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)) {
2136 unPackOp ? unPackOp.getOperation() : packOp.getOperation();
2137 return emitSilenceableError() << errorMsg <<
": " << *packOrUnpackOp;
2143 assert(packOp && linalgOp &&
"unexpected null op");
2147 rewriter, packOp, linalgOp, unPackOp, getOuterPerm(), getInnerPerm());
2149 assert(succeeded(res) &&
"unexpected packTranspose failure");
2152 transformResults.
set(cast<OpResult>(getPackOp()), {res->transposedPackOp});
2153 transformResults.
set(cast<OpResult>(getPackedOp()),
2154 {res->transposedLinalgOp});
2156 transformResults.
set(cast<OpResult>(getUnPackOp()),
2157 {res->transposedUnPackOp});
2159 transformResults.
set(cast<OpResult>(getUnPackOp()), {});
2174 StringRef copyBackOp,
2175 bool usePrescribedTensorShapes) {
2176 auto resultType = transform::AnyOpType::get(
b.getContext());
2182 b.getI64ArrayAttr(paddingDimensions),
2185 (padToMultipleOf.empty()
2187 :
b.getDenseI64ArrayAttr(padToMultipleOf)),
2188 b.getI64ArrayAttr(nofoldFlags),
2189 b.getArrayAttr(transposePaddings),
2190 b.getStringAttr(copyBackOp),
2192 usePrescribedTensorShapes ?
b.getUnitAttr() :
nullptr);
2200 StringRef copyBackOp,
2201 bool usePrescribedTensorShapes) {
2202 auto resultType = transform::AnyOpType::get(
b.getContext());
2206 staticPadToMultipleOf);
2212 b.getI64ArrayAttr(paddingDimensions),
2213 dynamicPadToMultipleOf,
2214 staticPadToMultipleOf,
2215 b.getI64ArrayAttr(nofoldFlags),
2216 b.getArrayAttr(transposePaddings),
2218 usePrescribedTensorShapes);
2221void PadOp::getEffects(
2229SmallVector<OpFoldResult> PadOp::getMixedPadToMultipleOf() {
2231 return getMixedValues(getStaticPadToMultipleOf(), getPadToMultipleOf(),
b);
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;
2242 auto linalgTarget = dyn_cast<LinalgOp>(
target);
2243 if (!linalgTarget) {
2244 auto diag = emitSilenceableError() <<
"expected LinalgOp target";
2250 SmallVector<bool> nofoldFlags;
2251 for (int64_t packPadding :
2253 nofoldFlags.push_back(
static_cast<bool>(packPadding));
2256 SmallVector<Attribute> paddingValues;
2257 for (
auto const &[untypedAttr, elementOrTensorType] :
2258 llvm::zip(getPaddingValues(), linalgTarget->getOperandTypes())) {
2261 paddingValues.push_back(untypedAttr);
2264 auto attr = dyn_cast<TypedAttr>(untypedAttr);
2266 emitOpError(
"expects padding values to be typed attributes or poison");
2271 if (
auto stringAttr = dyn_cast<StringAttr>(attr)) {
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";
2281 paddingValues.push_back(parsedAttr);
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";
2291 paddingValues.push_back(attr);
2295 SmallVector<SmallVector<int64_t>> transposePaddings;
2296 for (Attribute transposeVector : cast<ArrayAttr>(getTransposePaddings()))
2298 cast<ArrayAttr>(transposeVector)));
2305 SmallVector<int64_t> padToMultipleOf;
2307 state, transformOp, getMixedPadToMultipleOf(), padToMultipleOf);
2310 if (padToMultipleOf.empty())
2312 SmallVector<int64_t>(
options.paddingDimensions.size(), 1);
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;
2326 llvm_unreachable(
"unsupported copy_back op");
2329 bool irChanged =
false;
2330 if (getUsePrescribedTensorShapes() &&
2331 linalgTarget.hasPureTensorSemantics()) {
2332 OpBuilder::InsertionGuard g(rewriter);
2334 for (OpOperand &operand : linalgTarget->getOpOperands()) {
2335 for (
auto [i, dim] : llvm::enumerate(linalgTarget.getShape(&operand))) {
2336 if (ShapedType::isStatic(dim))
2338 options.setSizeToPadTo(operand.getOperandNumber(), i,
2340 operand.get().getLoc(),
2347 SmallVector<Value> replacements;
2348 SmallVector<tensor::PadOp> newPadOps;
2350 replacements, newPadOps))) {
2356 auto diag = emitSilenceableError() <<
"failed to pad op";
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);
2378 results.
set(cast<OpResult>(getPadded()), paddedOps);
2379 results.
set(cast<OpResult>(getPad()), padOps);
2380 results.
set(cast<OpResult>(getCopy()), copyBackOps);
2384LogicalResult transform::PadOp::verify() {
2385 SmallVector<int64_t> nofoldFlags =
2387 if (any_of(nofoldFlags, [](int64_t packPadding) {
2388 return packPadding != 0 && packPadding != 1;
2390 return emitOpError()
2391 <<
"expects nofold_flags to contain booleans (0/1), found "
2392 << getNofoldFlags();
2395 SmallVector<int64_t> paddingDimensions =
2397 if (any_of(paddingDimensions,
2398 [](int64_t paddingDimension) {
return paddingDimension < 0; })) {
2399 return emitOpError() <<
"expects padding_dimensions to contain positive "
2401 << getPaddingDimensions();
2403 if (!getMixedPadToMultipleOf().empty()) {
2404 if (getMixedPadToMultipleOf().size() != paddingDimensions.size()) {
2405 return emitOpError() <<
"expects as many multiples as padding_dimensions";
2408 ArrayAttr transposes = getTransposePaddings();
2409 for (Attribute attr : transposes) {
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 "
2419 if (getCopyBackOp() !=
2420 bufferization::MaterializeInDestinationOp::getOperationName() &&
2421 getCopyBackOp() != linalg::CopyOp::getOperationName() &&
2422 getCopyBackOp() != kCopyOpNone)
2423 return emitOpError() <<
"invalid copy_back_op";
2431void transform::PadTilingInterfaceOp::build(OpBuilder &
b,
2434 ArrayRef<int64_t> paddingSizes,
2435 bool padToMultipleOf) {
2436 auto resultType = transform::AnyOpType::get(
b.getContext());
2445 :
b.getDenseI64ArrayAttr(paddingSizes)),
2447 padToMultipleOf ?
b.getUnitAttr() :
nullptr);
2450void transform::PadTilingInterfaceOp::build(
2452 ArrayRef<OpFoldResult> mixedPaddingSizes,
bool padToMultipleOf) {
2453 auto resultType = transform::AnyOpType::get(
b.getContext());
2454 SmallVector<int64_t> staticPaddingSizes;
2455 SmallVector<Value> dynamicPaddingSizes;
2457 staticPaddingSizes);
2463 dynamicPaddingSizes,
2468void transform::PadTilingInterfaceOp::getEffects(
2469 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
2476SmallVector<OpFoldResult>
2477transform::PadTilingInterfaceOp::getMixedPaddingSizes() {
2482DiagnosedSilenceableFailure
2483transform::PadTilingInterfaceOp::apply(transform::TransformRewriter &rewriter,
2484 transform::TransformResults &results,
2485 transform::TransformState &state) {
2486 SmallVector<Operation *> paddedOps, padOps;
2489 auto targetOp = dyn_cast<TilingInterface>(
target);
2491 auto diag = emitSilenceableError() <<
"expected TilingInterface target";
2499 if (!isa<IndexingMapOpInterface>(targetOp.getOperation())) {
2500 auto diag = emitSilenceableError() <<
"only IndexingMapOpInterface ops "
2507 SmallVector<Attribute> paddingValues;
2508 for (
auto const &[untypedAttr, elementOrTensorType] :
2509 llvm::zip(getPaddingValues(), targetOp->getOperandTypes())) {
2510 auto attr = dyn_cast<TypedAttr>(untypedAttr);
2514 paddingValues.push_back(untypedAttr);
2518 emitOpError(
"expects padding values to be typed attributes or poison");
2522 if (
auto stringAttr = dyn_cast<StringAttr>(attr)) {
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";
2532 paddingValues.push_back(parsedAttr);
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";
2542 paddingValues.push_back(attr);
2546 PadTilingInterfaceOptions
options;
2547 options.paddingValues = std::move(paddingValues);
2548 options.setPaddingSizes(getMixedPaddingSizes())
2549 .setPadToMultipleOf(getPadToMultipleOf());
2551 OpBuilder::InsertionGuard g(rewriter);
2554 rewriter, cast<TilingInterface>(targetOp.getOperation()),
2556 if (
failed(maybePadOps)) {
2557 auto diag = emitSilenceableError() <<
"failed to pad op";
2561 const auto &[paddedOperands, paddedOp, slicedResults] = maybePadOps.value();
2564 paddedOps.push_back(paddedOp);
2565 padOps.append(paddedOperands.begin(), paddedOperands.end());
2566 rewriter.
replaceOp(targetOp.getOperation(), slicedResults);
2569 results.
set(cast<OpResult>(getPadded()), paddedOps);
2570 results.
set(cast<OpResult>(getPad()), padOps);
2574LogicalResult transform::PadTilingInterfaceOp::verify() {
return success(); }
2580DiagnosedSilenceableFailure transform::HoistPadBuildPackingLoopNestOp::apply(
2581 transform::TransformRewriter &rewriter,
2582 transform::TransformResults &transformResults,
2583 transform::TransformState &state) {
2586 if (!llvm::hasSingleElement(targetOps) || !llvm::hasSingleElement(loopOps)) {
2588 <<
"requires exactly one target and one loop handle (got "
2589 << llvm::range_size(targetOps) <<
" and "
2590 << llvm::range_size(loopOps) <<
")";
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)
2598 FailureOr<linalg::detail::PackingResult>
result =
2604 if (
result->clonedLoopIvs.empty()) {
2605 transformResults.
set(cast<OpResult>(getPackingLoop()),
2606 {
result->hoistedPadOp.getOperation()});
2609 auto outerPackedLoop =
2611 transformResults.
set(cast<OpResult>(getPackingLoop()),
2612 {outerPackedLoop.getOperation()});
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(),
2621 return emitOpError() <<
"expects transpose to be a permutation, found "
2627void transform::HoistPadBuildPackingLoopNestOp::getEffects(
2628 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
2635DiagnosedSilenceableFailure
2636transform::HoistPadOp::applyToOne(transform::TransformRewriter &rewriter,
2638 transform::ApplyToEachResultList &results,
2639 transform::TransformState &state) {
2640 tensor::PadOp hoistedPadOp;
2641 SmallVector<TransposeOp> transposeOps;
2642 FailureOr<Value>
result =
2644 hoistedPadOp, transposeOps);
2655 return emitDefaultSilenceableFailure(
target);
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(),
2663 return emitOpError() <<
"expects transpose to be a permutation, found "
2673DiagnosedSilenceableFailure
2674transform::PromoteOp::applyToOne(transform::TransformRewriter &rewriter,
2676 transform::ApplyToEachResultList &results,
2677 transform::TransformState &state) {
2678 LinalgPromotionOptions promotionOptions;
2679 if (!getOperandsToPromote().empty())
2682 if (getUseFullTilesByDefault())
2684 getUseFullTilesByDefault());
2685 if (getUseOriginalSubviewSize())
2689 promotionOptions = promotionOptions.
setUseAlloca(getUseAlloca());
2690 if (!getUseFullTileBuffers().empty())
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());
2698 if (getMapping().has_value()) {
2700 auto mapping = *getMapping();
2701 if (mapping.size() > 1)
2702 return emitDefaultDefiniteFailure(
target);
2704 auto addressSpace = cast<mlir::gpu::GPUMemorySpaceMappingAttr>(mapping[0]);
2706 if (addressSpace.getAddressSpace() ==
2707 mlir::gpu::GPUDialect::getWorkgroupAddressSpace()) {
2714 }
else if (addressSpace.getAddressSpace() ==
2715 mlir::gpu::GPUDialect::getPrivateAddressSpace()) {
2723 return emitDefaultDefiniteFailure(
target);
2728 return emitDefaultDefiniteFailure(
target);
2733 return emitDefaultDefiniteFailure(
target);
2742DiagnosedSilenceableFailure
2743transform::ReplaceOp::apply(transform::TransformRewriter &rewriter,
2744 TransformResults &transformResults,
2745 TransformState &state) {
2749 for (Operation *
target : payload) {
2750 if (
target->getNumOperands() > 0)
2752 if (!
target->hasTrait<OpTrait::IsIsolatedFromAbove>() &&
2753 target->getNumRegions() > 0)
2755 <<
"expected target that is isolated from above";
2759 Operation *pattern = &getBodyRegion().front().front();
2760 SmallVector<Operation *> replacements;
2761 for (Operation *
target : payload) {
2762 if (getOperation()->isAncestor(
target))
2769 transformResults.
set(cast<OpResult>(getReplacement()), replacements);
2773void transform::ReplaceOp::getEffects(
2774 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
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();
2789 <<
"expected replacement without operands";
2790 if (!
replacement->hasTrait<OpTrait::IsIsolatedFromAbove>() &&
2793 <<
"expect op that is isolated from above";
2801DiagnosedSilenceableFailure
2802transform::ScalarizeOp::applyToOne(transform::TransformRewriter &rewriter,
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();
2815 SmallVector<OpFoldResult> shapeSizes =
2820 for (OpFoldResult shapeSize : shapeSizes) {
2822 :
b.getIndexAttr(1));
2827 FailureOr<scf::SCFTilingResult> maybeTilingResult =
tileUsingSCF(
2828 rewriter, cast<TilingInterface>(
target.getOperation()), tilingOptions);
2829 if (
failed(maybeTilingResult))
2830 return emitDefaultDefiniteFailure(
target);
2832 if (
target->getNumResults())
2837 results.
reserve(maybeTilingResult->tiledOps.size());
2838 for (Operation *tiled : maybeTilingResult->tiledOps)
2847DiagnosedSilenceableFailure
2848transform::ConvertToLoopsOp::apply(transform::TransformRewriter &rewriter,
2849 transform::TransformResults &results,
2850 transform::TransformState &state) {
2851 SmallVector<Operation *> loops;
2853 auto tilingOp = dyn_cast<TilingInterface>(*
target);
2855 DiagnosedSilenceableFailure diag =
2856 emitSilenceableError()
2857 <<
"expected the payload to implement TilingInterface";
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());
2871 results.
set(cast<OpResult>(getResult()), loops);
2879DiagnosedSilenceableFailure
2880transform::RewriteInDestinationPassingStyleOp::applyToOne(
2881 transform::TransformRewriter &rewriter, Operation *
target,
2882 transform::ApplyToEachResultList &results,
2883 transform::TransformState &state) {
2885 FailureOr<Operation *> maybeResult =
2887 .Case<DestinationStyleOpInterface>([](
auto op) {
return op; })
2888 .Case<tensor::FromElementsOp, tensor::GenerateOp, tensor::PadOp>(
2889 [&rewriter](
auto op) {
2893 return emitDefaultSilenceableFailure(
target);
2902DiagnosedSilenceableFailure
2903SplitOp::apply(transform::TransformRewriter &rewriter,
2904 TransformResults &results, TransformState &state) {
2906 SmallVector<Operation *> payload =
2909 bool isMultiwaySplit = getMultiway();
2911 if (isMultiwaySplit && !llvm::hasSingleElement(payload)) {
2913 <<
"requires exactly one target when "
2914 "multiway split is enabled (got "
2915 << llvm::range_size(payload) <<
")";
2918 SmallVector<OpFoldResult> chunkSizes;
2920 if (!isMultiwaySplit)
2921 chunkSizes.reserve(payload.size());
2923 if (getDynamicChunkSizes()) {
2925 if (isa<TransformHandleTypeInterface>(getDynamicChunkSizes().
getType())) {
2926 chunkSizes = llvm::map_to_vector(
2927 state.
getPayloadOps(getDynamicChunkSizes()), [&](Operation *op) {
2930 diag = emitSilenceableError()
2931 <<
"expected dynamic split point handle to point to a "
2932 "single-result index-typed op";
2938 chunkSizes = llvm::map_to_vector(
2939 state.
getParams(getDynamicChunkSizes()),
2940 [](Attribute attr) {
return OpFoldResult(attr); });
2947 if (!isMultiwaySplit && chunkSizes.size() != payload.size()) {
2949 <<
"expected the dynamic split point handle to point to as "
2951 << chunkSizes.size() <<
") as the target handle ("
2952 << payload.size() <<
")";
2955 chunkSizes.resize(payload.size(),
2959 auto checkStructuredOpAndDimensions =
2960 [&](LinalgOp linalgOp, Location loc) -> DiagnosedSilenceableFailure {
2962 auto diag = emitSilenceableError() <<
"only applies to structured ops";
2967 if (getDimension() >= linalgOp.getNumLoops()) {
2968 auto diag = emitSilenceableError() <<
"dimension " << getDimension()
2969 <<
" does not exist in target op";
2976 auto checkFailureInSplitting =
2977 [&](
bool hasFailed, Location loc) -> DiagnosedSilenceableFailure {
2986 SmallVector<Operation *> opList;
2987 if (isMultiwaySplit) {
2990 TilingInterface head, tail;
2991 Operation *
target = payload.front();
2993 LinalgOp linalgOp = dyn_cast<LinalgOp>(
target);
2996 DiagnosedSilenceableFailure diag =
2997 checkStructuredOpAndDimensions(linalgOp,
target->getLoc());
3001 for (
auto &&[idx, chunkSize] : llvm::enumerate(chunkSizes)) {
3004 target = tail.getOperation();
3009 linalgOp = cast<LinalgOp>(
target);
3010 Location loc =
target->getLoc();
3014 rewriter, cast<TilingInterface>(linalgOp.getOperation()),
3015 getDimension(), chunkSize);
3018 DiagnosedSilenceableFailure diag =
3019 checkFailureInSplitting(!head && !tail, loc);
3023 opList.push_back(head.getOperation());
3028 opList.push_back(tail.getOperation());
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());
3045 std::tie(first.emplace_back(), second.emplace_back()) =
linalg::splitOp(
3046 rewriter, cast<TilingInterface>(linalgOp.getOperation()),
3047 getDimension(), std::get<1>(pair));
3050 DiagnosedSilenceableFailure diagSplit =
3051 checkFailureInSplitting(!first.back() && !second.back(), loc);
3056 if (!second.back()) {
3062 if (second.size() != first.size() && !second.empty()) {
3063 auto diag = emitSilenceableError()
3064 <<
"splitting does not produce the second part for a subset "
3067 <<
"expected splitting to produce the second part of all "
3068 "or none of the targets";
3070 <<
"first target with no second part";
3074 opList.append(first);
3075 if (!second.empty())
3076 opList.append(second);
3078 results.
set(cast<OpResult>(getSplitList()), opList);
3082void SplitOp::getEffects(
3083 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
3085 if (getDynamicChunkSizes())
3091ParseResult SplitOp::parse(OpAsmParser &parser, OperationState &
result) {
3092 OpAsmParser::UnresolvedOperand
target, dynamicChunkSizes;
3093 IntegerAttr staticChunkSizes;
3097 OptionalParseResult dynamicPointParseResult =
3099 if (!dynamicPointParseResult.
has_value()) {
3100 int64_t staticChunkSizesValue;
3114 if (dynamicPointParseResult.
has_value()) {
3115 Type chunkSizesType;
3128 SplitOp::getStaticChunkSizesAttrName(
result.name).getValue(),
3130 result.addTypes(targetType);
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;
3140 printer << getDynamicChunkSizes();
3142 NamedAttrList attrs(getOperation()->getDiscardableAttrDictionary());
3143 attrs.append(getDimensionAttrName(), getDimensionAttr());
3144 if (UnitAttr multiway = getMultiwayAttr())
3145 attrs.append(getMultiwayAttrName(), multiway);
3147 printer <<
" : " << getTarget().getType();
3148 if (staticChunkSize == ShapedType::kDynamic)
3149 printer <<
", " << getDynamicChunkSizes().getType();
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";
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) {
3171 result.addAttribute(SplitReductionOp::getSplitFactorAttrName(
result.name),
3174 SplitReductionOp::getInsertSplitDimensionAttrName(
result.name),
3176 if (innerParallel) {
3177 result.addAttribute(SplitReductionOp::getInnerParallelAttrName(
result.name),
3180 if (useScalingAlgorithm) {
3182 SplitReductionOp::getUseScalingAlgorithmAttrName(
result.name),
3186 result.addAttribute(SplitReductionOp::getUseAllocAttrName(
result.name),
3189 auto resultType = transform::AnyOpType::get(ctx);
3190 result.addTypes({resultType, resultType, resultType, resultType});
3193DiagnosedSilenceableFailure transform::SplitReductionOp::applyToOne(
3194 transform::TransformRewriter &rewriter, LinalgOp
target,
3195 transform::ApplyToEachResultList &results,
3196 transform::TransformState &state) {
3198 return linalg::SplitReductionOptions{int64_t(getSplitFactor()),
3199 unsigned(getInsertSplitDimension()),
3200 bool(getInnerParallel())};
3203 FailureOr<SplitReductionResult> splitResult =
3204 (getUseScalingAlgorithm())
3208 return emitDefaultDefiniteFailure(
target);
3210 results.
push_back(splitResult->initOrAlloc);
3212 results.
push_back(splitResult->splitLinalgOp);
3213 results.
push_back(splitResult->resultCombiningLinalgOp);
3221void transform::TileReductionUsingForOp::build(
3222 OpBuilder &builder, OperationState &
result, Value
target,
3223 ArrayRef<int64_t> staticTileSizes) {
3230 auto opTy = transform::AnyOpType::get(ctx);
3236 staticTileSizesAttr);
3239DiagnosedSilenceableFailure transform::TileReductionUsingForOp::applyToOne(
3240 transform::TransformRewriter &rewriter, Operation *
target,
3241 transform::ApplyToEachResultList &results,
3242 transform::TransformState &state) {
3245 auto partialReductionOp = dyn_cast<PartialReductionOpInterface>(
target);
3246 if (!partialReductionOp) {
3249 "Operation should implement PartialReductionOpInterface");
3252 SmallVector<unsigned> reductionDims =
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);
3262 scf::SCFTilingOptions
options;
3263 options.setLoopType(scf::SCFTilingOptions::LoopType::ForOp);
3264 options.setReductionTilingStrategy(
3267 options.setReductionDims(reductionDims);
3268 FailureOr<scf::SCFTilingResult>
result =
3269 scf::tileUsingSCF(rewriter, partialReductionOp,
options);
3273 "failed to tile using partial reduction");
3276 for (Value initValue :
result->initialValues)
3278 for (
auto *parallelTiledOp :
result->tiledOps)
3280 for (
auto *mergeOp :
result->mergeOps)
3290void transform::TileReductionUsingForallOp::build(
3291 OpBuilder &builder, OperationState &
result, Value
target,
3292 ArrayRef<int64_t> staticNumThreads, ArrayRef<int64_t> staticTileSizes,
3300 auto opTy = transform::AnyOpType::get(ctx);
3307 staticNumThreadsAttr,
3308 staticTileSizesAttr,
3312DiagnosedSilenceableFailure transform::TileReductionUsingForallOp::applyToOne(
3313 transform::TransformRewriter &rewriter, Operation *
target,
3314 transform::ApplyToEachResultList &results,
3315 transform::TransformState &state) {
3318 auto partialReductionOp = dyn_cast<PartialReductionOpInterface>(
target);
3319 if (!partialReductionOp) {
3322 "Operation should implement PartialReductionOpInterface");
3324 SmallVector<OpFoldResult> numThreads =
3326 SmallVector<OpFoldResult> tileSizes =
3329 scf::SCFTilingOptions
options;
3330 options.setLoopType(scf::SCFTilingOptions::LoopType::ForallOp);
3331 options.setReductionTilingStrategy(
3333 if (!getNumThreads().empty()) {
3334 options.setNumThreads(numThreads);
3336 options.setTileSizes(tileSizes);
3338 if (
auto mapping = getMapping()) {
3339 options.setMapping(mapping.value().getValue());
3341 SmallVector<unsigned> reductionDims =
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);
3350 options.setReductionDims(reductionDims);
3351 FailureOr<scf::SCFTilingResult>
result =
3352 scf::tileUsingSCF(rewriter, partialReductionOp,
options);
3355 auto diag = emitSilenceableError() <<
"could not tile reduction";
3360 for (Value initValue :
result->initialValues)
3362 for (
auto *parallelTiledOp :
result->tiledOps)
3364 for (
auto *mergeOp :
result->mergeOps)
3374DiagnosedSilenceableFailure
3375transform::ContinuousTileSizesOp::apply(transform::TransformRewriter &rewriter,
3376 TransformResults &transformResults,
3377 TransformState &state) {
3379 SmallVector<Operation *> targetOps =
3382 if (!llvm::hasSingleElement(targetOps)) {
3384 <<
"requires exactly one target (got " << llvm::range_size(targetOps)
3388 Operation *
target = *targetOps.begin();
3389 auto linalgOp = dyn_cast<LinalgOp>(
target);
3390 auto tileableOp = dyn_cast<TilingInterface>(
target);
3395 OpBuilder builder(linalgOp.getContext());
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";
3406 FailureOr<StaticContinuousTileSizeSpecification> spec =
3410 return emitSilenceableError()
3411 <<
"failed to compute multi-size tiling sizes";
3414 SmallVector<int64_t> chunkSizes;
3416 for (
auto &&[tileSize, tripCount] :
3417 llvm::zip_equal(spec->tileSizes, spec->tripCounts))
3418 chunkSizes.push_back(tileSize * tripCount);
3420 auto getI64AttrsFromI64 = [&](ArrayRef<int64_t> values) {
3421 return llvm::map_to_vector(values, [&](int64_t value) -> Attribute {
3426 getI64AttrsFromI64(spec->tileSizes));
3427 transformResults.
setParams(cast<OpResult>(getChunkSizes()),
3428 getI64AttrsFromI64(chunkSizes));
3435 OpFoldResult targetSize = builder.
getIndexAttr(getTargetSize());
3436 unsigned dimension = getDimension();
3439 builder, tileableOp, dimension, targetSize,
true);
3441 return emitSilenceableError() <<
"could not generate tile size computation";
3446 auto apply = [&](AffineExpr expr, ArrayRef<OpFoldResult> ofrs) -> Value {
3451 SmallVector<Value> chunkSizes;
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);
3459 auto getDefiningOps = [&](ArrayRef<Value> values) {
3460 return llvm::map_to_vector(values, [&](Value value) -> Operation * {
3466 getDefiningOps(spec->tileSizes));
3467 transformResults.
set(cast<OpResult>(getChunkSizes()),
3468 getDefiningOps(chunkSizes));
3473LogicalResult transform::ContinuousTileSizesOp::verify() {
3476 return emitOpError() <<
"expects all results type to be the same";
3482void transform::ContinuousTileSizesOp::getEffects(
3483 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
3500 Type &tileSizesType,
3501 Type &chunkSizesType) {
3502 FunctionType funcType;
3504 if (failed(parser.
parseType<FunctionType>(funcType)))
3507 if (funcType.getNumInputs() != 1 || funcType.getNumResults() != 1) {
3508 parser.
emitError(typeLoc) <<
"expects a trailing functional type with one "
3509 "argument and one result";
3511 targetType = funcType.getInput(0);
3512 tileSizesType = chunkSizesType = funcType.getResult(0);
3521void transform::TileUsingForOp::build(
3523 Value
target, ArrayRef<int64_t> staticTileSizes,
3524 ArrayRef<int64_t> interchange,
3525 std::optional<ArrayRef<bool>> scalableSizes) {
3526 return build(builder,
result, loopTypes,
3530 interchange, scalableSizes);
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) {
3539 interchange, scalableSizes);
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) {
3548 SmallVector<Type> loopTypes(1, builder.
getType<transform::AnyOpType>());
3549 build(builder,
result, loopTypes,
target, mixedTileSizes, interchange,
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) {
3560 SmallVector<Type> loopTypes(1, builder.
getType<transform::AnyOpType>());
3561 build(builder,
result, loopTypes,
target, mixedTileSizes, mixedInterchange,
3565void transform::TileUsingForOp::build(
3567 Value
target, ArrayRef<OpFoldResult> mixedTileSizes,
3568 ArrayRef<int64_t> interchange,
3569 std::optional<ArrayRef<bool>> scalableSizes) {
3570 SmallVector<OpFoldResult> mixedInterchange =
3572 build(builder,
result, loopTypes,
target, mixedTileSizes, mixedInterchange,
3576void transform::TileUsingForOp::build(
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;
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]);
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;
3614 staticTileSizesAttr,
3615 staticInterchangeAttr,
3616 expandedScalableSizes);
3619LogicalResult transform::TileUsingForOp::verify() {
3620 bool hasPackedTiles = getPackedTileSizes() != Value();
3621 bool hasPackedInterchange = getPackedInterchange() != Value();
3624 "tile_sizes and packed_tile_sizes are mutually exclusive");
3625 if (!getMixedInterchange().empty() && hasPackedInterchange)
3627 "interchange and packed_interchange are mutually exclusive");
3628 if (hasPackedTiles && !getScalableSizes().empty())
3630 "scalable tile_sizes are not supported with packed_tile_sizes");
3633 return emitOpError(
"expected same number of sizes (")
3635 << getScalableSizes().size() <<
")";
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;
3650 return emitOpError() <<
"found duplicate interchange value: " << v;
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() <<
")";
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());
3674 SmallVector<OpFoldResult> mixedInterchange;
3675 if (hasPackedInterchange) {
3676 DiagnosedSilenceableFailure status =
3678 state, transformOp, mixedInterchange, getPackedInterchange());
3682 mixedInterchange = getMixedInterchange();
3684 SmallVector<int64_t> tileInterchange;
3686 state, transformOp, mixedInterchange, tileInterchange);
3690 SmallVector<Operation *> targets =
3692 SmallVector<SmallVector<Operation *>> dynamicSizeProducers;
3693 SmallVector<SmallVector<int64_t>> paramSizes;
3694 SmallVector<OpFoldResult> mixedTileSizes;
3695 if (hasPackedTiles) {
3697 state, transformOp, mixedTileSizes, getPackedTileSizes());
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();
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";
3724 paramSizes.push_back({});
3725 dynamicSizeProducers.push_back(
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";
3738 for (Operation *op : dynamicSizeProducers.back()) {
3744 DiagnosedSilenceableFailure diag =
3745 emitSilenceableError() <<
"expected sizes to be produced by ops "
3746 "with a single index-type result";
3748 diag.
attachNote(transformValue.getLoc()) <<
"for this handle";
3754 SmallVector<Operation *> tiled;
3755 SmallVector<SmallVector<Operation *, 4>, 4> loops;
3758 ? llvm::count_if(mixedTileSizes,
3759 [](OpFoldResult ofr) {
3760 if (
auto attr = dyn_cast<Attribute>(ofr))
3761 return cast<IntegerAttr>(attr).getInt() != 0;
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";
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";
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 <<
")";
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;
3800 return emitSilenceableError()
3801 <<
"found duplicate interchange value: " << v;
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();
3816 scf::SCFTilingOptions tilingOptions;
3817 if (!hasPackedTiles && tileSizes.empty()) {
3818 tilingOptions.setTileSizeComputationFunction(
3819 [](OpBuilder &, Operation *) -> SmallVector<OpFoldResult> {
3822 }
else if (hasPackedTiles) {
3823 tilingOptions.setTileSizes(mixedTileSizes);
3825 tilingOptions.setTileSizeComputationFunction([&, index = i](OpBuilder &
b,
3827 SmallVector<OpFoldResult> sizes;
3828 sizes.reserve(tileSizes.size());
3829 unsigned dynamicIdx = 0;
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());
3837 vector::VectorScaleOp::create(
b, getLoc(),
b.getIndexType());
3839 arith::MulIOp::create(
b, getLoc(), val, vscale).getResult());
3841 sizes.push_back(attr);
3845 ArrayRef<Operation *> dynamicSizes = dynamicSizeProducers[dynamicIdx];
3846 ArrayRef<int64_t> params = paramSizes[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]));
3853 sizes.push_back(dynamicSizes[index]->getResult(0));
3860 tilingOptions.setInterchange(tileInterchange);
3861 tilingOptions.setInnerTileAlignments(
3863 FailureOr<scf::SCFTilingResult> maybeTilingResult =
3864 tileUsingSCF(rewriter, tilingInterface, tilingOptions);
3865 if (
failed(maybeTilingResult))
3868 rewriter.
replaceOp(op, maybeTilingResult->replacements);
3870 tiled.append(maybeTilingResult->tiledOps);
3871 for (
const auto &en2 : llvm::enumerate(maybeTilingResult->loops))
3872 loops[en2.index()].push_back(en2.value());
3875 transformResults.
set(cast<OpResult>(getTiledLinalgOp()), tiled);
3876 if (hasPackedTiles) {
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);
3884 for (
const auto &en : llvm::enumerate(loops))
3885 transformResults.
set(cast<OpResult>(getLoops()[en.index()]), en.value());
3891SmallVector<OpFoldResult> transform::TileUsingForOp::getMixedSizes() {
3893 ArrayRef<int64_t> tileSizes = getStaticSizes();
3894 SmallVector<OpFoldResult> results;
3895 results.reserve(tileSizes.size());
3896 unsigned dynamicPos = 0;
3898 for (int64_t size : tileSizes) {
3899 if (size == ShapedType::kDynamic) {
3900 results.push_back(dynamic[dynamicPos++]);
3908SmallVector<OpFoldResult> transform::TileUsingForOp::getMixedInterchange() {
3912void transform::TileUsingForOp::getEffects(
3913 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
3927void transform::TileUsingForallOp::build(OpBuilder &builder,
3929 ArrayRef<int64_t> staticTileSizes,
3930 transform::TileSizesSpec,
3932 ArrayRef<bool> scalableSizes) {
3933 return build(builder,
result,
3938 mapping, scalableSizes);
3941void transform::TileUsingForallOp::build(OpBuilder &builder,
3943 ArrayRef<OpFoldResult> mixedTileSizes,
3944 transform::TileSizesSpec,
3946 ArrayRef<bool> scalableSizes) {
3947 SmallVector<int64_t> staticTileSizes;
3948 SmallVector<Value> dynamicTileSizes;
3954 auto operationType = transform::AnyOpType::get(ctx);
3957 TypeRange{operationType, operationType},
3964 staticTileSizesAttr,
3969void transform::TileUsingForallOp::build(OpBuilder &builder,
3971 ArrayRef<int64_t> staticNumThreads,
3972 transform::NumThreadsSpec,
3976 NumThreadsSpec(), mapping);
3979void transform::TileUsingForallOp::build(OpBuilder &builder,
3981 ArrayRef<OpFoldResult> mixedNumThreads,
3982 transform::NumThreadsSpec,
3984 SmallVector<int64_t> staticNumThreads;
3985 SmallVector<Value> dynamicNumThreads;
3992 auto operationType = transform::AnyOpType::get(ctx);
3995 TypeRange{operationType, operationType},
4001 staticNumThreadsAttr,
4009static SmallVector<OpFoldResult>
4015 AffineExpr normalizedUbExpr = (s1 - s0).ceilDiv(s2);
4017 for (
auto [lb,
ub, step] : llvm::zip_equal(lbs, ubs, steps)) {
4019 rewriter, loc, normalizedUbExpr, {lb,
ub, step});
4020 normalizedUbs.push_back(normalizedUb);
4022 return normalizedUbs;
4038 for (
auto [iv, lb, step] : llvm::zip_equal(ivs, lbs, steps)) {
4041 denormalizedIvs.push_back(
4044 return denormalizedIvs;
4055 scf::ForallOp loop) {
4072 auto normalizedForallOp = scf::ForallOp::create(
4073 rewriter, loc, normalizedLbs, normalizedUbs, normalizedSteps,
4074 loop.getOutputs(), loop.getMapping(),
4077 auto normalizedLoopIvs = normalizedForallOp.getInductionVars();
4079 Block *normalizedLoopBlock = normalizedForallOp.getBody();
4084 argValues.append(normalizedForallOp.getRegionIterArgs().begin(),
4085 normalizedForallOp.getRegionIterArgs().end());
4086 Block *origLoopBlock = loop.getBody();
4087 rewriter.
mergeBlocks(origLoopBlock, normalizedLoopBlock, argValues);
4089 rewriter.
replaceOp(loop, normalizedForallOp);
4090 return normalizedForallOp;
4098 scf::SCFTilingResult &tilingResult,
ArrayRef<bool> scalableSizes) {
4100 auto tileableOp = dyn_cast<TilingInterface>(
target);
4103 transformOp.emitSilenceableError()
4104 <<
"only TilingInterface ops are supported";
4105 diag.attachNote(
target->getLoc()) <<
"target op";
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";
4118 scf::SCFTilingOptions
options;
4119 options.setLoopType(scf::SCFTilingOptions::LoopType::ForallOp);
4120 if (!mixedNumThreads.empty()) {
4121 options.setNumThreads(mixedNumThreads);
4125 options.setTileSizeComputationFunction(
4129 for (
auto [i, scalable] : llvm::enumerate(scalableSizes)) {
4134 vscale = vector::VectorScaleOp::create(builder, loc,
4139 arith::MulIOp::create(builder, loc, factor, vscale).getResult();
4145 options.setMapping(mapping.value().getValue());
4147 FailureOr<scf::SCFTilingResult> maybeTilingResult =
4148 scf::tileUsingSCF(rewriter, tileableOp,
options);
4150 if (failed(maybeTilingResult))
4151 return transformOp.emitDefaultSilenceableFailure(tileableOp);
4153 rewriter.
replaceOp(tileableOp, maybeTilingResult->replacements);
4155 tilingResult = *maybeTilingResult;
4159 if (mixedNumThreads.empty() && !tilingResult.loops.empty()) {
4160 auto generatedForallOp = cast<scf::ForallOp>(tilingResult.loops.front());
4163 scf::ForallOp normalizedForallOp =
4165 tilingResult.loops.front() = normalizedForallOp;
4175 auto transformOp = cast<TransformOpInterface>(getOperation());
4184 getPackedNumThreads()
4186 state, transformOp, mixedNumThreads, getPackedNumThreads())
4188 state, transformOp, mixedNumThreads, getMixedNumThreads());
4192 status = getPackedTileSizes()
4194 state, transformOp, mixedTileSizes, getPackedTileSizes())
4196 state, transformOp, mixedTileSizes, getMixedTileSizes());
4201 scf::SCFTilingResult tilingResult;
4203 rewriter, state, transformOp,
target, mixedNumThreads, mixedTileSizes,
4204 getMapping(), tilingResult, getScalableSizes());
4205 if (!
diag.succeeded())
4207 if (!tilingResult.loops.empty())
4208 tileOps.push_back(tilingResult.loops.front());
4209 tiledOps.append(tilingResult.tiledOps);
4212 transformResults.
set(cast<OpResult>(getForallOp()), tileOps);
4213 transformResults.
set(cast<OpResult>(getTiledOp()), tiledOps);
4218void transform::TileUsingForallOp::getEffects(
4219 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
4229SmallVector<OpFoldResult> TileUsingForallOp::getMixedNumThreads() {
4234SmallVector<OpFoldResult> TileUsingForallOp::getMixedTileSizes() {
4239LogicalResult TileUsingForallOp::verify() {
4240 ArrayRef<bool> scalableSizes = getScalableSizes();
4241 if (!scalableSizes.empty() &&
4242 scalableSizes.size() != getStaticTileSizes().size())
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))
4248 "scalable tile sizes must be non-negative static integers");
4250 int numThreadsSpec =
static_cast<int>(!getMixedNumThreads().empty()) +
4251 static_cast<int>(getPackedNumThreads() != Value());
4252 if (numThreadsSpec > 1)
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)
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");
4272void transform::VectorizeChildrenAndApplyPatternsOp::build(
4273 OpBuilder &builder, OperationState &
result, Value
target,
4274 bool foldTypeExtensionsIntoContract,
bool vectorizePadding,
4275 bool vectorizeExtract,
bool flatten1DDepthwiseConv) {
4277 if (foldTypeExtensionsIntoContract) {
4279 VectorizeChildrenAndApplyPatternsOp::
4280 getFoldTypeExtensionsIntoContractAttrName(
result.name),
4283 if (vectorizePadding) {
4285 VectorizeChildrenAndApplyPatternsOp::getVectorizePaddingAttrName(
4289 if (vectorizeExtract) {
4291 VectorizeChildrenAndApplyPatternsOp::getVectorizeNdExtractAttrName(
4295 if (flatten1DDepthwiseConv) {
4297 VectorizeChildrenAndApplyPatternsOp::getFlatten_1dDepthwiseConvAttrName(
4307struct VectorizationPattern :
public RewritePattern {
4308 explicit VectorizationPattern(MLIRContext *context,
4309 bool vectorizeExtract =
false,
4310 bool flattenConv =
false)
4311 : RewritePattern(MatchAnyOpTypeTag(), 1, context),
4312 vectorizeNDExtract(vectorizeExtract),
4313 flatten1DDepthwiseConv(flattenConv) {}
4314 LogicalResult matchAndRewrite(Operation *op,
4315 PatternRewriter &rewriter)
const override {
4318 "Unsupported Op, cannot vectorize");
4319 FailureOr<VectorizationResult> vectorResults =
4321 {}, vectorizeNDExtract,
4322 flatten1DDepthwiseConv);
4323 if (
failed(vectorResults))
4325 rewriter.
replaceOp(op, vectorResults->replacements);
4332 bool vectorizeNDExtract =
false;
4336 bool flatten1DDepthwiseConv =
false;
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");
4352 RewritePatternSet patterns(ctx);
4353 patterns.
add<VectorizationPattern>(ctx, getVectorizeNdExtract(),
4354 getFlatten_1dDepthwiseConv());
4356 if (!getDisableTransferPermutationMapLoweringPatterns())
4359 if (!getDisableMultiReductionToContractPatterns())
4364 patterns.
add<linalg::LinalgCopyVTRForwardingPattern,
4365 linalg::LinalgCopyVTWForwardingPattern>(ctx,
4367 vector::TransferReadOp::getCanonicalizationPatterns(patterns, ctx);
4368 vector::TransferWriteOp::getCanonicalizationPatterns(patterns, ctx);
4371 patterns.
add<CopyVectorizationPattern>(ctx);
4373 if (getFoldTypeExtensionsIntoContract())
4376 if (getVectorizePadding()) {
4384 TrackingListener listener(state, *
this);
4387 GreedyRewriteConfig().setListener(&listener))))
4388 return emitDefaultDefiniteFailure(
target);
4398DiagnosedSilenceableFailure transform::VectorizeOp::apply(
4399 transform::TransformRewriter &rewriter,
4400 mlir::transform::TransformResults &transformResults,
4401 mlir::transform::TransformState &state) {
4403 if (std::empty(targets))
4405 auto transformOp = cast<TransformOpInterface>(getOperation());
4406 SmallVector<int64_t> vectorSizes;
4408 state, transformOp, getMixedVectorSizes(), vectorSizes);
4413 for (Operation *
target : targets) {
4416 <<
"Unsupported Op, cannot vectorize";
4418 FailureOr<VectorizationResult> vectorResults =
4420 getVectorizeNdExtract().value_or(
false),
4422 getAssumeDynamicDimsMatchVecSizes().value_or(
false),
4423 getCreateNamedContraction().value_or(
false));
4424 if (
failed(vectorResults)) {
4426 <<
"Attempted to vectorize, but failed";
4434void transform::VectorizeOp::getEffects(
4435 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
4441SmallVector<OpFoldResult> VectorizeOp::getMixedVectorSizes() {
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() <<
")";
4458DiagnosedSilenceableFailure
4459transform::HoistRedundantVectorTransfersOp::applyToOne(
4460 transform::TransformRewriter &rewriter, func::FuncOp
target,
4461 transform::ApplyToEachResultList &results,
4462 transform::TransformState &state) {
4475DiagnosedSilenceableFailure
4476transform::HoistRedundantVectorBroadcastsOp::applyToOne(
4477 transform::TransformRewriter &rewriter, mlir::Operation *
target,
4478 transform::ApplyToEachResultList &results,
4479 transform::TransformState &state) {
4490DiagnosedSilenceableFailure transform::ConvertConv2DToImg2ColOp::applyToOne(
4491 transform::TransformRewriter &rewriter, linalg::LinalgOp
target,
4492 transform::ApplyToEachResultList &results,
4493 transform::TransformState &state) {
4495 auto maybeTransformed =
4498 .Case([&](linalg::Conv2DNhwcHwcfOp op) {
4501 .Case([&](linalg::Conv2DNhwcFhwcOp op) {
4504 .Case([&](linalg::DepthwiseConv2DNhwcHwcOp op) {
4507 .Case([&](linalg::Conv2DNchwFchwOp op) {
4510 .Default([&](Operation *op) {
4513 if (
failed(maybeTransformed))
4514 return emitDefaultSilenceableFailure(
target);
4516 results.
push_back(maybeTransformed->first);
4518 results.
push_back(maybeTransformed->second);
4526DiagnosedSilenceableFailure transform::FlattenElementwiseLinalgOp::applyToOne(
4527 transform::TransformRewriter &rewriter, linalg::LinalgOp
target,
4528 transform::ApplyToEachResultList &results,
4529 transform::TransformState &state) {
4533 <<
"only elementwise flattening is supported";
4535 if (!llvm::all_of(
target.getIndexingMapsArray(), [](AffineMap m) {
4536 return m.isPermutation() || m.getNumResults() == 0;
4540 <<
"broadcasting of non scalar operands is not supported";
4544 if (
target.getNumLoops() <= 1) {
4551 if (
auto broadcastOp = dyn_cast<linalg::BroadcastOp>(
target.getOperation());
4552 broadcastOp && broadcastOp.getInput().getType().getRank() != 0) {
4559 std::iota(reassociation.begin(), reassociation.end(), 0);
4560 auto maybeFlattened =
4562 if (
failed(maybeFlattened))
4564 <<
"attempted to flatten, but failed";
4565 results.
push_back(maybeFlattened->collapsedOp);
4574DiagnosedSilenceableFailure transform::TransposeConv2DOp::applyToOne(
4575 transform::TransformRewriter &rewriter, linalg::LinalgOp
target,
4576 transform::ApplyToEachResultList &results,
4577 transform::TransformState &state) {
4579 auto maybeTransformed =
4581 .Case([&](linalg::Conv2DNhwcFhwcOp op) {
4584 .Case([&](linalg::Conv2DNhwcFhwcQOp op) {
4587 .Default([&](Operation *op) {
4590 if (
failed(maybeTransformed))
4591 return emitDefaultSilenceableFailure(
target);
4601DiagnosedSilenceableFailure transform::TransposeMatmulOp::applyToOne(
4602 transform::TransformRewriter &rewriter, linalg::LinalgOp
target,
4603 transform::ApplyToEachResultList &results,
4604 transform::TransformState &state) {
4606 bool transposeLHS = getInputToTranspose() == TransposeMatmulInput::lhs;
4607 auto maybeTransformed =
4609 .Case([&](linalg::MatmulOp op) {
4612 .Case([&](linalg::BatchMatmulOp op) {
4615 .Default(failure());
4616 if (
failed(maybeTransformed))
4626template <
typename OpTy>
4627static DiagnosedSilenceableFailure
4631 static_assert(llvm::is_one_of<OpTy, tensor::InsertSliceOp,
4632 tensor::ParallelInsertSliceOp>() &&
4635 if (
auto copySource =
4636 target.getSource().template getDefiningOp<linalg::CopyOp>()) {
4644 if (isa<mlir::ParallelCombiningOpInterface>(
target.getOperation()))
4647 Value extracted = tensor::ExtractSliceOp::create(
4650 Value copied = linalg::CopyOp::create(rewriter,
target.getLoc(),
4651 target.getSource(), extracted)
4663DiagnosedSilenceableFailure transform::InsertSliceToCopyOp::applyToOne(
4664 transform::TransformRewriter &rewriter, Operation *targetOp,
4665 transform::ApplyToEachResultList &results,
4666 transform::TransformState &state) {
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);
4674 DiagnosedSilenceableFailure diag =
4675 emitSilenceableError()
4676 <<
"only InsertSliceOp and ParallelInsertSliceOp ops are supported";
4685DiagnosedSilenceableFailure transform::MapCopyToThreadsOp::applyToOne(
4686 transform::TransformRewriter &rewriter, Operation *
target,
4687 transform::ApplyToEachResultList &results,
4688 transform::TransformState &state) {
4690 if (!isa<linalg::CopyOp, tensor::PadOp>(
target)) {
4691 DiagnosedSilenceableFailure diag =
4692 emitSilenceableError()
4693 <<
"only linalg.copy and tensor.pad target ops are supported";
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";
4708 int64_t desiredBitAlignment = getDesiredBitAlignment();
4709 int64_t eltBitwidth =
4710 resultShapedType.getElementType().getIntOrFloatBitWidth();
4711 if (desiredBitAlignment % eltBitwidth != 0) {
4712 desiredBitAlignment = eltBitwidth;
4715 gpu::CopyMappingInfo mapping(
4717 getTotalNumThreads(),
4718 desiredBitAlignment,
4719 resultShapedType.getShape(),
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";
4735 scf::SCFTilingResult tilingResult;
4742 ArrayRef<OpFoldResult>{},
4743 b.getArrayAttr(mapping.threadMapping),
4748 results.
push_back(tilingResult.loops.front());
4749 for (
auto *op : tilingResult.tiledOps)
4758DiagnosedSilenceableFailure transform::WinogradConv2DOp::applyToOne(
4759 transform::TransformRewriter &rewriter, linalg::LinalgOp
target,
4760 transform::ApplyToEachResultList &results,
4761 transform::TransformState &state) {
4763 FailureOr<Operation *> maybeTransformed = failure();
4765 .Case([&](linalg::Conv2DNhwcFhwcOp op) {
4770 .Default([&](Operation *op) {
return false; });
4773 return emitSilenceableError()
4774 <<
"this operation is not supported to convert to Winograd Conv2D";
4777 if (
failed(maybeTransformed)) {
4778 return emitSilenceableError() <<
"apply Winograd Conv2D failed";
4785DiagnosedSilenceableFailure transform::DecomposeWinogradOp::applyToOne(
4786 transform::TransformRewriter &rewriter, Operation *
target,
4787 transform::ApplyToEachResultList &results,
4788 transform::TransformState &state) {
4790 FailureOr<Operation *> maybeTransformed = failure();
4793 .Case([&](linalg::WinogradFilterTransformOp op) {
4797 .Case([&](linalg::WinogradInputTransformOp op) {
4801 .Case([&](linalg::WinogradOutputTransformOp op) {
4808 DiagnosedSilenceableFailure diag =
4809 emitSilenceableError()
4810 <<
"this operation is not supported to decompose into other operations";
4815 if (
failed(maybeTransformed)) {
4816 DiagnosedSilenceableFailure diag =
4817 emitSilenceableError() <<
"decompose Winograd operations failed";
4826#include "mlir/Dialect/Linalg/TransformOps/LinalgTransformOpsEnums.cpp.inc"
4828#define GET_OP_CLASSES
4829#include "mlir/Dialect/Linalg/TransformOps/LinalgTransformOps.cpp.inc"
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
*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.
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.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
This class is a general helper class for creating context-global objects like types,...
IntegerAttr getIndexAttr(int64_t value)
IntegerAttr getIntegerAttr(Type type, int64_t value)
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
AffineExpr getAffineSymbolExpr(unsigned position)
IntegerAttr getI64IntegerAttr(int64_t value)
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
MLIRContext * getContext() const
DenseBoolArrayAttr getDenseBoolArrayAttr(ArrayRef< bool > values)
Tensor-typed DenseArrayAttr getters.
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
ArrayAttr getStrArrayAttr(ArrayRef< StringRef > values)
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.
bool dominates(Operation *a, Operation *b) const
Return true if operation A dominates operation B, i.e.
This is a utility class for mapping one set of IR entities to another.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
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...
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttribute represents a combination of a name and an Attribute value.
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.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setListener(Listener *newListener)
Sets the listener of this builder to the one provided.
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Listener * getListener() const
Returns the current listener of this builder, or nullptr if this builder doesn't have a listener.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
This class represents a single result from folding an operation.
This class represents an operand of an operation.
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
This is a value defined by a result of an operation.
StringRef getStringRef() const
Return the name of this operation. This always succeeds.
Operation is the basic unit of execution within MLIR.
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns a null Attribute if the discardable attribute does no...
OpResult getOpResult(unsigned idx)
void setOperand(unsigned idx, Value value)
bool hasOneUse()
Returns true if this operation has exactly one use.
Block * getBlock()
Returns the operation block that contains this operation.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
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.
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.
operand_type_range getOperandTypes()
result_type_range getResultTypes()
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
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),...
user_range getUsers()
Returns a range of all users.
result_range getOpResults()
Region * getParentRegion()
Returns the region to which the instruction belongs.
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.
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.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class provides an abstraction over the different types of ranges over Values.
Type front()
Return first type in the range.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
bool use_empty() const
Returns true if this value has no uses.
Type getType() const
Return the type of this value.
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
user_range getUsers() const
Location getLoc() const
Return the location of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
State for analysis-enabled bufferization.
Operation * getOwner() const
Return the owner of this operand.
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)
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...
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.
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.
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.
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)
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)
FailureOr< StaticContinuousTileSizeSpecification > computeStaticContinuousTileSizes(LinalgOp op, unsigned dimension, unsigned targetSize)
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,...
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...
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...
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...
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.
ForOp getForInductionVarOwner(Value val)
Returns the loop parent of an induction variable.
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.
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
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.
detail::poison_attr_matcher m_Poison()
Matches a poison constant (any attribute implementing PoisonAttrInterface).
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.
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...
@ PartialReductionOuterReduction
@ PartialReductionOuterParallel
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.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
LogicalResult applyPatternsGreedily(Region ®ion, 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
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
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 .
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
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
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
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
SmallVector< IntTy > extractFromIntegerArrayAttr(Attribute attr)
Extract integer values from the assumed ArrayAttr of IntegerAttr.
llvm::function_ref< Fn > function_ref
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.
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.