24#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/SmallBitVector.h"
26#include "llvm/ADT/SmallVectorExtras.h"
27#include "llvm/Support/FormatVariadic.h"
46 VectorType distributedType) {
52 for (
unsigned i = 0, e = sequentialType.getRank(); i < e; i++) {
53 if (sequentialType.getDimSize(i) != distributedType.getDimSize(i))
57 distributedType.getContext());
65 VectorType distributedType) {
66 assert(sequentialType.getRank() == distributedType.getRank() &&
67 "sequential and distributed vector types must have the same rank");
69 for (
int64_t i = 0; i < sequentialType.getRank(); ++i) {
70 if (distributedType.getDimSize(i) != sequentialType.getDimSize(i)) {
73 assert(distributedDim == -1 &&
"found multiple distributed dims");
77 return distributedDim;
87struct DistributedLoadStoreHelper {
88 DistributedLoadStoreHelper(Value sequentialVal, Value distributedVal,
89 Value laneId, Value zero)
90 : sequentialVal(sequentialVal), distributedVal(distributedVal),
91 laneId(laneId), zero(zero) {
92 sequentialVectorType = dyn_cast<VectorType>(sequentialVal.getType());
93 distributedVectorType = dyn_cast<VectorType>(distributedVal.getType());
94 if (sequentialVectorType && distributedVectorType)
99 Value buildDistributedOffset(RewriterBase &
b, Location loc, int64_t index) {
100 int64_t distributedSize = distributedVectorType.getDimSize(index);
102 return b.createOrFold<affine::AffineApplyOp>(loc, tid * distributedSize,
103 ArrayRef<Value>{laneId});
113 Operation *buildStore(RewriterBase &
b, Location loc, Value val,
115 assert((val == distributedVal || val == sequentialVal) &&
116 "Must store either the preregistered distributed or the "
117 "preregistered sequential value.");
119 if (!isa<VectorType>(val.
getType()))
120 return memref::StoreOp::create(
b, loc, val, buffer, zero);
124 int64_t rank = sequentialVectorType.getRank();
125 SmallVector<Value>
indices(rank, zero);
126 if (val == distributedVal) {
127 for (
auto dimExpr : distributionMap.getResults()) {
128 int64_t index = cast<AffineDimExpr>(dimExpr).getPosition();
129 indices[index] = buildDistributedOffset(
b, loc, index);
132 SmallVector<bool> inBounds(
indices.size(),
true);
133 return vector::TransferWriteOp::create(
135 ArrayRef<bool>(inBounds.begin(), inBounds.end()));
158 Value buildLoad(RewriterBase &
b, Location loc, Type type, Value buffer) {
161 if (!isa<VectorType>(type))
162 return memref::LoadOp::create(
b, loc, buffer, zero);
167 assert((type == distributedVectorType || type == sequentialVectorType) &&
168 "Must store either the preregistered distributed or the "
169 "preregistered sequential type.");
170 SmallVector<Value>
indices(sequentialVectorType.getRank(), zero);
171 if (type == distributedVectorType) {
172 for (
auto dimExpr : distributionMap.getResults()) {
173 int64_t index = cast<AffineDimExpr>(dimExpr).getPosition();
174 indices[index] = buildDistributedOffset(
b, loc, index);
177 SmallVector<bool> inBounds(
indices.size(),
true);
178 return vector::TransferReadOp::create(
179 b, loc, cast<VectorType>(type), buffer,
indices,
181 ArrayRef<bool>(inBounds.begin(), inBounds.end()));
184 Value sequentialVal, distributedVal, laneId, zero;
185 VectorType sequentialVectorType, distributedVectorType;
186 AffineMap distributionMap;
200 return rewriter.
create(res);
208 auto targetVecType = dyn_cast<VectorType>(targetType);
209 if (!targetVecType || !targetVecType.hasStaticShape())
212 for (
auto &entry : buffers) {
215 Value candidate = entry.first;
216 auto candidateMemref = dyn_cast<MemRefType>(candidate.
getType());
217 if (!candidateMemref || !candidateMemref.hasStaticShape())
219 if (candidateMemref.getElementType() != targetVecType.getElementType())
222 if (candidateMemref.getRank() != targetVecType.getRank())
227 if (!llvm::all_of(llvm::seq<unsigned>(0, targetVecType.getRank()),
229 return candidateMemref.getDimSize(i) >=
230 targetVecType.getDimSize(i);
238 if (candidateMemref.getShape() == targetVecType.getShape())
242 int64_t candidateRank = candidateMemref.getRank();
246 sizes.reserve(candidateRank);
247 for (
int64_t dim : targetVecType.getShape())
250 return memref::SubViewOp::create(rewriter, loc, candidate, offsets, sizes,
259 llvm::SmallSetVector<Block *, 4> visited;
262 while (!worklist.empty()) {
263 Block *current = worklist.pop_back_val();
264 if (current == block)
266 if (!visited.insert(current))
269 worklist.push_back(succ);
281 block = parent ? parent->
getBlock() :
nullptr;
316 WarpOpToScfIfPattern(MLIRContext *context,
317 const WarpExecuteOnLane0LoweringOptions &options,
318 PatternBenefit benefit = 1)
319 : WarpDistributionPattern(context, benefit), options(options) {}
321 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
322 PatternRewriter &rewriter)
const override {
323 assert(warpOp.getBodyRegion().hasOneBlock() &&
324 "expected WarpOp with single block");
325 Block *warpOpBody = &warpOp.getBodyRegion().front();
326 Location loc = warpOp.getLoc();
329 OpBuilder::InsertionGuard g(rewriter);
334 Value isLane0 = arith::CmpIOp::create(
335 rewriter, loc, arith::CmpIPredicate::eq, warpOp.getLaneid(), c0);
336 auto ifOp = scf::IfOp::create(rewriter, loc, isLane0,
338 rewriter.
eraseOp(ifOp.thenBlock()->getTerminator());
342 SmallVector<Value> bbArgReplacements;
348 SmallVector<std::pair<Value,
bool>> reusableArgBuffers;
349 bool canReuseArgBuffers = !warpOp->getParentOfType<LoopLikeOpInterface>() &&
351 if (canReuseArgBuffers)
352 reusableArgBuffers.reserve(warpOp.getArgs().size());
353 for (
const auto &it : llvm::enumerate(warpOp.getArgs())) {
354 Value sequentialVal = warpOpBody->
getArgument(it.index());
355 Value distributedVal = it.value();
356 DistributedLoadStoreHelper helper(sequentialVal, distributedVal,
357 warpOp.getLaneid(), c0);
361 Value buffer = options.warpAllocationFn(loc, rewriter, warpOp,
363 if (canReuseArgBuffers)
364 reusableArgBuffers.emplace_back(buffer,
false);
366 helper.buildStore(rewriter, loc, distributedVal, buffer);
369 bbArgReplacements.push_back(
370 helper.buildLoad(rewriter, loc, sequentialVal.
getType(), buffer));
374 if (!warpOp.getArgs().empty()) {
376 options.warpSynchronizationFn(loc, rewriter, warpOp);
380 rewriter.
mergeBlocks(warpOpBody, ifOp.thenBlock(), bbArgReplacements);
386 SmallVector<Value> replacements;
387 auto yieldOp = cast<gpu::YieldOp>(ifOp.thenBlock()->getTerminator());
388 Location yieldLoc = yieldOp.getLoc();
389 for (
const auto &it : llvm::enumerate(yieldOp.getOperands())) {
390 Value sequentialVal = it.value();
391 Value distributedVal = warpOp->getResult(it.index());
392 DistributedLoadStoreHelper helper(sequentialVal, distributedVal,
393 warpOp.getLaneid(), c0);
398 sequentialVal.
getType(), loc, rewriter);
400 buffer = options.warpAllocationFn(loc, rewriter, warpOp,
406 helper.buildStore(rewriter, loc, sequentialVal, buffer);
417 replacements.push_back(
418 helper.buildLoad(rewriter, loc, distributedVal.
getType(), buffer));
422 if (!yieldOp.getOperands().empty()) {
424 options.warpSynchronizationFn(loc, rewriter, warpOp);
430 scf::YieldOp::create(rewriter, yieldLoc);
433 rewriter.
replaceOp(warpOp, replacements);
439 const WarpExecuteOnLane0LoweringOptions &options;
452static VectorType getDistributedType(VectorType originalType,
AffineMap map,
460 if (targetShape[position] % warpSize != 0) {
461 if (warpSize % targetShape[position] != 0) {
464 warpSize /= targetShape[position];
465 targetShape[position] = 1;
468 targetShape[position] = targetShape[position] / warpSize;
475 VectorType targetType =
476 VectorType::get(targetShape, originalType.getElementType());
486getInnerRegionEscapingValues(WarpExecuteOnLane0Op warpOp,
Region &innerRegion,
488 llvm::SmallSetVector<Value, 32> escapingValues;
491 if (innerRegion.
empty())
492 return {std::move(escapingValues), std::move(escapingValueTypes),
493 std::move(escapingValueDistTypes)};
496 if (warpOp->isAncestor(parent)) {
497 if (!escapingValues.insert(operand->
get()))
500 if (
auto vecType = dyn_cast<VectorType>(distType)) {
502 distType = getDistributedType(vecType, map,
503 map.
isEmpty() ? 1 : warpOp.getWarpSize());
505 escapingValueTypes.push_back(operand->
get().
getType());
506 escapingValueDistTypes.push_back(distType);
509 return {std::move(escapingValues), std::move(escapingValueTypes),
510 std::move(escapingValueDistTypes)};
534 unsigned maxNumElementsToExtract, PatternBenefit
b = 1)
535 : WarpDistributionPattern(ctx,
b), distributionMapFn(std::move(fn)),
536 maxNumElementsToExtract(maxNumElementsToExtract) {}
540 LogicalResult tryDistributeOp(RewriterBase &rewriter,
541 vector::TransferWriteOp writeOp,
542 WarpExecuteOnLane0Op warpOp)
const {
543 VectorType writtenVectorType = writeOp.getVectorType();
547 if (writtenVectorType.getRank() == 0)
551 AffineMap map = distributionMapFn(writeOp.getVector());
552 VectorType targetType =
553 getDistributedType(writtenVectorType, map, warpOp.getWarpSize());
559 if (writeOp.getMask()) {
566 if (!writeOp.getPermutationMap().isMinorIdentity())
569 getDistributedType(writeOp.getMaskType(), map, warpOp.getWarpSize());
574 vector::TransferWriteOp newWriteOp =
575 cloneWriteOp(rewriter, warpOp, writeOp, targetType, maskType);
579 newWriteOp.getVector().getDefiningOp<WarpExecuteOnLane0Op>();
585 SmallVector<OpFoldResult> delinearizedIdSizes;
586 for (
auto [seqSize, distSize] :
587 llvm::zip_equal(writtenVectorType.getShape(), targetType.getShape())) {
588 assert(seqSize % distSize == 0 &&
"Invalid distributed vector shape");
589 delinearizedIdSizes.push_back(rewriter.
getIndexAttr(seqSize / distSize));
591 SmallVector<Value> delinearized;
593 delinearized = mlir::affine::AffineDelinearizeIndexOp::create(
594 rewriter, newWarpOp.getLoc(), newWarpOp.getLaneid(),
600 delinearized.append(targetType.getRank(), newWarpOp.getLaneid());
603 AffineMap indexMap = map.
compose(newWriteOp.getPermutationMap());
604 Location loc = newWriteOp.getLoc();
605 SmallVector<Value>
indices(newWriteOp.getIndices().begin(),
606 newWriteOp.getIndices().end());
609 bindDims(newWarpOp.getContext(), d0, d1);
610 auto indexExpr = dyn_cast<AffineDimExpr>(std::get<0>(it));
613 unsigned indexPos = indexExpr.getPosition();
614 unsigned vectorPos = cast<AffineDimExpr>(std::get<1>(it)).getPosition();
615 Value laneId = delinearized[vectorPos];
619 rewriter, loc, d0 + scale * d1, {
indices[indexPos], laneId});
621 newWriteOp.getIndicesMutable().assign(
indices);
627 LogicalResult tryExtractOp(RewriterBase &rewriter,
628 vector::TransferWriteOp writeOp,
629 WarpExecuteOnLane0Op warpOp)
const {
630 Location loc = writeOp.getLoc();
631 VectorType vecType = writeOp.getVectorType();
633 if (vecType.getNumElements() > maxNumElementsToExtract) {
637 "writes more elements ({0}) than allowed to extract ({1})",
638 vecType.getNumElements(), maxNumElementsToExtract));
642 if (llvm::all_of(warpOp.getOps(),
643 llvm::IsaPred<vector::TransferWriteOp, gpu::YieldOp>))
646 SmallVector<Value> yieldValues = {writeOp.getVector()};
647 SmallVector<Type> retTypes = {vecType};
648 SmallVector<size_t> newRetIndices;
650 rewriter, warpOp, yieldValues, retTypes, newRetIndices);
654 auto secondWarpOp = WarpExecuteOnLane0Op::create(rewriter, loc,
TypeRange(),
655 newWarpOp.getLaneid(),
656 newWarpOp.getWarpSize());
657 Block &body = secondWarpOp.getBodyRegion().front();
660 cast<vector::TransferWriteOp>(rewriter.
clone(*writeOp.getOperation()));
661 newWriteOp.getValueToStoreMutable().assign(
662 newWarpOp.getResult(newRetIndices[0]));
664 gpu::YieldOp::create(rewriter, newWarpOp.getLoc());
669 PatternRewriter &rewriter)
const override {
670 gpu::YieldOp yield = warpOp.getTerminator();
671 Operation *lastNode = yield->getPrevNode();
672 auto writeOp = dyn_cast_or_null<vector::TransferWriteOp>(lastNode);
676 Value maybeMask = writeOp.getMask();
677 if (!llvm::all_of(writeOp->getOperands(), [&](Value value) {
678 return writeOp.getVector() == value ||
679 (maybeMask && maybeMask == value) ||
680 warpOp.isDefinedOutsideOfRegion(value);
684 if (succeeded(tryDistributeOp(rewriter, writeOp, warpOp)))
688 if (writeOp.getMask())
691 if (succeeded(tryExtractOp(rewriter, writeOp, warpOp)))
701 vector::TransferWriteOp cloneWriteOp(RewriterBase &rewriter,
702 WarpExecuteOnLane0Op warpOp,
703 vector::TransferWriteOp writeOp,
704 VectorType targetType,
705 VectorType maybeMaskType)
const {
706 assert(writeOp->getParentOp() == warpOp &&
707 "write must be nested immediately under warp");
708 OpBuilder::InsertionGuard g(rewriter);
709 SmallVector<size_t> newRetIndices;
710 WarpExecuteOnLane0Op newWarpOp;
713 rewriter, warpOp,
ValueRange{writeOp.getVector(), writeOp.getMask()},
714 TypeRange{targetType, maybeMaskType}, newRetIndices);
717 rewriter, warpOp,
ValueRange{{writeOp.getVector()}},
722 cast<vector::TransferWriteOp>(rewriter.
clone(*writeOp.getOperation()));
724 newWriteOp.getValueToStoreMutable().assign(
725 newWarpOp.getResult(newRetIndices[0]));
727 newWriteOp.getMaskMutable().assign(newWarpOp.getResult(newRetIndices[1]));
732 unsigned maxNumElementsToExtract = 1;
755 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
756 PatternRewriter &rewriter)
const override {
757 OpOperand *yieldOperand = getWarpResult(warpOp, [](Operation *op) {
765 Value distributedVal = warpOp.getResult(operandIndex);
766 SmallVector<Value> yieldValues;
767 SmallVector<Type> retTypes;
768 Location loc = warpOp.getLoc();
771 if (
auto vecType = dyn_cast<VectorType>(distributedVal.
getType())) {
773 auto operandType = cast<VectorType>(operand.
get().
getType());
775 VectorType::get(vecType.getShape(), operandType.getElementType());
778 assert(!isa<VectorType>(operandType) &&
779 "unexpected yield of vector from op with scalar result type");
780 targetType = operandType;
782 retTypes.push_back(targetType);
783 yieldValues.push_back(operand.
get());
785 SmallVector<size_t> newRetIndices;
786 WarpExecuteOnLane0Op newWarpOp = moveRegionToNewWarpOpAndAppendReturns(
787 rewriter, warpOp, yieldValues, retTypes, newRetIndices);
789 SmallVector<Value> newOperands(elementWise->
getOperands().begin(),
791 for (
unsigned i : llvm::seq(
unsigned(0), elementWise->
getNumOperands())) {
792 newOperands[i] = newWarpOp.getResult(newRetIndices[i]);
794 OpBuilder::InsertionGuard g(rewriter);
797 rewriter, loc, elementWise, newOperands,
798 {newWarpOp.getResult(operandIndex).getType()});
822 PatternRewriter &rewriter)
const override {
823 OpOperand *yieldOperand =
828 auto dense = dyn_cast<SplatElementsAttr>(constantOp.getValue());
835 Attribute scalarAttr = dense.getSplatValue<Attribute>();
837 cast<ShapedType>(warpOp.getResult(operandIndex).getType()), scalarAttr);
838 Location loc = warpOp.getLoc();
840 Value distConstant = arith::ConstantOp::create(rewriter, loc, newAttr);
869 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
870 PatternRewriter &rewriter)
const override {
871 OpOperand *yieldOperand =
872 getWarpResult(warpOp, llvm::IsaPred<vector::StepOp>);
878 if (resTy.getNumElements() !=
static_cast<int64_t
>(warpOp.getWarpSize()))
881 llvm::formatv(
"Expected result size ({0}) to be of warp size ({1})",
882 resTy.getNumElements(), warpOp.getWarpSize()));
883 VectorType newVecTy =
884 cast<VectorType>(warpOp.getResult(operandIdx).getType());
886 Value laneIdVec = vector::BroadcastOp::create(rewriter, warpOp.getLoc(),
887 newVecTy, warpOp.getLaneid());
914 PatternRewriter &rewriter)
const override {
918 OpOperand *operand =
getWarpResult(warpOp, [](Operation *op) {
920 return isa<vector::TransferReadOp>(op) && op->
hasOneUse();
924 warpOp,
"warp result is not a vector.transfer_read op");
928 if (!warpOp.isDefinedOutsideOfRegion(read.getBase()))
930 read,
"source must be defined outside of the region");
933 Value distributedVal = warpOp.getResult(operandIndex);
935 SmallVector<Value, 4>
indices(read.getIndices().begin(),
936 read.getIndices().end());
937 auto sequentialType = cast<VectorType>(read.getResult().getType());
938 auto distributedType = cast<VectorType>(distributedVal.
getType());
940 AffineMap indexMap = map.
compose(read.getPermutationMap());
944 SmallVector<Value> delinearizedIds;
946 distributedType.getShape(), warpOp.getWarpSize(),
947 warpOp.getLaneid(), delinearizedIds)) {
949 read,
"cannot delinearize lane ID for distribution");
951 assert(!delinearizedIds.empty() || map.
getNumResults() == 0);
954 OpBuilder::InsertionGuard g(rewriter);
955 SmallVector<Value> additionalResults(
indices.begin(),
indices.end());
956 SmallVector<Type> additionalResultTypes(
indices.size(),
958 additionalResults.push_back(read.getPadding());
959 additionalResultTypes.push_back(read.getPadding().getType());
961 bool hasMask =
false;
962 if (read.getMask()) {
972 read,
"non-trivial permutation maps not supported");
973 VectorType maskType =
974 getDistributedType(read.getMaskType(), map, warpOp.getWarpSize());
975 additionalResults.push_back(read.getMask());
976 additionalResultTypes.push_back(maskType);
979 SmallVector<size_t> newRetIndices;
981 rewriter, warpOp, additionalResults, additionalResultTypes,
983 distributedVal = newWarpOp.getResult(operandIndex);
986 SmallVector<Value> newIndices;
987 for (int64_t i = 0, e =
indices.size(); i < e; ++i)
988 newIndices.push_back(newWarpOp.getResult(newRetIndices[i]));
993 bindDims(read.getContext(), d0, d1);
994 auto indexExpr = dyn_cast<AffineDimExpr>(std::get<0>(it));
997 unsigned indexPos = indexExpr.getPosition();
998 unsigned vectorPos = cast<AffineDimExpr>(std::get<1>(it)).getPosition();
999 int64_t scale = distributedType.getDimSize(vectorPos);
1001 rewriter, read.getLoc(), d0 + scale * d1,
1002 {newIndices[indexPos], delinearizedIds[vectorPos]});
1006 Value newPadding = newWarpOp.getResult(newRetIndices[
indices.size()]);
1009 hasMask ? newWarpOp.getResult(newRetIndices[newRetIndices.size() - 1])
1011 auto newRead = vector::TransferReadOp::create(
1012 rewriter, read.getLoc(), distributedVal.
getType(), read.getBase(),
1013 newIndices, read.getPermutationMapAttr(), newPadding, newMask,
1014 read.getInBoundsAttr());
1026 PatternRewriter &rewriter)
const override {
1027 SmallVector<Type> newResultTypes;
1028 newResultTypes.reserve(warpOp->getNumResults());
1029 SmallVector<Value> newYieldValues;
1030 newYieldValues.reserve(warpOp->getNumResults());
1033 gpu::YieldOp yield = warpOp.getTerminator();
1044 for (OpResult
result : warpOp.getResults()) {
1047 Value yieldOperand = yield.getOperand(
result.getResultNumber());
1048 auto it = dedupYieldOperandPositionMap.insert(
1049 std::make_pair(yieldOperand, newResultTypes.size()));
1050 dedupResultPositionMap.insert(std::make_pair(
result, it.first->second));
1053 newResultTypes.push_back(
result.getType());
1054 newYieldValues.push_back(yieldOperand);
1057 if (yield.getNumOperands() == newYieldValues.size())
1061 rewriter, warpOp, newYieldValues, newResultTypes);
1064 newWarpOp.getBody()->walk([&](Operation *op) {
1070 SmallVector<Value> newValues;
1071 newValues.reserve(warpOp->getNumResults());
1072 for (OpResult
result : warpOp.getResults()) {
1074 newValues.push_back(Value());
1076 newValues.push_back(
1077 newWarpOp.getResult(dedupResultPositionMap.lookup(
result)));
1089 PatternRewriter &rewriter)
const override {
1090 gpu::YieldOp yield = warpOp.getTerminator();
1092 unsigned resultIndex;
1093 for (OpOperand &operand : yield->getOpOperands()) {
1102 valForwarded = operand.
get();
1106 auto arg = dyn_cast<BlockArgument>(operand.
get());
1107 if (!arg || arg.getOwner()->getParentOp() != warpOp.getOperation())
1109 Value warpOperand = warpOp.getArgs()[arg.getArgNumber()];
1112 valForwarded = warpOperand;
1130 PatternRewriter &rewriter)
const override {
1131 OpOperand *operand =
1137 Location loc = broadcastOp.getLoc();
1139 cast<VectorType>(warpOp->getResultTypes()[operandNumber]);
1140 Value broadcastSrc = broadcastOp.getSource();
1141 Type broadcastSrcType = broadcastSrc.
getType();
1148 vector::BroadcastableToResult::Success)
1150 SmallVector<size_t> newRetIndices;
1152 rewriter, warpOp, {broadcastSrc}, {broadcastSrcType}, newRetIndices);
1154 Value broadcasted = vector::BroadcastOp::create(
1155 rewriter, loc, destVecType, newWarpOp->getResult(newRetIndices[0]));
1167 PatternRewriter &rewriter)
const override {
1168 OpOperand *operand =
1176 auto castDistributedType =
1177 cast<VectorType>(warpOp->getResultTypes()[operandNumber]);
1178 VectorType castOriginalType = oldCastOp.getSourceVectorType();
1179 VectorType castResultType = castDistributedType;
1181 FailureOr<VectorType> maybeSrcType =
1182 inferDistributedSrcType(castDistributedType, castOriginalType);
1183 if (
failed(maybeSrcType))
1185 castDistributedType = *maybeSrcType;
1187 SmallVector<size_t> newRetIndices;
1189 rewriter, warpOp, {oldCastOp.getSource()}, {castDistributedType},
1192 Value newCast = vector::ShapeCastOp::create(
1193 rewriter, oldCastOp.getLoc(), castResultType,
1194 newWarpOp->getResult(newRetIndices[0]));
1200 static FailureOr<VectorType>
1201 inferDistributedSrcType(VectorType distributedType, VectorType srcType) {
1202 unsigned distributedRank = distributedType.getRank();
1203 unsigned srcRank = srcType.getRank();
1204 if (distributedRank == srcRank)
1206 return distributedType;
1207 if (distributedRank < srcRank) {
1210 SmallVector<int64_t> shape(srcRank - distributedRank, 1);
1211 llvm::append_range(shape, distributedType.getShape());
1212 return VectorType::get(shape, distributedType.getElementType());
1224 return VectorType::get(distributedType.getNumElements(),
1225 srcType.getElementType());
1230 unsigned excessDims = distributedRank - srcRank;
1231 ArrayRef<int64_t> shape = distributedType.getShape();
1232 if (!llvm::all_of(shape.take_front(excessDims),
1233 [](int64_t d) { return d == 1; }))
1235 return VectorType::get(shape.drop_front(excessDims),
1236 distributedType.getElementType());
1260template <
typename OpType,
1261 typename = std::enable_if_t<llvm::is_one_of<
1262 OpType, vector::CreateMaskOp, vector::ConstantMaskOp>::value>>
1265 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
1266 PatternRewriter &rewriter)
const override {
1267 OpOperand *yieldOperand = getWarpResult(warpOp, (llvm::IsaPred<OpType>));
1275 if (mask->getOperands().size() &&
1276 !llvm::all_of(mask->getOperands(), [&](Value value) {
1277 return warpOp.isDefinedOutsideOfRegion(value);
1281 Location loc = mask->
getLoc();
1284 auto distType = cast<VectorType>(warpOp.getResult(operandIndex).getType());
1285 VectorType seqType = cast<VectorType>(mask->getResult(0).
getType());
1286 ArrayRef<int64_t> seqShape = seqType.getShape();
1287 ArrayRef<int64_t> distShape = distType.getShape();
1288 SmallVector<Value> materializedOperands;
1289 if constexpr (std::is_same_v<OpType, vector::CreateMaskOp>) {
1290 materializedOperands.append(mask->getOperands().begin(),
1291 mask->getOperands().end());
1293 auto constantMaskOp = cast<vector::ConstantMaskOp>(mask);
1294 auto dimSizes = constantMaskOp.getMaskDimSizesAttr().asArrayRef();
1295 for (
auto dimSize : dimSizes)
1296 materializedOperands.push_back(
1303 SmallVector<Value> delinearizedIds;
1304 if (!delinearizeLaneId(rewriter, loc, seqShape, distShape,
1305 warpOp.getWarpSize(), warpOp.getLaneid(),
1308 mask,
"cannot delinearize lane ID for distribution");
1309 assert(!delinearizedIds.empty());
1317 SmallVector<Value> newOperands;
1318 for (
int i = 0, e = distShape.size(); i < e; ++i) {
1324 Value maskDimIdx = affine::makeComposedAffineApply(
1325 rewriter, loc, s1 - s0 * distShape[i],
1326 {delinearizedIds[i], materializedOperands[i]});
1327 newOperands.push_back(maskDimIdx);
1331 vector::CreateMaskOp::create(rewriter, loc, distType, newOperands);
1366 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
1367 PatternRewriter &rewriter)
const override {
1368 OpOperand *operand =
1369 getWarpResult(warpOp, llvm::IsaPred<vector::InsertStridedSliceOp>);
1375 auto distributedType =
1376 cast<VectorType>(warpOp.getResult(operandNumber).getType());
1379 if (distributedType.getRank() < 2)
1381 insertOp,
"result vector type must be 2D or higher");
1384 auto yieldedType = cast<VectorType>(operand->
get().
getType());
1385 int64_t destDistributedDim =
1387 assert(destDistributedDim != -1 &&
"could not find distributed dimension");
1389 VectorType srcType = insertOp.getSourceVectorType();
1390 VectorType destType = insertOp.getDestVectorType();
1395 int64_t sourceDistributedDim =
1396 destDistributedDim - (destType.getRank() - srcType.getRank());
1397 if (sourceDistributedDim < 0)
1400 "distributed dimension must be in the last k dims of dest vector");
1402 if (srcType.getDimSize(sourceDistributedDim) !=
1403 destType.getDimSize(destDistributedDim))
1405 insertOp,
"distributed dimension must be fully inserted");
1406 SmallVector<int64_t> newSourceDistShape(
1407 insertOp.getSourceVectorType().getShape());
1408 newSourceDistShape[sourceDistributedDim] =
1409 distributedType.getDimSize(destDistributedDim);
1411 VectorType::get(newSourceDistShape, distributedType.getElementType());
1412 VectorType newDestTy = distributedType;
1413 SmallVector<size_t> newRetIndices;
1414 WarpExecuteOnLane0Op newWarpOp = moveRegionToNewWarpOpAndAppendReturns(
1415 rewriter, warpOp, {insertOp.getValueToStore(), insertOp.getDest()},
1416 {newSourceTy, newDestTy}, newRetIndices);
1418 Value distributedSource = newWarpOp->getResult(newRetIndices[0]);
1419 Value distributedDest = newWarpOp->getResult(newRetIndices[1]);
1422 Value newInsert = vector::InsertStridedSliceOp::create(
1423 rewriter, insertOp.getLoc(), distributedDest.
getType(),
1424 distributedSource, distributedDest, insertOp.getOffsets(),
1425 insertOp.getStrides());
1455 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
1456 PatternRewriter &rewriter)
const override {
1457 OpOperand *operand =
1458 getWarpResult(warpOp, llvm::IsaPred<vector::ExtractStridedSliceOp>);
1464 auto distributedType =
1465 cast<VectorType>(warpOp.getResult(operandNumber).getType());
1468 if (distributedType.getRank() < 2)
1470 extractOp,
"result vector type must be 2D or higher");
1473 auto yieldedType = cast<VectorType>(operand->
get().
getType());
1475 assert(distributedDim != -1 &&
"could not find distributed dimension");
1477 int64_t numOfExtractedDims =
1478 static_cast<int64_t
>(extractOp.getSizes().size());
1485 if (distributedDim < numOfExtractedDims) {
1486 int64_t distributedDimOffset =
1487 llvm::cast<IntegerAttr>(extractOp.getOffsets()[distributedDim])
1489 int64_t distributedDimSize =
1490 llvm::cast<IntegerAttr>(extractOp.getSizes()[distributedDim])
1492 if (distributedDimOffset != 0 ||
1493 distributedDimSize != yieldedType.getDimSize(distributedDim))
1495 extractOp,
"distributed dimension must be fully extracted");
1497 SmallVector<int64_t> newDistributedShape(
1498 extractOp.getSourceVectorType().getShape());
1499 newDistributedShape[distributedDim] =
1500 distributedType.getDimSize(distributedDim);
1501 auto newDistributedType =
1502 VectorType::get(newDistributedShape, distributedType.getElementType());
1503 SmallVector<size_t> newRetIndices;
1504 WarpExecuteOnLane0Op newWarpOp = moveRegionToNewWarpOpAndAppendReturns(
1505 rewriter, warpOp, {extractOp.getSource()}, {newDistributedType},
1508 SmallVector<Attribute> distributedSizes = llvm::map_to_vector(
1509 extractOp.getSizes(), [](Attribute attr) { return attr; });
1511 if (distributedDim <
static_cast<int64_t
>(distributedSizes.size()))
1513 distributedType.getDimSize(distributedDim));
1517 Value distributedVec = newWarpOp->getResult(newRetIndices[0]);
1518 Value newExtract = vector::ExtractStridedSliceOp::create(
1519 rewriter, extractOp.getLoc(), distributedType, distributedVec,
1520 extractOp.getOffsets(),
1521 ArrayAttr::get(rewriter.
getContext(), distributedSizes),
1522 extractOp.getStrides());
1533 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
1534 PatternRewriter &rewriter)
const override {
1535 OpOperand *operand =
1536 getWarpResult(warpOp, llvm::IsaPred<vector::ExtractOp>);
1541 VectorType extractSrcType = extractOp.getSourceVectorType();
1542 Location loc = extractOp.getLoc();
1545 if (extractSrcType.getRank() <= 1) {
1551 if (warpOp.getResult(operandNumber).getType() == operand->
get().
getType()) {
1557 SmallVector<size_t> newRetIndices;
1558 WarpExecuteOnLane0Op newWarpOp = moveRegionToNewWarpOpAndAppendReturns(
1559 rewriter, warpOp, {extractOp.getSource()},
1560 {extractOp.getSourceVectorType()}, newRetIndices);
1562 Value distributedVec = newWarpOp->getResult(newRetIndices[0]);
1564 Value newExtract = vector::ExtractOp::create(
1565 rewriter, loc, distributedVec, extractOp.getMixedPosition());
1572 auto distributedType =
1573 cast<VectorType>(warpOp.getResult(operandNumber).getType());
1574 auto yieldedType = cast<VectorType>(operand->
get().
getType());
1576 assert(distributedDim != -1 &&
"could not find distributed dimension");
1577 (void)distributedDim;
1580 SmallVector<int64_t> newDistributedShape(extractSrcType.getShape());
1581 for (
int i = 0; i < distributedType.getRank(); ++i)
1582 newDistributedShape[i + extractOp.getNumIndices()] =
1583 distributedType.getDimSize(i);
1584 auto newDistributedType =
1585 VectorType::get(newDistributedShape, distributedType.getElementType());
1586 SmallVector<size_t> newRetIndices;
1587 WarpExecuteOnLane0Op newWarpOp = moveRegionToNewWarpOpAndAppendReturns(
1588 rewriter, warpOp, {extractOp.getSource()}, {newDistributedType},
1591 Value distributedVec = newWarpOp->getResult(newRetIndices[0]);
1593 Value newExtract = vector::ExtractOp::create(rewriter, loc, distributedVec,
1594 extractOp.getMixedPosition());
1604 WarpOpExtractScalar(MLIRContext *ctx, WarpShuffleFromIdxFn fn,
1605 PatternBenefit
b = 1)
1606 : WarpDistributionPattern(ctx,
b), warpShuffleFromIdxFn(std::move(fn)) {}
1607 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
1608 PatternRewriter &rewriter)
const override {
1609 OpOperand *operand =
1610 getWarpResult(warpOp, llvm::IsaPred<vector::ExtractOp>);
1615 VectorType extractSrcType = extractOp.getSourceVectorType();
1617 if (extractSrcType.getRank() > 1) {
1619 extractOp,
"only 0-D or 1-D source supported for now");
1623 if (!extractSrcType.getElementType().isF32() &&
1624 !extractSrcType.getElementType().isInteger(32))
1626 extractOp,
"only f32/i32 element types are supported");
1627 bool is0dOrVec1Extract = extractSrcType.getNumElements() == 1;
1628 Type elType = extractSrcType.getElementType();
1629 VectorType distributedVecType;
1630 if (!is0dOrVec1Extract) {
1631 assert(extractSrcType.getRank() == 1 &&
1632 "expected that extract src rank is 0 or 1");
1633 if (extractSrcType.getShape()[0] % warpOp.getWarpSize() != 0)
1635 int64_t elementsPerLane =
1636 extractSrcType.getShape()[0] / warpOp.getWarpSize();
1637 distributedVecType = VectorType::get({elementsPerLane}, elType);
1639 distributedVecType = extractSrcType;
1642 SmallVector<Value> additionalResults{extractOp.getSource()};
1643 SmallVector<Type> additionalResultTypes{distributedVecType};
1644 additionalResults.append(
1645 SmallVector<Value>(extractOp.getDynamicPosition()));
1646 additionalResultTypes.append(
1647 SmallVector<Type>(extractOp.getDynamicPosition().getTypes()));
1649 Location loc = extractOp.getLoc();
1650 SmallVector<size_t> newRetIndices;
1651 WarpExecuteOnLane0Op newWarpOp = moveRegionToNewWarpOpAndAppendReturns(
1652 rewriter, warpOp, additionalResults, additionalResultTypes,
1655 Value distributedVec = newWarpOp->getResult(newRetIndices[0]);
1659 if (is0dOrVec1Extract) {
1661 SmallVector<int64_t>
indices(extractSrcType.getRank(), 0);
1663 vector::ExtractOp::create(rewriter, loc, distributedVec,
indices);
1669 int64_t staticPos = extractOp.getStaticPosition()[0];
1670 OpFoldResult pos = ShapedType::isDynamic(staticPos)
1671 ? (newWarpOp->getResult(newRetIndices[1]))
1675 int64_t elementsPerLane = distributedVecType.getShape()[0];
1678 Value broadcastFromTid = affine::makeComposedAffineApply(
1679 rewriter, loc, sym0.
ceilDiv(elementsPerLane), pos);
1682 elementsPerLane == 1
1684 : affine::makeComposedAffineApply(rewriter, loc,
1685 sym0 % elementsPerLane, pos);
1687 vector::ExtractOp::create(rewriter, loc, distributedVec, newPos);
1690 Value shuffled = warpShuffleFromIdxFn(
1691 loc, rewriter, extracted, broadcastFromTid, newWarpOp.getWarpSize());
1697 WarpShuffleFromIdxFn warpShuffleFromIdxFn;
1704 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
1705 PatternRewriter &rewriter)
const override {
1706 OpOperand *operand = getWarpResult(warpOp, llvm::IsaPred<vector::InsertOp>);
1711 VectorType vecType = insertOp.getDestVectorType();
1712 VectorType distrType =
1713 cast<VectorType>(warpOp.getResult(operandNumber).getType());
1716 if (vecType.getRank() > 1) {
1718 insertOp,
"only 0-D or 1-D source supported for now");
1722 SmallVector<Value> additionalResults{insertOp.getDest(),
1723 insertOp.getValueToStore()};
1724 SmallVector<Type> additionalResultTypes{
1725 distrType, insertOp.getValueToStore().getType()};
1726 additionalResults.append(SmallVector<Value>(insertOp.getDynamicPosition()));
1727 additionalResultTypes.append(
1728 SmallVector<Type>(insertOp.getDynamicPosition().getTypes()));
1730 Location loc = insertOp.getLoc();
1731 SmallVector<size_t> newRetIndices;
1732 WarpExecuteOnLane0Op newWarpOp = moveRegionToNewWarpOpAndAppendReturns(
1733 rewriter, warpOp, additionalResults, additionalResultTypes,
1736 Value distributedVec = newWarpOp->getResult(newRetIndices[0]);
1737 Value newSource = newWarpOp->getResult(newRetIndices[1]);
1741 if (vecType.getRank() != 0) {
1742 int64_t staticPos = insertOp.getStaticPosition()[0];
1743 pos = ShapedType::isDynamic(staticPos)
1744 ? (newWarpOp->getResult(newRetIndices[2]))
1749 if (vecType == distrType) {
1751 SmallVector<OpFoldResult>
indices;
1755 newInsert = vector::InsertOp::create(rewriter, loc, newSource,
1764 int64_t elementsPerLane = distrType.getShape()[0];
1767 Value insertingLane = affine::makeComposedAffineApply(
1768 rewriter, loc, sym0.
ceilDiv(elementsPerLane), pos);
1770 OpFoldResult newPos = affine::makeComposedFoldedAffineApply(
1771 rewriter, loc, sym0 % elementsPerLane, pos);
1772 Value isInsertingLane =
1773 arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::eq,
1774 newWarpOp.getLaneid(), insertingLane);
1777 rewriter, loc, isInsertingLane,
1779 [&](OpBuilder &builder, Location loc) {
1780 Value newInsert = vector::InsertOp::create(
1781 builder, loc, newSource, distributedVec, newPos);
1782 scf::YieldOp::create(builder, loc, newInsert);
1785 [&](OpBuilder &builder, Location loc) {
1786 scf::YieldOp::create(builder, loc, distributedVec);
1796 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
1797 PatternRewriter &rewriter)
const override {
1798 OpOperand *operand = getWarpResult(warpOp, llvm::IsaPred<vector::InsertOp>);
1803 Location loc = insertOp.getLoc();
1806 if (insertOp.getDestVectorType().getRank() <= 1) {
1812 if (warpOp.getResult(operandNumber).getType() == operand->
get().
getType()) {
1815 SmallVector<size_t> newRetIndices;
1816 WarpExecuteOnLane0Op newWarpOp = moveRegionToNewWarpOpAndAppendReturns(
1817 rewriter, warpOp, {insertOp.getValueToStore(), insertOp.getDest()},
1818 {insertOp.getValueToStoreType(), insertOp.getDestVectorType()},
1821 Value distributedSrc = newWarpOp->getResult(newRetIndices[0]);
1822 Value distributedDest = newWarpOp->getResult(newRetIndices[1]);
1823 Value newResult = vector::InsertOp::create(rewriter, loc, distributedSrc,
1825 insertOp.getMixedPosition());
1832 auto distrDestType =
1833 cast<VectorType>(warpOp.getResult(operandNumber).getType());
1834 auto yieldedType = cast<VectorType>(operand->
get().
getType());
1835 int64_t distrDestDim = -1;
1836 for (int64_t i = 0; i < yieldedType.getRank(); ++i) {
1837 if (distrDestType.getDimSize(i) != yieldedType.getDimSize(i)) {
1840 assert(distrDestDim == -1 &&
"found multiple distributed dims");
1844 assert(distrDestDim != -1 &&
"could not find distributed dimension");
1847 VectorType srcVecType = cast<VectorType>(insertOp.getValueToStoreType());
1848 SmallVector<int64_t> distrSrcShape(srcVecType.getShape());
1855 int64_t distrSrcDim = distrDestDim - insertOp.getNumIndices();
1856 if (distrSrcDim >= 0)
1857 distrSrcShape[distrSrcDim] = distrDestType.getDimSize(distrDestDim);
1859 VectorType::get(distrSrcShape, distrDestType.getElementType());
1862 SmallVector<size_t> newRetIndices;
1863 WarpExecuteOnLane0Op newWarpOp = moveRegionToNewWarpOpAndAppendReturns(
1864 rewriter, warpOp, {insertOp.getValueToStore(), insertOp.getDest()},
1865 {distrSrcType, distrDestType}, newRetIndices);
1867 Value distributedSrc = newWarpOp->getResult(newRetIndices[0]);
1868 Value distributedDest = newWarpOp->getResult(newRetIndices[1]);
1872 if (distrSrcDim >= 0) {
1874 newResult = vector::InsertOp::create(rewriter, loc, distributedSrc,
1876 insertOp.getMixedPosition());
1879 int64_t elementsPerLane = distrDestType.getDimSize(distrDestDim);
1880 SmallVector<OpFoldResult> pos = insertOp.getMixedPosition();
1884 rewriter, loc, newPos[distrDestDim] / elementsPerLane);
1885 Value isInsertingLane =
1886 arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::eq,
1887 newWarpOp.getLaneid(), insertingLane);
1889 newPos[distrDestDim] %= elementsPerLane;
1890 auto insertingBuilder = [&](OpBuilder &builder, Location loc) {
1891 Value newInsert = vector::InsertOp::create(builder, loc, distributedSrc,
1892 distributedDest, newPos);
1893 scf::YieldOp::create(builder, loc, newInsert);
1895 auto nonInsertingBuilder = [&](OpBuilder &builder, Location loc) {
1896 scf::YieldOp::create(builder, loc, distributedDest);
1898 newResult = scf::IfOp::create(rewriter, loc, isInsertingLane,
1900 nonInsertingBuilder)
1937 : WarpDistributionPattern(ctx,
b), distributionMapFn(std::move(fn)) {}
1939 PatternRewriter &rewriter)
const override {
1940 gpu::YieldOp warpOpYield = warpOp.getTerminator();
1942 Operation *lastNode = warpOpYield->getPrevNode();
1943 auto ifOp = dyn_cast_or_null<scf::IfOp>(lastNode);
1954 SmallVector<Value> nonIfYieldValues;
1955 SmallVector<unsigned> nonIfYieldIndices;
1956 llvm::SmallDenseMap<unsigned, unsigned> ifResultMapping;
1957 llvm::SmallDenseMap<unsigned, VectorType> ifResultDistTypes;
1958 for (OpOperand &yieldOperand : warpOpYield->getOpOperands()) {
1961 nonIfYieldValues.push_back(yieldOperand.
get());
1962 nonIfYieldIndices.push_back(yieldOperandIdx);
1965 OpResult ifResult = cast<OpResult>(yieldOperand.
get());
1967 ifResultMapping[yieldOperandIdx] = ifResultIdx;
1970 if (!isa<VectorType>(ifResult.
getType()))
1972 VectorType distType =
1973 cast<VectorType>(warpOp.getResult(yieldOperandIdx).getType());
1974 ifResultDistTypes[ifResultIdx] = distType;
1979 auto [escapingValuesThen, escapingValueInputTypesThen,
1980 escapingValueDistTypesThen] =
1981 getInnerRegionEscapingValues(warpOp, ifOp.getThenRegion(),
1983 auto [escapingValuesElse, escapingValueInputTypesElse,
1984 escapingValueDistTypesElse] =
1985 getInnerRegionEscapingValues(warpOp, ifOp.getElseRegion(),
1987 if (llvm::is_contained(escapingValueDistTypesThen, Type{}) ||
1988 llvm::is_contained(escapingValueDistTypesElse, Type{}))
1996 SmallVector<Value> newWarpOpYieldValues{ifOp.getCondition()};
1997 newWarpOpYieldValues.append(escapingValuesThen.begin(),
1998 escapingValuesThen.end());
1999 newWarpOpYieldValues.append(escapingValuesElse.begin(),
2000 escapingValuesElse.end());
2001 SmallVector<Type> newWarpOpDistTypes{ifOp.getCondition().getType()};
2002 newWarpOpDistTypes.append(escapingValueDistTypesThen.begin(),
2003 escapingValueDistTypesThen.end());
2004 newWarpOpDistTypes.append(escapingValueDistTypesElse.begin(),
2005 escapingValueDistTypesElse.end());
2007 for (
auto [idx, val] :
2008 llvm::zip_equal(nonIfYieldIndices, nonIfYieldValues)) {
2009 newWarpOpYieldValues.push_back(val);
2010 newWarpOpDistTypes.push_back(warpOp.getResult(idx).getType());
2014 SmallVector<size_t> newIndices;
2016 rewriter, warpOp, newWarpOpYieldValues, newWarpOpDistTypes, newIndices);
2018 SmallVector<Type> newIfOpDistResTypes;
2019 for (
auto [i, res] : llvm::enumerate(ifOp.getResults())) {
2020 Type distType = cast<Value>(res).getType();
2021 if (
auto vecType = dyn_cast<VectorType>(distType)) {
2022 AffineMap map = distributionMapFn(cast<Value>(res));
2024 distType = ifResultDistTypes.count(i)
2025 ? ifResultDistTypes[i]
2026 : getDistributedType(
2028 map.
isEmpty() ? 1 : newWarpOp.getWarpSize());
2030 newIfOpDistResTypes.push_back(distType);
2033 OpBuilder::InsertionGuard g(rewriter);
2035 auto newIfOp = scf::IfOp::create(
2036 rewriter, ifOp.getLoc(), newIfOpDistResTypes,
2037 newWarpOp.getResult(newIndices[0]),
static_cast<bool>(ifOp.thenBlock()),
2038 static_cast<bool>(ifOp.elseBlock()));
2039 auto encloseRegionInWarpOp =
2041 llvm::SmallSetVector<Value, 32> &escapingValues,
2042 SmallVector<Type> &escapingValueInputTypes,
2043 size_t warpResRangeStart) {
2044 OpBuilder::InsertionGuard g(rewriter);
2048 llvm::SmallDenseMap<Value, int64_t> escapeValToBlockArgIndex;
2049 SmallVector<Value> innerWarpInputVals;
2050 SmallVector<Type> innerWarpInputTypes;
2051 for (
size_t i = 0; i < escapingValues.size();
2052 ++i, ++warpResRangeStart) {
2053 innerWarpInputVals.push_back(
2054 newWarpOp.getResult(newIndices[warpResRangeStart]));
2055 escapeValToBlockArgIndex[escapingValues[i]] =
2056 innerWarpInputTypes.size();
2057 innerWarpInputTypes.push_back(escapingValueInputTypes[i]);
2059 auto innerWarp = WarpExecuteOnLane0Op::create(
2060 rewriter, newWarpOp.getLoc(), newIfOp.getResultTypes(),
2061 newWarpOp.getLaneid(), newWarpOp.getWarpSize(),
2062 innerWarpInputVals, innerWarpInputTypes);
2064 Region &warpRegion = innerWarp.getWarpRegion();
2068 innerWarp.getWarpRegion().addArguments(
2069 innerWarpInputTypes,
2070 SmallVector<Location>(innerWarpInputTypes.size(), ifOp.getLoc()));
2072 SmallVector<Value> yieldOperands;
2074 yieldOperands.push_back(operand);
2078 gpu::YieldOp::create(rewriter, innerWarp.getLoc(), yieldOperands);
2080 scf::YieldOp::create(rewriter, ifOp.getLoc(), innerWarp.getResults());
2084 innerWarp.walk([&](Operation *op) {
2085 SmallVector<std::pair<unsigned, Value>> replacements;
2087 auto it = escapeValToBlockArgIndex.find(operand.
get());
2088 if (it == escapeValToBlockArgIndex.end())
2090 replacements.emplace_back(
2092 innerWarp.getBodyRegion().getArgument(it->second));
2094 if (!replacements.empty()) {
2096 for (
auto [idx, newVal] : replacements)
2101 mlir::vector::moveScalarUniformCode(innerWarp);
2103 encloseRegionInWarpOp(&ifOp.getThenRegion().front(),
2104 &newIfOp.getThenRegion().front(), escapingValuesThen,
2105 escapingValueInputTypesThen, 1);
2106 if (!ifOp.getElseRegion().empty())
2107 encloseRegionInWarpOp(&ifOp.getElseRegion().front(),
2108 &newIfOp.getElseRegion().front(),
2109 escapingValuesElse, escapingValueInputTypesElse,
2110 1 + escapingValuesThen.size());
2113 for (
auto [origIdx, newIdx] : ifResultMapping)
2115 newIfOp.getResult(newIdx), newIfOp);
2123 OpBuilder::InsertionGuard guard(rewriter);
2125 Operation *yield = newWarpOp.getTerminator();
2127 for (
auto [origIdx, ifResultIdx] : ifResultMapping) {
2128 Value poison = ub::PoisonOp::create(
2129 rewriter, ifOp.getLoc(), ifOp.getResult(ifResultIdx).getType());
2178 : WarpDistributionPattern(ctx,
b), distributionMapFn(std::move(fn)) {}
2179 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
2180 PatternRewriter &rewriter)
const override {
2181 gpu::YieldOp warpOpYield = warpOp.getTerminator();
2183 Operation *lastNode = warpOpYield->getPrevNode();
2184 auto forOp = dyn_cast_or_null<scf::ForOp>(lastNode);
2189 auto [escapingValues, escapingValueInputTypes, escapingValueDistTypes] =
2190 getInnerRegionEscapingValues(warpOp, forOp.getBodyRegion(),
2192 if (llvm::is_contained(escapingValueDistTypes, Type{}))
2203 SmallVector<Value> nonForYieldedValues;
2204 SmallVector<unsigned> nonForResultIndices;
2205 llvm::SmallDenseMap<unsigned, unsigned> forResultMapping;
2206 llvm::SmallDenseMap<unsigned, VectorType> forResultDistTypes;
2207 llvm::SmallBitVector forResultsMapped(forOp.getNumResults());
2208 for (OpOperand &yieldOperand : warpOpYield->getOpOperands()) {
2211 nonForYieldedValues.push_back(yieldOperand.
get());
2215 OpResult forResult = cast<OpResult>(yieldOperand.
get());
2218 forResultsMapped.set(forResultNumber);
2221 if (!isa<VectorType>(forResult.
getType()))
2223 VectorType distType = cast<VectorType>(
2225 forResultDistTypes[forResultNumber] = distType;
2233 SmallVector<Value> newWarpOpYieldValues;
2234 SmallVector<Type> newWarpOpDistTypes;
2235 newWarpOpYieldValues.insert(
2236 newWarpOpYieldValues.end(),
2237 {forOp.getLowerBound(), forOp.getUpperBound(), forOp.getStep()});
2238 newWarpOpDistTypes.insert(newWarpOpDistTypes.end(),
2239 {forOp.getLowerBound().getType(),
2240 forOp.getUpperBound().getType(),
2241 forOp.getStep().getType()});
2242 for (
auto [i, initArg] : llvm::enumerate(forOp.getInitArgs())) {
2243 newWarpOpYieldValues.push_back(initArg);
2245 Type distType = initArg.getType();
2246 if (
auto vecType = dyn_cast<VectorType>(distType)) {
2250 AffineMap map = distributionMapFn(initArg);
2252 forResultDistTypes.count(i)
2253 ? forResultDistTypes[i]
2254 : getDistributedType(vecType, map,
2255 map.
isEmpty() ? 1 : warpOp.getWarpSize());
2257 newWarpOpDistTypes.push_back(distType);
2260 newWarpOpYieldValues.insert(newWarpOpYieldValues.end(),
2261 escapingValues.begin(), escapingValues.end());
2262 newWarpOpDistTypes.insert(newWarpOpDistTypes.end(),
2263 escapingValueDistTypes.begin(),
2264 escapingValueDistTypes.end());
2268 llvm::zip_equal(nonForResultIndices, nonForYieldedValues)) {
2269 newWarpOpYieldValues.push_back(v);
2270 newWarpOpDistTypes.push_back(warpOp.getResult(i).getType());
2273 SmallVector<size_t> newIndices;
2274 WarpExecuteOnLane0Op newWarpOp = moveRegionToNewWarpOpAndAppendReturns(
2275 rewriter, warpOp, newWarpOpYieldValues, newWarpOpDistTypes, newIndices);
2279 const unsigned initArgsStartIdx = 3;
2280 const unsigned escapingValuesStartIdx =
2282 forOp.getInitArgs().size();
2284 SmallVector<Value> newForOpOperands;
2285 for (
size_t i = initArgsStartIdx; i < escapingValuesStartIdx; ++i)
2286 newForOpOperands.push_back(newWarpOp.getResult(newIndices[i]));
2289 OpBuilder::InsertionGuard g(rewriter);
2291 auto newForOp = scf::ForOp::create(
2292 rewriter, forOp.getLoc(),
2293 newWarpOp.getResult(newIndices[0]),
2294 newWarpOp.getResult(newIndices[1]),
2295 newWarpOp.getResult(newIndices[2]), newForOpOperands,
2296 nullptr, forOp.getUnsignedCmp());
2302 SmallVector<Value> innerWarpInput(newForOp.getRegionIterArgs().begin(),
2303 newForOp.getRegionIterArgs().end());
2304 SmallVector<Type> innerWarpInputType(forOp.getResultTypes().begin(),
2305 forOp.getResultTypes().end());
2309 llvm::SmallDenseMap<Value, int64_t> argIndexMapping;
2310 for (
size_t i = escapingValuesStartIdx;
2311 i < escapingValuesStartIdx + escapingValues.size(); ++i) {
2312 innerWarpInput.push_back(newWarpOp.getResult(newIndices[i]));
2313 argIndexMapping[escapingValues[i - escapingValuesStartIdx]] =
2314 innerWarpInputType.size();
2315 innerWarpInputType.push_back(
2316 escapingValueInputTypes[i - escapingValuesStartIdx]);
2319 auto innerWarp = WarpExecuteOnLane0Op::create(
2320 rewriter, newWarpOp.getLoc(), newForOp.getResultTypes(),
2321 newWarpOp.getLaneid(), newWarpOp.getWarpSize(), innerWarpInput,
2322 innerWarpInputType);
2325 SmallVector<Value> argMapping;
2326 argMapping.push_back(newForOp.getInductionVar());
2327 for (Value args : innerWarp.getBody()->getArguments())
2328 argMapping.push_back(args);
2330 argMapping.resize(forOp.getBody()->getNumArguments());
2331 SmallVector<Value> yieldOperands;
2332 for (Value operand : forOp.getBody()->getTerminator()->getOperands()) {
2333 if (BlockArgument blockArg = dyn_cast<BlockArgument>(operand);
2334 blockArg && blockArg.getOwner() == forOp.getBody()) {
2335 yieldOperands.push_back(argMapping[blockArg.getArgNumber()]);
2338 yieldOperands.push_back(operand);
2341 rewriter.
eraseOp(forOp.getBody()->getTerminator());
2342 rewriter.
mergeBlocks(forOp.getBody(), innerWarp.getBody(), argMapping);
2347 gpu::YieldOp::create(rewriter, innerWarp.getLoc(), yieldOperands);
2351 if (!innerWarp.getResults().empty())
2352 scf::YieldOp::create(rewriter, forOp.getLoc(), innerWarp.getResults());
2356 for (
auto [origIdx, newIdx] : forResultMapping)
2358 newForOp.getResult(newIdx), newForOp);
2363 for (OpResult
result : forOp.getResults()) {
2364 if (forResultsMapped.test(
result.getResultNumber()))
2366 result, forOp.getInitArgs()[
result.getResultNumber()]);
2372 newForOp.walk([&](Operation *op) {
2373 SmallVector<std::pair<unsigned, Value>> replacements;
2375 auto it = argIndexMapping.find(operand.
get());
2376 if (it == argIndexMapping.end())
2378 replacements.emplace_back(
2380 innerWarp.getBodyRegion().getArgument(it->second));
2382 if (!replacements.empty()) {
2384 for (
auto [idx, newVal] : replacements)
2391 mlir::vector::moveScalarUniformCode(innerWarp);
2419 WarpOpReduction(MLIRContext *context,
2420 DistributedReductionFn distributedReductionFn,
2421 PatternBenefit benefit = 1)
2422 : WarpDistributionPattern(context, benefit),
2423 distributedReductionFn(std::move(distributedReductionFn)) {}
2425 LogicalResult matchAndRewrite(WarpExecuteOnLane0Op warpOp,
2426 PatternRewriter &rewriter)
const override {
2427 OpOperand *yieldOperand =
2428 getWarpResult(warpOp, llvm::IsaPred<vector::ReductionOp>);
2434 auto vectorType = cast<VectorType>(reductionOp.getVector().getType());
2436 if (vectorType.getRank() != 1)
2438 warpOp,
"Only rank 1 reductions can be distributed.");
2439 if (vectorType.isScalable())
2441 warpOp,
"Scalable reductions cannot be distributed.");
2443 if (vectorType.getShape()[0] % warpOp.getWarpSize() != 0)
2445 warpOp,
"Reduction vector dimension must match was size.");
2446 if (!reductionOp.getType().isIntOrFloat())
2448 warpOp,
"Reduction distribution currently only supports floats and "
2451 int64_t numElements = vectorType.getShape()[0] / warpOp.getWarpSize();
2454 SmallVector<Value> yieldValues = {reductionOp.getVector()};
2455 SmallVector<Type> retTypes = {
2456 VectorType::get({numElements}, reductionOp.getType())};
2457 if (reductionOp.getAcc()) {
2458 yieldValues.push_back(reductionOp.getAcc());
2459 retTypes.push_back(reductionOp.getAcc().getType());
2461 SmallVector<size_t> newRetIndices;
2462 WarpExecuteOnLane0Op newWarpOp = moveRegionToNewWarpOpAndAppendReturns(
2463 rewriter, warpOp, yieldValues, retTypes, newRetIndices);
2467 Value laneValVec = newWarpOp.getResult(newRetIndices[0]);
2470 distributedReductionFn(reductionOp.getLoc(), rewriter, laneValVec,
2471 reductionOp.getKind(), newWarpOp.getWarpSize());
2472 if (reductionOp.getAcc()) {
2474 rewriter, reductionOp.getLoc(), reductionOp.getKind(), fullReduce,
2475 newWarpOp.getResult(newRetIndices[1]));
2482 DistributedReductionFn distributedReductionFn;
2492void mlir::vector::populateDistributeTransferWriteOpPatterns(
2495 patterns.
add<WarpOpTransferWrite>(patterns.
getContext(), distributionMapFn,
2496 maxNumElementsToExtract, benefit);
2499void mlir::vector::populatePropagateWarpVectorDistributionPatterns(
2501 const WarpShuffleFromIdxFn &warpShuffleFromIdxFn,
PatternBenefit benefit,
2503 patterns.
add<WarpOpTransferRead>(patterns.
getContext(), readBenefit);
2504 patterns.
add<WarpOpElementwise, WarpOpDeadResult, WarpOpBroadcast,
2505 WarpOpShapeCast, WarpOpExtract, WarpOpForwardOperand,
2506 WarpOpConstant, WarpOpInsertScalar, WarpOpInsert,
2507 WarpOpCreateMask<vector::CreateMaskOp>,
2508 WarpOpCreateMask<vector::ConstantMaskOp>,
2509 WarpOpExtractStridedSlice, WarpOpInsertStridedSlice, WarpOpStep>(
2511 patterns.
add<WarpOpExtractScalar>(patterns.
getContext(), warpShuffleFromIdxFn,
2513 patterns.
add<WarpOpScfForOp>(patterns.
getContext(), distributionMapFn,
2515 patterns.
add<WarpOpScfIfOp>(patterns.
getContext(), distributionMapFn,
2519void mlir::vector::populateDistributeReduction(
2521 const DistributedReductionFn &distributedReductionFn,
2523 patterns.
add<WarpOpReduction>(patterns.
getContext(), distributedReductionFn,
2530 return llvm::all_of(op->
getOperands(), definedOutside) &&
2534void mlir::vector::moveScalarUniformCode(WarpExecuteOnLane0Op warpOp) {
2535 Block *body = warpOp.getBody();
2538 llvm::SmallSetVector<Operation *, 8> opsToMove;
2541 auto isDefinedOutsideOfBody = [&](
Value value) {
2543 return (definingOp && opsToMove.count(definingOp)) ||
2544 warpOp.isDefinedOutsideOfRegion(value);
2551 return isa<VectorType>(result.getType());
2553 if (!hasVectorResult &&
canBeHoisted(&op, isDefinedOutsideOfBody))
2554 opsToMove.insert(&op);
static llvm::ManagedStatic< PassManagerOptions > options
static AffineMap calculateImplicitMap(VectorType sequentialType, VectorType distributedType)
Currently the distribution map is implicit based on the vector shape.
static Value tryReuseArgBuffer(SmallVectorImpl< std::pair< Value, bool > > &buffers, Type targetType, Location loc, RewriterBase &rewriter)
Reuse an args buffer from buffers to transit a value of targetType, or return null if none fits.
static Operation * cloneOpWithOperandsAndTypes(RewriterBase &rewriter, Location loc, Operation *op, ArrayRef< Value > operands, ArrayRef< Type > resultTypes)
static bool isBlockInCFGLoop(Block *block)
Return true if block is part of a CFG cycle, which LoopLikeOpInterface does not cover.
static int getDistributedDim(VectorType sequentialType, VectorType distributedType)
Given a sequential and distributed vector type, returns the distributed dimension.
static bool canBeHoisted(Operation *op, function_ref< bool(Value)> definedOutside)
Helper to know if an op can be hoisted out of the region.
static bool isInCFGLoop(Block *block)
Return true if block or any of its ancestor blocks is part of a CFG cycle, which LoopLikeOpInterface ...
AffineExpr ceilDiv(uint64_t v) const
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
unsigned getDimPosition(unsigned idx) const
Extracts the position of the dimensional expression at the given result, when the caller knows it is ...
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
bool isEmpty() const
Returns true if this affine map is an empty map, i.e., () -> ().
ArrayRef< AffineExpr > getResults() const
unsigned getNumResults() const
AffineMap compose(AffineMap map) const
Returns the AffineMap resulting from composing this with map.
bool isIdentity() const
Returns true if this affine map is an identity affine map.
Block represents an ordered list of Operations.
BlockArgument getArgument(unsigned i)
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
SuccessorRange getSuccessors()
Operation * getTerminator()
Get the terminator operation of this block.
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
IntegerAttr getIndexAttr(int64_t value)
AffineExpr getAffineConstantExpr(int64_t constant)
IntegerAttr getI64IntegerAttr(int64_t value)
MLIRContext * getContext() const
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
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...
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
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.
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
This class represents an operand of an operation.
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
unsigned getResultNumber() const
Returns the number of this result.
StringRef getStringRef() const
Return the name of this operation. This always succeeds.
Operation is the basic unit of execution within MLIR.
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.
unsigned getNumRegions()
Returns the number of regions held by this operation.
MutableArrayRef< OpOperand > getOpOperands()
unsigned getNumOperands()
Attribute getPropertiesAsAttribute()
Return the properties converted to an attribute.
OperationName getName()
The name of an operation is the key identifier for it.
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
operand_range getOperands()
Returns an iterator on the underlying Value's.
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
result_range getResults()
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Operation * getParentOp()
Return the parent operation this region is attached to.
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void 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 finalizeOpModification(Operation *op)
This method is used to signal the end of an in-place modification of the given operation.
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.
void inlineRegionBefore(Region ®ion, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
virtual void startOpModification(Operation *op)
This method is used to notify the rewriter that an in-place operation modification is about to happen...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
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.
Region * getParentRegion()
Return the Region in which this Value is defined.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
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...
Value makeArithReduction(OpBuilder &b, Location loc, CombiningKind kind, Value v1, Value acc, arith::FastMathFlagsAttr fastmath=nullptr, Value mask=nullptr)
Returns the result value of reducing two scalar/vector values with the corresponding arith operation.
std::function< AffineMap(Value)> DistributionMapFn
BroadcastableToResult isBroadcastableTo(Type srcType, VectorType dstVectorType, std::pair< VectorDim, VectorDim > *mismatchingDims=nullptr)
Return whether srcType can be broadcast to dstVectorType under the semantics of the vector....
void populateWarpExecuteOnLane0OpToScfForPattern(RewritePatternSet &patterns, const WarpExecuteOnLane0LoweringOptions &options, PatternBenefit benefit=1)
SmallVector< int64_t > getAsIntegers(ArrayRef< Value > values)
Returns the integer numbers in values.
Include the generated interface declarations.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
bool isOpTriviallyDead(Operation *op)
Return true if the given operation is unused, and has no side effects on memory that prevent erasing.
void bindSymbols(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to SymbolExpr at positions: [0 .
AffineMap compressUnusedDims(AffineMap map)
Drop the dims that are not used.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
void visitUsedValuesDefinedAbove(Region ®ion, Region &limit, function_ref< void(OpOperand *)> callback)
Calls callback for each use of a value within region or its descendants that was defined at the ances...
llvm::function_ref< Fn > function_ref
AffineExpr getAffineSymbolExpr(unsigned position, MLIRContext *context)
This represents an operation in an abstracted form, suitable for use with the builder APIs.
WarpExecuteOnLane0Op moveRegionToNewWarpOpAndAppendReturns(RewriterBase &rewriter, WarpExecuteOnLane0Op warpOp, ValueRange newYieldedValues, TypeRange newReturnTypes, SmallVector< size_t > &indices) const
Helper to create a new WarpExecuteOnLane0Op region with extra outputs.
bool delinearizeLaneId(OpBuilder &builder, Location loc, ArrayRef< int64_t > originalShape, ArrayRef< int64_t > distributedShape, int64_t warpSize, Value laneId, SmallVectorImpl< Value > &delinearizedIds) const
Delinearize the given laneId into multiple dimensions, where each dimension's size is determined by o...
WarpExecuteOnLane0Op moveRegionToNewWarpOpAndReplaceReturns(RewriterBase &rewriter, WarpExecuteOnLane0Op warpOp, ValueRange newYieldedValues, TypeRange newReturnTypes) const
Helper to create a new WarpExecuteOnLane0Op with different signature.
virtual LogicalResult matchAndRewrite(WarpExecuteOnLane0Op op, PatternRewriter &rewriter) const override=0
OpOperand * getWarpResult(WarpExecuteOnLane0Op warpOp, llvm::function_ref< bool(Operation *)> fn) const
Return a value yielded by warpOp which statifies the filter lamdba condition and is not dead.