16#include "llvm/ADT/SmallVectorExtras.h"
17#include "llvm/ADT/TypeSwitch.h"
18#include "llvm/Support/Debug.h"
25void XeGPUDialect::initialize() {
27#define GET_TYPEDEF_LIST
28#include <mlir/Dialect/XeGPU/IR/XeGPUTypes.cpp.inc>
32#include <mlir/Dialect/XeGPU/IR/XeGPU.cpp.inc>
35#define GET_ATTRDEF_LIST
36#include <mlir/Dialect/XeGPU/IR/XeGPUAttrs.cpp.inc>
39#define GET_OP_INTERFACE_CLASSES
40#include "mlir/Dialect/XeGPU/IR/XeGPUOpInterface.cpp.inc"
59 llvm::zip_equal(srcShape,
61 [](
const auto &t) {
return std::min(std::get<0>(t), std::get<1>(t)); });
65 llvm::zip(delinearizedId, subShape), [&](
const auto &t) ->
Value {
81 llvm::map_to_vector(llvm::zip_equal(base, distUnitLocalOffset),
82 [&](
const auto &t) ->
Value {
84 loc, std::get<0>(t), std::get<1>(t));
88 llvm::zip_equal(adds, srcShape), [&](
const auto &t) ->
Value {
94 coordinates.push_back(mods);
102 xegpu::DistributeLayoutAttr attr) {
103 assert(attr &&
"Layout attribute is missing.");
120 if (layout.size() !=
shape.size())
123 if (ratio.has_value()) {
124 newShape = ratio.value();
132 if (data.size() != shape.size())
135 if (!ratio.has_value() && rr)
137 if (!ratio.has_value())
147 auto maybeSgShape = tryDistribute(shape, attr.getEffectiveSgLayoutAsInt(),
148 attr.getEffectiveSgDataAsInt());
151 auto sgShape = maybeSgShape.value();
154 auto maybeInstShape =
155 tryDistribute(sgShape, {}, attr.getEffectiveInstDataAsInt(),
false);
158 auto instShape = maybeInstShape.value();
161 auto maybeLaneShape =
162 tryDistribute(instShape, attr.getEffectiveLaneLayoutAsInt(),
163 attr.getEffectiveLaneDataAsInt(),
false);
164 return maybeLaneShape.has_value();
170BlockTensorDescAttr BlockTensorDescAttr::get(mlir::MLIRContext *context,
171 xegpu::MemorySpace memory_space,
173 bool boundary_check) {
174 auto scopeAttr = MemorySpaceAttr::get(context, memory_space);
176 IntegerAttr::get(IntegerType::get(context, 64), array_length);
178 return Base::get(context, scopeAttr, lengthAttr, boundaryAttr);
181bool BlockTensorDescAttr::hasDefaultsOnly() {
182 return getMemorySpace().getValue() == xegpu::MemorySpace::Global &&
183 getArrayLength().getInt() == 1 && getBoundaryCheck().getValue();
190ScatterTensorDescAttr::get(mlir::MLIRContext *context,
191 xegpu::MemorySpace memory_space,
int chunk_size) {
192 auto scopeAttr = MemorySpaceAttr::get(context, memory_space);
194 IntegerAttr::get(IntegerType::get(context, 64), chunk_size);
195 return Base::get(context, scopeAttr, chunkSizeAttr);
198LogicalResult ScatterTensorDescAttr::verify(
199 llvm::function_ref<mlir::InFlightDiagnostic()>
emitError,
200 MemorySpaceAttr memory_space, IntegerAttr chunk_size) {
201 int64_t chunkSize = chunk_size.getInt();
203 return emitError() <<
"invalid chunk size";
212LayoutAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()>
emitError,
218 if (!sg_layout && !inst_data && !lane_layout)
224 if (sg_layout && inst_data && sg_layout.size() != inst_data.size()) {
226 <<
"expected sg_layout and inst_data to have the same rank";
229 if (sg_layout && lane_layout && sg_layout.size() != lane_layout.size()) {
231 <<
"expected sg_layout and lane_layout to have the same rank";
234 if (inst_data && lane_layout && inst_data.size() != lane_layout.size()) {
235 return emitError() <<
"expected inst_data and lane_layout to have the same "
236 "rank, got inst_data "
237 << inst_data.size() <<
", lane_layout "
238 << lane_layout.size();
245 return emitError() <<
"expected sg_layout being used with sg_data";
246 if (sg_data.size() != sg_layout.size())
248 <<
"expected sg_data and sg_layout to have the same rank";
255 return emitError() <<
"expected lane_layout being used with lane_data";
256 if (lane_data.size() != lane_layout.size())
258 <<
"expected lane_data and lane_layout to have the same rank";
262 if (!sg_layout && !lane_layout)
264 <<
"expected sg_layout/lane_layout being used with order";
266 if (sg_layout && order.size() != sg_layout.size())
268 <<
"expected order and sg_layout to have the same rank";
270 if (lane_layout && order.size() != lane_layout.size())
272 <<
"expected order and lane_layout to have the same rank";
278FailureOr<SmallVector<Value>>
279LayoutAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
281 SmallVector<int64_t> sgLayoutInt;
282 if (isForWorkgroup()) {
283 sgLayoutInt = getEffectiveSgLayoutAsInt();
284 }
else if (isForSubgroup()) {
285 sgLayoutInt = getEffectiveLaneLayoutAsInt();
293 SmallVector<int64_t> order;
294 if (orderAttr && !orderAttr.empty()) {
295 order = llvm::map_to_vector(orderAttr.
asArrayRef(), [](int32_t idx) {
296 return static_cast<int64_t>(idx);
300 order = llvm::to_vector(
301 llvm::reverse(llvm::seq<int64_t>(0, sgLayoutInt.size())));
304 if (order.size() != sgLayoutInt.size()) {
308 SmallVector<Value>
result(sgLayoutInt.size());
309 Value remaining = linearId;
332 for (
size_t i = 0; i < order.size(); ++i) {
333 int64_t dimIdx = order[i];
334 int64_t dimSize = sgLayoutInt[dimIdx];
337 builder.
createOrFold<arith::ConstantIndexOp>(loc, dimSize);
344 builder.
createOrFold<arith::RemUIOp>(loc, remaining, dimSizeVal);
351 if (i < order.size() - 1) {
353 builder.
createOrFold<arith::DivUIOp>(loc, remaining, dimSizeVal);
362FailureOr<SmallVector<SmallVector<Value>>>
363LayoutAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
364 Value linearId, ArrayRef<int64_t> shape) {
365 SmallVector<int64_t> layout;
366 SmallVector<int64_t> subShape;
367 if (isForWorkgroup()) {
368 layout = getEffectiveSgLayoutAsInt();
369 subShape = getEffectiveSgDataAsInt();
370 }
else if (isForSubgroup()) {
371 layout = getEffectiveLaneLayoutAsInt();
372 subShape = getEffectiveLaneDataAsInt();
376 if (subShape.empty()) {
378 subShape = derivedShape.value();
384 auto maybeIds = delinearizeId(builder, loc, linearId);
387 SmallVector<Value> ids = *maybeIds;
389 return genCoordinates(builder, loc, ids, layout, subShape, shape);
392bool LayoutAttr::isEqualTo(
const xegpu::DistributeLayoutAttr &other) {
393 if (dyn_cast<xegpu::SliceAttr>(other))
396 return *
this == dyn_cast<xegpu::LayoutAttr>(other);
401LayoutAttr::setUnitDimData(SmallVector<int64_t> unitDims)
const {
402 auto sgDataOpt = getSgData();
403 auto instDataOpt = getInstData();
404 auto laneDataOpt = getLaneData();
406 SmallVector<int32_t> sgData;
407 SmallVector<int32_t> instData;
408 SmallVector<int32_t> laneData;
411 sgData = llvm::to_vector(sgDataOpt.asArrayRef());
414 instData = llvm::to_vector(instDataOpt.asArrayRef());
417 laneData = llvm::to_vector(laneDataOpt.asArrayRef());
419 for (
auto dim : unitDims) {
420 if (dim <
static_cast<int64_t
>(sgData.size()))
422 if (dim <
static_cast<int64_t
>(instData.size()))
424 if (dim <
static_cast<int64_t
>(laneData.size()))
428 return LayoutAttr::get(
442LayoutAttr::setUnitDimLayout(SmallVector<int64_t> unitDims)
const {
443 auto sgLayoutOpt = getSgLayout();
444 auto laneLayoutOpt = getLaneLayout();
446 SmallVector<int32_t> sgLayout;
447 SmallVector<int32_t> laneLayout;
450 sgLayout = llvm::to_vector(sgLayoutOpt.asArrayRef());
452 laneLayout = llvm::to_vector(laneLayoutOpt.asArrayRef());
454 for (
auto dim : unitDims) {
455 if (dim <
static_cast<int64_t
>(sgLayout.size()))
457 if (dim <
static_cast<int64_t
>(laneLayout.size()))
461 return LayoutAttr::get(
465 getSgData(), getInstData(),
468 getLaneData(), getOrder());
473DistributeLayoutAttr LayoutAttr::setDimData(int64_t dim, int64_t sgData,
477 SmallVector<int64_t> sgDataVec = getEffectiveSgDataAsInt();
478 SmallVector<int64_t> instDataVec = getEffectiveInstDataAsInt();
479 SmallVector<int64_t> laneDataVec = getEffectiveLaneDataAsInt();
481 if (dim <
static_cast<int64_t
>(sgDataVec.size()) && sgData != -1)
482 sgDataVec[dim] = sgData;
483 if (dim <
static_cast<int64_t
>(instDataVec.size()) && instData != -1)
484 instDataVec[dim] = instData;
485 if (dim <
static_cast<int64_t
>(laneDataVec.size()) && laneData != -1)
486 laneDataVec[dim] = laneData;
488 SmallVector<int32_t> sgDataVec32(sgDataVec.begin(), sgDataVec.end());
489 SmallVector<int32_t> instDataVec32(instDataVec.begin(), instDataVec.end());
490 SmallVector<int32_t> laneDataVec32(laneDataVec.begin(), laneDataVec.end());
492 return LayoutAttr::get(
507DistributeLayoutAttr LayoutAttr::dropDims(SmallVector<int64_t> dimGroup) {
509 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
510 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
511 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
512 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
513 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
514 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
516 SmallVector<int64_t> sortedDimGroup = dimGroup;
517 llvm::sort(sortedDimGroup);
519 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
520 if (!sgLayout.empty()) {
521 sgLayout.erase(sgLayout.begin() + dimIdx);
522 sgData.erase(sgData.begin() + dimIdx);
524 if (!instData.empty())
525 instData.erase(instData.begin() + dimIdx);
526 if (!laneLayout.empty()) {
527 laneLayout.erase(laneLayout.begin() + dimIdx);
528 laneData.erase(laneData.begin() + dimIdx);
532 SmallVector<int64_t> newOrder;
533 for (int64_t d : origOrder) {
534 if (llvm::is_contained(dimGroup, d))
536 int64_t offset = llvm::count_if(dimGroup, [&](int64_t s) {
return s < d; });
537 newOrder.push_back(d - offset);
539 if (sgLayout.empty() && laneLayout.empty())
545 SmallVector<int32_t> v32(v.begin(), v.end());
548 auto droppedLayout = xegpu::LayoutAttr::get(
549 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
550 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
551 return droppedLayout;
557DistributeLayoutAttr LayoutAttr::collapseDims(SmallVector<int64_t> dimGroup) {
559 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
560 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
561 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
562 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
563 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
564 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
566 SmallVector<int64_t> sortedDimGroup = dimGroup;
567 llvm::sort(sortedDimGroup);
568 int64_t dimBeforeCurrent = -1;
569 for (
auto dimIdx : sortedDimGroup) {
573 if (dimBeforeCurrent >= 0) {
574 if (getOrder() && !getOrder().empty()) {
575 int64_t orderBefore = origOrder[dimBeforeCurrent];
576 int64_t orderCurrent = origOrder[dimIdx];
577 if (orderBefore != (orderCurrent - 1))
578 llvm::report_fatal_error(
579 "dimensions being collapsed must be adjacent in order");
581 if (dimIdx != (dimBeforeCurrent + 1))
582 llvm::report_fatal_error(
583 "dimensions being collapsed must be adjacent");
586 dimBeforeCurrent = dimIdx;
589 int firstDim = sortedDimGroup.front();
594 if (!sgLayout.empty()) {
595 int64_t collapsedSglayout = 1, collapsedSgData = 1;
596 for (
auto dimIdx : dimGroup) {
597 collapsedSglayout *= sgLayout[dimIdx];
598 collapsedSgData *= sgData[dimIdx];
600 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
601 sgLayout.erase(sgLayout.begin() + dimIdx, sgLayout.begin() + dimIdx + 1);
602 sgData.erase(sgData.begin() + dimIdx, sgData.begin() + dimIdx + 1);
604 sgLayout.insert(sgLayout.begin() + firstDim, collapsedSglayout);
605 sgData.insert(sgData.begin() + firstDim, collapsedSgData);
608 if (!instData.empty()) {
609 int64_t collapsedInstData = 1;
610 for (
auto dimIdx : dimGroup)
611 collapsedInstData *= instData[dimIdx];
612 for (
auto dimIdx : llvm::reverse(sortedDimGroup))
613 instData.erase(instData.begin() + dimIdx, instData.begin() + dimIdx + 1);
614 instData.insert(instData.begin() + firstDim, collapsedInstData);
617 if (!laneLayout.empty()) {
618 int64_t collapsedLaneLayout = 1, collapsedLaneData = 1;
619 for (
auto dimIdx : dimGroup) {
620 collapsedLaneLayout *= laneLayout[dimIdx];
621 collapsedLaneData *= laneData[dimIdx];
623 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
624 laneLayout.erase(laneLayout.begin() + dimIdx,
625 laneLayout.begin() + dimIdx + 1);
626 laneData.erase(laneData.begin() + dimIdx, laneData.begin() + dimIdx + 1);
628 laneLayout.insert(laneLayout.begin() + firstDim, collapsedLaneLayout);
629 laneData.insert(laneData.begin() + firstDim, collapsedLaneData);
632 SmallVector<int64_t> newOrder;
634 if (orderAttr && !orderAttr.empty()) {
636 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
637 if (dimIdx != firstDim)
638 origOrder.erase(origOrder.begin() + dimIdx);
643 llvm::to_vector(llvm::seq<size_t>(0, orderAttr.size()));
647 [&](
size_t a,
size_t b) {
return origOrder[a] < origOrder[
b]; });
649 newOrder = llvm::to_vector(llvm::map_range(
650 indices, [&](
size_t i) {
return static_cast<int64_t
>(i); }));
656 SmallVector<int32_t> v32(v.begin(), v.end());
659 auto collapsedLayout = xegpu::LayoutAttr::get(
660 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
661 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
662 return collapsedLayout;
666DistributeLayoutAttr LayoutAttr::transposeDims(ArrayRef<int64_t> permutation) {
668 SmallVector<int64_t> origSgLayout = getEffectiveSgLayoutAsInt();
669 SmallVector<int64_t> origSgData = getEffectiveSgDataAsInt();
670 SmallVector<int64_t> origInstData = getEffectiveInstDataAsInt();
671 SmallVector<int64_t> origLaneLayout = getEffectiveLaneLayoutAsInt();
672 SmallVector<int64_t> origLaneData = getEffectiveLaneDataAsInt();
673 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
675 SmallVector<int32_t> sgLayout;
676 SmallVector<int32_t> sgData;
677 SmallVector<int32_t> instData;
678 SmallVector<int32_t> laneLayout;
679 SmallVector<int32_t> laneData;
680 SmallVector<int32_t> order;
682 for (int64_t idx : permutation) {
683 if (!origLaneLayout.empty()) {
684 laneLayout.push_back(
static_cast<int32_t
>(origLaneLayout[idx]));
685 laneData.push_back(
static_cast<int32_t
>(origLaneData[idx]));
687 if (!origInstData.empty())
688 instData.push_back(
static_cast<int32_t
>(origInstData[idx]));
689 if (!origSgLayout.empty()) {
690 sgLayout.push_back(
static_cast<int32_t
>(origSgLayout[idx]));
691 sgData.push_back(
static_cast<int32_t
>(origSgData[idx]));
693 order.push_back(
static_cast<int32_t
>(origOrder[idx]));
695 if (origLaneLayout.empty() && origSgLayout.empty())
701 return xegpu::LayoutAttr::get(
getContext(), toAttr(sgLayout), toAttr(sgData),
702 toAttr(instData), toAttr(laneLayout),
703 toAttr(laneData), toAttr(order));
707bool LayoutAttr::isTransposeOf(
const xegpu::DistributeLayoutAttr &other,
708 ArrayRef<int64_t> perm,
712 if (getRank() != other.getRank() ||
713 perm.size() !=
static_cast<size_t>(getRank()))
717 auto checkTranspose = [](ArrayRef<int64_t> dst, ArrayRef<int64_t> src,
718 ArrayRef<int64_t> perm) {
719 for (
const auto &ta : llvm::enumerate(perm)) {
720 if (src[ta.index()] != dst[ta.value()])
726 return checkTranspose(getEffectiveSgLayoutAsInt(),
727 other.getEffectiveSgLayoutAsInt(), perm) &&
728 checkTranspose(getEffectiveSgDataAsInt(),
729 other.getEffectiveSgDataAsInt(), perm) &&
730 checkTranspose(getEffectiveOrderAsInt(),
731 other.getEffectiveOrderAsInt(), perm);
733 return checkTranspose(getEffectiveInstDataAsInt(),
734 other.getEffectiveInstDataAsInt(), perm);
736 return checkTranspose(getEffectiveLaneLayoutAsInt(),
737 other.getEffectiveLaneLayoutAsInt(), perm) &&
738 checkTranspose(getEffectiveLaneDataAsInt(),
739 other.getEffectiveLaneDataAsInt(), perm) &&
740 checkTranspose(getEffectiveOrderAsInt(),
741 other.getEffectiveOrderAsInt(), perm);
750SliceAttr::verify(llvm::function_ref<InFlightDiagnostic()>
emitError,
754 return emitError() <<
"expected dims attribute";
757 llvm::SmallDenseSet<int64_t> seen;
760 return emitError() <<
"invalid dim (" << dim <<
") in slice attribute.";
761 if (!seen.insert(dim).second)
762 return emitError() <<
"repeated dim (" << dim <<
") in slice attribute.";
767SliceAttr SliceAttr::flatten()
const {
768 xegpu::DistributeLayoutAttr parent = getParent();
769 SmallVector<DenseI64ArrayAttr> slicedDims({
getDims()});
771 while (
auto sliceAttr = dyn_cast<xegpu::SliceAttr>(parent)) {
772 parent = sliceAttr.getParent();
773 slicedDims.push_back(sliceAttr.getDims());
776 auto layoutAttr = dyn_cast<xegpu::LayoutAttr>(parent);
778 llvm::to_vector(llvm::seq<int64_t>(0, layoutAttr.getRank()));
781 SmallVector<int64_t> remainingDims(
indices);
782 for (
auto dim : llvm::reverse(slicedDims))
783 remainingDims = XeGPUDialect::slice(llvm::ArrayRef<int64_t>(remainingDims),
787 SmallVector<int64_t> flattendDims = XeGPUDialect::slice(
788 llvm::ArrayRef<int64_t>(
indices), llvm::ArrayRef<int64_t>(remainingDims));
790 return xegpu::SliceAttr::get(
795FailureOr<SmallVector<Value>>
796SliceAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
797 SliceAttr attr = flatten();
798 auto parent = dyn_cast<LayoutAttr>(attr.getParent());
799 return parent.delinearizeId(builder, loc, linearId);
805FailureOr<SmallVector<SmallVector<Value>>>
806SliceAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
807 Value linearId, ArrayRef<int64_t> shape) {
808 assert(getRank() ==
static_cast<int64_t
>(shape.size()) &&
"invalid shape.");
810 SmallVector<int64_t> layout;
811 SmallVector<int64_t> subShape;
812 if (isForWorkgroup()) {
813 layout = getEffectiveSgLayoutAsInt();
814 subShape = getEffectiveSgDataAsInt();
815 }
else if (isForSubgroup()) {
816 layout = getEffectiveLaneLayoutAsInt();
817 subShape = getEffectiveLaneDataAsInt();
822 if (subShape.empty()) {
824 subShape = derivedShape.value();
830 auto maybeIds = delinearizeId(builder, loc, linearId);
836 ArrayRef<int64_t> dims = flatten().getDims().
asArrayRef();
837 SmallVector<Value> sgIds =
838 XeGPUDialect::slice(ArrayRef<Value>(*maybeIds), dims);
840 return genCoordinates(builder, loc, sgIds, layout, subShape, shape);
843bool SliceAttr::isSliceOf(
const xegpu::DistributeLayoutAttr &other) {
844 auto flattenedThis = flatten();
847 if (
auto otherLayout = dyn_cast<xegpu::LayoutAttr>(other))
848 return flattenedThis.getParent() == otherLayout;
850 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
852 if (flattenedThis.getParent() != flattenedOther.getParent())
856 llvm::SmallDenseSet<int64_t> thisDims(
857 flattenedThis.getDims().asArrayRef().begin(),
858 flattenedThis.getDims().asArrayRef().end());
859 return llvm::all_of(flattenedOther.getDims().asArrayRef(),
860 [&](int64_t dim) { return thisDims.contains(dim); });
863bool SliceAttr::isEqualTo(
const xegpu::DistributeLayoutAttr &other) {
864 if (dyn_cast<xegpu::LayoutAttr>(other))
867 auto flattenedThis = flatten();
868 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
870 return ((flattenedThis.getParent() == flattenedOther.getParent()) &&
871 (flattenedThis.getDims() == flattenedOther.getDims()));
874xegpu::SliceAttr SliceAttr::dropSliceDims(ArrayRef<int64_t> sliceDimsToDrop) {
875 if (sliceDimsToDrop.empty())
877 SmallVector<int64_t> sliceDims{
getDims().asArrayRef()};
878 for (
auto dim : sliceDimsToDrop) {
879 auto foundIt = std::find(sliceDims.begin(), sliceDims.end(), dim);
880 assert(foundIt != sliceDims.end() &&
881 "Expected to find the specified reduction dim in slice dims");
882 sliceDims.erase(foundIt);
885 auto sliceWithoutDims = xegpu::SliceAttr::get(
889 return sliceWithoutDims;
897static SmallVector<int64_t>
905 std::max(maxDim, *std::max_element(sliceDims.begin(), sliceDims.end()));
907 std::max(maxDim, *std::max_element(dimsToMap.begin(), dimsToMap.end()));
908 int64_t parentSpaceRank = maxDim + sliceDims.size() + 1;
912 llvm::SmallDenseSet<int64_t> slicedDimsSet(sliceDims.begin(),
915 for (
int64_t i = 0; i < parentSpaceRank; ++i) {
916 if (!slicedDimsSet.contains(i))
917 remainingDims.push_back(i);
922 for (
auto dim : dimsToMap) {
923 int64_t mappedDim = remainingDims[dim];
924 adjustUnitDims.push_back(mappedDim);
927 return adjustUnitDims;
933 DistributeLayoutAttr parentLayout = getParent();
941 parentLayout.setUnitDimData(adjustUnitDims), getDims());
947 DistributeLayoutAttr parentLayout = getParent();
954 return SliceAttr::get(
955 getContext(), parentLayout.setUnitDimLayout(adjustUnitDims), getDims());
960DistributeLayoutAttr SliceAttr::setDimData(int64_t dim, int64_t sgData,
961 int64_t instData, int64_t laneData) {
962 ArrayRef<int64_t> sliceDims =
getDims().asArrayRef();
963 auto parent = getParent();
965 SmallVector<int64_t> dimSet;
966 dimSet.push_back(dim);
967 SmallVector<int64_t> adjustDims =
969 return SliceAttr::get(
971 parent.setDimData(adjustDims[0], sgData, instData, laneData),
getDims());
992DistributeLayoutAttr SliceAttr::dropDims(SmallVector<int64_t> dimGroup) {
994 SmallVector<int64_t> sliceDims = llvm::to_vector(
getDims().asArrayRef());
995 SmallVector<int64_t> dimsInParentSpace =
998 auto droppedParent = getParent().dropDims(dimsInParentSpace);
1003 SmallVector<int64_t> newSliceDims;
1004 for (int64_t d : sliceDims) {
1006 llvm::count_if(dimsInParentSpace, [&](int64_t s) {
return s < d; });
1007 newSliceDims.push_back(d - offset);
1010 return SliceAttr::get(
getContext(), droppedParent,
1017DistributeLayoutAttr SliceAttr::collapseDims(SmallVector<int64_t> dimGroup) {
1020 SmallVector<int64_t> sliceDims = llvm::to_vector(
getDims().asArrayRef());
1021 assert(
"expect sliceDims not being collapsed" &&
1022 llvm::none_of(dimGroup, [&](int64_t dim) {
1023 return llvm::is_contained(sliceDims, dim);
1025 SmallVector<int64_t> dimsInParentSpace =
1028 auto collapsedParent = getParent().collapseDims(dimsInParentSpace);
1029 return SliceAttr::get(
getContext(), collapsedParent,
1036 llvm::sort(sortedSliceDims);
1038 for (
size_t i = 1; i < sortedSliceDims.size(); ++i) {
1039 assert((sortedSliceDims[i] == sortedSliceDims[i - 1] + 1) &&
1040 "slice dims non consecutive, cannot be transposed");
1044 if (sortedSliceDims.front() == 0) {
1047 for (
int64_t dim : permutation)
1048 permForParent.push_back(dim + sortedSliceDims.size());
1049 for (
int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1050 permForParent.push_back(i);
1054 for (
int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1055 permForParent.push_back(i + permutation.size());
1056 for (
int64_t dim : permutation)
1057 permForParent.push_back(dim);
1059 return permForParent;
1065 DistributeLayoutAttr parent = getParent();
1068 auto transposedParent = parent.transposeDims(permForParent);
1069 return SliceAttr::get(
getContext(), transposedParent,
1074bool SliceAttr::isTransposeOf(
const xegpu::DistributeLayoutAttr &other,
1078 auto otherSlice = dyn_cast<xegpu::SliceAttr>(other);
1079 if (!otherSlice || getDims() != otherSlice.getDims())
1083 DistributeLayoutAttr parent = getParent();
1085 auto otherParent = otherSlice.getParent();
1086 return parent.isTransposeOf(otherParent, permForParent, kind);
1094RangeAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()>
emitError,
1095 IntegerAttr startOfRange, IntegerAttr endOfRange) {
1096 if (startOfRange.getInt() >= endOfRange.getInt())
1097 return emitError() <<
"'end' : " << endOfRange.getInt()
1098 <<
" must be greater than 'start' : "
1099 << startOfRange.getInt();
1108mlir::Type TensorDescType::parse(AsmParser &parser) {
1109 llvm::SmallVector<int64_t> shape;
1110 mlir::Type elementType;
1111 mlir::FailureOr<mlir::Attribute> encoding;
1112 mlir::FailureOr<mlir::Attribute> layout;
1120 parser.
emitError(shapeLoc,
"failed to parse parameter 'shape'");
1125 if (mlir::failed(parser.
parseType(elementType))) {
1126 parser.
emitError(elemTypeLoc,
"failed to parse parameter 'elementType'");
1132 mlir::Attribute attr;
1134 if (mlir::succeeded(res)) {
1135 if (mlir::isa<LayoutAttr>(attr)) {
1139 if (mlir::isa<BlockTensorDescAttr, ScatterTensorDescAttr>(attr)) {
1152 return TensorDescType::getChecked(
1154 elementType, encoding.value_or(BlockTensorDescAttr::get(ctxt)),
1155 layout.value_or(mlir::Attribute()));
1158void TensorDescType::print(AsmPrinter &printer)
const {
1162 for (int64_t dim : shape) {
1163 if (mlir::ShapedType::isDynamic(dim))
1172 auto encoding = getEncoding();
1173 auto blockAttr = llvm::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1174 if (encoding && (!blockAttr || !blockAttr.hasDefaultsOnly()))
1175 printer <<
", " << encoding;
1177 if (
auto layout = getLayout())
1178 printer <<
", " << layout;
1183TensorDescType TensorDescType::get(llvm::ArrayRef<int64_t> shape,
1184 mlir::Type elementType,
int array_length,
1185 bool boundary_check,
1186 MemorySpace memory_space,
1187 mlir::Attribute layout) {
1189 auto attr = BlockTensorDescAttr::get(context, memory_space, array_length,
1191 return Base::get(context, shape, elementType, attr, layout);
1194TensorDescType TensorDescType::get(llvm::ArrayRef<int64_t> shape,
1195 mlir::Type elementType,
int chunk_size,
1196 MemorySpace memory_space,
1197 mlir::Attribute layout) {
1199 auto attr = ScatterTensorDescAttr::get(context, memory_space, chunk_size);
1200 return Base::get(context, shape, elementType, attr, layout);
1204TensorDescType::verify(llvm::function_ref<InFlightDiagnostic()>
emitError,
1205 llvm::ArrayRef<int64_t> shape, mlir::Type elementType,
1206 mlir::Attribute encoding, mlir::Attribute layout) {
1207 size_t rank = shape.size();
1210 return emitError() <<
"expected non-zero rank tensor";
1212 auto blockAttr = mlir::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1214 MemorySpaceAttr memorySpaceAttr = blockAttr.getMemorySpace();
1215 if (rank > 1 && memorySpaceAttr &&
1216 memorySpaceAttr.getValue() == MemorySpace::SLM)
1217 return emitError() <<
"SLM is only supported for 1D block tensor";
1221 return emitError() <<
"unsupported element type " << elementType
1222 <<
": expected integer or float";
1227 int chunkAlignmentFactor =
1231 auto scatterAttr = mlir::dyn_cast_if_present<ScatterTensorDescAttr>(encoding);
1233 int64_t chunkSize = scatterAttr.getChunkSizeAsInt();
1234 if (rank == 1 && chunkSize != 1)
1235 return emitError() <<
"expected non-contiguous elements for 1D tensor";
1240 if (chunkSize > 1) {
1241 if (shape.back() != chunkSize)
1242 return emitError() <<
"expected last dim of tensor to match chunk size";
1243 if (shape.back() % chunkAlignmentFactor != 0)
1244 return emitError() <<
"expected last dim of tensor to be a multiple of "
1245 << chunkAlignmentFactor;
1249 auto layoutAttr = llvm::dyn_cast_if_present<LayoutAttr>(layout);
1251 if (rank != (
size_t)layoutAttr.getRank())
1252 return emitError() <<
"expected layout rank to match tensor rank";
1254 auto laneData = layoutAttr.getLaneData();
1255 if (scatterAttr && laneData) {
1259 int64_t chunkSize = scatterAttr.getChunkSizeAsInt();
1260 if (chunkSize > 1 && laneData[rank - 1] % chunkAlignmentFactor)
1262 <<
"expected last dim of lane_data to be a multiple of: "
1263 << chunkAlignmentFactor;
1266 if (!XeGPUDialect::isEvenlyDistributable(shape, layoutAttr)) {
1267 std::string shapeStr;
1268 llvm::raw_string_ostream stream(shapeStr);
1269 llvm::interleaveComma(shape, stream);
1270 return emitError() <<
"cannot distribute [" << shapeStr <<
"] using "
1280mlir::Type MemDescType::parse(AsmParser &parser) {
1281 llvm::SmallVector<int64_t> shape;
1282 mlir::Type elementType;
1283 mlir::FailureOr<MemLayoutAttr> layout;
1291 parser.
emitError(shapeLoc,
"failed to parse parameter 'shape'");
1296 if (mlir::failed(parser.
parseType(elementType))) {
1297 parser.
emitError(elemTypeLoc,
"failed to parse parameter 'elementType'");
1305 if (mlir::failed(res))
1315 return MemDescType::getChecked(
1317 elementType, layout.value_or(MemLayoutAttr()));
1320void MemDescType::print(AsmPrinter &printer)
const {
1327 if (
auto layout = getMemLayout())
1328 printer <<
", " << layout;
1337Attribute MemLayoutAttr::parse(AsmParser &parser, Type type) {
1342 llvm::SmallDenseSet<StringRef> seenKeys;
1343 SmallVector<NamedAttribute> attributes;
1345 auto parseElt = [&]() -> ParseResult {
1348 return parser.
emitError(loc,
"expected valid attribute name");
1350 if (!seenKeys.insert(nameId).second)
1351 return parser.
emitError(loc,
"duplicate key '")
1352 << nameId <<
" in mem layout attribute";
1360 attributes.emplace_back(nameId, attr);
1376 loc, context, DictionaryAttr::get(context, attributes));
1379void MemLayoutAttr::print(AsmPrinter &printer)
const {
1381 ArrayRef<NamedAttribute> attrs = getAttrs().getValue();
1382 for (
size_t i = 0; i < attrs.size(); i++) {
1383 printer << attrs[i].getName().str() <<
" = " << attrs[i].getValue();
1384 if (i < attrs.size() - 1)
1393template <
typename ArithOp>
1398 return ArithOp::create(builder, loc, aVal, bVal).getResult();
1403 genBinOp<arith::DivSIOp>(a, builder.getIndexAttr(b), loc, builder)
1407 genBinOp<arith::RemSIOp>(a, builder.getIndexAttr(b), loc, builder)
1411 genBinOp<arith::MulIOp>(a, builder.getIndexAttr(b), loc, builder)
1414#define add(a, b) genBinOp<arith::AddIOp>(a, b, loc, builder)
1423 assert(offsets.size() == blockShape.size() &&
1424 "offsets and blockShape must have the same size");
1428 for (
auto [offset, block] : llvm::zip(offsets, blockShape)) {
1429 divs.push_back(
div(offset, block));
1430 rems.push_back(
rem(offset, block));
1432 blockedOffsets.append(divs.begin(), divs.end());
1433 blockedOffsets.append(rems.begin(), rems.end());
1435 return blockedOffsets;
1443 ArrayAttr strideAttr = getStrideAttr();
1445 for (
Attribute attr : strideAttr.getValue()) {
1446 strides.push_back(cast<IntegerAttr>(attr).getInt());
1454 llvm::to_vector<4>(llvm::seq<int>(0, strides.size()));
1455 llvm::sort(perm, [&](
int a,
int b) {
return strides[a] < strides[
b]; });
1457 assert(strides[perm[0]] == 1 &&
"inner most dim must have stride 1");
1459 SmallVector<int64_t> innerBlkStride(innerBlkShape.size());
1460 innerBlkStride[perm[0]] = 1;
1461 for (
size_t i = 1; i < perm.size(); ++i)
1462 innerBlkStride[perm[i]] =
1463 innerBlkStride[perm[i - 1]] * innerBlkShape[perm[i - 1]];
1469 SmallVector<int64_t> matrixShapeOrig(matrixShape.size());
1470 SmallVector<int64_t> BlkShapeOrig(matrixShape.size());
1471 for (
size_t i = 0; i < perm.size() - 1; ++i) {
1472 matrixShapeOrig[perm[i]] = strides[perm[i + 1]] / strides[perm[i]];
1473 BlkShapeOrig[perm[i]] = matrixShapeOrig[perm[i]] / innerBlkShape[perm[i]];
1476 int64_t innerBlkSize = 1;
1477 for (
auto s : innerBlkShape)
1480 SmallVector<int64_t> outerBlkStride(matrixShape.size());
1481 outerBlkStride[perm[0]] = innerBlkSize;
1482 for (
size_t i = 0; i < perm.size() - 1; ++i) {
1483 outerBlkStride[perm[i + 1]] =
1484 outerBlkStride[perm[i]] * BlkShapeOrig[perm[i]];
1488 SmallVector<int64_t> blockedStrides;
1489 blockedStrides.append(outerBlkStride.begin(), outerBlkStride.end());
1490 blockedStrides.append(innerBlkStride.begin(), innerBlkStride.end());
1492 return blockedStrides;
1496Value MemDescType::getLinearOffsets(OpBuilder &builder, Location loc,
1497 ArrayRef<OpFoldResult> offsets) {
1500 SmallVector<int64_t> blockShape = getBlockShape();
1501 SmallVector<int64_t> strides = getStrideShape();
1502 SmallVector<OpFoldResult> blockedOffsets;
1505 if (llvm::equal(blockShape, matrixShape)) {
1507 strides.erase(strides.begin(), strides.begin() + matrixShape.size());
1509 assert(offsets.size() == blockShape.size() &&
1510 "offsets and blockShape must have the same size");
1514 SmallVector<OpFoldResult> divs, rems;
1516 for (
auto [offset, block] : llvm::zip(offsets, blockShape)) {
1517 divs.push_back(
div(offset, block));
1518 rems.push_back(
rem(offset, block));
1520 blockedOffsets.append(divs.begin(), divs.end());
1521 blockedOffsets.append(rems.begin(), rems.end());
1522 offsets = blockedOffsets;
1527 for (
size_t i = 0; i < offsets.size(); ++i) {
1528 OpFoldResult mulResult =
mul(offsets[i], strides[i]);
1530 linearOffset = arith::AddIOp::create(builder, loc, mulVal, linearOffset);
1533 return linearOffset;
1539#include <mlir/Dialect/XeGPU/IR/XeGPUDialect.cpp.inc>
1540#define GET_ATTRDEF_CLASSES
1541#include <mlir/Dialect/XeGPU/IR/XeGPUAttrs.cpp.inc>
1542#define GET_TYPEDEF_CLASSES
1543#include <mlir/Dialect/XeGPU/IR/XeGPUTypes.cpp.inc>
static Type getElementType(Type type)
Determine the element type of type.
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseDimensionList(SmallVectorImpl< int64_t > &dimensions, bool allowDynamic=true, bool withTrailingX=true)=0
Parse a dimension list of a tensor or memref type.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
auto getChecked(SMLoc loc, ParamsT &&...params)
Invoke the getChecked method of the given Attribute or Type class, using the provided location to emi...
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
void printDimensionList(ArrayRef< int64_t > shape)
Attributes are known-constant values of operations.
static BoolAttr get(MLIRContext *context, bool value)
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
This class helps build Operations.
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 a single result from folding an operation.
A range-style iterator that allows for iterating over the offsets of all potential tiles of size tile...
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Specialization of arith.constant op that returns an integer of index type.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int32_t > content)
ArrayRef< T > asArrayRef() const
auto getDims(VectorType vType)
Returns a range over the dims (size and scalability) of a VectorType.
constexpr unsigned generalPackedFormatBitSize
LayoutKind
Specifies the level of a layout hierarchy for comparison or propagation.
static SmallVector< int64_t > mapSlicedDimsToParentSpace(const SmallVector< int64_t > &dimsToMap, ArrayRef< int64_t > sliceDims)
SmallVector< OpFoldResult > getBlockedOffsets(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > offsets, ArrayRef< int64_t > blockShape)
OpFoldResult genBinOp(OpFoldResult a, OpFoldResult b, Location loc, OpBuilder &builder)
static SmallVector< SmallVector< Value > > genCoordinates(OpBuilder &builder, Location loc, SmallVector< Value > delinearizedId, ArrayRef< int64_t > subShapesLayout, ArrayRef< int64_t > subShape, ArrayRef< int64_t > srcShape)
SmallVector< int64_t > getPermForParentLayout(ArrayRef< int64_t > sliceDims, ArrayRef< int64_t > permutation)
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
SmallVector< int64_t > computeElementwiseMul(ArrayRef< int64_t > v1, ArrayRef< int64_t > v2)
Return a vector containing llvm::zip_equal(v1, v2) multiplied elementwise.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
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.
bool isPermutationVector(ArrayRef< int64_t > interchange)
Method to check if an interchange vector is a permutation.