18#include "llvm/ADT/SmallVectorExtras.h"
19#include "llvm/ADT/TypeSwitch.h"
20#include "llvm/Support/Debug.h"
27#define GET_OP_INTERFACE_CLASSES
28#include "mlir/Dialect/XeGPU/IR/XeGPUOpInterface.cpp.inc"
38static SmallVector<SmallVector<Value>>
47 llvm::zip_equal(srcShape,
49 [](
const auto &t) {
return std::min(std::get<0>(t), std::get<1>(t)); });
53 llvm::zip(delinearizedId, subShape), [&](
const auto &t) ->
Value {
69 llvm::map_to_vector(llvm::zip_equal(base, distUnitLocalOffset),
70 [&](
const auto &t) ->
Value {
72 loc, std::get<0>(t), std::get<1>(t));
76 llvm::zip_equal(adds, srcShape), [&](
const auto &t) ->
Value {
82 coordinates.push_back(mods);
92 for (
size_t i = 0; i <
shape.size(); ++i)
93 distUnitShape[i] = std::min(
shape[i], layout[i] * subShape[i]);
97 for (
size_t i = 0; i <
shape.size(); ++i)
98 localOffset[i] = canonicalIds[i] * subShape[i];
105 for (
size_t i = 0; i <
shape.size(); ++i)
106 coord[i] = (unitOffs[i] + localOffset[i]) %
shape[i];
107 coordinates.push_back(coord);
125 for (
size_t i = 0; i < start.size(); ++i)
126 coord[i] = start[i] + off[i];
127 expanded.push_back(std::move(coord));
145 const xegpu::DistributeLayoutAttr &other,
150 self.getEffectiveLaneDataAsInt() != other.getEffectiveLaneDataAsInt();
153 selfSubShape = self.getEffectiveLaneDataAsInt();
154 otherSubShape = other.getEffectiveLaneDataAsInt();
156 for (
int64_t id : llvm::seq<int64_t>(0, size)) {
157 auto coords = self.computeStaticDistributedCoords(
id,
shape);
158 auto otherCoords = other.computeStaticDistributedCoords(
id,
shape);
163 if (coords != otherCoords)
170bool XeGPUDialect::isSharedMemory(
const MemRefType &memrefTy) {
171 Attribute attr = memrefTy.getMemorySpace();
174 if (
auto intAttr = llvm::dyn_cast_if_present<IntegerAttr>(attr))
175 return intAttr.getInt() == 3;
176 if (
auto memrefSpace = llvm::dyn_cast_if_present<MemorySpaceAttr>(attr))
177 return memrefSpace.getValue() == MemorySpace::SLM;
178 if (
auto xevmSpace = llvm::dyn_cast_if_present<xevm::AddrSpaceAttr>(attr))
179 return xevmSpace.getValue() == xevm::AddrSpace::SHARED;
180 return gpu::GPUDialect::isWorkgroupMemoryAddressSpace(attr);
187 xegpu::MemorySpace memory_space,
189 bool boundary_check) {
190 auto scopeAttr = MemorySpaceAttr::get(context, memory_space);
192 IntegerAttr::get(IntegerType::get(context, 64), array_length);
194 return Base::get(context, scopeAttr, lengthAttr, boundaryAttr);
197bool BlockTensorDescAttr::hasDefaultsOnly() {
198 return getMemorySpace().getValue() == xegpu::MemorySpace::Global &&
199 getArrayLength().getInt() == 1 && getBoundaryCheck().getValue();
206LayoutAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()>
emitError,
212 if (!sg_layout && !inst_data && !lane_layout)
218 if (sg_layout && inst_data && sg_layout.size() != inst_data.size()) {
220 <<
"expected sg_layout and inst_data to have the same rank";
223 if (sg_layout && lane_layout && sg_layout.size() != lane_layout.size()) {
225 <<
"expected sg_layout and lane_layout to have the same rank";
228 if (inst_data && lane_layout && inst_data.size() != lane_layout.size()) {
229 return emitError() <<
"expected inst_data and lane_layout to have the same "
230 "rank, got inst_data "
231 << inst_data.size() <<
", lane_layout "
232 << lane_layout.size();
235 if ((sg_layout && !sg_data) || (!sg_layout && sg_data))
236 return emitError() <<
"sg_layout and sg_data must be used together";
237 if (sg_layout && sg_data && sg_layout.size() != sg_data.size())
239 <<
"expected sg_data and sg_layout to have the same rank";
241 if ((lane_layout && !lane_data) || (!lane_layout && lane_data))
242 return emitError() <<
"lane_layout and lane_data must be used together";
243 if (lane_layout && lane_data && lane_layout.size() != lane_data.size())
245 <<
"expected lane_data and lane_layout to have the same rank";
248 if (!sg_layout && !lane_layout)
250 <<
"expected sg_layout/lane_layout being used with order";
252 if (sg_layout && order.size() != sg_layout.size())
254 <<
"expected order and sg_layout to have the same rank";
256 if (lane_layout && order.size() != lane_layout.size())
258 <<
"expected order and lane_layout to have the same rank";
264FailureOr<SmallVector<Value>>
265LayoutAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
267 SmallVector<int64_t> sgLayoutInt;
268 if (isForWorkgroup()) {
269 sgLayoutInt = getEffectiveSgLayoutAsInt();
270 }
else if (isForSubgroup()) {
271 sgLayoutInt = getEffectiveLaneLayoutAsInt();
279 SmallVector<int64_t> order;
280 if (orderAttr && !orderAttr.empty()) {
281 order = llvm::map_to_vector(orderAttr.asArrayRef(), [](int32_t idx) {
282 return static_cast<int64_t>(idx);
286 order = llvm::to_vector(
287 llvm::reverse(llvm::seq<int64_t>(0, sgLayoutInt.size())));
290 if (order.size() != sgLayoutInt.size()) {
294 SmallVector<Value>
result(sgLayoutInt.size());
295 Value remaining = linearId;
318 for (
size_t i = 0; i < order.size(); ++i) {
319 int64_t dimIdx = order[i];
320 int64_t dimSize = sgLayoutInt[dimIdx];
323 builder.createOrFold<arith::ConstantIndexOp>(loc, dimSize);
330 builder.createOrFold<arith::RemUIOp>(loc, remaining, dimSizeVal);
337 if (i < order.size() - 1) {
339 builder.createOrFold<arith::DivUIOp>(loc, remaining, dimSizeVal);
348FailureOr<SmallVector<SmallVector<Value>>>
349LayoutAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
350 Value linearId, ArrayRef<int64_t> shape) {
351 SmallVector<int64_t> layout;
352 SmallVector<int64_t> subShape;
353 if (isForWorkgroup()) {
354 layout = getEffectiveSgLayoutAsInt();
355 subShape = getEffectiveSgDataAsInt();
356 }
else if (isForSubgroup()) {
357 layout = getEffectiveLaneLayoutAsInt();
358 subShape = getEffectiveLaneDataAsInt();
362 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty for "
363 "distributed coordinates computation");
366 auto maybeIds = delinearizeId(builder, loc, linearId);
369 SmallVector<Value> ids = *maybeIds;
371 return genCoordinates(builder, loc, ids, layout, subShape, shape);
374bool LayoutAttr::isEqualTo(
const xegpu::DistributeLayoutAttr &other) {
375 if (dyn_cast<xegpu::SliceAttr>(other))
378 return *
this == dyn_cast<xegpu::LayoutAttr>(other);
384SmallVector<SmallVector<int64_t>>
385LayoutAttr::computeStaticDistributedCoords(int64_t linearId,
386 ArrayRef<int64_t> shape) {
387 SmallVector<int64_t> layoutVec;
388 SmallVector<int64_t> subShape;
389 SmallVector<int64_t> instData;
390 if (isForWorkgroup()) {
391 layoutVec = getEffectiveSgLayoutAsInt();
392 subShape = getEffectiveSgDataAsInt();
393 }
else if (isForSubgroup()) {
394 instData = getEffectiveInstDataAsInt();
395 layoutVec = getEffectiveLaneLayoutAsInt();
396 subShape = getEffectiveLaneDataAsInt();
398 if (!instData.empty()) {
402 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty");
405 SmallVector<int64_t> order = getEffectiveOrderAsInt();
406 SmallVector<int64_t> delinearizedId(layoutVec.size());
407 int64_t remaining = linearId;
408 for (
size_t i = 0; i < order.size(); ++i) {
409 int64_t dimIdx = order[i];
410 delinearizedId[dimIdx] = remaining % layoutVec[dimIdx];
411 remaining = remaining / layoutVec[dimIdx];
419LayoutAttr::setUnitDimData(SmallVector<int64_t> unitDims)
const {
420 auto sgDataOpt = getSgData();
421 auto instDataOpt = getInstData();
422 auto laneDataOpt = getLaneData();
424 SmallVector<int32_t> sgData;
425 SmallVector<int32_t> instData;
426 SmallVector<int32_t> laneData;
429 sgData = llvm::to_vector(sgDataOpt.asArrayRef());
432 instData = llvm::to_vector(instDataOpt.asArrayRef());
435 laneData = llvm::to_vector(laneDataOpt.asArrayRef());
437 for (
auto dim : unitDims) {
438 if (dim <
static_cast<int64_t
>(sgData.size()))
440 if (dim <
static_cast<int64_t
>(instData.size()))
442 if (dim <
static_cast<int64_t
>(laneData.size()))
446 return LayoutAttr::get(
460LayoutAttr::setUnitDimLayout(SmallVector<int64_t> unitDims)
const {
461 auto sgLayoutOpt = getSgLayout();
462 auto laneLayoutOpt = getLaneLayout();
464 SmallVector<int32_t> sgLayout;
465 SmallVector<int32_t> laneLayout;
468 sgLayout = llvm::to_vector(sgLayoutOpt.asArrayRef());
470 laneLayout = llvm::to_vector(laneLayoutOpt.asArrayRef());
472 for (
auto dim : unitDims) {
473 if (dim <
static_cast<int64_t
>(sgLayout.size()))
475 if (dim <
static_cast<int64_t
>(laneLayout.size()))
479 return LayoutAttr::get(
483 getSgData(), getInstData(),
486 getLaneData(), getOrder());
491DistributeLayoutAttr LayoutAttr::setDimData(int64_t dim, int64_t sgData,
495 SmallVector<int64_t> sgDataVec = getEffectiveSgDataAsInt();
496 SmallVector<int64_t> instDataVec = getEffectiveInstDataAsInt();
497 SmallVector<int64_t> laneDataVec = getEffectiveLaneDataAsInt();
499 if (dim <
static_cast<int64_t
>(sgDataVec.size()) && sgData != -1)
500 sgDataVec[dim] = sgData;
501 if (dim <
static_cast<int64_t
>(instDataVec.size()) && instData != -1)
502 instDataVec[dim] = instData;
503 if (dim <
static_cast<int64_t
>(laneDataVec.size()) && laneData != -1)
504 laneDataVec[dim] = laneData;
506 SmallVector<int32_t> sgDataVec32(sgDataVec.begin(), sgDataVec.end());
507 SmallVector<int32_t> instDataVec32(instDataVec.begin(), instDataVec.end());
508 SmallVector<int32_t> laneDataVec32(laneDataVec.begin(), laneDataVec.end());
510 return LayoutAttr::get(
525DistributeLayoutAttr LayoutAttr::dropDims(SmallVector<int64_t> dimGroup) {
527 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
528 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
529 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
530 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
531 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
534 SmallVector<int64_t> sortedDimGroup = dimGroup;
535 llvm::sort(sortedDimGroup);
537 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
538 if (!sgLayout.empty()) {
539 sgLayout.erase(sgLayout.begin() + dimIdx);
540 sgData.erase(sgData.begin() + dimIdx);
542 if (!instData.empty())
543 instData.erase(instData.begin() + dimIdx);
544 if (!laneLayout.empty()) {
545 laneLayout.erase(laneLayout.begin() + dimIdx);
546 laneData.erase(laneData.begin() + dimIdx);
553 SmallVector<int64_t> newOrder;
554 if (origOrderAttr && !origOrderAttr.empty()) {
555 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
556 for (int64_t d : origOrder) {
557 if (llvm::is_contained(dimGroup, d))
560 llvm::count_if(dimGroup, [&](int64_t s) {
return s < d; });
561 newOrder.push_back(d - offset);
563 if ((sgLayout.empty() && laneLayout.empty()) || newOrder.size() == 1)
570 SmallVector<int32_t> v32(v.begin(), v.end());
573 auto droppedLayout = xegpu::LayoutAttr::get(
574 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
575 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
576 return droppedLayout;
582DistributeLayoutAttr LayoutAttr::collapseDims(SmallVector<int64_t> dimGroup) {
584 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
585 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
586 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
587 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
588 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
589 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
591 SmallVector<int64_t> sortedDimGroup = dimGroup;
592 llvm::sort(sortedDimGroup);
594 bool hasExplicitWalkOrder = getOrder() && !getOrder().empty();
595 for (
size_t dimIdx = 1; dimIdx < sortedDimGroup.size(); ++dimIdx) {
596 int64_t prev = sortedDimGroup[dimIdx - 1];
597 int64_t curr = sortedDimGroup[dimIdx];
599 if (hasExplicitWalkOrder) {
601 if ((sgLayout.empty() || (sgLayout[prev] == 1 && sgLayout[curr] == 1)) &&
602 (laneLayout.empty() ||
603 (laneLayout[prev] == 1 && laneLayout[curr] == 1)))
605 if (std::abs(origOrder[prev] - origOrder[curr]) != 1)
606 llvm::report_fatal_error(
607 "dimensions being collapsed must be adjacent in order");
608 }
else if (curr - prev != 1)
609 llvm::report_fatal_error(
"dimensions being collapsed must be adjacent");
612 int firstDim = sortedDimGroup.front();
617 if (!sgLayout.empty()) {
618 int64_t collapsedSglayout = 1, collapsedSgData = 1;
619 for (
auto dimIdx : dimGroup) {
620 collapsedSglayout *= sgLayout[dimIdx];
621 collapsedSgData *= sgData[dimIdx];
623 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
624 sgLayout.erase(sgLayout.begin() + dimIdx, sgLayout.begin() + dimIdx + 1);
625 sgData.erase(sgData.begin() + dimIdx, sgData.begin() + dimIdx + 1);
627 sgLayout.insert(sgLayout.begin() + firstDim, collapsedSglayout);
628 sgData.insert(sgData.begin() + firstDim, collapsedSgData);
631 if (!instData.empty()) {
632 int64_t collapsedInstData = 1;
633 for (
auto dimIdx : dimGroup)
634 collapsedInstData *= instData[dimIdx];
635 for (
auto dimIdx : llvm::reverse(sortedDimGroup))
636 instData.erase(instData.begin() + dimIdx, instData.begin() + dimIdx + 1);
637 instData.insert(instData.begin() + firstDim, collapsedInstData);
640 if (!laneLayout.empty()) {
641 int64_t collapsedLaneLayout = 1, collapsedLaneData = 1;
642 for (
auto dimIdx : dimGroup) {
643 collapsedLaneLayout *= laneLayout[dimIdx];
644 collapsedLaneData *= laneData[dimIdx];
646 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
647 laneLayout.erase(laneLayout.begin() + dimIdx,
648 laneLayout.begin() + dimIdx + 1);
649 laneData.erase(laneData.begin() + dimIdx, laneData.begin() + dimIdx + 1);
651 laneLayout.insert(laneLayout.begin() + firstDim, collapsedLaneLayout);
652 laneData.insert(laneData.begin() + firstDim, collapsedLaneData);
655 SmallVector<int64_t> newOrder;
657 if (orderAttr && !orderAttr.empty()) {
659 for (
auto dimIdx : llvm::reverse(sortedDimGroup)) {
660 if (dimIdx != firstDim)
661 origOrder.erase(origOrder.begin() + dimIdx);
666 llvm::to_vector(llvm::seq<size_t>(0, origOrder.size()));
670 [&](
size_t a,
size_t b) {
return origOrder[a] < origOrder[
b]; });
672 newOrder = llvm::to_vector(llvm::map_range(
673 indices, [&](
size_t i) {
return static_cast<int64_t
>(i); }));
679 SmallVector<int32_t> v32(v.begin(), v.end());
682 auto collapsedLayout = xegpu::LayoutAttr::get(
683 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
684 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
685 return collapsedLayout;
713DistributeLayoutAttr LayoutAttr::expandDim(int64_t dim,
714 ArrayRef<int64_t> targetShape) {
715 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
716 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
717 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
718 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
719 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
721 int64_t origRank = getRank();
722 int64_t expCount =
static_cast<int64_t
>(targetShape.size());
723 assert(dim >= 0 && dim < origRank &&
"dim out of range");
724 assert(expCount >= 1 &&
"targetShape must have at least one dim");
725 int64_t newRank = origRank + expCount - 1;
730 int64_t origSgLayoutDim = sgLayout.empty() ? 1 : sgLayout[dim];
731 int64_t origSgDataDim = sgData.empty() ? 1 : sgData[dim];
732 int64_t origLaneLayoutDim = laneLayout.empty() ? 1 : laneLayout[dim];
733 int64_t origLaneDataDim = laneData.empty() ? 1 : laneData[dim];
734 int64_t origInstDataDim = instData.empty() ? 1 : instData[dim];
738 auto spread = [&](int64_t total,
739 ArrayRef<int64_t> dimSizeCap) -> SmallVector<int64_t> {
740 SmallVector<int64_t> out(expCount, 1);
741 int64_t remaining = total;
742 for (int64_t i = expCount - 1; i >= 0; --i) {
745 int64_t take = std::min(remaining, dimSizeCap[i]);
746 assert(take > 0 &&
"expandDim distribution must not be zero");
747 assert(remaining % take == 0 &&
748 "expandDims must divide evenly across dims");
752 assert(remaining == 1 &&
"expandDims total must fit within target shape");
758 auto splice = [&](SmallVector<int64_t> &vec, ArrayRef<int64_t> expanded) {
761 vec.erase(vec.begin() + dim);
762 vec.insert(vec.begin() + dim, expanded.begin(), expanded.end());
765 bool hasSgLayout = !sgLayout.empty();
766 bool hasSgData = !sgData.empty();
767 bool hasLaneLayout = !laneLayout.empty();
768 bool hasLaneData = !laneData.empty();
769 bool hasInstData = !instData.empty();
778 bool sgDataReplicated =
780 SmallVector<int64_t> expSgData(expCount, 1);
782 expSgData = spread(origSgDataDim, targetShape);
783 splice(sgData, expSgData);
785 SmallVector<int64_t> expSgLayout(expCount, 1);
787 if (sgDataReplicated) {
788 expSgLayout[0] = origSgLayoutDim;
790 SmallVector<int64_t> dimSizeCap(targetShape.begin(), targetShape.end());
792 for (int64_t i = 0; i < expCount; ++i)
793 dimSizeCap[i] /= expSgData[i];
794 expSgLayout = spread(origSgLayoutDim, dimSizeCap);
796 splice(sgLayout, expSgLayout);
800 SmallVector<int64_t> perSgShape(targetShape.begin(), targetShape.end());
801 if (hasSgLayout && !sgDataReplicated)
802 for (int64_t i = 0; i < expCount; ++i)
803 perSgShape[i] /= expSgLayout[i];
808 bool laneDataReplicated =
810 SmallVector<int64_t> expLaneLayout(expCount, 1);
811 SmallVector<int64_t> expLaneData(expCount, 1);
813 expLaneData = spread(origLaneDataDim, perSgShape);
815 SmallVector<int64_t> dimSizeCap(perSgShape.begin(), perSgShape.end());
816 if (hasLaneData && !laneDataReplicated)
817 for (int64_t i = 0; i < expCount; ++i)
818 dimSizeCap[i] /= expLaneData[i];
819 expLaneLayout = spread(origLaneLayoutDim, dimSizeCap);
822 splice(laneData, expLaneData);
824 splice(laneLayout, expLaneLayout);
831 SmallVector<int64_t> expInstData;
832 if (!hasLaneLayout || !hasLaneData) {
833 expInstData = spread(origInstDataDim, perSgShape);
835 int64_t laneAtom = origLaneLayoutDim * origLaneDataDim;
836 SmallVector<int64_t> atom(expCount, 1);
837 SmallVector<int64_t> dimSizeCap(expCount, 1);
838 for (int64_t i = 0; i < expCount; ++i) {
839 atom[i] = expLaneLayout[i] * expLaneData[i];
840 dimSizeCap[i] = perSgShape[i] / atom[i];
842 expInstData = spread(origInstDataDim / laneAtom, dimSizeCap);
843 for (int64_t i = 0; i < expCount; ++i)
844 expInstData[i] *= atom[i];
846 splice(instData, expInstData);
852 SmallVector<int64_t> newOrder;
854 if (orderAttr && !orderAttr.empty()) {
855 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
856 newOrder.reserve(newRank);
857 for (int64_t o : origOrder) {
860 for (int64_t i = expCount - 1; i >= 0; --i)
861 newOrder.push_back(dim + i);
862 }
else if (o > dim) {
863 newOrder.push_back(o + expCount - 1);
865 newOrder.push_back(o);
873 SmallVector<int32_t> v32(v.begin(), v.end());
876 return xegpu::LayoutAttr::get(
getContext(), toAttr(sgLayout), toAttr(sgData),
877 toAttr(instData), toAttr(laneLayout),
878 toAttr(laneData), toAttr(newOrder));
882DistributeLayoutAttr LayoutAttr::transposeDims(ArrayRef<int64_t> permutation) {
884 SmallVector<int64_t> origSgLayout = getEffectiveSgLayoutAsInt();
885 SmallVector<int64_t> origSgData = getEffectiveSgDataAsInt();
886 SmallVector<int64_t> origInstData = getEffectiveInstDataAsInt();
887 SmallVector<int64_t> origLaneLayout = getEffectiveLaneLayoutAsInt();
888 SmallVector<int64_t> origLaneData = getEffectiveLaneDataAsInt();
889 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
891 SmallVector<int32_t> sgLayout;
892 SmallVector<int32_t> sgData;
893 SmallVector<int32_t> instData;
894 SmallVector<int32_t> laneLayout;
895 SmallVector<int32_t> laneData;
896 SmallVector<int32_t> order;
898 for (int64_t idx : permutation) {
899 if (!origLaneLayout.empty()) {
900 laneLayout.push_back(
static_cast<int32_t
>(origLaneLayout[idx]));
901 laneData.push_back(
static_cast<int32_t
>(origLaneData[idx]));
903 if (!origInstData.empty())
904 instData.push_back(
static_cast<int32_t
>(origInstData[idx]));
905 if (!origSgLayout.empty()) {
906 sgLayout.push_back(
static_cast<int32_t
>(origSgLayout[idx]));
907 sgData.push_back(
static_cast<int32_t
>(origSgData[idx]));
923 for (int64_t dim : origOrder)
925 if (origLaneLayout.empty() && origSgLayout.empty())
931 return xegpu::LayoutAttr::get(
getContext(), toAttr(sgLayout), toAttr(sgData),
932 toAttr(instData), toAttr(laneLayout),
933 toAttr(laneData), toAttr(order));
937bool LayoutAttr::isTransposeOf(
const xegpu::DistributeLayoutAttr &other,
938 ArrayRef<int64_t> perm,
942 if (getRank() != other.getRank() ||
943 perm.size() !=
static_cast<size_t>(getRank()))
950 auto checkTranspose = [](ArrayRef<int64_t> dst, ArrayRef<int64_t> src,
951 ArrayRef<int64_t> perm) {
952 for (
const auto &ta : llvm::enumerate(perm)) {
953 if (dst[ta.index()] != src[ta.value()])
963 auto checkOrderTranspose = [](ArrayRef<int64_t> dstOrder,
964 ArrayRef<int64_t> srcOrder,
965 ArrayRef<int64_t> perm) {
966 if (dstOrder.size() != srcOrder.size())
969 for (
auto [d, s] : llvm::zip_equal(dstOrder, srcOrder)) {
970 if (d != inversePerm[s])
976 return checkTranspose(getEffectiveSgLayoutAsInt(),
977 other.getEffectiveSgLayoutAsInt(), perm) &&
978 checkTranspose(getEffectiveSgDataAsInt(),
979 other.getEffectiveSgDataAsInt(), perm) &&
980 checkOrderTranspose(getEffectiveOrderAsInt(),
981 other.getEffectiveOrderAsInt(), perm);
983 return checkTranspose(getEffectiveInstDataAsInt(),
984 other.getEffectiveInstDataAsInt(), perm);
986 return checkTranspose(getEffectiveLaneLayoutAsInt(),
987 other.getEffectiveLaneLayoutAsInt(), perm) &&
988 checkTranspose(getEffectiveLaneDataAsInt(),
989 other.getEffectiveLaneDataAsInt(), perm) &&
990 checkOrderTranspose(getEffectiveOrderAsInt(),
991 other.getEffectiveOrderAsInt(), perm);
996bool LayoutAttr::isCompatibleWith(
const xegpu::DistributeLayoutAttr &other,
997 SmallVector<int64_t> shape,
1001 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
1004 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
1005 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
1008 if (getEffectiveLaneLayoutAsInt() ==
1009 other.getEffectiveLaneLayoutAsInt() &&
1010 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
1014 auto compareCoordsForAllIds = [&](int64_t size) {
1020 return compareCoordsForAllIds(wgSize);
1023 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
1026 int64_t subgroupSize =
computeProduct(getEffectiveLaneLayoutAsInt());
1027 return compareCoordsForAllIds(subgroupSize);
1036SliceAttr::verify(llvm::function_ref<InFlightDiagnostic()>
emitError,
1040 return emitError() <<
"expected dims attribute";
1043 llvm::SmallDenseSet<int64_t> seen;
1044 for (int64_t dim : dims.asArrayRef()) {
1046 return emitError() <<
"invalid dim (" << dim <<
") in slice attribute.";
1047 if (!seen.insert(dim).second)
1048 return emitError() <<
"repeated dim (" << dim <<
") in slice attribute.";
1053SliceAttr SliceAttr::flatten()
const {
1054 xegpu::DistributeLayoutAttr parent = getParent();
1055 SmallVector<DenseI64ArrayAttr> slicedDims({
getDims()});
1057 while (
auto sliceAttr = dyn_cast<xegpu::SliceAttr>(parent)) {
1058 parent = sliceAttr.getParent();
1059 slicedDims.push_back(sliceAttr.getDims());
1062 auto layoutAttr = dyn_cast<xegpu::LayoutAttr>(parent);
1063 SmallVector<int64_t>
indices =
1064 llvm::to_vector(llvm::seq<int64_t>(0, layoutAttr.getRank()));
1067 SmallVector<int64_t> remainingDims(
indices);
1068 for (
auto dim : llvm::reverse(slicedDims))
1069 remainingDims = XeGPUDialect::slice(llvm::ArrayRef<int64_t>(remainingDims),
1073 SmallVector<int64_t> flattenedDims = XeGPUDialect::slice(
1074 llvm::ArrayRef<int64_t>(
indices), llvm::ArrayRef<int64_t>(remainingDims));
1076 return xegpu::SliceAttr::get(
1081FailureOr<SmallVector<Value>>
1082SliceAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
1083 SliceAttr attr = flatten();
1084 auto parent = dyn_cast<LayoutAttr>(attr.getParent());
1085 return parent.delinearizeId(builder, loc, linearId);
1091FailureOr<SmallVector<SmallVector<Value>>>
1092SliceAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
1093 Value linearId, ArrayRef<int64_t> shape) {
1094 assert(getRank() ==
static_cast<int64_t
>(shape.size()) &&
"invalid shape.");
1096 SmallVector<int64_t> layout;
1097 SmallVector<int64_t> subShape;
1098 if (isForWorkgroup()) {
1099 layout = getEffectiveSgLayoutAsInt();
1100 subShape = getEffectiveSgDataAsInt();
1101 }
else if (isForSubgroup()) {
1102 layout = getEffectiveLaneLayoutAsInt();
1103 subShape = getEffectiveLaneDataAsInt();
1108 if (subShape.empty())
1112 auto maybeIds = delinearizeId(builder, loc, linearId);
1118 ArrayRef<int64_t> dims = flatten().getDims().asArrayRef();
1119 SmallVector<Value> canonicalIds =
1120 XeGPUDialect::slice(ArrayRef<Value>(*maybeIds), dims);
1122 return genCoordinates(builder, loc, canonicalIds, layout, subShape, shape);
1129SmallVector<SmallVector<int64_t>>
1130SliceAttr::computeStaticDistributedCoords(int64_t linearId,
1131 ArrayRef<int64_t> shape) {
1132 assert(getRank() ==
static_cast<int64_t
>(shape.size()) &&
"invalid shape.");
1134 SmallVector<int64_t> layout;
1135 SmallVector<int64_t> subShape;
1136 SmallVector<int64_t> instData;
1137 if (isForWorkgroup()) {
1138 layout = getEffectiveSgLayoutAsInt();
1139 subShape = getEffectiveSgDataAsInt();
1140 }
else if (isForSubgroup()) {
1141 instData = getEffectiveInstDataAsInt();
1142 layout = getEffectiveLaneLayoutAsInt();
1143 subShape = getEffectiveLaneDataAsInt();
1145 if (!instData.empty()) {
1147 subShape = instData;
1150 assert(!subShape.empty() &&
"sgdata or lanedata cannot be empty");
1153 SliceAttr flattened = flatten();
1154 auto parent = dyn_cast<LayoutAttr>(flattened.getParent());
1155 SmallVector<int64_t> parentLayoutVec;
1156 if (parent.isForWorkgroup())
1157 parentLayoutVec = parent.getEffectiveSgLayoutAsInt();
1159 parentLayoutVec = parent.getEffectiveLaneLayoutAsInt();
1161 SmallVector<int64_t> order = parent.getEffectiveOrderAsInt();
1162 SmallVector<int64_t> allIds(parentLayoutVec.size());
1163 int64_t remaining = linearId;
1164 for (
size_t i = 0; i < order.size(); ++i) {
1165 int64_t dimIdx = order[i];
1166 allIds[dimIdx] = remaining % parentLayoutVec[dimIdx];
1167 if (i < order.size() - 1)
1168 remaining = remaining / parentLayoutVec[dimIdx];
1173 ArrayRef<int64_t> dims = flattened.getDims().asArrayRef();
1174 SmallVector<int64_t> canonicalIds =
1175 XeGPUDialect::slice(ArrayRef<int64_t>(allIds), dims);
1180bool SliceAttr::isSliceOf(
const xegpu::DistributeLayoutAttr &other) {
1181 auto flattenedThis = flatten();
1184 if (
auto otherLayout = dyn_cast<xegpu::LayoutAttr>(other))
1185 return flattenedThis.getParent() == otherLayout;
1187 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
1189 if (flattenedThis.getParent() != flattenedOther.getParent())
1193 llvm::SmallDenseSet<int64_t> thisDims(
1194 flattenedThis.getDims().asArrayRef().begin(),
1195 flattenedThis.getDims().asArrayRef().end());
1196 return llvm::all_of(flattenedOther.getDims().asArrayRef(),
1197 [&](int64_t dim) { return thisDims.contains(dim); });
1200bool SliceAttr::isEqualTo(
const xegpu::DistributeLayoutAttr &other) {
1201 if (dyn_cast<xegpu::LayoutAttr>(other))
1204 auto flattenedThis = flatten();
1205 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
1207 return ((flattenedThis.getParent() == flattenedOther.getParent()) &&
1208 (flattenedThis.getDims() == flattenedOther.getDims()));
1211bool SliceAttr::isCompatibleWith(
const xegpu::DistributeLayoutAttr &other,
1212 SmallVector<int64_t> shape,
1216 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
1219 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
1220 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
1223 if (getEffectiveLaneLayoutAsInt() ==
1224 other.getEffectiveLaneLayoutAsInt() &&
1225 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
1229 auto compareCoordsForAllIds = [&](int64_t size) {
1233 auto flattenedThis = flatten();
1234 auto parent = dyn_cast<LayoutAttr>(flattenedThis.getParent());
1236 int64_t wgSize =
computeProduct(parent.getEffectiveSgLayoutAsInt());
1237 return compareCoordsForAllIds(wgSize);
1240 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
1243 int64_t subgroupSize =
computeProduct(parent.getEffectiveLaneLayoutAsInt());
1244 return compareCoordsForAllIds(subgroupSize);
1249xegpu::SliceAttr SliceAttr::dropSliceDims(ArrayRef<int64_t> sliceDimsToDrop) {
1250 if (sliceDimsToDrop.empty())
1252 SmallVector<int64_t> sliceDims{
getDims().asArrayRef()};
1253 for (
auto dim : sliceDimsToDrop) {
1254 auto foundIt = std::find(sliceDims.begin(), sliceDims.end(), dim);
1255 assert(foundIt != sliceDims.end() &&
1256 "Expected to find the specified reduction dim in slice dims");
1257 sliceDims.erase(foundIt);
1260 auto sliceWithoutDims = xegpu::SliceAttr::get(
1264 return sliceWithoutDims;
1272static SmallVector<int64_t>
1280 std::max(maxDim, *std::max_element(sliceDims.begin(), sliceDims.end()));
1282 std::max(maxDim, *std::max_element(dimsToMap.begin(), dimsToMap.end()));
1283 int64_t parentSpaceRank = maxDim + sliceDims.size() + 1;
1287 llvm::SmallDenseSet<int64_t> slicedDimsSet(sliceDims.begin(),
1290 for (
int64_t i = 0; i < parentSpaceRank; ++i) {
1291 if (!slicedDimsSet.contains(i))
1292 remainingDims.push_back(i);
1297 for (
auto dim : dimsToMap) {
1298 int64_t mappedDim = remainingDims[dim];
1299 adjustUnitDims.push_back(mappedDim);
1302 return adjustUnitDims;
1308 DistributeLayoutAttr parentLayout = getParent();
1316 parentLayout.setUnitDimData(adjustUnitDims), getDims());
1321SliceAttr::setUnitDimLayout(SmallVector<int64_t> unitDims)
const {
1322 DistributeLayoutAttr parentLayout = getParent();
1324 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
1326 SmallVector<int64_t> adjustUnitDims =
1329 return SliceAttr::get(
1330 getContext(), parentLayout.setUnitDimLayout(adjustUnitDims), getDims());
1335DistributeLayoutAttr SliceAttr::setDimData(int64_t dim, int64_t sgData,
1336 int64_t instData, int64_t laneData) {
1337 ArrayRef<int64_t> sliceDims =
getDims().asArrayRef();
1338 auto parent = getParent();
1340 SmallVector<int64_t> dimSet;
1341 dimSet.push_back(dim);
1342 SmallVector<int64_t> adjustDims =
1344 return SliceAttr::get(
1346 parent.setDimData(adjustDims[0], sgData, instData, laneData),
getDims());
1367DistributeLayoutAttr SliceAttr::dropDims(SmallVector<int64_t> dimGroup) {
1369 SmallVector<int64_t> sliceDims = llvm::to_vector(
getDims().asArrayRef());
1370 SmallVector<int64_t> dimsInParentSpace =
1373 auto droppedParent = getParent().dropDims(dimsInParentSpace);
1378 SmallVector<int64_t> newSliceDims;
1379 for (int64_t d : sliceDims) {
1381 llvm::count_if(dimsInParentSpace, [&](int64_t s) {
return s < d; });
1382 newSliceDims.push_back(d - offset);
1385 return SliceAttr::get(
getContext(), droppedParent,
1392DistributeLayoutAttr SliceAttr::collapseDims(SmallVector<int64_t> dimGroup) {
1395 SmallVector<int64_t> sliceDims = llvm::to_vector(
getDims().asArrayRef());
1396 assert(
"expect sliceDims not being collapsed" &&
1397 llvm::none_of(dimGroup, [&](int64_t dim) {
1398 return llvm::is_contained(sliceDims, dim);
1400 SmallVector<int64_t> dimsInParentSpace =
1403 auto collapsedParent = getParent().collapseDims(dimsInParentSpace);
1404 return SliceAttr::get(
getContext(), collapsedParent,
1412DistributeLayoutAttr SliceAttr::expandDim(int64_t dim,
1413 ArrayRef<int64_t> targetShape) {
1417 ArrayRef<int64_t> sliceDims =
getDims().asArrayRef();
1418 SmallVector<int64_t> dimSet = {dim};
1419 SmallVector<int64_t> dimsInParentSpace =
1421 int64_t parentDim = dimsInParentSpace[0];
1423 auto expandedParent = getParent().expandDim(parentDim, targetShape);
1425 int64_t shift =
static_cast<int64_t
>(targetShape.size()) - 1;
1426 SmallVector<int64_t> newSliceDims;
1427 newSliceDims.reserve(sliceDims.size());
1428 for (int64_t s : sliceDims)
1429 newSliceDims.push_back(s > parentDim ? s + shift : s);
1431 return SliceAttr::get(
getContext(), expandedParent,
1438 llvm::sort(sortedSliceDims);
1440 for (
size_t i = 1; i < sortedSliceDims.size(); ++i) {
1441 assert((sortedSliceDims[i] == sortedSliceDims[i - 1] + 1) &&
1442 "slice dims non consecutive, cannot be transposed");
1446 if (sortedSliceDims.front() == 0) {
1449 for (
int64_t dim : permutation)
1450 permForParent.push_back(dim + sortedSliceDims.size());
1451 for (
int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1452 permForParent.push_back(i);
1456 for (
int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1457 permForParent.push_back(i + permutation.size());
1458 for (
int64_t dim : permutation)
1459 permForParent.push_back(dim);
1461 return permForParent;
1467 DistributeLayoutAttr parent = getParent();
1470 auto transposedParent = parent.transposeDims(permForParent);
1471 return SliceAttr::get(
getContext(), transposedParent,
1476bool SliceAttr::isTransposeOf(
const xegpu::DistributeLayoutAttr &other,
1477 ArrayRef<int64_t> perm,
1480 auto otherSlice = dyn_cast<xegpu::SliceAttr>(other);
1481 if (!otherSlice || getDims() != otherSlice.getDims())
1484 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1485 DistributeLayoutAttr parent = getParent();
1487 auto otherParent = otherSlice.getParent();
1488 return parent.isTransposeOf(otherParent, permForParent, kind);
1496RangeAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()>
emitError,
1497 IntegerAttr startOfRange, IntegerAttr endOfRange) {
1498 if (startOfRange.getInt() >= endOfRange.getInt())
1499 return emitError() <<
"'end' : " << endOfRange.getInt()
1500 <<
" must be greater than 'start' : "
1501 << startOfRange.getInt();
1510mlir::Type TensorDescType::parse(AsmParser &parser) {
1511 llvm::SmallVector<int64_t> shape;
1512 mlir::Type elementType;
1513 mlir::FailureOr<mlir::Attribute> encoding;
1514 mlir::FailureOr<mlir::Attribute> layout;
1517 if (parser.parseLess())
1520 auto shapeLoc = parser.getCurrentLocation();
1521 if (mlir::failed(parser.parseDimensionList(shape))) {
1522 parser.emitError(shapeLoc,
"failed to parse parameter 'shape'");
1526 auto elemTypeLoc = parser.getCurrentLocation();
1527 if (mlir::failed(parser.parseType(elementType))) {
1528 parser.emitError(elemTypeLoc,
"failed to parse parameter 'elementType'");
1533 while (mlir::succeeded(parser.parseOptionalComma())) {
1534 mlir::Attribute attr;
1535 ParseResult res = parser.parseAttribute(attr);
1536 if (mlir::succeeded(res)) {
1537 if (mlir::isa<DistributeLayoutAttr>(attr)) {
1541 if (mlir::isa<BlockTensorDescAttr>(attr)) {
1550 if (parser.parseGreater())
1553 MLIRContext *ctxt = parser.getContext();
1554 return TensorDescType::getChecked(
1555 [&]() {
return parser.emitError(parser.getNameLoc()); }, ctxt, shape,
1556 elementType, encoding.value_or(BlockTensorDescAttr::get(ctxt)),
1557 layout.value_or(mlir::Attribute()));
1560void TensorDescType::print(AsmPrinter &printer)
const {
1564 for (int64_t dim : shape) {
1565 if (mlir::ShapedType::isDynamic(dim))
1574 auto encoding = getEncoding();
1575 auto blockAttr = llvm::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1576 if (encoding && (!blockAttr || !blockAttr.hasDefaultsOnly()))
1577 printer <<
", " << encoding;
1579 if (
auto layout = getLayout())
1580 printer <<
", " << layout;
1585TensorDescType TensorDescType::get(llvm::ArrayRef<int64_t> shape,
1586 mlir::Type elementType,
int array_length,
1587 bool boundary_check,
1588 MemorySpace memory_space,
1589 mlir::Attribute layout) {
1591 auto attr = BlockTensorDescAttr::get(context, memory_space, array_length,
1593 return Base::get(context, shape, elementType, attr, layout);
1597TensorDescType::verify(llvm::function_ref<InFlightDiagnostic()>
emitError,
1598 llvm::ArrayRef<int64_t> shape, mlir::Type elementType,
1599 mlir::Attribute encoding, mlir::Attribute layout) {
1600 size_t rank = shape.size();
1603 return emitError() <<
"expected non-zero rank tensor";
1605 if (mlir::ShapedType::isDynamicShape(shape))
1606 return emitError() <<
"expected static shape";
1608 auto blockAttr = mlir::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1610 MemorySpaceAttr memorySpaceAttr = blockAttr.getMemorySpace();
1611 if (rank > 1 && memorySpaceAttr &&
1612 memorySpaceAttr.getValue() == MemorySpace::SLM)
1613 return emitError() <<
"SLM is only supported for 1D block tensor";
1617 return emitError() <<
"unsupported element type " << elementType
1618 <<
": expected integer or float";
1620 if (
auto layoutAttr =
1621 mlir::dyn_cast_if_present<DistributeLayoutAttr>(layout)) {
1622 if (rank != (
size_t)layoutAttr.getRank())
1623 return emitError() <<
"expected layout rank to match tensor rank";
1625 if (!layoutAttr.isDistributable(SmallVector<int64_t>(shape))) {
1626 std::string shapeStr;
1627 llvm::raw_string_ostream stream(shapeStr);
1628 llvm::interleaveComma(shape, stream);
1629 return emitError() <<
"cannot distribute [" << shapeStr <<
"] using "
1640mlir::Type MemDescType::parse(AsmParser &parser) {
1641 llvm::SmallVector<int64_t> shape;
1642 mlir::Type elementType;
1643 mlir::FailureOr<MemLayoutAttr> layout;
1646 if (parser.parseLess())
1649 auto shapeLoc = parser.getCurrentLocation();
1650 if (mlir::failed(parser.parseDimensionList(shape,
false,
true))) {
1651 parser.emitError(shapeLoc,
"failed to parse parameter 'shape'");
1655 auto elemTypeLoc = parser.getCurrentLocation();
1656 if (mlir::failed(parser.parseType(elementType))) {
1657 parser.emitError(elemTypeLoc,
"failed to parse parameter 'elementType'");
1662 if (mlir::succeeded(parser.parseOptionalComma())) {
1664 ParseResult res = parser.parseAttribute(attr);
1665 if (mlir::failed(res))
1671 if (parser.parseGreater())
1675 return MemDescType::getChecked(
1676 [&]() {
return parser.emitError(parser.getNameLoc()); }, ctxt, shape,
1677 elementType, layout.value_or(MemLayoutAttr()));
1680void MemDescType::print(AsmPrinter &printer)
const {
1683 printer.printDimensionList(
getShape());
1687 if (
auto layout = getMemLayout())
1688 printer <<
", " << layout;
1697Attribute MemLayoutAttr::parse(AsmParser &parser, Type type) {
1699 auto *context = parser.getContext();
1700 llvm::SMLoc loc = parser.getCurrentLocation();
1702 llvm::SmallDenseSet<StringRef> seenKeys;
1703 SmallVector<NamedAttribute> attributes;
1705 auto parseElt = [&]() -> ParseResult {
1707 if (
failed(parser.parseKeyword(&nameId)))
1708 return parser.emitError(loc,
"expected valid attribute name");
1710 if (!seenKeys.insert(nameId).second)
1711 return parser.emitError(loc,
"duplicate key '")
1712 << nameId <<
" in mem layout attribute";
1714 if (
failed(parser.parseEqual()))
1718 if (
failed(parser.parseAttribute(attr)))
1720 attributes.emplace_back(nameId, attr);
1725 if (parser.parseLess())
1728 if (
failed(parser.parseCommaSeparatedList(parseElt)))
1732 if (parser.parseGreater())
1735 return parser.getChecked<MemLayoutAttr>(
1736 loc, context, DictionaryAttr::get(context, attributes));
1739void MemLayoutAttr::print(AsmPrinter &printer)
const {
1741 ArrayRef<NamedAttribute> attrs = getAttrs().getValue();
1742 for (
size_t i = 0; i < attrs.size(); i++) {
1743 printer << attrs[i].getName().str() <<
" = " << attrs[i].getValue();
1744 if (i < attrs.size() - 1)
1753template <
typename ArithOp>
1758 return ArithOp::create(builder, loc, aVal, bVal).getResult();
1763 genBinOp<arith::DivSIOp>(a, builder.getIndexAttr(b), loc, builder)
1767 genBinOp<arith::RemSIOp>(a, builder.getIndexAttr(b), loc, builder)
1771 genBinOp<arith::MulIOp>(a, builder.getIndexAttr(b), loc, builder)
1774#define add(a, b) genBinOp<arith::AddIOp>(a, b, loc, builder)
1783 assert(offsets.size() == blockShape.size() &&
1784 "offsets and blockShape must have the same size");
1788 for (
auto [offset, block] : llvm::zip(offsets, blockShape)) {
1789 divs.push_back(
div(offset, block));
1790 rems.push_back(
rem(offset, block));
1792 blockedOffsets.append(divs.begin(), divs.end());
1793 blockedOffsets.append(rems.begin(), rems.end());
1795 return blockedOffsets;
1805 for (
Attribute attr : strideAttr.getValue()) {
1806 strides.push_back(cast<IntegerAttr>(attr).getInt());
1809 SmallVector<int64_t> innerBlkShape = getBlockShape();
1813 SmallVector<int, 4> perm =
1814 llvm::to_vector<4>(llvm::seq<int>(0, strides.size()));
1815 llvm::sort(perm, [&](
int a,
int b) {
return strides[a] < strides[
b]; });
1817 assert(strides[perm[0]] == 1 &&
"inner most dim must have stride 1");
1819 SmallVector<int64_t> innerBlkStride(innerBlkShape.size());
1820 innerBlkStride[perm[0]] = 1;
1821 for (
size_t i = 1; i < perm.size(); ++i)
1822 innerBlkStride[perm[i]] =
1823 innerBlkStride[perm[i - 1]] * innerBlkShape[perm[i - 1]];
1829 SmallVector<int64_t> matrixShapeOrig(matrixShape.size());
1830 SmallVector<int64_t> BlkShapeOrig(matrixShape.size());
1831 for (
size_t i = 0; i < perm.size() - 1; ++i) {
1832 matrixShapeOrig[perm[i]] = strides[perm[i + 1]] / strides[perm[i]];
1833 BlkShapeOrig[perm[i]] = matrixShapeOrig[perm[i]] / innerBlkShape[perm[i]];
1836 int64_t innerBlkSize = 1;
1837 for (
auto s : innerBlkShape)
1840 SmallVector<int64_t> outerBlkStride(matrixShape.size());
1841 outerBlkStride[perm[0]] = innerBlkSize;
1842 for (
size_t i = 0; i < perm.size() - 1; ++i) {
1843 outerBlkStride[perm[i + 1]] =
1844 outerBlkStride[perm[i]] * BlkShapeOrig[perm[i]];
1848 SmallVector<int64_t> blockedStrides;
1849 blockedStrides.append(outerBlkStride.begin(), outerBlkStride.end());
1850 blockedStrides.append(innerBlkStride.begin(), innerBlkStride.end());
1852 return blockedStrides;
1856Value MemDescType::getLinearOffsets(OpBuilder &builder, Location loc,
1857 ArrayRef<OpFoldResult> offsets) {
1860 SmallVector<int64_t> blockShape = getBlockShape();
1861 SmallVector<int64_t> strides = getStrideShape();
1862 SmallVector<OpFoldResult> blockedOffsets;
1865 if (llvm::equal(blockShape, matrixShape)) {
1867 strides.erase(strides.begin(), strides.begin() + matrixShape.size());
1869 assert(offsets.size() == blockShape.size() &&
1870 "offsets and blockShape must have the same size");
1874 SmallVector<OpFoldResult> divs, rems;
1876 for (
auto [offset, block] : llvm::zip(offsets, blockShape)) {
1877 divs.push_back(
div(offset, block));
1878 rems.push_back(
rem(offset, block));
1880 blockedOffsets.append(divs.begin(), divs.end());
1881 blockedOffsets.append(rems.begin(), rems.end());
1882 offsets = blockedOffsets;
1887 for (
size_t i = 0; i < offsets.size(); ++i) {
1888 OpFoldResult mulResult =
mul(offsets[i], strides[i]);
1890 linearOffset = arith::AddIOp::create(builder, loc, mulVal, linearOffset);
1893 return linearOffset;
1899#include <mlir/Dialect/XeGPU/IR/XeGPUDialect.cpp.inc>
1900#define GET_ATTRDEF_CLASSES
1901#include <mlir/Dialect/XeGPU/IR/XeGPUAttrs.cpp.inc>
1902#define GET_TYPEDEF_CLASSES
1903#include <mlir/Dialect/XeGPU/IR/XeGPUTypes.cpp.inc>
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
static Value splice(OpBuilder &b, Location loc, ValueRange values, VectorType regTileType)
Attributes are known-constant values of operations.
MLIRContext * getContext() const
Return the context this attribute belongs to.
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...
MLIRContext is the top-level object for a collection of MLIR operations.
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.
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)
auto getDims(VectorType vType)
Returns a range over the dims (size and scalability) of a VectorType.
static SmallVector< SmallVector< int64_t > > genStaticCoordinates(llvm::ArrayRef< int64_t > canonicalIds, llvm::ArrayRef< int64_t > layout, llvm::ArrayRef< int64_t > subShape, llvm::ArrayRef< int64_t > shape)
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 bool compareDistributedCoords(xegpu::DistributeLayoutAttr self, const xegpu::DistributeLayoutAttr &other, ArrayRef< int64_t > shape, xegpu::LayoutKind level, int64_t size)
Returns true if self and other distribute shape identically at level: every id in [0,...
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)
static SmallVector< SmallVector< int64_t > > expandBlockCoords(ArrayRef< SmallVector< int64_t > > blockStarts, ArrayRef< int64_t > subShape)
Expands per-distribution-unit block-start coordinates into the full list of element coordinates each ...
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.
AffineMap inversePermutation(AffineMap map)
Returns a map of codomain to domain dimensions such that the first codomain dimension for a particula...
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
bool isPermutationVector(ArrayRef< int64_t > interchange)
Method to check if an interchange vector is a permutation.
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.