29#include "llvm/Support/Casting.h"
30#include "llvm/Support/FormatVariadic.h"
39 for (
const auto &vals : values)
40 llvm::append_range(
result, vals);
46 auto layout = llvm::dyn_cast_if_present<LayoutAttr>(tdescTy.getLayout());
49 if (!layout || !layout.isForSubgroup())
54 auto tdescShape = tdescTy.getShape();
55 auto elementType = tdescTy.getElementType();
60 int64_t sgSize = llvm::product_of(laneLayout);
64 for (
auto [tdescDim, laneDim, laneDataDim] :
65 llvm::zip_equal(tdescShape, laneLayout, laneData)) {
66 assert((tdescDim % (laneDim * laneDataDim) == 0) &&
67 "tensor descriptor shape is not distributable");
68 tensorSize *= tdescDim;
71 tensorSize *= tdescTy.getArrayLength();
73 return VectorType::get({tensorSize / sgSize}, elementType);
78 xegpu::LayoutAttr layout) {
79 int64_t rank = originalType.getRank();
86 while (
shape.size() > 2) {
87 arrayLength *=
shape[0];
92 auto laneLayout = layout.getEffectiveLaneLayoutAsInt();
93 auto laneData = layout.getEffectiveLaneDataAsInt();
94 while (!laneLayout.empty() && laneLayout.size() >
shape.size()) {
95 laneLayout.erase(laneLayout.begin());
96 laneData.erase(laneData.begin());
98 auto trimmedLayout = xegpu::LayoutAttr::get(
102 auto helperTdescTy = xegpu::TensorDescType::get(
103 shape, originalType.getElementType(), arrayLength,
105 xegpu::MemorySpace::Global, trimmedLayout);
111 VectorType originalType) {
114 assert((isa<xegpu::LayoutAttr>(layout) || isa<xegpu::SliceAttr>(layout)) &&
115 "Expecting a valid layout.");
117 int64_t vectorRank = originalType.getRank();
118 int64_t layoutRank = layout.getRank();
119 assert(vectorRank >= layoutRank &&
"Vector rank must be >= layout rank.");
123 int64_t offset = vectorRank - layoutRank;
127 auto distributedShapeOrFailure =
128 layout.computeDistributedShape(trailingShape);
129 if (
failed(distributedShapeOrFailure))
133 fullShape.begin() + offset);
134 resultShape.append(distributedShapeOrFailure->begin(),
135 distributedShapeOrFailure->end());
136 return VectorType::get(resultShape, originalType.getElementType());
140 const StringRef prefix(
"layout_operand_");
141 unsigned idx =
const_cast<OpOperand &
>(operand).getOperandNumber();
142 return llvm::formatv(
"{0}{1}", prefix, idx).str();
146 const StringRef prefix =
"layout_result_";
147 return llvm::formatv(
"{0}{1}", prefix,
result.getResultNumber()).str();
151 return isa<VectorType, xegpu::TensorDescType>(type);
158 if (
auto result = dyn_cast<OpResult>(value)) {
160 assert(defOp &&
"result must have a defining op");
162 if (
auto anchorOp = dyn_cast<xegpu::AnchorLayoutInterface>(defOp)) {
163 auto layout = anchorOp.getAnchorLayout();
176 if (
auto arg = dyn_cast<BlockArgument>(value)) {
177 auto *parentOp = arg.getOwner()->getParentOp();
178 auto loop = dyn_cast_if_present<LoopLikeOpInterface>(parentOp);
180 if (
OpOperand *tiedInit = loop.getTiedLoopInit(arg))
186 if (
auto whileOp = dyn_cast_if_present<scf::WhileOp>(parentOp);
187 whileOp && arg.getOwner()->getParent() == &whileOp.getAfter()) {
188 Value forwarded = whileOp.getConditionOp().getArgs()[arg.getArgNumber()];
189 if (
auto beforeArg = dyn_cast<BlockArgument>(forwarded))
190 if (
OpOperand *tiedInit = whileOp.getTiedLoopInit(beforeArg))
196 dyn_cast_if_present<xegpu::TensorDescType>(value.
getType()))
197 return tdescTy.getLayoutAttr();
201xegpu::DistributeLayoutAttr
204 unsigned idx =
const_cast<OpOperand &
>(opr).getOperandNumber();
206 if (
auto anchorOp = dyn_cast<xegpu::AnchorLayoutInterface>(op)) {
207 if (
auto dpasOp = dyn_cast<xegpu::DpasOp>(op)) {
209 return dpasOp.getLayoutAAttr();
210 }
else if (idx == 1) {
211 return dpasOp.getLayoutBAttr();
212 }
else if (idx == 2) {
213 return dpasOp.getLayoutCdAttr();
216 if (
auto dpasMxOp = dyn_cast<xegpu::DpasMxOp>(op)) {
219 unsigned currentIdx = 0;
221 if (idx == currentIdx++)
222 return dpasMxOp.getLayoutAAttr();
224 if (idx == currentIdx++)
225 return dpasMxOp.getLayoutBAttr();
227 if (dpasMxOp.getAcc())
228 if (idx == currentIdx++)
229 return dpasMxOp.getLayoutCdAttr();
231 if (dpasMxOp.getScaleA())
232 if (idx == currentIdx++)
233 return dpasMxOp.getLayoutAScaleAttr();
235 if (dpasMxOp.getScaleB())
236 if (idx == currentIdx++)
237 return dpasMxOp.getLayoutBScaleAttr();
241 if (
auto convertOp = dyn_cast<xegpu::ConvertLayoutOp>(op)) {
242 return convertOp.getEffectiveInputLayout();
244 auto layout = anchorOp.getAnchorLayout();
251 if (isa<xegpu::StoreNdOp, xegpu::StoreMatrixOp>(op) && (idx < 2))
255 if (isa<xegpu::StoreScatterOp, xegpu::LoadGatherOp>(op))
271xegpu::DistributeLayoutAttr
274 const std::string &name) {
275 xegpu::DistributeLayoutAttr candidate = layout;
277 if (
auto loadOp = dyn_cast<xegpu::LoadGatherOp>(owner)) {
278 if (
auto perm = loadOp.getLayoutAttr())
287xegpu::DistributeLayoutAttr
290 const std::string &name) {
291 xegpu::DistributeLayoutAttr candidate = layout;
292 unsigned idx =
const_cast<OpOperand &
>(operand).getOperandNumber();
294 if (
auto storeOp = dyn_cast<xegpu::StoreScatterOp>(owner)) {
296 if (
auto perm = storeOp.getLayoutAttr())
308 const mlir::xegpu::DistributeLayoutAttr layout) {
311 if (
auto anchorOp = dyn_cast<xegpu::AnchorLayoutInterface>(owner)) {
312 if (anchorOp.getAnchorLayout() == layout)
314 anchorOp.setAnchorLayout(layout);
330 const DistributeLayoutAttr layout) {
332 unsigned idx =
const_cast<OpOperand &
>(operand).getOperandNumber();
337 if (
auto anchorOp = dyn_cast<xegpu::AnchorLayoutInterface>(owner)) {
338 if (
auto dpasOp = dyn_cast<xegpu::DpasOp>(owner)) {
340 return dpasOp.setLayoutAAttr(layout);
341 }
else if (idx == 1) {
342 return dpasOp.setLayoutBAttr(layout);
343 }
else if (idx == 2) {
344 return dpasOp.setLayoutCdAttr(layout);
347 if (
auto convertOp = dyn_cast<xegpu::ConvertLayoutOp>(owner)) {
348 return convertOp.setInputLayoutAttr(layout);
354 if (isa<xegpu::StoreScatterOp, xegpu::StoreNdOp, xegpu::StoreMatrixOp>(
357 anchorOp.setAnchorLayout(layout);
361 anchorOp.setAnchorLayout(layout);
375template <
typename T,
typename>
376xegpu::DistributeLayoutAttr
378 Operation *op = operandOrResult.getOwner();
390template xegpu::DistributeLayoutAttr
392template xegpu::DistributeLayoutAttr
395template <
typename T,
typename>
397 const xegpu::DistributeLayoutAttr layout) {
398 Operation *owner = operandOrResult.getOwner();
410 const mlir::xegpu::DistributeLayoutAttr layout);
414 const mlir::xegpu::DistributeLayoutAttr layout);
417 auto tdescTy = cast<xegpu::TensorDescType>(value.
getType());
418 value.
setType(xegpu::TensorDescType::get(
419 tdescTy.getContext(), tdescTy.getShape(), tdescTy.getElementType(),
420 tdescTy.getEncoding(), layout));
426 auto vecTy = dyn_cast<VectorType>(value.
getType());
434 int64_t srcShapeRank = srcShape.size();
438 int64_t rankDiff = srcShapeRank - targetShapeRank;
439 std::fill(adjustedTargetShape.begin(), adjustedTargetShape.begin() + rankDiff,
441 llvm::copy(
shape, adjustedTargetShape.begin() + rankDiff);
447 Value slice = vector::ExtractStridedSliceOp::create(
448 builder, loc, value, offsets, adjustedTargetShape, staticStrides);
451 if (srcShapeRank > targetShapeRank) {
452 auto targetTy = VectorType::get(
shape, vecTy.getElementType());
453 slice = vector::ShapeCastOp::create(builder, loc, targetTy,
slice);
464 VectorType inputTy = dyn_cast<VectorType>(values[0].
getType());
465 assert(llvm::all_of(values.
getTypes(),
466 [&](
Type type) { return type == inputTy; }) &&
467 "values must be of the same VectorType");
469 Type elemTy = inputTy.getElementType();
472 VectorType resultTy = VectorType::get(
shape, elemTy);
477 for (
auto [src, offsets] :
480 result = vector::InsertStridedSliceOp::create(builder, loc, src,
result,
481 offsets, staticStrides);
492 auto targetAttrs = gpuModuleOp.getTargets();
494 for (
auto &attr : *targetAttrs) {
495 auto xevmAttr = llvm::dyn_cast<xevm::XeVMTargetAttr>(attr);
497 return xevmAttr.getChip().str();
509 std::optional<ArrayRef<int32_t>> blockSize = gpuFunc.getKnownBlockSize();
512 if (!llvm::all_of(*blockSize, [](int32_t dim) {
513 return dim > 0 && llvm::isPowerOf2_32(dim);
516 int64_t numSubgroups = llvm::product_of(*blockSize) / subgroupSize;
517 if (numSubgroups < 1)
527 assert(lhs.size() == rhs.size() &&
"lhs and rhs must have the same size");
529 for (
auto [l, r] : llvm::zip_equal(lhs, rhs)) {
532 results.push_back(builder.
createOrFold<arith::AddIOp>(loc, lval, rval));
555 a = a.slice(a.size() -
b.size());
563 static_assert(std::is_integral<T>::value,
"T must be an integer type");
566 if (!candidateMultiples.empty())
568 SmallVector<T>(candidateMultiples.begin(), candidateMultiples.end());
569 for (T candidate : candidates) {
570 for (T multiple : multiples) {
571 int value =
static_cast<int>(candidate * multiple);
572 if (value != 0 && dim % value == 0 && value > largest)
580static arith::FastMathFlags
getFlags(arith::FastMathFlagsAttr fastmath) {
581 return fastmath ? fastmath.getValue() : arith::FastMathFlags::none;
585 vector::CombiningKind kind, uint32_t size,
586 arith::FastMathFlagsAttr fastmath) {
588 Value laneVal = vector::ReductionOp::create(builder, loc, kind, input,
591 for (uint64_t i = 1; i < size; i <<= 1) {
593 gpu::ShuffleOp::create(builder, loc, laneVal, i, size,
594 gpu::ShuffleMode::XOR)
597 makeArithReduction(builder, loc, kind, laneVal, shuffled, fastmath);
604 vector::CombiningKind kind,
607 arith::FastMathFlagsAttr fastmath) {
608 VectorType sourceType = src.
getType();
609 int64_t sourceRank = sourceType.getRank();
612 assert(sourceRank >= 2 &&
"expected at least a 2D source vector");
613 for (
int64_t i = 0; i < sourceRank - 2; ++i)
614 assert(sourceType.getShape()[i] == 1 &&
615 "expected leading dimensions to be unit");
616 int64_t rowIdx = sourceRank - 2;
617 int64_t columnIdx = sourceRank - 1;
618 assert((reductionDim == rowIdx || reductionDim == columnIdx) &&
619 "expected the reduction dim to be one of the last two dims");
620 int64_t sourceH = sourceType.getShape()[rowIdx];
621 int64_t sourceW = sourceType.getShape()[columnIdx];
622 int nSlices = (reductionDim == rowIdx) ? sourceW : sourceH;
624 TypedAttr zeroAttr = rewriter.
getZeroAttr(sourceType.getElementType());
625 Value reductionResult = arith::ConstantOp::create(
626 rewriter, loc,
acc.getType(),
635 for (
int i = 0; i < nSlices; ++i) {
641 if (reductionDim == columnIdx) {
642 sliceOffsets[rowIdx] = i;
643 sliceSizes[columnIdx] = sourceW;
645 sliceOffsets[columnIdx] = i;
646 sliceSizes[rowIdx] = sourceH;
649 vector::ExtractStridedSliceOp extractOp =
650 vector::ExtractStridedSliceOp::create(rewriter, loc, src, sliceOffsets,
651 sliceSizes, strides);
655 int64_t nSliceElements = extractOp.getResult().getType().getNumElements();
657 vector::ShapeCastOp
slice = vector::ShapeCastOp::create(
659 VectorType::get({nSliceElements}, sourceType.getElementType()),
660 extractOp.getResult());
670 accIdx[accRank - 1] = i;
671 Value accExtract = vector::ExtractOp::create(rewriter, loc,
acc, accIdx);
672 Value reduction = vector::ReductionOp::create(
673 rewriter, loc, kind,
slice.getResult(), accExtract,
getFlags(fastmath));
674 reductionResult = vector::InsertOp::create(rewriter, loc, reduction,
675 reductionResult, accIdx);
679 return reductionResult;
684 vector::CombiningKind kind,
int64_t reductionDim,
int64_t reductionSize,
686 arith::FastMathFlagsAttr fastmath) {
687 VectorType sourceType = src.
getType();
688 int64_t sourceRank = sourceType.getRank();
691 assert(sourceRank >= 2 &&
"expected at least a 2D source vector");
692 for (
int64_t i = 0; i < sourceRank - 2; ++i)
693 assert(sourceType.getShape()[i] == 1 &&
694 "expected leading dimensions to be unit");
695 int64_t rowIdx = sourceRank - 2;
696 int64_t columnIdx = sourceRank - 1;
697 int64_t sourceH = sourceType.getShape()[rowIdx];
698 int64_t sourceW = sourceType.getShape()[columnIdx];
701 TypedAttr zeroAttr = rewriter.
getZeroAttr(sourceType.getElementType());
702 Value reductionResult = arith::ConstantOp::create(
703 rewriter, loc,
acc.getType(),
710 int nSlices = (reductionDim == rowIdx) ? sourceW : sourceH;
715 for (
int i = 0; i < nSlices; ++i) {
721 if (reductionDim == columnIdx) {
722 sliceOffsets[rowIdx] = i;
723 sliceSizes[columnIdx] = sourceW;
725 sliceOffsets[columnIdx] = i;
726 sliceSizes[rowIdx] = sourceH;
729 vector::ExtractStridedSliceOp extractOp =
730 vector::ExtractStridedSliceOp::create(rewriter, loc, src, sliceOffsets,
731 sliceSizes, strides);
732 int64_t nSliceElements = extractOp.getResult().getType().getNumElements();
733 vector::ShapeCastOp
slice = vector::ShapeCastOp::create(
735 VectorType::get({nSliceElements}, sourceType.getElementType()),
736 extractOp.getResult());
739 accIdx[accRank - 1] = i;
740 Value accExtract = vector::ExtractOp::create(rewriter, loc,
acc, accIdx);
742 reductionSize, fastmath);
744 accExtract, fastmath);
745 reductionResult = vector::InsertOp::create(rewriter, loc, fullReduce,
746 reductionResult, accIdx);
748 return reductionResult;
763 vector::CombiningKind kind,
764 arith::FastMathFlags flags) {
765 bool isMax = kind == vector::CombiningKind::MAXIMUMF ||
766 kind == vector::CombiningKind::MAXNUMF ||
767 kind == vector::CombiningKind::MAXIMUMNUMF;
768 bool ignoresNaN = kind != vector::CombiningKind::MINIMUMF &&
769 kind != vector::CombiningKind::MAXIMUMF;
770 if (ignoresNaN && APFloat::semanticsHasNaN(semantics) &&
771 !arith::bitEnumContainsAny(flags, arith::FastMathFlags::nnan))
772 return APFloat::getQNaN(semantics);
773 bool useInf = APFloat::semanticsHasInf(semantics) &&
774 !arith::bitEnumContainsAny(flags, arith::FastMathFlags::ninf);
776 return useInf ? APFloat::getInf(semantics) : APFloat::getLargest(semantics);
779 if (!APFloat::semanticsHasSignedRepr(semantics))
780 return APFloat::semanticsHasZero(semantics)
781 ? APFloat::getZero(semantics)
782 : APFloat::getSmallest(semantics);
783 return useInf ? APFloat::getInf(semantics,
true)
784 : APFloat::getLargest(semantics,
true);
788 Type type, vector::CombiningKind kind,
789 arith::FastMathFlagsAttr fastmath) {
790 auto vecTy = dyn_cast<VectorType>(type);
791 Type elemTy = vecTy ? vecTy.getElementType() : type;
796 return arith::ConstantOp::create(
798 return arith::ConstantOp::create(builder, loc, cast<TypedAttr>(scalarAttr));
802 case vector::CombiningKind::ADD:
803 case vector::CombiningKind::XOR:
804 case vector::CombiningKind::OR:
805 case vector::CombiningKind::MAXUI:
808 case vector::CombiningKind::MUL:
811 case vector::CombiningKind::AND:
812 if (
auto intTy = dyn_cast<IntegerType>(elemTy))
814 builder.
getIntegerAttr(elemTy, APInt::getAllOnes(intTy.getWidth())));
819 case vector::CombiningKind::MINSI:
820 if (
auto intTy = dyn_cast<IntegerType>(elemTy))
822 elemTy, APInt::getSignedMaxValue(intTy.getWidth())));
825 case vector::CombiningKind::MINUI:
826 if (
auto intTy = dyn_cast<IntegerType>(elemTy))
828 builder.
getIntegerAttr(elemTy, APInt::getMaxValue(intTy.getWidth())));
831 case vector::CombiningKind::MAXSI:
832 if (
auto intTy = dyn_cast<IntegerType>(elemTy))
834 elemTy, APInt::getSignedMinValue(intTy.getWidth())));
837 case vector::CombiningKind::MINIMUMF:
838 case vector::CombiningKind::MAXIMUMF:
839 case vector::CombiningKind::MINNUMF:
840 case vector::CombiningKind::MINIMUMNUMF:
841 case vector::CombiningKind::MAXNUMF:
842 case vector::CombiningKind::MAXIMUMNUMF:
843 if (
auto floatTy = dyn_cast<FloatType>(elemTy))
859std::optional<SmallVector<int64_t>>
863 if (llvm::any_of(vals.drop_back(2), [](
int64_t v) { return v != 1; }))
872 getInner2DIfUnitLeadingDims(layout.getEffectiveLaneDataAsInt());
873 return laneData && (*laneData)[0] != 1;
880 if (!isa<xegpu::uArch::Xe2>(uArch) && !isa<xegpu::uArch::Xe3p>(uArch))
885 getInner2DIfUnitLeadingDims(layout.getEffectiveLaneLayoutAsInt());
887 (*laneLayout)[1] == 1;
891 if (!type.hasStaticShape())
895 return succeeded(type.getStridesAndOffset(strides, offset)) &&
896 llvm::none_of(strides, ShapedType::isDynamic);
901 MemRefType memrefTy) {
903 assert(baseAddr.
getType() == type &&
904 "expected base address and offset of the same type");
906 return arith::ConstantOp::create(builder, loc, type,
911 unsigned elemBits = memrefTy.getElementTypeBitWidth();
913 if (elemBits % 8 == 0) {
917 byteOffset = arith::MulIOp::create(builder, loc, elemOffset,
918 makeConst(elemBits / 8));
923 Value bitSize = makeConst(elemBits);
924 Value eight = makeConst(8);
925 byteOffset = arith::DivUIOp::create(
926 builder, loc, arith::MulIOp::create(builder, loc, elemOffset, bitSize),
929 return arith::AddIOp::create(builder, loc, baseAddr, byteOffset);
942 for (
size_t dstIdx = 0; dstIdx < dst.size(); ++dstIdx)
943 if (srcIdx < src.size() && src[srcIdx] == dst[dstIdx])
945 else if (dst[dstIdx] == 1)
946 expandedUnitDims.push_back(dstIdx);
949 return srcIdx == src.size();
963 !expandedUnitDims.empty())
972 splitDimGroups.clear();
973 for (
size_t dstIdx = 0; dstIdx < dst.size(); ++dstIdx) {
974 if (srcIdx >= src.size())
976 accumulatedSize *= dst[dstIdx];
977 currentDstDims.push_back(dstIdx);
979 if (accumulatedSize == src[srcIdx]) {
982 if (srcIdx == src.size() - 1) {
983 while (++dstIdx < dst.size() && dst[dstIdx] == 1)
984 currentDstDims.push_back(dstIdx);
987 splitDimGroups.push_back(currentDstDims);
991 currentDstDims.clear();
992 }
else if (accumulatedSize > src[srcIdx]) {
996 return srcIdx == src.size();
1025 auto vecTy = dyn_cast<VectorType>(layoutSrc.
getType());
1031 auto [subShape, count] = getSubShapeAndCount(vecTy, layout);
1034 auto newTy = VectorType::get(subShape, vecTy.getElementType());
1035 for (
Value dest : dests)
1039 if (
auto whileOp = dyn_cast<scf::WhileOp>(op)) {
1043 cast<scf::YieldOp>(whileOp.getAfterBody()->getTerminator());
1044 for (
auto [init, beforeArg, yieldVal] :
1045 llvm::zip(whileOp.getInits(), whileOp.getBeforeArguments(),
1046 yieldOp.getOperands()))
1047 recordTypes(init, {beforeArg, yieldVal});
1050 scf::ConditionOp condOp = whileOp.getConditionOp();
1051 for (
auto [condArg, afterArg, res] :
1052 llvm::zip(condOp.getArgs(), whileOp.getAfterArguments(),
1053 whileOp.getResults()))
1054 recordTypes(condArg, {afterArg, res});
1057 if (
auto forOp = dyn_cast<scf::ForOp>(op)) {
1060 auto yieldOp = cast<scf::YieldOp>(forOp.getBody()->getTerminator());
1061 for (
auto [init, arg, res, yieldVal] :
1062 llvm::zip(forOp.getInitArgs(), forOp.getRegionIterArgs(),
1063 forOp.getResults(), yieldOp.getOperands()))
1064 recordTypes(init, {arg, res, yieldVal});
1067 if (
auto ifOp = dyn_cast<scf::IfOp>(op)) {
1070 scf::YieldOp thenYield = ifOp.thenYield();
1071 scf::YieldOp elseYield = ifOp.elseBlock() ? ifOp.elseYield() :
nullptr;
1072 for (
auto [idx, res] : llvm::enumerate(ifOp.getResults())) {
1075 dests.push_back(elseYield.getOperand(idx));
1076 recordTypes(res, dests);
1081 return loopArgTypes;
1091 auto loopArgTypeMap = std::make_shared<DenseMap<Value, SmallVector<Type>>>(
1092 std::move(loopArgTypes));
1093 converter.addConversion(
1094 [loopArgTypeMap, getSubShapeAndCount](
1097 if (!isa<VectorType>(v.
getType()))
1098 return std::nullopt;
1103 auto it = loopArgTypeMap->find(v);
1104 if (it != loopArgTypeMap->end()) {
1105 result.append(it->second.begin(), it->second.end());
1112 return std::nullopt;
1114 auto vecType = cast<VectorType>(v.
getType());
1115 auto [subShape, count] = getSubShapeAndCount(vecType, layout);
1117 return std::nullopt;
1119 auto newTy = VectorType::get(subShape, vecType.getElementType());
1120 result.append(count, newTy);
1127 const llvm::SmallSetVector<UnrealizedConversionCastOp, 8> &existingCasts) {
1146 auto hasIdenticalVectorTypes = [](
ValueRange values) {
1147 auto types = values.getTypes();
1148 return !types.empty() && llvm::all_of(types, [&](
Type type) {
1149 return isa<VectorType>(type) && type == types.front();
1153 root->
walk([&](UnrealizedConversionCastOp op) {
1154 if (existingCasts.contains(op))
1157 if (op.getNumResults() == 1 && op.getNumOperands() >= 1) {
1159 op.getInputs()[0].getDefiningOp<UnrealizedConversionCastOp>();
1160 if (defOp && !existingCasts.contains(defOp) &&
1161 defOp.getNumOperands() == 1 &&
1162 defOp.getNumResults() == op.getNumOperands() &&
1163 llvm::all_of(op.getInputs(),
1164 [&](
Value v) { return v.getDefiningOp() == defOp; })) {
1165 Value orig = defOp.getInputs()[0];
1166 auto origTy = dyn_cast<VectorType>(orig.
getType());
1167 auto resTy = dyn_cast<VectorType>(op.getResult(0).getType());
1168 if (origTy && resTy &&
1169 origTy.getNumElements() == resTy.getNumElements() &&
1173 vector::ShapeCastOp::create(builder, op.getLoc(), resTy, orig);
1174 op.replaceAllUsesWith(
ValueRange{shapeCast.getResult()});
1182 auto outputTy = dyn_cast<VectorType>(op.getResult(0).getType());
1183 if (op.getNumOperands() > 1 && outputTy &&
1184 hasIdenticalVectorTypes(op.getInputs())) {
1187 builder, op.getLoc(), op.getInputs(), outputTy.getShape());
1193 if (op.getNumOperands() == 1 && op.getNumResults() > 1) {
1195 op.getInputs()[0].getDefiningOp<UnrealizedConversionCastOp>();
1196 if (defOp && !existingCasts.contains(defOp) &&
1197 defOp.getNumResults() == 1 &&
1198 defOp.getNumOperands() == op.getNumResults() &&
1200 op->getResultTypes())) {
1201 op.replaceAllUsesWith(defOp.getInputs());
1206 auto tileTy = dyn_cast<VectorType>(op.getResult(0).getType());
1207 if (tileTy && hasIdenticalVectorTypes(op.getResults())) {
1210 builder, op.getLoc(), op.getInputs()[0], tileTy.getShape());
1211 op->replaceAllUsesWith(results);
1218 bool changed =
true;
1221 root->
walk([&](UnrealizedConversionCastOp op) {
1222 if (existingCasts.contains(op))
1224 if (op.use_empty()) {
1246 collapseDims.clear();
1247 collapseDims.resize(dst.size());
1251 int64_t srcProd = std::accumulate(src.begin(), src.end(),
int64_t{1},
1252 std::multiplies<int64_t>());
1253 int64_t dstProd = std::accumulate(dst.begin(), dst.end(),
int64_t{1},
1254 std::multiplies<int64_t>());
1255 if (srcProd != dstProd)
1264 srcCompact.push_back(s);
1267 dstCompact.push_back(d);
1270 for (
int64_t need : dstCompact) {
1272 while (s < srcCompact.size() &&
acc < need)
1273 acc *= srcCompact[s++];
1277 if (s != srcCompact.size())
1288 while (dstIdx < dst.size() && dst[dstIdx] == 1)
1293 for (
size_t srcIdx = 0; srcIdx < src.size(); ++srcIdx) {
1294 if (dstIdx >= dst.size()) {
1297 if (lastNonEmpty >= 0)
1298 collapseDims[lastNonEmpty].push_back(srcIdx);
1302 collapseDims[dstIdx].push_back(srcIdx);
1303 lastNonEmpty = dstIdx;
1304 if (
acc == dst[dstIdx]) {
1307 while (dstIdx < dst.size() && dst[dstIdx] == 1)
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
xegpu::DistributeLayoutAttr maybePickPermanentLayout(xegpu::DistributeLayoutAttr layout, const OpResult &result, mlir::Operation *owner, const std::string &name)
static APFloat getMinMaxNeutral(const llvm::fltSemantics &semantics, vector::CombiningKind kind, arith::FastMathFlags flags)
Returns the neutral value of the float min or max reduction kind over elements of semantics.
static arith::FastMathFlags getFlags(arith::FastMathFlagsAttr fastmath)
Returns the flags held by fastmath, or none if it is null.
Attributes are known-constant values of operations.
IntegerAttr getIndexAttr(int64_t value)
IntegerAttr getIntegerAttr(Type type, int64_t value)
FloatAttr getFloatAttr(Type type, double value)
TypedAttr getZeroAttr(Type type)
TypedAttr getOneAttr(Type type)
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
This class helps build Operations.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
This class represents an operand of an operation.
This is a value defined by a result of an operation.
Operation is the basic unit of execution within MLIR.
bool hasDiscardableAttrOfType(NameT &&name)
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
bool hasDiscardableAttr(StringRef name)
Return true if this operation has a discardable attribute with the provided name.
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),...
AttrClass getDiscardableAttrOfType(StringRef name)
Access a discardable attribute by name and cast it to AttrClass.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
A range-style iterator that allows for iterating over the offsets of all potential tiles of size tile...
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_range getTypes() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
void setType(Type newType)
Mutate the type of this Value to be of the specified type.
Type getType() const
Return the type of this value.
Operation * getOwner() const
Return the owner of this operand.
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.
bool matchDimCollapse(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< SmallVector< int64_t > > &collapseDims)
Value createVectorWithShapeFromValues(OpBuilder &builder, Location loc, ValueRange values, ArrayRef< int64_t > shape)
Create a vector of shape from a set of values using vector.insert_stride_slice.
bool requirePacked(const DistributeLayoutAttr layout)
Helper function to check if the layout is packed.
void setTemporaryLayout(const T &operandOrResult, const DistributeLayoutAttr layout)
void setDistributeLayoutAttr(const OpResult &Result, const DistributeLayoutAttr layout)
[to-be-deprecated] Sets the DistributeLayoutAttr for a given OpResult user should use setAnchorLayout...
bool matchUnitDimExpansion(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< int64_t > &expandedUnitDims)
std::optional< SmallVector< int64_t > > getInner2DIfUnitLeadingDims(ArrayRef< int64_t > vals)
Returns the innermost 2 entries of vals if it is at least 2D and all of its leading entries are unit;...
int getLargestDivisor(T dim, ArrayRef< T > candidates, ArrayRef< T > candidateMultiples={})
Helper Function to find a proper instruction multiple for the user-supplied sg-level data shape (dive...
FailureOr< int64_t > getNumSubgroupsFromBlockSize(Operation *op, int64_t subgroupSize)
Returns the number of subgroups the kernel enclosing op runs, derived from the known_block_size of it...
bool hasStaticShapeAndStrides(MemRefType type)
Returns true if type has a static shape and static strides.
FailureOr< VectorType > getDistVecTypeBasedOnLaneLayout(DistributeLayoutAttr layout, VectorType originalType)
Helper function to get distributed vector type for a source vector type according to the lane_layout.
bool requireTranspose(const DistributeLayoutAttr layout, const uArch::uArch *uArch)
Helper function to check if the layout requires a transpose effect.
bool matchSplitDimExpansion(ArrayRef< int64_t > src, ArrayRef< int64_t > dst, SmallVector< SmallVector< int64_t > > &splitDimGroups)
bool isLayoutCarrierType(Type type)
Returns true if values of type can carry a DistributeLayoutAttr, i.e.
DistributeLayoutAttr getDistributeLayoutAttr(const Value value)
Retrieves the DistributeLayoutAttr associated with a given Value, or nullptr if none is found.
DenseMap< Value, SmallVector< Type > > precomputeLoopBlockArgTypes(Operation *topLevelOp, SubShapeAndCountFn getSubShapeAndCount)
Pre-computes distributed VectorType mappings for every value carried through an SCF loop under topLev...
std::string getTemporaryLayoutName(const OpOperand &operand)
Return the attribute name for the OpOperand to attach DistributeLayoutAttr.
Value addElemOffsetInBytes(OpBuilder &builder, Location loc, Value baseAddr, Value elemOffset, MemRefType memrefTy)
Returns baseAddr + elemOffset * bitWidth / 8, i.e.
std::optional< std::string > getChipStr(Operation *op)
Retrieves the chip string from the XeVM target attribute of the parent GPU module operation.
void addVectorTypeConversion(TypeConverter &converter, SubShapeAndCountFn getSubShapeAndCount, DenseMap< Value, SmallVector< Type > > loopArgTypes)
Adds a context-aware VectorType conversion to converter (1:1 shape-changing or 1:N,...
Value lowerToVectorReductions(TypedValue< VectorType > src, TypedValue< VectorType > acc, vector::CombiningKind kind, int64_t reductionDim, Location loc, PatternRewriter &rewriter, arith::FastMathFlagsAttr fastmath=nullptr)
Given a src and an acc argumments from a vector::MultiDimReductionOp, lower to a set of vector::Reduc...
SmallVector< Value > extractVectorsWithShapeFromValue(OpBuilder &builder, Location loc, Value value, ArrayRef< int64_t > shape)
Extract a set of small vectors from a value with a given shape using vector.extract_stride_slice.
Value createReductionNeutralValue(OpBuilder &builder, Location loc, Type type, vector::CombiningKind kind, arith::FastMathFlagsAttr fastmath=nullptr)
Creates a constant filled with the neutral (identity) value for the given reduction kind.
DistributeLayoutAttr getTemporaryLayout(const T &operandOrResult)
get and set distribute layout attribute for non-anchor operations (and offsets/masks of load/store op...
Value lowerCrossLaneReductionToShuffles(TypedValue< VectorType > src, TypedValue< VectorType > acc, vector::CombiningKind kind, int64_t reductionDim, int64_t reductionSize, Location loc, PatternRewriter &rewriter, arith::FastMathFlagsAttr fastmath=nullptr)
Lowers cross-lane reductions to shuffle operations on a 2D vector.
std::function< std::pair< SmallVector< int64_t >, int >( VectorType, DistributeLayoutAttr)> SubShapeAndCountFn
Callback type for computing sub-shape and count for 1:N (or 1:1 shape-changing) VectorType conversion...
void setTensorDescLayout(Value value, DistributeLayoutAttr layout)
Sets layout on the type of the tensor_desc value value, replacing any layout the type already has.
void cleanupUnrealizedConversionCasts(Operation *root, const llvm::SmallSetVector< UnrealizedConversionCastOp, 8 > &existingCasts)
Cleans up UnrealizedConversionCastOps inserted during SCF structural type conversion and/or XeGPU unr...
SmallVector< Value > flattenValues(ArrayRef< ValueRange > values)
Flatten a set of ValueRange into a single SmallVector<Value>
SmallVector< OpFoldResult > addWithRightAligned(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > lhs, ArrayRef< OpFoldResult > rhs)
Generates element-wise addition ops of two arrays with automatic alignment.
SmallVector< OpFoldResult > addElementwise(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > lhs, ArrayRef< OpFoldResult > rhs)
Generates element-wise addition ops of two arrays with same length.
FailureOr< VectorType > getDistributedVectorType(xegpu::TensorDescType tdescTy)
If tensor descriptor has a layout attribute it is used in SIMT mode.
Value subgroupReduction(Location loc, OpBuilder &builder, Value input, vector::CombiningKind kind, uint32_t size, arith::FastMathFlagsAttr fastmath=nullptr)
Given an input value representing per-lane data, this function returns the result after performing a ...
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
std::optional< SmallVector< int64_t > > computeShapeRatio(ArrayRef< int64_t > shape, ArrayRef< int64_t > subShape)
Return the multi-dimensional integral ratio of subShape to the trailing dimensions of shape.
virtual int getSubgroupSize() const =0