MLIR 23.0.0git
XeGPUDialect.cpp
Go to the documentation of this file.
1//===- XeGPUDialect.cpp - MLIR XeGPU dialect implementation -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
16#include "mlir/IR/Builders.h"
18#include "llvm/ADT/SmallVectorExtras.h"
19#include "llvm/ADT/TypeSwitch.h"
20#include "llvm/Support/Debug.h"
21
22using std::optional;
23
24namespace mlir {
25namespace xegpu {
26
27void XeGPUDialect::initialize() {
28 addTypes<
29#define GET_TYPEDEF_LIST
30#include <mlir/Dialect/XeGPU/IR/XeGPUTypes.cpp.inc>
31 >();
32 addOperations<
33#define GET_OP_LIST
34#include <mlir/Dialect/XeGPU/IR/XeGPU.cpp.inc>
35 >();
36 addAttributes<
37#define GET_ATTRDEF_LIST
38#include <mlir/Dialect/XeGPU/IR/XeGPUAttrs.cpp.inc>
39 >();
40}
41#define GET_OP_INTERFACE_CLASSES
42#include "mlir/Dialect/XeGPU/IR/XeGPUOpInterface.cpp.inc"
43
44// A `srcShape` consists of N distribution units, each being `subShapesLayout` x
45// `subShape`. A `delinearizedId` is used to identify a particular `subShape`
46// within each distribution unit.
47// Example:
48// WG data is 128x256. SG data is 16x32, in 4x2 layout, this gives a
49// distribution unit of shape 64x64, we have 2x4 such distribution units.
50// `delinearizedId` is used to identify a 16x32 of a subgroup in each
51// distribution unit.
52static SmallVector<SmallVector<Value>>
54 SmallVector<Value> delinearizedId,
55 ArrayRef<int64_t> subShapesLayout, ArrayRef<int64_t> subShape,
56 ArrayRef<int64_t> srcShape) {
58
59 // A distribution unit must be less than or equal to `srcShape`
60 SmallVector<int64_t> distUnitShape = llvm::map_to_vector(
61 llvm::zip_equal(srcShape,
62 computeElementwiseMul(subShapesLayout, subShape)),
63 [](const auto &t) { return std::min(std::get<0>(t), std::get<1>(t)); });
64
65 // Get the offset of `subShape` within a distribution unit.
66 SmallVector<Value> distUnitLocalOffset = llvm::map_to_vector(
67 llvm::zip(delinearizedId, subShape), [&](const auto &t) -> Value {
68 return builder.createOrFold<arith::MulIOp>(
69 loc, std::get<0>(t),
70 builder.createOrFold<arith::ConstantIndexOp>(loc, std::get<1>(t)));
71 });
72
73 // For each dist unit
74 for (SmallVector<int64_t> unitOffs :
75 StaticTileOffsetRange(srcShape, distUnitShape)) {
76 // Get dist unit offset within `srcShape`.
78 llvm::map_to_vector(unitOffs, [&](int64_t d) -> Value {
79 return arith::ConstantIndexOp::create(builder, loc, d);
80 });
81 // Calculate `subShape` offset within `srcShape`.
83 llvm::map_to_vector(llvm::zip_equal(base, distUnitLocalOffset),
84 [&](const auto &t) -> Value {
85 return builder.createOrFold<arith::AddIOp>(
86 loc, std::get<0>(t), std::get<1>(t));
87 });
88 // Do not go beyond `srcShape` bounds.
89 SmallVector<Value> mods = llvm::map_to_vector(
90 llvm::zip_equal(adds, srcShape), [&](const auto &t) -> Value {
91 return builder.createOrFold<arith::RemUIOp>(
92 loc, std::get<0>(t),
93 arith::ConstantIndexOp::create(builder, loc, std::get<1>(t)));
94 });
95
96 coordinates.push_back(mods);
97 }
98 return coordinates;
99}
100
104 // Compute distribution unit shape (clamped to srcShape).
105 SmallVector<int64_t> distUnitShape(shape.size());
106 for (size_t i = 0; i < shape.size(); ++i)
107 distUnitShape[i] = std::min(shape[i], layout[i] * subShape[i]);
108
109 // Compute local offset of this ID within a distribution unit.
110 SmallVector<int64_t> localOffset(shape.size());
111 for (size_t i = 0; i < shape.size(); ++i)
112 localOffset[i] = canonicalIds[i] * subShape[i];
113
114 // Enumerate all distribution units and compute coordinates.
116 for (SmallVector<int64_t> unitOffs :
117 StaticTileOffsetRange(shape, distUnitShape)) {
118 SmallVector<int64_t> coord(shape.size());
119 for (size_t i = 0; i < shape.size(); ++i)
120 coord[i] = (unitOffs[i] + localOffset[i]) % shape[i];
121 coordinates.push_back(coord);
122 }
123 return coordinates;
124}
125
126/// Expands per-distribution-unit block-start coordinates into the full list of
127/// element coordinates each block covers: every element of the `subShape`-sized
128/// region (row-major) offset by the block start. Comparing these instead of the
129/// bare block starts lets layouts that differ only in `lane_data` blocking, but
130/// own the same elements in the same order, be recognized as equivalent.
133 ArrayRef<int64_t> subShape) {
134 SmallVector<int64_t> unitTile(subShape.size(), 1);
136 for (const SmallVector<int64_t> &start : blockStarts) {
137 for (SmallVector<int64_t> off : StaticTileOffsetRange(subShape, unitTile)) {
138 SmallVector<int64_t> coord(start.size());
139 for (size_t i = 0; i < start.size(); ++i)
140 coord[i] = start[i] + off[i];
141 expanded.push_back(std::move(coord));
142 }
143 }
144 return expanded;
145}
146
147/// Returns true if `self` and `other` distribute `shape` identically at
148/// `level`: every id in `[0, size)` owns the same coordinates under both.
149///
150/// At the Lane level, layouts that pack `lane_data` differently can still own
151/// the same per-lane elements in the same order; their block starts differ but
152/// the expanded per-element coordinates match. So block starts are expanded
153/// (via `expandBlockCoords`) before comparing, but only when it can change the
154/// result (Lane level with differing `lane_data`) - otherwise comparing the
155/// cheaper block starts is already exact.
156///
157/// TODO: Extend the same handling to the Subgroup level (sg_data repacks).
158static bool compareDistributedCoords(xegpu::DistributeLayoutAttr self,
159 const xegpu::DistributeLayoutAttr &other,
161 xegpu::LayoutKind level, int64_t size) {
162 bool expandCoords =
163 level == xegpu::LayoutKind::Lane &&
164 self.getEffectiveLaneDataAsInt() != other.getEffectiveLaneDataAsInt();
165 SmallVector<int64_t> selfSubShape, otherSubShape;
166 if (expandCoords) {
167 selfSubShape = self.getEffectiveLaneDataAsInt();
168 otherSubShape = other.getEffectiveLaneDataAsInt();
169 }
170 for (int64_t id : llvm::seq<int64_t>(0, size)) {
171 auto coords = self.computeStaticDistributedCoords(id, shape);
172 auto otherCoords = other.computeStaticDistributedCoords(id, shape);
173 if (expandCoords) {
174 coords = expandBlockCoords(coords, selfSubShape);
175 otherCoords = expandBlockCoords(otherCoords, otherSubShape);
176 }
177 if (coords != otherCoords)
178 return false;
179 }
180 return true;
181}
182
183// Checks if the given memref type represents shared local memory (SLM).
184bool XeGPUDialect::isSharedMemory(const MemRefType &memrefTy) {
185 Attribute attr = memrefTy.getMemorySpace();
186 if (!attr)
187 return false; // Default memory space is not shared local memory
188 if (auto intAttr = llvm::dyn_cast_if_present<IntegerAttr>(attr))
189 return intAttr.getInt() == 3;
190 if (auto memrefSpace = llvm::dyn_cast_if_present<MemorySpaceAttr>(attr))
191 return memrefSpace.getValue() == MemorySpace::SLM;
192 if (auto xevmSpace = llvm::dyn_cast_if_present<xevm::AddrSpaceAttr>(attr))
193 return xevmSpace.getValue() == xevm::AddrSpace::SHARED;
194 return gpu::GPUDialect::isWorkgroupMemoryAddressSpace(attr);
195}
196
197//===----------------------------------------------------------------------===//
198// XeGPU_BlockTensorDescAttr
199//===----------------------------------------------------------------------===//
200BlockTensorDescAttr BlockTensorDescAttr::get(mlir::MLIRContext *context,
201 xegpu::MemorySpace memory_space,
202 int array_length,
203 bool boundary_check) {
204 auto scopeAttr = MemorySpaceAttr::get(context, memory_space);
205 auto lengthAttr =
206 IntegerAttr::get(IntegerType::get(context, 64), array_length);
207 auto boundaryAttr = BoolAttr::get(context, boundary_check);
208 return Base::get(context, scopeAttr, lengthAttr, boundaryAttr);
209}
210
211bool BlockTensorDescAttr::hasDefaultsOnly() {
212 return getMemorySpace().getValue() == xegpu::MemorySpace::Global &&
213 getArrayLength().getInt() == 1 && getBoundaryCheck().getValue();
214}
215
216//===----------------------------------------------------------------------===//
217// XeGPU_LayoutAttr
218//===----------------------------------------------------------------------===//
219LogicalResult
220LayoutAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
221 DenseI32ArrayAttr sg_layout, DenseI32ArrayAttr sg_data,
222 DenseI32ArrayAttr inst_data, DenseI32ArrayAttr lane_layout,
223 DenseI32ArrayAttr lane_data, DenseI32ArrayAttr order) {
224
225 // Special case for store_matrix
226 if (!sg_layout && !inst_data && !lane_layout)
227 return success();
228
229 // generate code to check sg_laout, inst_data and lane_layout having the same
230 // rank if they are not null.
231
232 if (sg_layout && inst_data && sg_layout.size() != inst_data.size()) {
233 return emitError()
234 << "expected sg_layout and inst_data to have the same rank";
235 }
236
237 if (sg_layout && lane_layout && sg_layout.size() != lane_layout.size()) {
238 return emitError()
239 << "expected sg_layout and lane_layout to have the same rank";
240 }
241
242 if (inst_data && lane_layout && inst_data.size() != lane_layout.size()) {
243 return emitError() << "expected inst_data and lane_layout to have the same "
244 "rank, got inst_data "
245 << inst_data.size() << ", lane_layout "
246 << lane_layout.size();
247 }
248
249 if ((sg_layout && !sg_data) || (!sg_layout && sg_data))
250 return emitError() << "sg_layout and sg_data must be used together";
251 if (sg_layout && sg_data && sg_layout.size() != sg_data.size())
252 return emitError()
253 << "expected sg_data and sg_layout to have the same rank";
254
255 if ((lane_layout && !lane_data) || (!lane_layout && lane_data))
256 return emitError() << "lane_layout and lane_data must be used together";
257 if (lane_layout && lane_data && lane_layout.size() != lane_data.size())
258 return emitError()
259 << "expected lane_data and lane_layout to have the same rank";
260
261 if (order) {
262 if (!sg_layout && !lane_layout)
263 return emitError()
264 << "expected sg_layout/lane_layout being used with order";
265
266 if (sg_layout && order.size() != sg_layout.size())
267 return emitError()
268 << "expected order and sg_layout to have the same rank";
269
270 if (lane_layout && order.size() != lane_layout.size())
271 return emitError()
272 << "expected order and lane_layout to have the same rank";
273 }
274
275 return success();
276}
277
278FailureOr<SmallVector<Value>>
279LayoutAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
280
281 SmallVector<int64_t> sgLayoutInt;
282 if (isForWorkgroup()) {
283 sgLayoutInt = getEffectiveSgLayoutAsInt();
284 } else if (isForSubgroup()) {
285 sgLayoutInt = getEffectiveLaneLayoutAsInt();
286 } else {
287 return failure();
288 }
289
290 DenseI32ArrayAttr orderAttr = getOrder();
291
292 // Handle order attribute
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);
297 });
298 } else {
299 // Default order: [1, 0] for 2D (row-major), [2, 1, 0] for 3D, etc.
300 order = llvm::to_vector(
301 llvm::reverse(llvm::seq<int64_t>(0, sgLayoutInt.size())));
302 }
303
304 if (order.size() != sgLayoutInt.size()) {
305 return failure();
306 }
307
308 SmallVector<Value> result(sgLayoutInt.size());
309 Value remaining = linearId;
310
311 /// Process dimensions in the order they appear in the order array
312 /// The first dimension in order is the fastest-changing
313 ///
314 /// Example walkthrough for linearId=22, sgLayout=[2,4,4], order=[2,1,0]:
315 ///
316 /// Initial: remaining=22, dimIdx = order[i], dimSize = sgLayout[dimIdx],
317 /// result=[?,?,?]
318 ///
319 /// i=0 (process columns, dimIdx=2, dimSize=4):
320 /// result[2] = 22 % 4 = 2 (column coordinate)
321 /// remaining = 22 / 4 = 5 (5 complete groups of 4 columns processed)
322 ///
323 /// i=1 (process rows, dimIdx=1, dimSize=4):
324 /// result[1] = 5 % 4 = 1 (row coordinate)
325 /// remaining = 5 / 4 = 1 (1 complete group of 4 rows processed)
326 ///
327 /// i=2 (process layers, dimIdx=0, dimSize=2):
328 /// result[0] = 1 % 2 = 1 (layer coordinate)
329 /// (no remaining update - last iteration)
330 ///
331 /// Final result: [1,1,2] = Layer 1, Row 1, Column 2
332 for (size_t i = 0; i < order.size(); ++i) {
333 int64_t dimIdx = order[i];
334 int64_t dimSize = sgLayoutInt[dimIdx];
335
336 Value dimSizeVal =
337 builder.createOrFold<arith::ConstantIndexOp>(loc, dimSize);
338
339 /// Extract the coordinate for this dimension using modulo operation
340 /// This gives us "how far within this dimension" we are
341 /// e.g., linearId=22, dimSize=4: 22 % 4 = 2 (we're at position 2 within
342 /// this dimension)
343 result[dimIdx] =
344 builder.createOrFold<arith::RemUIOp>(loc, remaining, dimSizeVal);
345
346 /// Update remaining for the next dimension by removing what we've already
347 /// processed. Division tells us "how many complete groups of this dimension
348 /// we've gone through" e.g., linearId=22, dimSize=4: 22 / 4 = 5 (we've
349 /// completed 5 groups of 4) Skip this for the last iteration since there's
350 /// no next dimension to process
351 if (i < order.size() - 1) {
352 remaining =
353 builder.createOrFold<arith::DivUIOp>(loc, remaining, dimSizeVal);
354 }
355 }
356 return result;
357}
358
359/// Implements DistributeLayoutAttr::computeDistributedCoords to generate
360/// instructions for computing multi-dimensional offsets when distributed by
361/// LayoutAttr.
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();
373 } else {
374 return failure();
375 }
376 assert(!subShape.empty() && "sgdata or lanedata cannot be empty for "
377 "distributed coordinates computation");
378
379 // delinearize Ids
380 auto maybeIds = delinearizeId(builder, loc, linearId);
381 if (failed(maybeIds))
382 return failure();
383 SmallVector<Value> ids = *maybeIds;
384
385 return genCoordinates(builder, loc, ids, layout, subShape, shape);
386}
387
388bool LayoutAttr::isEqualTo(const xegpu::DistributeLayoutAttr &other) {
389 if (dyn_cast<xegpu::SliceAttr>(other))
390 return false;
391
392 return *this == dyn_cast<xegpu::LayoutAttr>(other);
393}
394
395/// Implements DistributeLayoutAttr::computeStaticDistributedCoords to
396/// compute multi-dimensional offsets for a given linear ID when distributed by
397/// LayoutAttr.
398SmallVector<SmallVector<int64_t>>
399LayoutAttr::computeStaticDistributedCoords(int64_t linearId,
400 ArrayRef<int64_t> shape) {
401 SmallVector<int64_t> layoutVec;
402 SmallVector<int64_t> subShape;
403 SmallVector<int64_t> instData;
404 if (isForWorkgroup()) {
405 layoutVec = getEffectiveSgLayoutAsInt();
406 subShape = getEffectiveSgDataAsInt();
407 } else if (isForSubgroup()) {
408 instData = getEffectiveInstDataAsInt();
409 layoutVec = getEffectiveLaneLayoutAsInt();
410 subShape = getEffectiveLaneDataAsInt();
411 }
412 if (!instData.empty()) {
413 linearId = 0;
414 subShape = instData;
415 }
416 assert(!subShape.empty() && "sgdata or lanedata cannot be empty");
417
418 // Delinearize the linear ID using the order attribute.
419 SmallVector<int64_t> order = getEffectiveOrderAsInt();
420 SmallVector<int64_t> delinearizedId(layoutVec.size());
421 int64_t remaining = linearId;
422 for (size_t i = 0; i < order.size(); ++i) {
423 int64_t dimIdx = order[i];
424 delinearizedId[dimIdx] = remaining % layoutVec[dimIdx];
425 remaining = remaining / layoutVec[dimIdx];
426 }
427
428 return genStaticCoordinates(delinearizedId, layoutVec, subShape, shape);
429}
430
431// set the layout for unit dims: sg_data, inst_data and lane_data to 1
432DistributeLayoutAttr
433LayoutAttr::setUnitDimData(SmallVector<int64_t> unitDims) const {
434 auto sgDataOpt = getSgData();
435 auto instDataOpt = getInstData();
436 auto laneDataOpt = getLaneData();
437
438 SmallVector<int32_t> sgData;
439 SmallVector<int32_t> instData;
440 SmallVector<int32_t> laneData;
441
442 if (sgDataOpt)
443 sgData = llvm::to_vector(sgDataOpt.asArrayRef());
444
445 if (instDataOpt)
446 instData = llvm::to_vector(instDataOpt.asArrayRef());
447
448 if (laneDataOpt)
449 laneData = llvm::to_vector(laneDataOpt.asArrayRef());
450
451 for (auto dim : unitDims) {
452 if (dim < static_cast<int64_t>(sgData.size()))
453 sgData[dim] = 1;
454 if (dim < static_cast<int64_t>(instData.size()))
455 instData[dim] = 1;
456 if (dim < static_cast<int64_t>(laneData.size()))
457 laneData[dim] = 1;
458 }
459
460 return LayoutAttr::get(
461 getContext(), getSgLayout(),
462 sgData.empty() ? DenseI32ArrayAttr()
464 instData.empty() ? DenseI32ArrayAttr()
465 : DenseI32ArrayAttr::get(getContext(), instData),
466 getLaneLayout(),
467 laneData.empty() ? DenseI32ArrayAttr()
468 : DenseI32ArrayAttr::get(getContext(), laneData),
469 getOrder());
470}
471
472// set the layout for the sepcified unit dims: sg_lane and lane_layout to 1
473DistributeLayoutAttr
474LayoutAttr::setUnitDimLayout(SmallVector<int64_t> unitDims) const {
475 auto sgLayoutOpt = getSgLayout();
476 auto laneLayoutOpt = getLaneLayout();
477
478 SmallVector<int32_t> sgLayout;
479 SmallVector<int32_t> laneLayout;
480
481 if (sgLayoutOpt)
482 sgLayout = llvm::to_vector(sgLayoutOpt.asArrayRef());
483 if (laneLayoutOpt)
484 laneLayout = llvm::to_vector(laneLayoutOpt.asArrayRef());
485
486 for (auto dim : unitDims) {
487 if (dim < static_cast<int64_t>(sgLayout.size()))
488 sgLayout[dim] = 1;
489 if (dim < static_cast<int64_t>(laneLayout.size()))
490 laneLayout[dim] = 1;
491 }
492
493 return LayoutAttr::get(
494 getContext(),
495 sgLayout.empty() ? DenseI32ArrayAttr()
496 : DenseI32ArrayAttr::get(getContext(), sgLayout),
497 getSgData(), getInstData(),
498 laneLayout.empty() ? DenseI32ArrayAttr()
499 : DenseI32ArrayAttr::get(getContext(), laneLayout),
500 getLaneData(), getOrder());
501}
502
503// Derive a new layout with sg_data, inst_data and lane_data set to the
504// specified values for the given dimension
505DistributeLayoutAttr LayoutAttr::setDimData(int64_t dim, int64_t sgData,
506 int64_t instData,
507 int64_t laneData) {
508
509 SmallVector<int64_t> sgDataVec = getEffectiveSgDataAsInt();
510 SmallVector<int64_t> instDataVec = getEffectiveInstDataAsInt();
511 SmallVector<int64_t> laneDataVec = getEffectiveLaneDataAsInt();
512
513 if (dim < static_cast<int64_t>(sgDataVec.size()) && sgData != -1)
514 sgDataVec[dim] = sgData;
515 if (dim < static_cast<int64_t>(instDataVec.size()) && instData != -1)
516 instDataVec[dim] = instData;
517 if (dim < static_cast<int64_t>(laneDataVec.size()) && laneData != -1)
518 laneDataVec[dim] = laneData;
519
520 SmallVector<int32_t> sgDataVec32(sgDataVec.begin(), sgDataVec.end());
521 SmallVector<int32_t> instDataVec32(instDataVec.begin(), instDataVec.end());
522 SmallVector<int32_t> laneDataVec32(laneDataVec.begin(), laneDataVec.end());
523
524 return LayoutAttr::get(
525 getContext(), getSgLayout(),
526 sgDataVec.empty() ? DenseI32ArrayAttr()
527 : DenseI32ArrayAttr::get(getContext(), sgDataVec32),
528 instDataVec.empty() ? DenseI32ArrayAttr()
529 : DenseI32ArrayAttr::get(getContext(), instDataVec32),
530 getLaneLayout(),
531 laneDataVec.empty() ? DenseI32ArrayAttr()
532 : DenseI32ArrayAttr::get(getContext(), laneDataVec32),
533 getOrder());
534}
535
536// Derive a new layout by removing dimensions.
537// `dimGroup` specifies a group of dimensions to be removed in the derived
538// layout.
539DistributeLayoutAttr LayoutAttr::dropDims(SmallVector<int64_t> dimGroup) {
540
541 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
542 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
543 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
544 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
545 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
546 DenseI32ArrayAttr origOrderAttr = getOrder();
547
548 SmallVector<int64_t> sortedDimGroup = dimGroup;
549 llvm::sort(sortedDimGroup);
550
551 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
552 if (!sgLayout.empty()) {
553 sgLayout.erase(sgLayout.begin() + dimIdx);
554 sgData.erase(sgData.begin() + dimIdx);
555 }
556 if (!instData.empty())
557 instData.erase(instData.begin() + dimIdx);
558 if (!laneLayout.empty()) {
559 laneLayout.erase(laneLayout.begin() + dimIdx);
560 laneData.erase(laneData.begin() + dimIdx);
561 }
562 }
563
564 // Only emit a new order attribute when the input had one, so that "no
565 // order" inputs do not gain a synthetic default that would later trip
566 // adjacency checks in collapseDims.
567 SmallVector<int64_t> newOrder;
568 if (origOrderAttr && !origOrderAttr.empty()) {
569 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
570 for (int64_t d : origOrder) {
571 if (llvm::is_contained(dimGroup, d))
572 continue;
573 int64_t offset =
574 llvm::count_if(dimGroup, [&](int64_t s) { return s < d; });
575 newOrder.push_back(d - offset);
576 }
577 if ((sgLayout.empty() && laneLayout.empty()) || newOrder.size() == 1)
578 newOrder.clear();
579 }
580
581 auto toAttr = [&](ArrayRef<int64_t> v) -> DenseI32ArrayAttr {
582 if (v.empty())
583 return nullptr;
584 SmallVector<int32_t> v32(v.begin(), v.end());
585 return DenseI32ArrayAttr::get(getContext(), v32);
586 };
587 auto droppedLayout = xegpu::LayoutAttr::get(
588 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
589 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
590 return droppedLayout;
591}
592
593// Derive a new layout by collapsing dimensions.
594// `dimGroup` specifies a group of adjacent dimensions
595// that are collapsed into a single dimension in the derived layout.
596DistributeLayoutAttr LayoutAttr::collapseDims(SmallVector<int64_t> dimGroup) {
597
598 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
599 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
600 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
601 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
602 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
603 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
604
605 SmallVector<int64_t> sortedDimGroup = dimGroup;
606 llvm::sort(sortedDimGroup);
607 int64_t dimBeforeCurrent = -1;
608 for (auto dimIdx : sortedDimGroup) {
609 // when order attr is present, adjacency dims are values like [3, 2, 1, 0]
610 // in decreasing order; otherwise based on dim indices like [0, 1, 2, 3]
611 // in increasing order
612 if (dimBeforeCurrent >= 0) {
613 if (getOrder() && !getOrder().empty()) {
614 int64_t orderBefore = origOrder[dimBeforeCurrent];
615 int64_t orderCurrent = origOrder[dimIdx];
616 if (orderBefore != (orderCurrent - 1))
617 llvm::report_fatal_error(
618 "dimensions being collapsed must be adjacent in order");
619 } else {
620 if (dimIdx != (dimBeforeCurrent + 1))
621 llvm::report_fatal_error(
622 "dimensions being collapsed must be adjacent");
623 }
624 }
625 dimBeforeCurrent = dimIdx;
626 }
627
628 int firstDim = sortedDimGroup.front();
629
630 // collapse the dimensions in dimGroup into one dimension by multiplying their
631 // sizes together
632
633 if (!sgLayout.empty()) {
634 int64_t collapsedSglayout = 1, collapsedSgData = 1;
635 for (auto dimIdx : dimGroup) {
636 collapsedSglayout *= sgLayout[dimIdx];
637 collapsedSgData *= sgData[dimIdx];
638 }
639 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
640 sgLayout.erase(sgLayout.begin() + dimIdx, sgLayout.begin() + dimIdx + 1);
641 sgData.erase(sgData.begin() + dimIdx, sgData.begin() + dimIdx + 1);
642 }
643 sgLayout.insert(sgLayout.begin() + firstDim, collapsedSglayout);
644 sgData.insert(sgData.begin() + firstDim, collapsedSgData);
645 }
646
647 if (!instData.empty()) {
648 int64_t collapsedInstData = 1;
649 for (auto dimIdx : dimGroup)
650 collapsedInstData *= instData[dimIdx];
651 for (auto dimIdx : llvm::reverse(sortedDimGroup))
652 instData.erase(instData.begin() + dimIdx, instData.begin() + dimIdx + 1);
653 instData.insert(instData.begin() + firstDim, collapsedInstData);
654 }
655
656 if (!laneLayout.empty()) {
657 int64_t collapsedLaneLayout = 1, collapsedLaneData = 1;
658 for (auto dimIdx : dimGroup) {
659 collapsedLaneLayout *= laneLayout[dimIdx];
660 collapsedLaneData *= laneData[dimIdx];
661 }
662 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
663 laneLayout.erase(laneLayout.begin() + dimIdx,
664 laneLayout.begin() + dimIdx + 1);
665 laneData.erase(laneData.begin() + dimIdx, laneData.begin() + dimIdx + 1);
666 }
667 laneLayout.insert(laneLayout.begin() + firstDim, collapsedLaneLayout);
668 laneData.insert(laneData.begin() + firstDim, collapsedLaneData);
669 }
670
671 SmallVector<int64_t> newOrder;
672 DenseI32ArrayAttr orderAttr = getOrder();
673 if (orderAttr && !orderAttr.empty()) {
674
675 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
676 if (dimIdx != firstDim)
677 origOrder.erase(origOrder.begin() + dimIdx);
678 }
679 // say we have orderVec = {5, 3, 2, 1, 0}
680 // Create indices [0, 1, 2, 3, 4]
681 SmallVector<size_t> indices =
682 llvm::to_vector(llvm::seq<size_t>(0, origOrder.size()));
683
684 // Sort indices based on corresponding values
685 llvm::sort(indices,
686 [&](size_t a, size_t b) { return origOrder[a] < origOrder[b]; });
687
688 newOrder = llvm::to_vector(llvm::map_range(
689 indices, [&](size_t i) { return static_cast<int64_t>(i); }));
690 }
691
692 auto toAttr = [&](ArrayRef<int64_t> v) -> DenseI32ArrayAttr {
693 if (v.empty())
694 return nullptr;
695 SmallVector<int32_t> v32(v.begin(), v.end());
696 return DenseI32ArrayAttr::get(getContext(), v32);
697 };
698 auto collapsedLayout = xegpu::LayoutAttr::get(
699 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
700 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
701 return collapsedLayout;
702}
703
704// Derive a new layout by expanding a single dimension `dim` into multiple
705// adjacent dimensions whose extents are given by `targetShape`.
706//
707// The expanded dims are row-major (innermost is fastest-varying), so every
708// field is spread innermost-first. For sg and lane levels the data component
709// (sg_data / lane_data) is distributed first and the layout component
710// (sg_layout / lane_layout) then strides over the per-dim leftover; this
711// shared inner-first sweep is what makes "wrap-around" distributions correct.
712// When the data component spans the full extent (replicated/broadcast across
713// subgroups or lanes), the layout component is capped by the full extent
714// instead of the leftover. order entries past `dim` shift up by
715// `targetShape.size() - 1`.
716//
717// Examples (only the affected dim shown; assume rank-1 input):
718// sg_layout=[8], sg_data=[512], expandDim(0, [8,16,32])
719// -> sg_layout=[8,1,1], sg_data=[1,16,32]
720// sg_layout=[4], sg_data=[4], expandDim(0, [2,16])
721// -> sg_layout=[1,4], sg_data=[1,4] (wrap-around)
722// inst_data=[32], lane_layout=[16], lane_data=[1], expandDim(0, [8,16,32])
723// -> inst_data=[1,1,32], lane_layout=[1,1,16], lane_data=[1,1,1]
724DistributeLayoutAttr LayoutAttr::expandDim(int64_t dim,
725 ArrayRef<int64_t> targetShape) {
726 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
727 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
728 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
729 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
730 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
731
732 int64_t origRank = getRank();
733 int64_t expCount = static_cast<int64_t>(targetShape.size());
734 assert(dim >= 0 && dim < origRank && "dim out of range");
735 assert(expCount >= 1 && "targetShape must have at least one dim");
736 int64_t newRank = origRank + expCount - 1;
737
738 // Snapshot the per-dim values we need before any field is mutated by
739 // splice() below; without this, computations that read e.g. `laneLayout[dim]`
740 // after laneLayout has already been expanded would see the wrong value.
741 int64_t origSgLayoutDim = sgLayout.empty() ? 1 : sgLayout[dim];
742 int64_t origSgDataDim = sgData.empty() ? 1 : sgData[dim];
743 int64_t origLaneLayoutDim = laneLayout.empty() ? 1 : laneLayout[dim];
744 int64_t origLaneDataDim = laneData.empty() ? 1 : laneData[dim];
745 int64_t origInstDataDim = instData.empty() ? 1 : instData[dim];
746
747 // Spread `total` across the new dims (length expCount), innermost-first,
748 // capped per dim by `dimSizeCap[i]`.
749 auto spread = [&](int64_t total,
750 ArrayRef<int64_t> dimSizeCap) -> SmallVector<int64_t> {
751 SmallVector<int64_t> out(expCount, 1);
752 int64_t remaining = total;
753 for (int64_t i = expCount - 1; i >= 0; --i) {
754 if (remaining == 1)
755 break;
756 int64_t take = std::min(remaining, dimSizeCap[i]);
757 assert(take > 0 && "expandDim distribution must not be zero");
758 assert(remaining % take == 0 &&
759 "expandDims must divide evenly across dims");
760 out[i] = take;
761 remaining /= take;
762 }
763 assert(remaining == 1 && "expandDims total must fit within target shape");
764 return out;
765 };
766
767 // Splice `expanded` (length expCount) into `vec` at position `dim`,
768 // replacing the single entry at `dim`.
769 auto splice = [&](SmallVector<int64_t> &vec, ArrayRef<int64_t> expanded) {
770 if (vec.empty())
771 return;
772 vec.erase(vec.begin() + dim);
773 vec.insert(vec.begin() + dim, expanded.begin(), expanded.end());
774 };
775
776 bool hasSgLayout = !sgLayout.empty();
777 bool hasSgData = !sgData.empty();
778 bool hasLaneLayout = !laneLayout.empty();
779 bool hasLaneData = !laneData.empty();
780 bool hasInstData = !instData.empty();
781
782 // sg_data first, then sg_layout into the per-dim leftover. When sg_data is
783 // replicated across subgroups it spans the full extent, so sg_layout is
784 // capped by targetShape itself instead of the leftover.
785 bool sgDataReplicated =
786 hasSgData && origSgDataDim == computeProduct(targetShape);
787 SmallVector<int64_t> expSgData(expCount, 1);
788 if (hasSgData) {
789 expSgData = spread(origSgDataDim, targetShape);
790 splice(sgData, expSgData);
791 }
792 SmallVector<int64_t> expSgLayout(expCount, 1);
793 if (hasSgLayout) {
794 SmallVector<int64_t> dimSizeCap(targetShape.begin(), targetShape.end());
795 if (hasSgData && !sgDataReplicated)
796 for (int64_t i = 0; i < expCount; ++i)
797 dimSizeCap[i] /= expSgData[i];
798 expSgLayout = spread(origSgLayoutDim, dimSizeCap);
799 splice(sgLayout, expSgLayout);
800 }
801
802 // Per-sg extent feeding lane_layout / lane_data / inst_data.
803 SmallVector<int64_t> perSgShape(targetShape.begin(), targetShape.end());
804 if (hasSgLayout && !sgDataReplicated)
805 for (int64_t i = 0; i < expCount; ++i)
806 perSgShape[i] /= expSgLayout[i];
807
808 // lane_data first, then lane_layout into the per-dim leftover. When lane_data
809 // is replicated across lanes it spans the full per-sg extent, so lane_layout
810 // is capped by perSgShape itself instead of the leftover.
811 bool laneDataReplicated =
812 hasLaneData && origLaneDataDim == computeProduct(perSgShape);
813 SmallVector<int64_t> expLaneLayout(expCount, 1);
814 SmallVector<int64_t> expLaneData(expCount, 1);
815 if (hasLaneData)
816 expLaneData = spread(origLaneDataDim, perSgShape);
817 if (hasLaneLayout) {
818 SmallVector<int64_t> dimSizeCap(perSgShape.begin(), perSgShape.end());
819 if (hasLaneData && !laneDataReplicated)
820 for (int64_t i = 0; i < expCount; ++i)
821 dimSizeCap[i] /= expLaneData[i];
822 expLaneLayout = spread(origLaneLayoutDim, dimSizeCap);
823 }
824 if (hasLaneData)
825 splice(laneData, expLaneData);
826 if (hasLaneLayout)
827 splice(laneLayout, expLaneLayout);
828
829 // inst_data: seed each dim from the per-lane atom
830 // `laneLayout[i]*laneData[i]`, spread the remaining factor over the leftover,
831 // then scale back by the atom. Without lane info, spread inst_data directly
832 // over the per-sg extent.
833 if (hasInstData) {
834 SmallVector<int64_t> expInstData;
835 if (!hasLaneLayout || !hasLaneData) {
836 expInstData = spread(origInstDataDim, perSgShape);
837 } else {
838 int64_t laneAtom = origLaneLayoutDim * origLaneDataDim;
839 SmallVector<int64_t> atom(expCount, 1);
840 SmallVector<int64_t> dimSizeCap(expCount, 1);
841 for (int64_t i = 0; i < expCount; ++i) {
842 atom[i] = expLaneLayout[i] * expLaneData[i];
843 dimSizeCap[i] = perSgShape[i] / atom[i];
844 }
845 expInstData = spread(origInstDataDim / laneAtom, dimSizeCap);
846 for (int64_t i = 0; i < expCount; ++i)
847 expInstData[i] *= atom[i];
848 }
849 splice(instData, expInstData);
850 }
851
852 // order: replace `dim`'s entry with the expanded dim indices in
853 // innermost-fastest order; shift every other entry past `dim` up by
854 // (expCount - 1).
855 SmallVector<int64_t> newOrder;
856 DenseI32ArrayAttr orderAttr = getOrder();
857 if (orderAttr && !orderAttr.empty()) {
858 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
859 newOrder.reserve(newRank);
860 for (int64_t o : origOrder) {
861 if (o == dim) {
862 // Innermost dim of the expanded group is fastest-varying.
863 for (int64_t i = expCount - 1; i >= 0; --i)
864 newOrder.push_back(dim + i);
865 } else if (o > dim) {
866 newOrder.push_back(o + expCount - 1);
867 } else {
868 newOrder.push_back(o);
869 }
870 }
871 }
872
873 auto toAttr = [&](ArrayRef<int64_t> v) -> DenseI32ArrayAttr {
874 if (v.empty())
875 return nullptr;
876 SmallVector<int32_t> v32(v.begin(), v.end());
877 return DenseI32ArrayAttr::get(getContext(), v32);
878 };
879 return xegpu::LayoutAttr::get(getContext(), toAttr(sgLayout), toAttr(sgData),
880 toAttr(instData), toAttr(laneLayout),
881 toAttr(laneData), toAttr(newOrder));
882}
883
884// Derive a new layout by transpose the layout using `permutation`.
885DistributeLayoutAttr LayoutAttr::transposeDims(ArrayRef<int64_t> permutation) {
886
887 SmallVector<int64_t> origSgLayout = getEffectiveSgLayoutAsInt();
888 SmallVector<int64_t> origSgData = getEffectiveSgDataAsInt();
889 SmallVector<int64_t> origInstData = getEffectiveInstDataAsInt();
890 SmallVector<int64_t> origLaneLayout = getEffectiveLaneLayoutAsInt();
891 SmallVector<int64_t> origLaneData = getEffectiveLaneDataAsInt();
892 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
893
894 SmallVector<int32_t> sgLayout;
895 SmallVector<int32_t> sgData;
896 SmallVector<int32_t> instData;
897 SmallVector<int32_t> laneLayout;
898 SmallVector<int32_t> laneData;
899 SmallVector<int32_t> order;
900
901 for (int64_t idx : permutation) {
902 if (!origLaneLayout.empty()) {
903 laneLayout.push_back(static_cast<int32_t>(origLaneLayout[idx]));
904 laneData.push_back(static_cast<int32_t>(origLaneData[idx]));
905 }
906 if (!origInstData.empty())
907 instData.push_back(static_cast<int32_t>(origInstData[idx]));
908 if (!origSgLayout.empty()) {
909 sgLayout.push_back(static_cast<int32_t>(origSgLayout[idx]));
910 sgData.push_back(static_cast<int32_t>(origSgData[idx]));
911 }
912 }
913
914 // `order` is distinct from the size-valued fields above: its *values* are
915 // dimension indices (order[0] is the fastest-varying dim), not per-position
916 // sizes. A transpose relabels dimensions (source dim d becomes result dim
917 // inversePerm[d]) so the dimension values are remapped through the inverse
918 // permutation: newOrder[i] = inversePerm[origOrder[i]].
919 //
920 // The linearization order this describes is invariant under transpose: a
921 // transpose only renames dimensions, so the subgroup ID assigned to a given
922 // block of data must stay the same. Remapping the values through the inverse
923 // permutation is exactly what preserves that order.
924 SmallVector<int64_t> inversePermutation =
925 invertPermutationVector(permutation);
926 for (int64_t dim : origOrder)
927 order.push_back(static_cast<int32_t>(inversePermutation[dim]));
928 if (origLaneLayout.empty() && origSgLayout.empty())
929 order.clear();
930
931 auto toAttr = [&](ArrayRef<int32_t> v) -> DenseI32ArrayAttr {
932 return v.empty() ? nullptr : DenseI32ArrayAttr::get(getContext(), v);
933 };
934 return xegpu::LayoutAttr::get(getContext(), toAttr(sgLayout), toAttr(sgData),
935 toAttr(instData), toAttr(laneLayout),
936 toAttr(laneData), toAttr(order));
937}
938
939/// Check if this layout is a transpose of another layout.
940bool LayoutAttr::isTransposeOf(const xegpu::DistributeLayoutAttr &other,
941 ArrayRef<int64_t> perm,
942 const xegpu::LayoutKind kind) {
943 if (!other)
944 return false;
945 if (getRank() != other.getRank() ||
946 perm.size() != static_cast<size_t>(getRank()))
947 return false;
948 if (!isPermutationVector(perm))
949 return false;
950 // vector.transpose semantics: dst[i] = src[perm[i]]. So `this` (= dst) is a
951 // transpose of `other` (= src) via `perm` iff for all i, dst[i] ==
952 // src[perm[i]].
953 auto checkTranspose = [](ArrayRef<int64_t> dst, ArrayRef<int64_t> src,
954 ArrayRef<int64_t> perm) {
955 for (const auto &ta : llvm::enumerate(perm)) {
956 if (dst[ta.index()] != src[ta.value()])
957 return false;
958 }
959 return true;
960 };
961 // `order` is different: its *values* are dimension indices, so a transpose
962 // relabels them through the inverse permutation rather than reindexing by
963 // position. `this` (= dst) is a transpose of `other` (= src) iff
964 // dst.order[i] == inversePerm[src.order[i]] for all i. This matches the
965 // convention produced by `transposeDims`.
966 auto checkOrderTranspose = [](ArrayRef<int64_t> dstOrder,
967 ArrayRef<int64_t> srcOrder,
968 ArrayRef<int64_t> perm) {
969 if (dstOrder.size() != srcOrder.size())
970 return false;
971 SmallVector<int64_t> inversePerm = invertPermutationVector(perm);
972 for (auto [d, s] : llvm::zip_equal(dstOrder, srcOrder)) {
973 if (d != inversePerm[s])
974 return false;
975 }
976 return true;
977 };
978 if (kind == xegpu::LayoutKind::Subgroup)
979 return checkTranspose(getEffectiveSgLayoutAsInt(),
980 other.getEffectiveSgLayoutAsInt(), perm) &&
981 checkTranspose(getEffectiveSgDataAsInt(),
982 other.getEffectiveSgDataAsInt(), perm) &&
983 checkOrderTranspose(getEffectiveOrderAsInt(),
984 other.getEffectiveOrderAsInt(), perm);
985 if (kind == xegpu::LayoutKind::InstData)
986 return checkTranspose(getEffectiveInstDataAsInt(),
987 other.getEffectiveInstDataAsInt(), perm);
988 if (kind == xegpu::LayoutKind::Lane)
989 return checkTranspose(getEffectiveLaneLayoutAsInt(),
990 other.getEffectiveLaneLayoutAsInt(), perm) &&
991 checkTranspose(getEffectiveLaneDataAsInt(),
992 other.getEffectiveLaneDataAsInt(), perm) &&
993 checkOrderTranspose(getEffectiveOrderAsInt(),
994 other.getEffectiveOrderAsInt(), perm);
995
996 return false;
997}
998
999bool LayoutAttr::isCompatibleWith(const xegpu::DistributeLayoutAttr &other,
1000 SmallVector<int64_t> shape,
1001 xegpu::LayoutKind level) {
1002 if (!other)
1003 return false;
1004 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
1005 // short cut when order is the same, no need to compute coords and compare
1006 if (level == xegpu::LayoutKind::Subgroup)
1007 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
1008 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
1009 return true;
1010 if (level == xegpu::LayoutKind::Lane)
1011 if (getEffectiveLaneLayoutAsInt() ==
1012 other.getEffectiveLaneLayoutAsInt() &&
1013 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
1014 return true;
1015 }
1016
1017 auto compareCoordsForAllIds = [&](int64_t size) {
1018 return compareDistributedCoords(*this, other, shape, level, size);
1019 };
1020
1021 if (level == xegpu::LayoutKind::Subgroup) {
1022 int64_t wgSize = computeProduct(getEffectiveSgLayoutAsInt());
1023 return compareCoordsForAllIds(wgSize);
1024 }
1025 if (level == xegpu::LayoutKind::InstData) {
1026 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
1027 }
1028 if (level == xegpu::LayoutKind::Lane) {
1029 int64_t subgroupSize = computeProduct(getEffectiveLaneLayoutAsInt());
1030 return compareCoordsForAllIds(subgroupSize);
1031 }
1032 return true;
1033}
1034
1035//===----------------------------------------------------------------------===//
1036// XeGPU_SliceAttr
1037//===----------------------------------------------------------------------===//
1038LogicalResult
1039SliceAttr::verify(llvm::function_ref<InFlightDiagnostic()> emitError,
1040 xegpu::DistributeLayoutAttr parent, DenseI64ArrayAttr dims) {
1041
1042 if (!dims)
1043 return emitError() << "expected dims attribute";
1044
1045 // check every element in dims is unique and smaller than rank
1046 llvm::SmallDenseSet<int64_t> seen;
1047 for (int64_t dim : dims.asArrayRef()) {
1048 if (dim < 0)
1049 return emitError() << "invalid dim (" << dim << ") in slice attribute.";
1050 if (!seen.insert(dim).second)
1051 return emitError() << "repeated dim (" << dim << ") in slice attribute.";
1052 }
1053 return success();
1054}
1055
1056SliceAttr SliceAttr::flatten() const {
1057 xegpu::DistributeLayoutAttr parent = getParent();
1058 SmallVector<DenseI64ArrayAttr> slicedDims({getDims()});
1059
1060 while (auto sliceAttr = dyn_cast<xegpu::SliceAttr>(parent)) {
1061 parent = sliceAttr.getParent();
1062 slicedDims.push_back(sliceAttr.getDims());
1063 }
1064
1065 auto layoutAttr = dyn_cast<xegpu::LayoutAttr>(parent);
1066 SmallVector<int64_t> indices =
1067 llvm::to_vector(llvm::seq<int64_t>(0, layoutAttr.getRank()));
1068
1069 // get remaining dims (flattened) by applying slice ops with all slicedDims
1070 SmallVector<int64_t> remainingDims(indices);
1071 for (auto dim : llvm::reverse(slicedDims))
1072 remainingDims = XeGPUDialect::slice(llvm::ArrayRef<int64_t>(remainingDims),
1073 dim.asArrayRef());
1074
1075 // get flattened sliced dims by applying slice ops with the remaining dims
1076 SmallVector<int64_t> flattenedDims = XeGPUDialect::slice(
1077 llvm::ArrayRef<int64_t>(indices), llvm::ArrayRef<int64_t>(remainingDims));
1078
1079 return xegpu::SliceAttr::get(
1080 getContext(), layoutAttr,
1081 DenseI64ArrayAttr::get(getContext(), flattenedDims));
1082}
1083
1084FailureOr<SmallVector<Value>>
1085SliceAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
1086 SliceAttr attr = flatten();
1087 auto parent = dyn_cast<LayoutAttr>(attr.getParent());
1088 return parent.delinearizeId(builder, loc, linearId);
1089}
1090
1091// Implements DistributeLayoutAttr::computeDistributedCoords to generate
1092// instructions for computing multi-dimensional offsets when distributed by
1093// LayoutAttr.
1094FailureOr<SmallVector<SmallVector<Value>>>
1095SliceAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
1096 Value linearId, ArrayRef<int64_t> shape) {
1097 assert(getRank() == static_cast<int64_t>(shape.size()) && "invalid shape.");
1098
1099 SmallVector<int64_t> layout;
1100 SmallVector<int64_t> subShape;
1101 if (isForWorkgroup()) {
1102 layout = getEffectiveSgLayoutAsInt();
1103 subShape = getEffectiveSgDataAsInt();
1104 } else if (isForSubgroup()) {
1105 layout = getEffectiveLaneLayoutAsInt();
1106 subShape = getEffectiveLaneDataAsInt();
1107 } else {
1108 return failure();
1109 }
1110
1111 if (subShape.empty())
1112 return failure();
1113
1114 // delinearize Ids
1115 auto maybeIds = delinearizeId(builder, loc, linearId);
1116 if (failed(maybeIds))
1117 return failure();
1118
1119 // The effective sgIds for offsets computing correspond
1120 // to the dims that are not sliced.
1121 ArrayRef<int64_t> dims = flatten().getDims().asArrayRef();
1122 SmallVector<Value> canonicalIds =
1123 XeGPUDialect::slice(ArrayRef<Value>(*maybeIds), dims);
1124
1125 return genCoordinates(builder, loc, canonicalIds, layout, subShape, shape);
1126}
1127
1128/// Implements DistributeLayoutAttr::computeStaticDistributedCoords to
1129/// compute multi-dimensional offsets for a given linear ID when distributed by
1130/// SliceAttr. Delegates delinearization to the parent LayoutAttr, then uses
1131/// only the non-sliced dimensions for coordinate computation.
1132SmallVector<SmallVector<int64_t>>
1133SliceAttr::computeStaticDistributedCoords(int64_t linearId,
1134 ArrayRef<int64_t> shape) {
1135 assert(getRank() == static_cast<int64_t>(shape.size()) && "invalid shape.");
1136
1137 SmallVector<int64_t> layout;
1138 SmallVector<int64_t> subShape;
1139 SmallVector<int64_t> instData;
1140 if (isForWorkgroup()) {
1141 layout = getEffectiveSgLayoutAsInt();
1142 subShape = getEffectiveSgDataAsInt();
1143 } else if (isForSubgroup()) {
1144 instData = getEffectiveInstDataAsInt();
1145 layout = getEffectiveLaneLayoutAsInt();
1146 subShape = getEffectiveLaneDataAsInt();
1147 }
1148 if (!instData.empty()) {
1149 linearId = 0;
1150 subShape = instData;
1151 }
1152
1153 assert(!subShape.empty() && "sgdata or lanedata cannot be empty");
1154
1155 // Delinearize the ID using the parent layout (same as the IR version).
1156 SliceAttr flattened = flatten();
1157 auto parent = dyn_cast<LayoutAttr>(flattened.getParent());
1158 SmallVector<int64_t> parentLayoutVec;
1159 if (parent.isForWorkgroup())
1160 parentLayoutVec = parent.getEffectiveSgLayoutAsInt();
1161 else
1162 parentLayoutVec = parent.getEffectiveLaneLayoutAsInt();
1163
1164 SmallVector<int64_t> order = parent.getEffectiveOrderAsInt();
1165 SmallVector<int64_t> allIds(parentLayoutVec.size());
1166 int64_t remaining = linearId;
1167 for (size_t i = 0; i < order.size(); ++i) {
1168 int64_t dimIdx = order[i];
1169 allIds[dimIdx] = remaining % parentLayoutVec[dimIdx];
1170 if (i < order.size() - 1)
1171 remaining = remaining / parentLayoutVec[dimIdx];
1172 }
1173
1174 // The effective IDs for coordinate computation correspond
1175 // to the dims that are not sliced.
1176 ArrayRef<int64_t> dims = flattened.getDims().asArrayRef();
1177 SmallVector<int64_t> canonicalIds =
1178 XeGPUDialect::slice(ArrayRef<int64_t>(allIds), dims);
1179
1180 return genStaticCoordinates(canonicalIds, layout, subShape, shape);
1181}
1182
1183bool SliceAttr::isSliceOf(const xegpu::DistributeLayoutAttr &other) {
1184 auto flattenedThis = flatten();
1185 // If other is a LayoutAttr, just compare directly with parent of
1186 // flattenedThis.
1187 if (auto otherLayout = dyn_cast<xegpu::LayoutAttr>(other))
1188 return flattenedThis.getParent() == otherLayout;
1189 // If other is a SliceAttr, flatten it first before comparing.
1190 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
1191 // Both must have common parent LayoutAttr.
1192 if (flattenedThis.getParent() != flattenedOther.getParent())
1193 return false;
1194 // otherFlattened's sliced dims must be a subset of flattenedThis's sliced
1195 // dims.
1196 llvm::SmallDenseSet<int64_t> thisDims(
1197 flattenedThis.getDims().asArrayRef().begin(),
1198 flattenedThis.getDims().asArrayRef().end());
1199 return llvm::all_of(flattenedOther.getDims().asArrayRef(),
1200 [&](int64_t dim) { return thisDims.contains(dim); });
1201}
1202
1203bool SliceAttr::isEqualTo(const xegpu::DistributeLayoutAttr &other) {
1204 if (dyn_cast<xegpu::LayoutAttr>(other))
1205 return false;
1206
1207 auto flattenedThis = flatten();
1208 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
1209
1210 return ((flattenedThis.getParent() == flattenedOther.getParent()) &&
1211 (flattenedThis.getDims() == flattenedOther.getDims()));
1212}
1213
1214bool SliceAttr::isCompatibleWith(const xegpu::DistributeLayoutAttr &other,
1215 SmallVector<int64_t> shape,
1216 xegpu::LayoutKind level) {
1217 if (!other)
1218 return false;
1219 if (getEffectiveOrderAsInt() == other.getEffectiveOrderAsInt()) {
1220 // short cut when order is the same, no need to compute coords and compare
1221 if (level == xegpu::LayoutKind::Subgroup)
1222 if (getEffectiveSgLayoutAsInt() == other.getEffectiveSgLayoutAsInt() &&
1223 getEffectiveSgDataAsInt() == other.getEffectiveSgDataAsInt())
1224 return true;
1225 if (level == xegpu::LayoutKind::Lane)
1226 if (getEffectiveLaneLayoutAsInt() ==
1227 other.getEffectiveLaneLayoutAsInt() &&
1228 getEffectiveLaneDataAsInt() == other.getEffectiveLaneDataAsInt())
1229 return true;
1230 }
1231
1232 auto compareCoordsForAllIds = [&](int64_t size) {
1233 return compareDistributedCoords(*this, other, shape, level, size);
1234 };
1235
1236 auto flattenedThis = flatten();
1237 auto parent = dyn_cast<LayoutAttr>(flattenedThis.getParent());
1238 if (level == xegpu::LayoutKind::Subgroup) {
1239 int64_t wgSize = computeProduct(parent.getEffectiveSgLayoutAsInt());
1240 return compareCoordsForAllIds(wgSize);
1241 }
1242 if (level == xegpu::LayoutKind::InstData) {
1243 return (getEffectiveInstDataAsInt() == other.getEffectiveInstDataAsInt());
1244 }
1245 if (level == xegpu::LayoutKind::Lane) {
1246 int64_t subgroupSize = computeProduct(parent.getEffectiveLaneLayoutAsInt());
1247 return compareCoordsForAllIds(subgroupSize);
1248 }
1249 return true;
1250}
1251
1252xegpu::SliceAttr SliceAttr::dropSliceDims(ArrayRef<int64_t> sliceDimsToDrop) {
1253 if (sliceDimsToDrop.empty())
1254 return *this;
1255 SmallVector<int64_t> sliceDims{getDims().asArrayRef()};
1256 for (auto dim : sliceDimsToDrop) {
1257 auto foundIt = std::find(sliceDims.begin(), sliceDims.end(), dim);
1258 assert(foundIt != sliceDims.end() &&
1259 "Expected to find the specified reduction dim in slice dims");
1260 sliceDims.erase(foundIt);
1261 }
1262
1263 auto sliceWithoutDims = xegpu::SliceAttr::get(
1264 this->getContext(), getParent(),
1265 DenseI64ArrayAttr::get(this->getContext(), sliceDims));
1266
1267 return sliceWithoutDims;
1268}
1269
1270// Helper function to adjust dimensions from sliced space to parent space
1271// say we have a parent shape of rank 4, and slice dims [1,3], so the sliced
1272// shape is of rank 2, if we want to set unit dim [0] in sliced space, it maps
1273// to dim [0] in parent space; if we want to set unit dim [1] in sliced space,
1274// it maps to dim [2] in parent space.
1275static SmallVector<int64_t>
1277 ArrayRef<int64_t> sliceDims) {
1278 // Rather than recovering the exact parent rank, we compute a safe upper
1279 // bound so that dimsToMap can be adjusted safely. This upper bound is
1280 // defined as max(dimsToMap, sliceDims) + 1 + sliceDims.size().
1281 int64_t maxDim = -1;
1282 maxDim =
1283 std::max(maxDim, *std::max_element(sliceDims.begin(), sliceDims.end()));
1284 maxDim =
1285 std::max(maxDim, *std::max_element(dimsToMap.begin(), dimsToMap.end()));
1286 int64_t parentSpaceRank = maxDim + sliceDims.size() + 1;
1287
1288 // get remaining dims in parent space after applying slicing with parent's
1289 // slice Dims
1290 llvm::SmallDenseSet<int64_t> slicedDimsSet(sliceDims.begin(),
1291 sliceDims.end());
1292 SmallVector<int64_t> remainingDims;
1293 for (int64_t i = 0; i < parentSpaceRank; ++i) {
1294 if (!slicedDimsSet.contains(i))
1295 remainingDims.push_back(i);
1296 }
1297
1298 // Map unit dims from sliced space to parent space
1299 SmallVector<int64_t> adjustUnitDims;
1300 for (auto dim : dimsToMap) {
1301 int64_t mappedDim = remainingDims[dim];
1302 adjustUnitDims.push_back(mappedDim);
1303 }
1304
1305 return adjustUnitDims;
1306}
1307
1308// set the layout for unit dims: sg_data, inst_data and lane_data to 1
1309DistributeLayoutAttr
1310SliceAttr::setUnitDimData(SmallVector<int64_t> unitDims) const {
1311 DistributeLayoutAttr parentLayout = getParent();
1312
1313 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
1314
1315 SmallVector<int64_t> adjustUnitDims =
1316 mapSlicedDimsToParentSpace(unitDims, sliceDims);
1317
1318 return SliceAttr::get(getContext(),
1319 parentLayout.setUnitDimData(adjustUnitDims), getDims());
1320}
1321
1322// set the layout for the sepcified unit dims: sg_lane and lane_layout to 1
1323DistributeLayoutAttr
1324SliceAttr::setUnitDimLayout(SmallVector<int64_t> unitDims) const {
1325 DistributeLayoutAttr parentLayout = getParent();
1326
1327 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
1328
1329 SmallVector<int64_t> adjustUnitDims =
1330 mapSlicedDimsToParentSpace(unitDims, sliceDims);
1331
1332 return SliceAttr::get(
1333 getContext(), parentLayout.setUnitDimLayout(adjustUnitDims), getDims());
1334}
1335
1336// Derive a new layout with sg_data, inst_data and lane_data set to the
1337// specified values for the given dimension
1338DistributeLayoutAttr SliceAttr::setDimData(int64_t dim, int64_t sgData,
1339 int64_t instData, int64_t laneData) {
1340 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
1341 auto parent = getParent();
1342
1343 SmallVector<int64_t> dimSet;
1344 dimSet.push_back(dim);
1345 SmallVector<int64_t> adjustDims =
1346 mapSlicedDimsToParentSpace(dimSet, sliceDims);
1347 return SliceAttr::get(
1348 getContext(),
1349 parent.setDimData(adjustDims[0], sgData, instData, laneData), getDims());
1350}
1351
1352// Derive a new layout by removing dimensions. `dimGroup` specifies a group of
1353// dimensions to be removed in the derived layout.
1354//
1355// Example: drop the 2nd dimension from a rank-3 sliced view.
1356//
1357// Suppose:
1358// xegpu.layout = slice<layout<[V0, V1, V2, V3, V4]>, [1, 3]>
1359//
1360// The slice removes parent dims [1, 3], so the sliced-space dims map to
1361// parent dims [V0, V2, V4].
1362//
1363// If we drop sliced-space dim 1 (the 2nd dim), that corresponds to dropping
1364// parent dim 2, result in parent layout [V0, V1, V3, V4] after dropping.
1365// After parent dim 2 is removed, sliced dims [1, 3] must be reindexed to [1,
1366// 2].
1367//
1368// Result:
1369// xegpu.layout = slice<layout<[0, 1, 3, 4]>, [1, 2]>
1370DistributeLayoutAttr SliceAttr::dropDims(SmallVector<int64_t> dimGroup) {
1371 // Map the sliced dims from parent space to collapsed space
1372 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1373 SmallVector<int64_t> dimsInParentSpace =
1374 mapSlicedDimsToParentSpace(dimGroup, sliceDims);
1375
1376 auto droppedParent = getParent().dropDims(dimsInParentSpace);
1377
1378 // Adjust the sliced dims after dropping dims in parent space. For example, if
1379 // we drop dim 2 in parent space, the dims after dim 2 will all be shifted by
1380 // 1, so sliced dim 3 will be adjusted to 2.
1381 SmallVector<int64_t> newSliceDims;
1382 for (int64_t d : sliceDims) {
1383 int64_t offset =
1384 llvm::count_if(dimsInParentSpace, [&](int64_t s) { return s < d; });
1385 newSliceDims.push_back(d - offset);
1386 }
1387
1388 return SliceAttr::get(getContext(), droppedParent,
1389 DenseI64ArrayAttr::get(getContext(), newSliceDims));
1390}
1391
1392// Derive a new layout by collapsing dimensions.
1393// `dimGroup` specifies a group of adjacent dimensions
1394// that are collapsed into a single dimension in the derived layout.
1395DistributeLayoutAttr SliceAttr::collapseDims(SmallVector<int64_t> dimGroup) {
1396
1397 // Map the sliced dims from parent space to collapsed space
1398 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1399 assert("expect sliceDims not being collapsed" &&
1400 llvm::none_of(dimGroup, [&](int64_t dim) {
1401 return llvm::is_contained(sliceDims, dim);
1402 }));
1403 SmallVector<int64_t> dimsInParentSpace =
1404 mapSlicedDimsToParentSpace(dimGroup, sliceDims);
1405
1406 auto collapsedParent = getParent().collapseDims(dimsInParentSpace);
1407 return SliceAttr::get(getContext(), collapsedParent,
1408 DenseI64ArrayAttr::get(getContext(), sliceDims));
1409}
1410
1411// Derive a new layout by expanding a single sliced-space dim into multiple
1412// adjacent dims. The dim is mapped to parent space, the parent layout is
1413// expanded there, and the slice dims that lie past the expanded position
1414// are shifted up by `targetShape.size() - 1`.
1415DistributeLayoutAttr SliceAttr::expandDim(int64_t dim,
1416 ArrayRef<int64_t> targetShape) {
1417 // `dim` is in slice space; map it to parent space (parent dims listed in
1418 // `sliceDims` are removed by the slice, so the mapping always lands on a
1419 // non-sliced parent dim).
1420 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
1421 SmallVector<int64_t> dimSet = {dim};
1422 SmallVector<int64_t> dimsInParentSpace =
1423 mapSlicedDimsToParentSpace(dimSet, sliceDims);
1424 int64_t parentDim = dimsInParentSpace[0];
1425
1426 auto expandedParent = getParent().expandDim(parentDim, targetShape);
1427
1428 int64_t shift = static_cast<int64_t>(targetShape.size()) - 1;
1429 SmallVector<int64_t> newSliceDims;
1430 newSliceDims.reserve(sliceDims.size());
1431 for (int64_t s : sliceDims)
1432 newSliceDims.push_back(s > parentDim ? s + shift : s);
1433
1434 return SliceAttr::get(getContext(), expandedParent,
1435 DenseI64ArrayAttr::get(getContext(), newSliceDims));
1436}
1437
1439 ArrayRef<int64_t> permutation) {
1440 SmallVector<int64_t> sortedSliceDims = llvm::to_vector(sliceDims);
1441 llvm::sort(sortedSliceDims);
1442
1443 for (size_t i = 1; i < sortedSliceDims.size(); ++i) {
1444 assert((sortedSliceDims[i] == sortedSliceDims[i - 1] + 1) &&
1445 "slice dims non consecutive, cannot be transposed");
1446 }
1447
1448 SmallVector<int64_t> permForParent;
1449 if (sortedSliceDims.front() == 0) {
1450 // Example: sliceDims.size() = 2, permutation= {1, 0}
1451 // result: {3, 2, 1, 0}.
1452 for (int64_t dim : permutation)
1453 permForParent.push_back(dim + sortedSliceDims.size());
1454 for (int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1455 permForParent.push_back(i);
1456 } else {
1457 // Example: sliceDims.size() = 2, permutation = {0, 1}
1458 // result: {3, 2, 0, 1}.
1459 for (int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1460 permForParent.push_back(i + permutation.size());
1461 for (int64_t dim : permutation)
1462 permForParent.push_back(dim);
1463 }
1464 return permForParent;
1465}
1466
1467// Derive a new layout by transpose the layout using `permutation`.
1468DistributeLayoutAttr SliceAttr::transposeDims(ArrayRef<int64_t> permutation) {
1469 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1470 DistributeLayoutAttr parent = getParent();
1471 SmallVector<int64_t> permForParent =
1472 getPermForParentLayout(sliceDims, permutation);
1473 auto transposedParent = parent.transposeDims(permForParent);
1474 return SliceAttr::get(getContext(), transposedParent,
1475 DenseI64ArrayAttr::get(getContext(), sliceDims));
1476}
1477
1478/// Check if this layout is a transpose of another layout.
1479bool SliceAttr::isTransposeOf(const xegpu::DistributeLayoutAttr &other,
1480 ArrayRef<int64_t> perm,
1481 const xegpu::LayoutKind kind) {
1482 // other must be a SliceAttr with the same slice dims.
1483 auto otherSlice = dyn_cast<xegpu::SliceAttr>(other);
1484 if (!otherSlice || getDims() != otherSlice.getDims())
1485 return false;
1486 // check whether the parent layout is transpose of each other.
1487 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1488 DistributeLayoutAttr parent = getParent();
1489 SmallVector<int64_t> permForParent = getPermForParentLayout(sliceDims, perm);
1490 auto otherParent = otherSlice.getParent();
1491 return parent.isTransposeOf(otherParent, permForParent, kind);
1492}
1493
1494//===----------------------------------------------------------------------===//
1495// XeGPU_RangeAttr
1496//===----------------------------------------------------------------------===//
1497
1498LogicalResult
1499RangeAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
1500 IntegerAttr startOfRange, IntegerAttr endOfRange) {
1501 if (startOfRange.getInt() >= endOfRange.getInt())
1502 return emitError() << "'end' : " << endOfRange.getInt()
1503 << " must be greater than 'start' : "
1504 << startOfRange.getInt();
1505
1506 return success();
1507}
1508
1509//===----------------------------------------------------------------------===//
1510// XeGPU_TensorDescType
1511//===----------------------------------------------------------------------===//
1512
1513mlir::Type TensorDescType::parse(AsmParser &parser) {
1514 llvm::SmallVector<int64_t> shape;
1515 mlir::Type elementType;
1516 mlir::FailureOr<mlir::Attribute> encoding;
1517 mlir::FailureOr<mlir::Attribute> layout;
1518
1519 // Parse literal '<'
1520 if (parser.parseLess())
1521 return {};
1522
1523 auto shapeLoc = parser.getCurrentLocation();
1524 if (mlir::failed(parser.parseDimensionList(shape))) {
1525 parser.emitError(shapeLoc, "failed to parse parameter 'shape'");
1526 return {};
1527 }
1528
1529 auto elemTypeLoc = parser.getCurrentLocation();
1530 if (mlir::failed(parser.parseType(elementType))) {
1531 parser.emitError(elemTypeLoc, "failed to parse parameter 'elementType'");
1532 return {};
1533 }
1534
1535 // parse optional attributes
1536 while (mlir::succeeded(parser.parseOptionalComma())) {
1537 mlir::Attribute attr;
1538 ParseResult res = parser.parseAttribute(attr);
1539 if (mlir::succeeded(res)) {
1540 if (mlir::isa<DistributeLayoutAttr>(attr)) {
1541 layout = attr;
1542 continue;
1543 }
1544 if (mlir::isa<BlockTensorDescAttr>(attr)) {
1545 encoding = attr;
1546 continue;
1547 }
1548 }
1549 return {};
1550 }
1551
1552 // Parse literal '>'
1553 if (parser.parseGreater())
1554 return {};
1555
1556 MLIRContext *ctxt = parser.getContext();
1557 return TensorDescType::getChecked(
1558 [&]() { return parser.emitError(parser.getNameLoc()); }, ctxt, shape,
1559 elementType, encoding.value_or(BlockTensorDescAttr::get(ctxt)),
1560 layout.value_or(mlir::Attribute()));
1561}
1562
1563void TensorDescType::print(AsmPrinter &printer) const {
1564 printer << "<";
1565
1566 auto shape = getShape();
1567 for (int64_t dim : shape) {
1568 if (mlir::ShapedType::isDynamic(dim))
1569 printer << '?';
1570 else
1571 printer << dim;
1572 printer << 'x';
1573 }
1574
1575 printer << getElementType();
1576
1577 auto encoding = getEncoding();
1578 auto blockAttr = llvm::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1579 if (encoding && (!blockAttr || !blockAttr.hasDefaultsOnly()))
1580 printer << ", " << encoding;
1581
1582 if (auto layout = getLayout())
1583 printer << ", " << layout;
1584
1585 printer << ">";
1586}
1587
1588TensorDescType TensorDescType::get(llvm::ArrayRef<int64_t> shape,
1589 mlir::Type elementType, int array_length,
1590 bool boundary_check,
1591 MemorySpace memory_space,
1592 mlir::Attribute layout) {
1593 auto *context = elementType.getContext();
1594 auto attr = BlockTensorDescAttr::get(context, memory_space, array_length,
1595 boundary_check);
1596 return Base::get(context, shape, elementType, attr, layout);
1597}
1598
1599LogicalResult
1600TensorDescType::verify(llvm::function_ref<InFlightDiagnostic()> emitError,
1601 llvm::ArrayRef<int64_t> shape, mlir::Type elementType,
1602 mlir::Attribute encoding, mlir::Attribute layout) {
1603 size_t rank = shape.size();
1604
1605 if (rank == 0)
1606 return emitError() << "expected non-zero rank tensor";
1607
1608 auto blockAttr = mlir::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1609 if (blockAttr) {
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";
1614 }
1615
1616 if (!elementType.isIntOrFloat())
1617 return emitError() << "unsupported element type " << elementType
1618 << ": expected integer or float";
1619
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";
1624
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 "
1630 << layoutAttr;
1631 }
1632 }
1633
1634 return success();
1635}
1636
1637//===----------------------------------------------------------------------===//
1638// XeGPU_MemDescType
1639//===----------------------------------------------------------------------===//
1640mlir::Type MemDescType::parse(AsmParser &parser) {
1641 llvm::SmallVector<int64_t> shape;
1642 mlir::Type elementType;
1643 mlir::FailureOr<MemLayoutAttr> layout;
1644
1645 // Parse literal '<'
1646 if (parser.parseLess())
1647 return {};
1648
1649 auto shapeLoc = parser.getCurrentLocation();
1650 if (mlir::failed(parser.parseDimensionList(shape, false, true))) {
1651 parser.emitError(shapeLoc, "failed to parse parameter 'shape'");
1652 return {};
1653 }
1654
1655 auto elemTypeLoc = parser.getCurrentLocation();
1656 if (mlir::failed(parser.parseType(elementType))) {
1657 parser.emitError(elemTypeLoc, "failed to parse parameter 'elementType'");
1658 return {};
1659 }
1660
1661 // parse optional attributes
1662 if (mlir::succeeded(parser.parseOptionalComma())) {
1663 MemLayoutAttr attr;
1664 ParseResult res = parser.parseAttribute(attr);
1665 if (mlir::failed(res))
1666 return {};
1667 layout = attr;
1668 }
1669
1670 // Parse literal '>'
1671 if (parser.parseGreater())
1672 return {};
1673
1674 MLIRContext *ctxt = parser.getContext();
1675 return MemDescType::getChecked(
1676 [&]() { return parser.emitError(parser.getNameLoc()); }, ctxt, shape,
1677 elementType, layout.value_or(MemLayoutAttr()));
1678}
1679
1680void MemDescType::print(AsmPrinter &printer) const {
1681 printer << "<";
1682
1683 printer.printDimensionList(getShape());
1684 printer << 'x';
1685 printer << getElementType();
1686
1687 if (auto layout = getMemLayout())
1688 printer << ", " << layout;
1689
1690 printer << ">";
1691}
1692
1693//===----------------------------------------------------------------------===//
1694// XeGPU_MemDescType
1695//===----------------------------------------------------------------------===//
1696
1697Attribute MemLayoutAttr::parse(AsmParser &parser, Type type) {
1698
1699 auto *context = parser.getContext();
1700 llvm::SMLoc loc = parser.getCurrentLocation();
1701
1702 llvm::SmallDenseSet<StringRef> seenKeys;
1703 SmallVector<NamedAttribute> attributes;
1704
1705 auto parseElt = [&]() -> ParseResult {
1706 StringRef nameId;
1707 if (failed(parser.parseKeyword(&nameId)))
1708 return parser.emitError(loc, "expected valid attribute name");
1709
1710 if (!seenKeys.insert(nameId).second)
1711 return parser.emitError(loc, "duplicate key '")
1712 << nameId << " in mem layout attribute";
1713
1714 if (failed(parser.parseEqual()))
1715 return failure();
1716
1717 Attribute attr;
1718 if (failed(parser.parseAttribute(attr)))
1719 return failure();
1720 attributes.emplace_back(nameId, attr);
1721 return success();
1722 };
1723
1724 // Parse literal '<'
1725 if (parser.parseLess())
1726 return {};
1727
1728 if (failed(parser.parseCommaSeparatedList(parseElt)))
1729 return {};
1730
1731 // Parse literal '>'
1732 if (parser.parseGreater())
1733 return {};
1734
1735 return parser.getChecked<MemLayoutAttr>(
1736 loc, context, DictionaryAttr::get(context, attributes));
1737}
1738
1739void MemLayoutAttr::print(AsmPrinter &printer) const {
1740 printer << "<";
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)
1745 printer << ", ";
1746 }
1747 printer << ">";
1748}
1749// a helper utility to perform binary operation on OpFoldResult.
1750// If both a and b are attributes, it will simply return the result.
1751// Otherwise, the corresponding arith op will be generated, and an
1752// contant op will be created if one of them is an attribute.
1753template <typename ArithOp>
1755 OpBuilder &builder) {
1756 auto aVal = getValueOrCreateConstantIndexOp(builder, loc, a);
1757 auto bVal = getValueOrCreateConstantIndexOp(builder, loc, b);
1758 return ArithOp::create(builder, loc, aVal, bVal).getResult();
1759}
1760
1761// a helper utility to perform division operation on OpFoldResult and int64_t.
1762#define div(a, b) \
1763 genBinOp<arith::DivSIOp>(a, builder.getIndexAttr(b), loc, builder)
1764
1765// a helper utility to perform reminder operation on OpFoldResult and int64_t.
1766#define rem(a, b) \
1767 genBinOp<arith::RemSIOp>(a, builder.getIndexAttr(b), loc, builder)
1768
1769// a helper utility to perform multiply operation on OpFoldResult and int64_t.
1770#define mul(a, b) \
1771 genBinOp<arith::MulIOp>(a, builder.getIndexAttr(b), loc, builder)
1772
1773// a helper utility to perform addition operation on two OpFoldResult.
1774#define add(a, b) genBinOp<arith::AddIOp>(a, b, loc, builder)
1775
1776// block the given offsets according to the block shape
1777// say the original offset is [y, x], and the block shape is [By, Bx],
1778// then the blocked offset is [y/By, x/Bx, y%By, x%Bx]
1780 ArrayRef<OpFoldResult> offsets,
1781 ArrayRef<int64_t> blockShape) {
1782
1783 assert(offsets.size() == blockShape.size() &&
1784 "offsets and blockShape must have the same size");
1785 SmallVector<OpFoldResult> blockedOffsets;
1786 SmallVector<OpFoldResult> divs, rems;
1787
1788 for (auto [offset, block] : llvm::zip(offsets, blockShape)) {
1789 divs.push_back(div(offset, block));
1790 rems.push_back(rem(offset, block));
1791 }
1792 blockedOffsets.append(divs.begin(), divs.end());
1793 blockedOffsets.append(rems.begin(), rems.end());
1794
1795 return blockedOffsets;
1796}
1797
1798// Get strides as vector of integer for MemDesc.
1799SmallVector<int64_t> MemDescType::getStrideShape() {
1800
1801 SmallVector<int64_t> matrixShape(getShape().begin(), getShape().end());
1802
1803 ArrayAttr strideAttr = getStrideAttr();
1804 SmallVector<int64_t> strides;
1805 for (Attribute attr : strideAttr.getValue()) {
1806 strides.push_back(cast<IntegerAttr>(attr).getInt());
1807 }
1808
1809 SmallVector<int64_t> innerBlkShape = getBlockShape();
1810
1811 // get perm from FCD to LCD
1812 // perm[i] = the dim with i-th smallest stride
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]; });
1816
1817 assert(strides[perm[0]] == 1 && "inner most dim must have stride 1");
1818
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]];
1824
1825 // compute the original matrix shape using the stride info
1826 // and compute the number of blocks in each dimension
1827 // The shape of highest dim can't be derived from stride info,
1828 // but doesn't impact the stride computation for blocked layout.
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]];
1834 }
1835
1836 int64_t innerBlkSize = 1;
1837 for (auto s : innerBlkShape)
1838 innerBlkSize *= s;
1839
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]];
1845 }
1846
1847 // combine the inner and outer strides
1848 SmallVector<int64_t> blockedStrides;
1849 blockedStrides.append(outerBlkStride.begin(), outerBlkStride.end());
1850 blockedStrides.append(innerBlkStride.begin(), innerBlkStride.end());
1851
1852 return blockedStrides;
1853}
1854
1855// Calculate the linear offset using the blocked offsets and stride
1856Value MemDescType::getLinearOffsets(OpBuilder &builder, Location loc,
1857 ArrayRef<OpFoldResult> offsets) {
1858
1859 SmallVector<int64_t> matrixShape(getShape().begin(), getShape().end());
1860 SmallVector<int64_t> blockShape = getBlockShape();
1861 SmallVector<int64_t> strides = getStrideShape();
1862 SmallVector<OpFoldResult> blockedOffsets;
1863
1864 // blockshape equal to matrixshape means no blocking
1865 if (llvm::equal(blockShape, matrixShape)) {
1866 // remove the outer dims from strides
1867 strides.erase(strides.begin(), strides.begin() + matrixShape.size());
1868 } else {
1869 assert(offsets.size() == blockShape.size() &&
1870 "offsets and blockShape must have the same size");
1871 // say the original offset is [y, x], and the block shape is [By, Bx],
1872 // then the blocked offset is [y/By, x/Bx, y%By, x%Bx]
1873
1874 SmallVector<OpFoldResult> divs, rems;
1875
1876 for (auto [offset, block] : llvm::zip(offsets, blockShape)) {
1877 divs.push_back(div(offset, block));
1878 rems.push_back(rem(offset, block));
1879 }
1880 blockedOffsets.append(divs.begin(), divs.end());
1881 blockedOffsets.append(rems.begin(), rems.end());
1882 offsets = blockedOffsets;
1883 }
1884
1885 // Start with initial value as matrix descriptor's base offset.
1886 Value linearOffset = arith::ConstantIndexOp::create(builder, loc, 0);
1887 for (size_t i = 0; i < offsets.size(); ++i) {
1888 OpFoldResult mulResult = mul(offsets[i], strides[i]);
1889 Value mulVal = getValueOrCreateConstantIndexOp(builder, loc, mulResult);
1890 linearOffset = arith::AddIOp::create(builder, loc, mulVal, linearOffset);
1891 }
1892
1893 return linearOffset;
1894}
1895
1896} // namespace xegpu
1897} // namespace mlir
1898
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>
return success()
static Type getElementType(Type type)
Determine the element type of type.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
b getContext())
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
#define mul(a, b)
#define div(a, b)
#define rem(a, b)
Attributes are known-constant values of operations.
Definition Attributes.h:25
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...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
This class helps build Operations.
Definition Builders.h:209
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...
Definition Builders.h:528
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.
Definition Types.cpp:35
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Specialization of arith.constant op that returns an integer of index type.
Definition Arith.h:114
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:384
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int32_t > content)
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:717
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.
Definition XeGPU.h:32
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.
Definition Utils.cpp:114
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.