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
14#include "mlir/IR/Builders.h"
16#include "llvm/ADT/SmallVectorExtras.h"
17#include "llvm/ADT/TypeSwitch.h"
18#include "llvm/Support/Debug.h"
19
20using std::optional;
21
22namespace mlir {
23namespace xegpu {
24
25void XeGPUDialect::initialize() {
26 addTypes<
27#define GET_TYPEDEF_LIST
28#include <mlir/Dialect/XeGPU/IR/XeGPUTypes.cpp.inc>
29 >();
30 addOperations<
31#define GET_OP_LIST
32#include <mlir/Dialect/XeGPU/IR/XeGPU.cpp.inc>
33 >();
34 addAttributes<
35#define GET_ATTRDEF_LIST
36#include <mlir/Dialect/XeGPU/IR/XeGPUAttrs.cpp.inc>
37 >();
38}
39#define GET_OP_INTERFACE_CLASSES
40#include "mlir/Dialect/XeGPU/IR/XeGPUOpInterface.cpp.inc"
41
42// A `srcShape` consists of N distribution units, each being `subShapesLayout` x
43// `subShape`. A `delinearizedId` is used to identify a particular `subShape`
44// within each distribution unit.
45// Example:
46// WG data is 128x256. SG data is 16x32, in 4x2 layout, this gives a
47// distribution unit of shape 64x64, we have 2x4 such distribution units.
48// `delinearizedId` is used to identify a 16x32 of a subgroup in each
49// distribution unit.
52 SmallVector<Value> delinearizedId,
53 ArrayRef<int64_t> subShapesLayout, ArrayRef<int64_t> subShape,
54 ArrayRef<int64_t> srcShape) {
56
57 // A distribution unit must be less than or equal to `srcShape`
58 SmallVector<int64_t> distUnitShape = llvm::map_to_vector(
59 llvm::zip_equal(srcShape,
60 computeElementwiseMul(subShapesLayout, subShape)),
61 [](const auto &t) { return std::min(std::get<0>(t), std::get<1>(t)); });
62
63 // Get the offset of `subShape` within a distribution unit.
64 SmallVector<Value> distUnitLocalOffset = llvm::map_to_vector(
65 llvm::zip(delinearizedId, subShape), [&](const auto &t) -> Value {
66 return builder.createOrFold<arith::MulIOp>(
67 loc, std::get<0>(t),
68 builder.createOrFold<arith::ConstantIndexOp>(loc, std::get<1>(t)));
69 });
70
71 // For each dist unit
72 for (SmallVector<int64_t> unitOffs :
73 StaticTileOffsetRange(srcShape, distUnitShape)) {
74 // Get dist unit offset within `srcShape`.
76 llvm::map_to_vector(unitOffs, [&](int64_t d) -> Value {
77 return arith::ConstantIndexOp::create(builder, loc, d);
78 });
79 // Calculate `subShape` offset within `srcShape`.
81 llvm::map_to_vector(llvm::zip_equal(base, distUnitLocalOffset),
82 [&](const auto &t) -> Value {
83 return builder.createOrFold<arith::AddIOp>(
84 loc, std::get<0>(t), std::get<1>(t));
85 });
86 // Do not go beyond `srcShape` bounds.
87 SmallVector<Value> mods = llvm::map_to_vector(
88 llvm::zip_equal(adds, srcShape), [&](const auto &t) -> Value {
89 return builder.createOrFold<arith::RemUIOp>(
90 loc, std::get<0>(t),
91 arith::ConstantIndexOp::create(builder, loc, std::get<1>(t)));
92 });
93
94 coordinates.push_back(mods);
95 }
96 return coordinates;
97}
98
99// Checks if the given shape can be evenly distributed based on the layout
100// and data factors provided by the LayoutAttr.
101bool XeGPUDialect::isEvenlyDistributable(llvm::ArrayRef<int64_t> shape,
102 xegpu::DistributeLayoutAttr attr) {
103 assert(attr && "Layout attribute is missing.");
104
105 // Checks whether the given shape can be evenly distributed using the
106 // specified layout and data attributes. If successful, it returns the work
107 // size for each compute unit; otherwise, it returns `std::nullopt`. The work
108 // size per compute unit is calculated as follows:
109 // - If `data` is null: newShape[i] = shape[i] / layout[i]
110 // - If `data` is not null: newShape[i] = data[i]
111 // When round-robin distribution (`rr`) is enabled, `shape[i]` can be
112 // smaller than `layout[i] * data[i]`, allowing multiple compute units to
113 // share the data.
114 auto tryDistribute = [&](llvm::ArrayRef<int64_t> shape,
117 bool rr = true) -> optional<SmallVector<int64_t>> {
119 if (layout.size()) {
120 if (layout.size() != shape.size())
121 return std::nullopt;
122 auto ratio = computeShapeRatio(shape, layout);
123 if (ratio.has_value()) {
124 newShape = ratio.value();
125 } else if (!rr || !computeShapeRatio(layout, shape).has_value()) {
126 return std::nullopt;
127 }
128 // Round-robin case: continue with original newShape
129 }
130
131 if (data.size()) {
132 if (data.size() != shape.size())
133 return std::nullopt;
134 auto ratio = computeShapeRatio(newShape, data);
135 if (!ratio.has_value() && rr)
136 ratio = computeShapeRatio(data, newShape);
137 if (!ratio.has_value())
138 return std::nullopt;
139
140 // if data is not null, we always return it for next phase.
141 newShape = data;
142 }
143 return newShape;
144 };
145
146 // check the sgLayout and sgData
147 auto maybeSgShape = tryDistribute(shape, attr.getEffectiveSgLayoutAsInt(),
148 attr.getEffectiveSgDataAsInt());
149 if (!maybeSgShape)
150 return false;
151 auto sgShape = maybeSgShape.value();
152
153 // check InstData, it neither have layout nor need round-robin
154 auto maybeInstShape =
155 tryDistribute(sgShape, {}, attr.getEffectiveInstDataAsInt(), false);
156 if (!maybeInstShape)
157 return false;
158 auto instShape = maybeInstShape.value();
159
160 // check LaneLayout and LaneData
161 auto maybeLaneShape =
162 tryDistribute(instShape, attr.getEffectiveLaneLayoutAsInt(),
163 attr.getEffectiveLaneDataAsInt(), false);
164 return maybeLaneShape.has_value();
165}
166
167//===----------------------------------------------------------------------===//
168// XeGPU_BlockTensorDescAttr
169//===----------------------------------------------------------------------===//
170BlockTensorDescAttr BlockTensorDescAttr::get(mlir::MLIRContext *context,
171 xegpu::MemorySpace memory_space,
172 int array_length,
173 bool boundary_check) {
174 auto scopeAttr = MemorySpaceAttr::get(context, memory_space);
175 auto lengthAttr =
176 IntegerAttr::get(IntegerType::get(context, 64), array_length);
177 auto boundaryAttr = BoolAttr::get(context, boundary_check);
178 return Base::get(context, scopeAttr, lengthAttr, boundaryAttr);
179}
180
181bool BlockTensorDescAttr::hasDefaultsOnly() {
182 return getMemorySpace().getValue() == xegpu::MemorySpace::Global &&
183 getArrayLength().getInt() == 1 && getBoundaryCheck().getValue();
184}
185
186//===----------------------------------------------------------------------===//
187// XeGPU_ScatterTensorDescAttr
188//===----------------------------------------------------------------------===//
189ScatterTensorDescAttr
190ScatterTensorDescAttr::get(mlir::MLIRContext *context,
191 xegpu::MemorySpace memory_space, int chunk_size) {
192 auto scopeAttr = MemorySpaceAttr::get(context, memory_space);
193 auto chunkSizeAttr =
194 IntegerAttr::get(IntegerType::get(context, 64), chunk_size);
195 return Base::get(context, scopeAttr, chunkSizeAttr);
196}
197
198LogicalResult ScatterTensorDescAttr::verify(
199 llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
200 MemorySpaceAttr memory_space, IntegerAttr chunk_size) {
201 int64_t chunkSize = chunk_size.getInt();
202 if (chunkSize <= 0)
203 return emitError() << "invalid chunk size";
204
205 return success();
206}
207
208//===----------------------------------------------------------------------===//
209// XeGPU_LayoutAttr
210//===----------------------------------------------------------------------===//
211LogicalResult
212LayoutAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
213 DenseI32ArrayAttr sg_layout, DenseI32ArrayAttr sg_data,
214 DenseI32ArrayAttr inst_data, DenseI32ArrayAttr lane_layout,
215 DenseI32ArrayAttr lane_data, DenseI32ArrayAttr order) {
216
217 // Special case for store_matrix
218 if (!sg_layout && !inst_data && !lane_layout)
219 return success();
220
221 // generate code to check sg_laout, inst_data and lane_layout having the same
222 // rank if they are not null.
223
224 if (sg_layout && inst_data && sg_layout.size() != inst_data.size()) {
225 return emitError()
226 << "expected sg_layout and inst_data to have the same rank";
227 }
228
229 if (sg_layout && lane_layout && sg_layout.size() != lane_layout.size()) {
230 return emitError()
231 << "expected sg_layout and lane_layout to have the same rank";
232 }
233
234 if (inst_data && lane_layout && inst_data.size() != lane_layout.size()) {
235 return emitError() << "expected inst_data and lane_layout to have the same "
236 "rank, got inst_data "
237 << inst_data.size() << ", lane_layout "
238 << lane_layout.size();
239 }
240
241 // sg_data is optional for Workgroup layout, but its presence requires
242 // sg_layout.
243 if (sg_data) {
244 if (!sg_layout)
245 return emitError() << "expected sg_layout being used with sg_data";
246 if (sg_data.size() != sg_layout.size())
247 return emitError()
248 << "expected sg_data and sg_layout to have the same rank";
249 }
250
251 // lane_data is optional for Subgroup layout, but its presence requires
252 // lane_layout.
253 if (lane_data) {
254 if (!lane_layout)
255 return emitError() << "expected lane_layout being used with lane_data";
256 if (lane_data.size() != lane_layout.size())
257 return emitError()
258 << "expected lane_data and lane_layout to have the same rank";
259 }
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 if (subShape.empty()) {
377 if (auto derivedShape = computeShapeRatio(shape, layout))
378 subShape = derivedShape.value();
379 else
380 return failure();
381 }
382
383 // delinearize Ids
384 auto maybeIds = delinearizeId(builder, loc, linearId);
385 if (failed(maybeIds))
386 return failure();
387 SmallVector<Value> ids = *maybeIds;
388
389 return genCoordinates(builder, loc, ids, layout, subShape, shape);
390}
391
392bool LayoutAttr::isEqualTo(const xegpu::DistributeLayoutAttr &other) {
393 if (dyn_cast<xegpu::SliceAttr>(other))
394 return false;
395
396 return *this == dyn_cast<xegpu::LayoutAttr>(other);
397}
398
399// set the layout for unit dims: sg_data, inst_data and lane_data to 1
400DistributeLayoutAttr
401LayoutAttr::setUnitDimData(SmallVector<int64_t> unitDims) const {
402 auto sgDataOpt = getSgData();
403 auto instDataOpt = getInstData();
404 auto laneDataOpt = getLaneData();
405
406 SmallVector<int32_t> sgData;
407 SmallVector<int32_t> instData;
408 SmallVector<int32_t> laneData;
409
410 if (sgDataOpt)
411 sgData = llvm::to_vector(sgDataOpt.asArrayRef());
412
413 if (instDataOpt)
414 instData = llvm::to_vector(instDataOpt.asArrayRef());
415
416 if (laneDataOpt)
417 laneData = llvm::to_vector(laneDataOpt.asArrayRef());
418
419 for (auto dim : unitDims) {
420 if (dim < static_cast<int64_t>(sgData.size()))
421 sgData[dim] = 1;
422 if (dim < static_cast<int64_t>(instData.size()))
423 instData[dim] = 1;
424 if (dim < static_cast<int64_t>(laneData.size()))
425 laneData[dim] = 1;
426 }
427
428 return LayoutAttr::get(
429 getContext(), getSgLayout(),
430 sgData.empty() ? DenseI32ArrayAttr()
432 instData.empty() ? DenseI32ArrayAttr()
433 : DenseI32ArrayAttr::get(getContext(), instData),
434 getLaneLayout(),
435 laneData.empty() ? DenseI32ArrayAttr()
436 : DenseI32ArrayAttr::get(getContext(), laneData),
437 getOrder());
438}
439
440// set the layout for the sepcified unit dims: sg_lane and lane_layout to 1
441DistributeLayoutAttr
442LayoutAttr::setUnitDimLayout(SmallVector<int64_t> unitDims) const {
443 auto sgLayoutOpt = getSgLayout();
444 auto laneLayoutOpt = getLaneLayout();
445
446 SmallVector<int32_t> sgLayout;
447 SmallVector<int32_t> laneLayout;
448
449 if (sgLayoutOpt)
450 sgLayout = llvm::to_vector(sgLayoutOpt.asArrayRef());
451 if (laneLayoutOpt)
452 laneLayout = llvm::to_vector(laneLayoutOpt.asArrayRef());
453
454 for (auto dim : unitDims) {
455 if (dim < static_cast<int64_t>(sgLayout.size()))
456 sgLayout[dim] = 1;
457 if (dim < static_cast<int64_t>(laneLayout.size()))
458 laneLayout[dim] = 1;
459 }
460
461 return LayoutAttr::get(
462 getContext(),
463 sgLayout.empty() ? DenseI32ArrayAttr()
464 : DenseI32ArrayAttr::get(getContext(), sgLayout),
465 getSgData(), getInstData(),
466 laneLayout.empty() ? DenseI32ArrayAttr()
467 : DenseI32ArrayAttr::get(getContext(), laneLayout),
468 getLaneData(), getOrder());
469}
470
471// Derive a new layout with sg_data, inst_data and lane_data set to the
472// specified values for the given dimension
473DistributeLayoutAttr LayoutAttr::setDimData(int64_t dim, int64_t sgData,
474 int64_t instData,
475 int64_t laneData) {
476
477 SmallVector<int64_t> sgDataVec = getEffectiveSgDataAsInt();
478 SmallVector<int64_t> instDataVec = getEffectiveInstDataAsInt();
479 SmallVector<int64_t> laneDataVec = getEffectiveLaneDataAsInt();
480
481 if (dim < static_cast<int64_t>(sgDataVec.size()) && sgData != -1)
482 sgDataVec[dim] = sgData;
483 if (dim < static_cast<int64_t>(instDataVec.size()) && instData != -1)
484 instDataVec[dim] = instData;
485 if (dim < static_cast<int64_t>(laneDataVec.size()) && laneData != -1)
486 laneDataVec[dim] = laneData;
487
488 SmallVector<int32_t> sgDataVec32(sgDataVec.begin(), sgDataVec.end());
489 SmallVector<int32_t> instDataVec32(instDataVec.begin(), instDataVec.end());
490 SmallVector<int32_t> laneDataVec32(laneDataVec.begin(), laneDataVec.end());
491
492 return LayoutAttr::get(
493 getContext(), getSgLayout(),
494 sgDataVec.empty() ? DenseI32ArrayAttr()
495 : DenseI32ArrayAttr::get(getContext(), sgDataVec32),
496 instDataVec.empty() ? DenseI32ArrayAttr()
497 : DenseI32ArrayAttr::get(getContext(), instDataVec32),
498 getLaneLayout(),
499 laneDataVec.empty() ? DenseI32ArrayAttr()
500 : DenseI32ArrayAttr::get(getContext(), laneDataVec32),
501 getOrder());
502}
503
504// Derive a new layout by removing dimensions.
505// `dimGroup` specifies a group of dimensions to be removed in the derived
506// layout.
507DistributeLayoutAttr LayoutAttr::dropDims(SmallVector<int64_t> dimGroup) {
508
509 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
510 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
511 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
512 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
513 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
514 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
515
516 SmallVector<int64_t> sortedDimGroup = dimGroup;
517 llvm::sort(sortedDimGroup);
518
519 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
520 if (!sgLayout.empty()) {
521 sgLayout.erase(sgLayout.begin() + dimIdx);
522 sgData.erase(sgData.begin() + dimIdx);
523 }
524 if (!instData.empty())
525 instData.erase(instData.begin() + dimIdx);
526 if (!laneLayout.empty()) {
527 laneLayout.erase(laneLayout.begin() + dimIdx);
528 laneData.erase(laneData.begin() + dimIdx);
529 }
530 }
531
532 SmallVector<int64_t> newOrder;
533 for (int64_t d : origOrder) {
534 if (llvm::is_contained(dimGroup, d))
535 continue;
536 int64_t offset = llvm::count_if(dimGroup, [&](int64_t s) { return s < d; });
537 newOrder.push_back(d - offset);
538 }
539 if (sgLayout.empty() && laneLayout.empty())
540 newOrder.clear();
541
542 auto toAttr = [&](ArrayRef<int64_t> v) -> DenseI32ArrayAttr {
543 if (v.empty())
544 return DenseI32ArrayAttr();
545 SmallVector<int32_t> v32(v.begin(), v.end());
546 return DenseI32ArrayAttr::get(getContext(), v32);
547 };
548 auto droppedLayout = xegpu::LayoutAttr::get(
549 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
550 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
551 return droppedLayout;
552}
553
554// Derive a new layout by collapsing dimensions.
555// `dimGroup` specifies a group of adjacent dimensions
556// that are collapsed into a single dimension in the derived layout.
557DistributeLayoutAttr LayoutAttr::collapseDims(SmallVector<int64_t> dimGroup) {
558
559 SmallVector<int64_t> sgLayout = getEffectiveSgLayoutAsInt();
560 SmallVector<int64_t> sgData = getEffectiveSgDataAsInt();
561 SmallVector<int64_t> instData = getEffectiveInstDataAsInt();
562 SmallVector<int64_t> laneLayout = getEffectiveLaneLayoutAsInt();
563 SmallVector<int64_t> laneData = getEffectiveLaneDataAsInt();
564 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
565
566 SmallVector<int64_t> sortedDimGroup = dimGroup;
567 llvm::sort(sortedDimGroup);
568 int64_t dimBeforeCurrent = -1;
569 for (auto dimIdx : sortedDimGroup) {
570 // when order attr is present, adjacency dims are values like [3, 2, 1, 0]
571 // in decreasing order; otherwise based on dim indices like [0, 1, 2, 3]
572 // in increasing order
573 if (dimBeforeCurrent >= 0) {
574 if (getOrder() && !getOrder().empty()) {
575 int64_t orderBefore = origOrder[dimBeforeCurrent];
576 int64_t orderCurrent = origOrder[dimIdx];
577 if (orderBefore != (orderCurrent - 1))
578 llvm::report_fatal_error(
579 "dimensions being collapsed must be adjacent in order");
580 } else {
581 if (dimIdx != (dimBeforeCurrent + 1))
582 llvm::report_fatal_error(
583 "dimensions being collapsed must be adjacent");
584 }
585 }
586 dimBeforeCurrent = dimIdx;
587 }
588
589 int firstDim = sortedDimGroup.front();
590
591 // collapse the dimensions in dimGroup into one dimension by multiplying their
592 // sizes together
593
594 if (!sgLayout.empty()) {
595 int64_t collapsedSglayout = 1, collapsedSgData = 1;
596 for (auto dimIdx : dimGroup) {
597 collapsedSglayout *= sgLayout[dimIdx];
598 collapsedSgData *= sgData[dimIdx];
599 }
600 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
601 sgLayout.erase(sgLayout.begin() + dimIdx, sgLayout.begin() + dimIdx + 1);
602 sgData.erase(sgData.begin() + dimIdx, sgData.begin() + dimIdx + 1);
603 }
604 sgLayout.insert(sgLayout.begin() + firstDim, collapsedSglayout);
605 sgData.insert(sgData.begin() + firstDim, collapsedSgData);
606 }
607
608 if (!instData.empty()) {
609 int64_t collapsedInstData = 1;
610 for (auto dimIdx : dimGroup)
611 collapsedInstData *= instData[dimIdx];
612 for (auto dimIdx : llvm::reverse(sortedDimGroup))
613 instData.erase(instData.begin() + dimIdx, instData.begin() + dimIdx + 1);
614 instData.insert(instData.begin() + firstDim, collapsedInstData);
615 }
616
617 if (!laneLayout.empty()) {
618 int64_t collapsedLaneLayout = 1, collapsedLaneData = 1;
619 for (auto dimIdx : dimGroup) {
620 collapsedLaneLayout *= laneLayout[dimIdx];
621 collapsedLaneData *= laneData[dimIdx];
622 }
623 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
624 laneLayout.erase(laneLayout.begin() + dimIdx,
625 laneLayout.begin() + dimIdx + 1);
626 laneData.erase(laneData.begin() + dimIdx, laneData.begin() + dimIdx + 1);
627 }
628 laneLayout.insert(laneLayout.begin() + firstDim, collapsedLaneLayout);
629 laneData.insert(laneData.begin() + firstDim, collapsedLaneData);
630 }
631
632 SmallVector<int64_t> newOrder;
633 DenseI32ArrayAttr orderAttr = getOrder();
634 if (orderAttr && !orderAttr.empty()) {
635
636 for (auto dimIdx : llvm::reverse(sortedDimGroup)) {
637 if (dimIdx != firstDim)
638 origOrder.erase(origOrder.begin() + dimIdx);
639 }
640 // say we have orderVec = {5, 3, 2, 1, 0}
641 // Create indices [0, 1, 2, 3, 4]
642 SmallVector<size_t> indices =
643 llvm::to_vector(llvm::seq<size_t>(0, orderAttr.size()));
644
645 // Sort indices based on corresponding values
646 llvm::sort(indices,
647 [&](size_t a, size_t b) { return origOrder[a] < origOrder[b]; });
648
649 newOrder = llvm::to_vector(llvm::map_range(
650 indices, [&](size_t i) { return static_cast<int64_t>(i); }));
651 }
652
653 auto toAttr = [&](ArrayRef<int64_t> v) -> DenseI32ArrayAttr {
654 if (v.empty())
655 return DenseI32ArrayAttr();
656 SmallVector<int32_t> v32(v.begin(), v.end());
657 return DenseI32ArrayAttr::get(getContext(), v32);
658 };
659 auto collapsedLayout = xegpu::LayoutAttr::get(
660 getContext(), toAttr(sgLayout), toAttr(sgData), toAttr(instData),
661 toAttr(laneLayout), toAttr(laneData), toAttr(newOrder));
662 return collapsedLayout;
663}
664
665// Derive a new layout by transpose the layout using `permutation`.
666DistributeLayoutAttr LayoutAttr::transposeDims(ArrayRef<int64_t> permutation) {
667
668 SmallVector<int64_t> origSgLayout = getEffectiveSgLayoutAsInt();
669 SmallVector<int64_t> origSgData = getEffectiveSgDataAsInt();
670 SmallVector<int64_t> origInstData = getEffectiveInstDataAsInt();
671 SmallVector<int64_t> origLaneLayout = getEffectiveLaneLayoutAsInt();
672 SmallVector<int64_t> origLaneData = getEffectiveLaneDataAsInt();
673 SmallVector<int64_t> origOrder = getEffectiveOrderAsInt();
674
675 SmallVector<int32_t> sgLayout;
676 SmallVector<int32_t> sgData;
677 SmallVector<int32_t> instData;
678 SmallVector<int32_t> laneLayout;
679 SmallVector<int32_t> laneData;
680 SmallVector<int32_t> order;
681
682 for (int64_t idx : permutation) {
683 if (!origLaneLayout.empty()) {
684 laneLayout.push_back(static_cast<int32_t>(origLaneLayout[idx]));
685 laneData.push_back(static_cast<int32_t>(origLaneData[idx]));
686 }
687 if (!origInstData.empty())
688 instData.push_back(static_cast<int32_t>(origInstData[idx]));
689 if (!origSgLayout.empty()) {
690 sgLayout.push_back(static_cast<int32_t>(origSgLayout[idx]));
691 sgData.push_back(static_cast<int32_t>(origSgData[idx]));
692 }
693 order.push_back(static_cast<int32_t>(origOrder[idx]));
694 }
695 if (origLaneLayout.empty() && origSgLayout.empty())
696 order.clear();
697
698 auto toAttr = [&](ArrayRef<int32_t> v) -> DenseI32ArrayAttr {
699 return v.empty() ? nullptr : DenseI32ArrayAttr::get(getContext(), v);
700 };
701 return xegpu::LayoutAttr::get(getContext(), toAttr(sgLayout), toAttr(sgData),
702 toAttr(instData), toAttr(laneLayout),
703 toAttr(laneData), toAttr(order));
704}
705
706/// Check if this layout is a transpose of another layout.
707bool LayoutAttr::isTransposeOf(const xegpu::DistributeLayoutAttr &other,
708 ArrayRef<int64_t> perm,
709 const xegpu::LayoutKind kind) {
710 if (!other)
711 return false;
712 if (getRank() != other.getRank() ||
713 perm.size() != static_cast<size_t>(getRank()))
714 return false;
715 if (!isPermutationVector(perm))
716 return false;
717 auto checkTranspose = [](ArrayRef<int64_t> dst, ArrayRef<int64_t> src,
718 ArrayRef<int64_t> perm) {
719 for (const auto &ta : llvm::enumerate(perm)) {
720 if (src[ta.index()] != dst[ta.value()])
721 return false;
722 }
723 return true;
724 };
725 if (kind == xegpu::LayoutKind::Subgroup)
726 return checkTranspose(getEffectiveSgLayoutAsInt(),
727 other.getEffectiveSgLayoutAsInt(), perm) &&
728 checkTranspose(getEffectiveSgDataAsInt(),
729 other.getEffectiveSgDataAsInt(), perm) &&
730 checkTranspose(getEffectiveOrderAsInt(),
731 other.getEffectiveOrderAsInt(), perm);
732 if (kind == xegpu::LayoutKind::InstData)
733 return checkTranspose(getEffectiveInstDataAsInt(),
734 other.getEffectiveInstDataAsInt(), perm);
735 if (kind == xegpu::LayoutKind::Lane)
736 return checkTranspose(getEffectiveLaneLayoutAsInt(),
737 other.getEffectiveLaneLayoutAsInt(), perm) &&
738 checkTranspose(getEffectiveLaneDataAsInt(),
739 other.getEffectiveLaneDataAsInt(), perm) &&
740 checkTranspose(getEffectiveOrderAsInt(),
741 other.getEffectiveOrderAsInt(), perm);
742
743 return false;
744}
745
746//===----------------------------------------------------------------------===//
747// XeGPU_SliceAttr
748//===----------------------------------------------------------------------===//
749LogicalResult
750SliceAttr::verify(llvm::function_ref<InFlightDiagnostic()> emitError,
751 xegpu::DistributeLayoutAttr parent, DenseI64ArrayAttr dims) {
752
753 if (!dims)
754 return emitError() << "expected dims attribute";
755
756 // check every element in dims is unique and smaller than rank
757 llvm::SmallDenseSet<int64_t> seen;
758 for (int64_t dim : dims.asArrayRef()) {
759 if (dim < 0)
760 return emitError() << "invalid dim (" << dim << ") in slice attribute.";
761 if (!seen.insert(dim).second)
762 return emitError() << "repeated dim (" << dim << ") in slice attribute.";
763 }
764 return success();
765}
766
767SliceAttr SliceAttr::flatten() const {
768 xegpu::DistributeLayoutAttr parent = getParent();
769 SmallVector<DenseI64ArrayAttr> slicedDims({getDims()});
770
771 while (auto sliceAttr = dyn_cast<xegpu::SliceAttr>(parent)) {
772 parent = sliceAttr.getParent();
773 slicedDims.push_back(sliceAttr.getDims());
774 }
775
776 auto layoutAttr = dyn_cast<xegpu::LayoutAttr>(parent);
777 SmallVector<int64_t> indices =
778 llvm::to_vector(llvm::seq<int64_t>(0, layoutAttr.getRank()));
779
780 // get remaining dims (flattend) by applying slice ops with all slicedDims
781 SmallVector<int64_t> remainingDims(indices);
782 for (auto dim : llvm::reverse(slicedDims))
783 remainingDims = XeGPUDialect::slice(llvm::ArrayRef<int64_t>(remainingDims),
784 dim.asArrayRef());
785
786 // get flattend sliced dims by applying slice ops with the remaining dims
787 SmallVector<int64_t> flattendDims = XeGPUDialect::slice(
788 llvm::ArrayRef<int64_t>(indices), llvm::ArrayRef<int64_t>(remainingDims));
789
790 return xegpu::SliceAttr::get(
791 getContext(), layoutAttr,
792 DenseI64ArrayAttr::get(getContext(), flattendDims));
793}
794
795FailureOr<SmallVector<Value>>
796SliceAttr::delinearizeId(OpBuilder &builder, Location loc, Value linearId) {
797 SliceAttr attr = flatten();
798 auto parent = dyn_cast<LayoutAttr>(attr.getParent());
799 return parent.delinearizeId(builder, loc, linearId);
800}
801
802// Implements DistributeLayoutAttr::computeDistributedCoords to generate
803// instructions for computing multi-dimensional offsets when distributed by
804// LayoutAttr.
805FailureOr<SmallVector<SmallVector<Value>>>
806SliceAttr::computeDistributedCoords(OpBuilder &builder, Location loc,
807 Value linearId, ArrayRef<int64_t> shape) {
808 assert(getRank() == static_cast<int64_t>(shape.size()) && "invalid shape.");
809
810 SmallVector<int64_t> layout;
811 SmallVector<int64_t> subShape;
812 if (isForWorkgroup()) {
813 layout = getEffectiveSgLayoutAsInt();
814 subShape = getEffectiveSgDataAsInt();
815 } else if (isForSubgroup()) {
816 layout = getEffectiveLaneLayoutAsInt();
817 subShape = getEffectiveLaneDataAsInt();
818 } else {
819 return failure();
820 }
821
822 if (subShape.empty()) {
823 if (auto derivedShape = computeShapeRatio(shape, layout))
824 subShape = derivedShape.value();
825 else
826 return failure();
827 }
828
829 // delinearize Ids
830 auto maybeIds = delinearizeId(builder, loc, linearId);
831 if (failed(maybeIds))
832 return failure();
833
834 // The effective sgIds for offsets computing correspond
835 // to the dims that are not sliced.
836 ArrayRef<int64_t> dims = flatten().getDims().asArrayRef();
837 SmallVector<Value> sgIds =
838 XeGPUDialect::slice(ArrayRef<Value>(*maybeIds), dims);
839
840 return genCoordinates(builder, loc, sgIds, layout, subShape, shape);
841}
842
843bool SliceAttr::isSliceOf(const xegpu::DistributeLayoutAttr &other) {
844 auto flattenedThis = flatten();
845 // If other is a LayoutAttr, just compare directly with parent of
846 // flattenedThis.
847 if (auto otherLayout = dyn_cast<xegpu::LayoutAttr>(other))
848 return flattenedThis.getParent() == otherLayout;
849 // If other is a SliceAttr, flatten it first before comparing.
850 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
851 // Both must have common parent LayoutAttr.
852 if (flattenedThis.getParent() != flattenedOther.getParent())
853 return false;
854 // otherFlattened's sliced dims must be a subset of flattenedThis's sliced
855 // dims.
856 llvm::SmallDenseSet<int64_t> thisDims(
857 flattenedThis.getDims().asArrayRef().begin(),
858 flattenedThis.getDims().asArrayRef().end());
859 return llvm::all_of(flattenedOther.getDims().asArrayRef(),
860 [&](int64_t dim) { return thisDims.contains(dim); });
861}
862
863bool SliceAttr::isEqualTo(const xegpu::DistributeLayoutAttr &other) {
864 if (dyn_cast<xegpu::LayoutAttr>(other))
865 return false;
866
867 auto flattenedThis = flatten();
868 auto flattenedOther = dyn_cast<xegpu::SliceAttr>(other).flatten();
869
870 return ((flattenedThis.getParent() == flattenedOther.getParent()) &&
871 (flattenedThis.getDims() == flattenedOther.getDims()));
872}
873
874xegpu::SliceAttr SliceAttr::dropSliceDims(ArrayRef<int64_t> sliceDimsToDrop) {
875 if (sliceDimsToDrop.empty())
876 return *this;
877 SmallVector<int64_t> sliceDims{getDims().asArrayRef()};
878 for (auto dim : sliceDimsToDrop) {
879 auto foundIt = std::find(sliceDims.begin(), sliceDims.end(), dim);
880 assert(foundIt != sliceDims.end() &&
881 "Expected to find the specified reduction dim in slice dims");
882 sliceDims.erase(foundIt);
883 }
884
885 auto sliceWithoutDims = xegpu::SliceAttr::get(
886 this->getContext(), getParent(),
887 DenseI64ArrayAttr::get(this->getContext(), sliceDims));
888
889 return sliceWithoutDims;
890}
891
892// Helper function to adjust dimensions from sliced space to parent space
893// say we have a parent shape of rank 4, and slice dims [1,3], so the sliced
894// shape is of rank 2, if we want to set unit dim [0] in sliced space, it maps
895// to dim [0] in parent space; if we want to set unit dim [1] in sliced space,
896// it maps to dim [2] in parent space.
897static SmallVector<int64_t>
899 ArrayRef<int64_t> sliceDims) {
900 // Rather than recovering the exact parent rank, we compute a safe upper
901 // bound so that dimsToMap can be adjusted safely. This upper bound is
902 // defined as max(dimsToMap, sliceDims) + 1 + sliceDims.size().
903 int64_t maxDim = -1;
904 maxDim =
905 std::max(maxDim, *std::max_element(sliceDims.begin(), sliceDims.end()));
906 maxDim =
907 std::max(maxDim, *std::max_element(dimsToMap.begin(), dimsToMap.end()));
908 int64_t parentSpaceRank = maxDim + sliceDims.size() + 1;
909
910 // get remaining dims in parent space after applying slicing with parent's
911 // slice Dims
912 llvm::SmallDenseSet<int64_t> slicedDimsSet(sliceDims.begin(),
913 sliceDims.end());
914 SmallVector<int64_t> remainingDims;
915 for (int64_t i = 0; i < parentSpaceRank; ++i) {
916 if (!slicedDimsSet.contains(i))
917 remainingDims.push_back(i);
918 }
919
920 // Map unit dims from sliced space to parent space
921 SmallVector<int64_t> adjustUnitDims;
922 for (auto dim : dimsToMap) {
923 int64_t mappedDim = remainingDims[dim];
924 adjustUnitDims.push_back(mappedDim);
925 }
926
927 return adjustUnitDims;
928}
929
930// set the layout for unit dims: sg_data, inst_data and lane_data to 1
931DistributeLayoutAttr
932SliceAttr::setUnitDimData(SmallVector<int64_t> unitDims) const {
933 DistributeLayoutAttr parentLayout = getParent();
934
935 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
936
937 SmallVector<int64_t> adjustUnitDims =
938 mapSlicedDimsToParentSpace(unitDims, sliceDims);
939
940 return SliceAttr::get(getContext(),
941 parentLayout.setUnitDimData(adjustUnitDims), getDims());
942}
943
944// set the layout for the sepcified unit dims: sg_lane and lane_layout to 1
945DistributeLayoutAttr
946SliceAttr::setUnitDimLayout(SmallVector<int64_t> unitDims) const {
947 DistributeLayoutAttr parentLayout = getParent();
948
949 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
950
951 SmallVector<int64_t> adjustUnitDims =
952 mapSlicedDimsToParentSpace(unitDims, sliceDims);
953
954 return SliceAttr::get(
955 getContext(), parentLayout.setUnitDimLayout(adjustUnitDims), getDims());
956}
957
958// Derive a new layout with sg_data, inst_data and lane_data set to the
959// specified values for the given dimension
960DistributeLayoutAttr SliceAttr::setDimData(int64_t dim, int64_t sgData,
961 int64_t instData, int64_t laneData) {
962 ArrayRef<int64_t> sliceDims = getDims().asArrayRef();
963 auto parent = getParent();
964
965 SmallVector<int64_t> dimSet;
966 dimSet.push_back(dim);
967 SmallVector<int64_t> adjustDims =
968 mapSlicedDimsToParentSpace(dimSet, sliceDims);
969 return SliceAttr::get(
970 getContext(),
971 parent.setDimData(adjustDims[0], sgData, instData, laneData), getDims());
972}
973
974// Derive a new layout by removing dimensions. `dimGroup` specifies a group of
975// dimensions to be removed in the derived layout.
976//
977// Example: drop the 2nd dimension from a rank-3 sliced view.
978//
979// Suppose:
980// xegpu.layout = slice<layout<[V0, V1, V2, V3, V4]>, [1, 3]>
981//
982// The slice removes parent dims [1, 3], so the sliced-space dims map to
983// parent dims [V0, V2, V4].
984//
985// If we drop sliced-space dim 1 (the 2nd dim), that corresponds to dropping
986// parent dim 2, result in parent layout [V0, V1, V3, V4] after dropping.
987// After parent dim 2 is removed, sliced dims [1, 3] must be reindexed to [1,
988// 2].
989//
990// Result:
991// xegpu.layout = slice<layout<[0, 1, 3, 4]>, [1, 2]>
992DistributeLayoutAttr SliceAttr::dropDims(SmallVector<int64_t> dimGroup) {
993 // Map the sliced dims from parent space to collapsed space
994 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
995 SmallVector<int64_t> dimsInParentSpace =
996 mapSlicedDimsToParentSpace(dimGroup, sliceDims);
997
998 auto droppedParent = getParent().dropDims(dimsInParentSpace);
999
1000 // Adjust the sliced dims after dropping dims in parent space. For example, if
1001 // we drop dim 2 in parent space, the dims after dim 2 will all be shifted by
1002 // 1, so sliced dim 3 will be adjusted to 2.
1003 SmallVector<int64_t> newSliceDims;
1004 for (int64_t d : sliceDims) {
1005 int64_t offset =
1006 llvm::count_if(dimsInParentSpace, [&](int64_t s) { return s < d; });
1007 newSliceDims.push_back(d - offset);
1008 }
1009
1010 return SliceAttr::get(getContext(), droppedParent,
1011 DenseI64ArrayAttr::get(getContext(), newSliceDims));
1012}
1013
1014// Derive a new layout by collapsing dimensions.
1015// `dimGroup` specifies a group of adjacent dimensions
1016// that are collapsed into a single dimension in the derived layout.
1017DistributeLayoutAttr SliceAttr::collapseDims(SmallVector<int64_t> dimGroup) {
1018
1019 // Map the sliced dims from parent space to collapsed space
1020 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1021 assert("expect sliceDims not being collapsed" &&
1022 llvm::none_of(dimGroup, [&](int64_t dim) {
1023 return llvm::is_contained(sliceDims, dim);
1024 }));
1025 SmallVector<int64_t> dimsInParentSpace =
1026 mapSlicedDimsToParentSpace(dimGroup, sliceDims);
1027
1028 auto collapsedParent = getParent().collapseDims(dimsInParentSpace);
1029 return SliceAttr::get(getContext(), collapsedParent,
1030 DenseI64ArrayAttr::get(getContext(), sliceDims));
1031}
1032
1034 ArrayRef<int64_t> permutation) {
1035 SmallVector<int64_t> sortedSliceDims = llvm::to_vector(sliceDims);
1036 llvm::sort(sortedSliceDims);
1037
1038 for (size_t i = 1; i < sortedSliceDims.size(); ++i) {
1039 assert((sortedSliceDims[i] == sortedSliceDims[i - 1] + 1) &&
1040 "slice dims non consecutive, cannot be transposed");
1041 }
1042
1043 SmallVector<int64_t> permForParent;
1044 if (sortedSliceDims.front() == 0) {
1045 // Example: sliceDims.size() = 2, permutation= {1, 0}
1046 // result: {3, 2, 1, 0}.
1047 for (int64_t dim : permutation)
1048 permForParent.push_back(dim + sortedSliceDims.size());
1049 for (int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1050 permForParent.push_back(i);
1051 } else {
1052 // Example: sliceDims.size() = 2, permutation = {0, 1}
1053 // result: {3, 2, 0, 1}.
1054 for (int64_t i = sortedSliceDims.size() - 1; i >= 0; --i)
1055 permForParent.push_back(i + permutation.size());
1056 for (int64_t dim : permutation)
1057 permForParent.push_back(dim);
1058 }
1059 return permForParent;
1060}
1061
1062// Derive a new layout by transpose the layout using `permutation`.
1063DistributeLayoutAttr SliceAttr::transposeDims(ArrayRef<int64_t> permutation) {
1064 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1065 DistributeLayoutAttr parent = getParent();
1066 SmallVector<int64_t> permForParent =
1067 getPermForParentLayout(sliceDims, permutation);
1068 auto transposedParent = parent.transposeDims(permForParent);
1069 return SliceAttr::get(getContext(), transposedParent,
1070 DenseI64ArrayAttr::get(getContext(), sliceDims));
1071}
1072
1073/// Check if this layout is a transpose of another layout.
1074bool SliceAttr::isTransposeOf(const xegpu::DistributeLayoutAttr &other,
1075 ArrayRef<int64_t> perm,
1076 const xegpu::LayoutKind kind) {
1077 // other must be a SliceAttr with the same slice dims.
1078 auto otherSlice = dyn_cast<xegpu::SliceAttr>(other);
1079 if (!otherSlice || getDims() != otherSlice.getDims())
1080 return false;
1081 // check whether the parent layout is transpose of each other.
1082 SmallVector<int64_t> sliceDims = llvm::to_vector(getDims().asArrayRef());
1083 DistributeLayoutAttr parent = getParent();
1084 SmallVector<int64_t> permForParent = getPermForParentLayout(sliceDims, perm);
1085 auto otherParent = otherSlice.getParent();
1086 return parent.isTransposeOf(otherParent, permForParent, kind);
1087}
1088
1089//===----------------------------------------------------------------------===//
1090// XeGPU_RangeAttr
1091//===----------------------------------------------------------------------===//
1092
1093LogicalResult
1094RangeAttr::verify(llvm::function_ref<mlir::InFlightDiagnostic()> emitError,
1095 IntegerAttr startOfRange, IntegerAttr endOfRange) {
1096 if (startOfRange.getInt() >= endOfRange.getInt())
1097 return emitError() << "'end' : " << endOfRange.getInt()
1098 << " must be greater than 'start' : "
1099 << startOfRange.getInt();
1100
1101 return success();
1102}
1103
1104//===----------------------------------------------------------------------===//
1105// XeGPU_TensorDescType
1106//===----------------------------------------------------------------------===//
1107
1108mlir::Type TensorDescType::parse(AsmParser &parser) {
1109 llvm::SmallVector<int64_t> shape;
1110 mlir::Type elementType;
1111 mlir::FailureOr<mlir::Attribute> encoding;
1112 mlir::FailureOr<mlir::Attribute> layout;
1113
1114 // Parse literal '<'
1115 if (parser.parseLess())
1116 return {};
1117
1118 auto shapeLoc = parser.getCurrentLocation();
1119 if (mlir::failed(parser.parseDimensionList(shape))) {
1120 parser.emitError(shapeLoc, "failed to parse parameter 'shape'");
1121 return {};
1122 }
1123
1124 auto elemTypeLoc = parser.getCurrentLocation();
1125 if (mlir::failed(parser.parseType(elementType))) {
1126 parser.emitError(elemTypeLoc, "failed to parse parameter 'elementType'");
1127 return {};
1128 }
1129
1130 // parse optional attributes
1131 while (mlir::succeeded(parser.parseOptionalComma())) {
1132 mlir::Attribute attr;
1133 ParseResult res = parser.parseAttribute(attr);
1134 if (mlir::succeeded(res)) {
1135 if (mlir::isa<LayoutAttr>(attr)) {
1136 layout = attr;
1137 continue;
1138 }
1139 if (mlir::isa<BlockTensorDescAttr, ScatterTensorDescAttr>(attr)) {
1140 encoding = attr;
1141 continue;
1142 }
1143 }
1144 return {};
1145 }
1146
1147 // Parse literal '>'
1148 if (parser.parseGreater())
1149 return {};
1150
1151 MLIRContext *ctxt = parser.getContext();
1152 return TensorDescType::getChecked(
1153 [&]() { return parser.emitError(parser.getNameLoc()); }, ctxt, shape,
1154 elementType, encoding.value_or(BlockTensorDescAttr::get(ctxt)),
1155 layout.value_or(mlir::Attribute()));
1156}
1157
1158void TensorDescType::print(AsmPrinter &printer) const {
1159 printer << "<";
1160
1161 auto shape = getShape();
1162 for (int64_t dim : shape) {
1163 if (mlir::ShapedType::isDynamic(dim))
1164 printer << '?';
1165 else
1166 printer << dim;
1167 printer << 'x';
1168 }
1169
1170 printer << getElementType();
1171
1172 auto encoding = getEncoding();
1173 auto blockAttr = llvm::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1174 if (encoding && (!blockAttr || !blockAttr.hasDefaultsOnly()))
1175 printer << ", " << encoding;
1176
1177 if (auto layout = getLayout())
1178 printer << ", " << layout;
1179
1180 printer << ">";
1181}
1182
1183TensorDescType TensorDescType::get(llvm::ArrayRef<int64_t> shape,
1184 mlir::Type elementType, int array_length,
1185 bool boundary_check,
1186 MemorySpace memory_space,
1187 mlir::Attribute layout) {
1188 auto *context = elementType.getContext();
1189 auto attr = BlockTensorDescAttr::get(context, memory_space, array_length,
1190 boundary_check);
1191 return Base::get(context, shape, elementType, attr, layout);
1192}
1193
1194TensorDescType TensorDescType::get(llvm::ArrayRef<int64_t> shape,
1195 mlir::Type elementType, int chunk_size,
1196 MemorySpace memory_space,
1197 mlir::Attribute layout) {
1198 auto *context = elementType.getContext();
1199 auto attr = ScatterTensorDescAttr::get(context, memory_space, chunk_size);
1200 return Base::get(context, shape, elementType, attr, layout);
1201}
1202
1203LogicalResult
1204TensorDescType::verify(llvm::function_ref<InFlightDiagnostic()> emitError,
1205 llvm::ArrayRef<int64_t> shape, mlir::Type elementType,
1206 mlir::Attribute encoding, mlir::Attribute layout) {
1207 size_t rank = shape.size();
1208
1209 if (rank == 0)
1210 return emitError() << "expected non-zero rank tensor";
1211
1212 auto blockAttr = mlir::dyn_cast_if_present<BlockTensorDescAttr>(encoding);
1213 if (blockAttr) {
1214 MemorySpaceAttr memorySpaceAttr = blockAttr.getMemorySpace();
1215 if (rank > 1 && memorySpaceAttr &&
1216 memorySpaceAttr.getValue() == MemorySpace::SLM)
1217 return emitError() << "SLM is only supported for 1D block tensor";
1218 }
1219
1220 if (!elementType.isIntOrFloat())
1221 return emitError() << "unsupported element type " << elementType
1222 << ": expected integer or float";
1223
1224 // for gather and scatter ops, Low-precision types are packed in 32-bit
1225 // units.
1226 unsigned bitWidth = elementType.getIntOrFloatBitWidth();
1227 int chunkAlignmentFactor =
1230 : 1;
1231 auto scatterAttr = mlir::dyn_cast_if_present<ScatterTensorDescAttr>(encoding);
1232 if (scatterAttr) {
1233 int64_t chunkSize = scatterAttr.getChunkSizeAsInt();
1234 if (rank == 1 && chunkSize != 1)
1235 return emitError() << "expected non-contiguous elements for 1D tensor";
1236
1237 // If chunk size > 1, the second dimension of the tensor shape must be
1238 // equal to chunk size and it must be a multiple of the
1239 // chunkAlignmentFactor.
1240 if (chunkSize > 1) {
1241 if (shape.back() != chunkSize)
1242 return emitError() << "expected last dim of tensor to match chunk size";
1243 if (shape.back() % chunkAlignmentFactor != 0)
1244 return emitError() << "expected last dim of tensor to be a multiple of "
1245 << chunkAlignmentFactor;
1246 }
1247 }
1248
1249 auto layoutAttr = llvm::dyn_cast_if_present<LayoutAttr>(layout);
1250 if (layoutAttr) {
1251 if (rank != (size_t)layoutAttr.getRank())
1252 return emitError() << "expected layout rank to match tensor rank";
1253
1254 auto laneData = layoutAttr.getLaneData();
1255 if (scatterAttr && laneData) {
1256 // Validate subgroup mapping rules for scattered tensors.
1257 // if chunkSize > 1, the last dimension of the tensor should
1258 // be distributed in the units divisible by chunkAlignmentFactor.
1259 int64_t chunkSize = scatterAttr.getChunkSizeAsInt();
1260 if (chunkSize > 1 && laneData[rank - 1] % chunkAlignmentFactor)
1261 return emitError()
1262 << "expected last dim of lane_data to be a multiple of: "
1263 << chunkAlignmentFactor;
1264 }
1265
1266 if (!XeGPUDialect::isEvenlyDistributable(shape, layoutAttr)) {
1267 std::string shapeStr;
1268 llvm::raw_string_ostream stream(shapeStr);
1269 llvm::interleaveComma(shape, stream);
1270 return emitError() << "cannot distribute [" << shapeStr << "] using "
1271 << layoutAttr;
1272 }
1273 }
1274 return success();
1275}
1276
1277//===----------------------------------------------------------------------===//
1278// XeGPU_MemDescType
1279//===----------------------------------------------------------------------===//
1280mlir::Type MemDescType::parse(AsmParser &parser) {
1281 llvm::SmallVector<int64_t> shape;
1282 mlir::Type elementType;
1283 mlir::FailureOr<MemLayoutAttr> layout;
1284
1285 // Parse literal '<'
1286 if (parser.parseLess())
1287 return {};
1288
1289 auto shapeLoc = parser.getCurrentLocation();
1290 if (mlir::failed(parser.parseDimensionList(shape, false, true))) {
1291 parser.emitError(shapeLoc, "failed to parse parameter 'shape'");
1292 return {};
1293 }
1294
1295 auto elemTypeLoc = parser.getCurrentLocation();
1296 if (mlir::failed(parser.parseType(elementType))) {
1297 parser.emitError(elemTypeLoc, "failed to parse parameter 'elementType'");
1298 return {};
1299 }
1300
1301 // parse optional attributes
1302 if (mlir::succeeded(parser.parseOptionalComma())) {
1303 MemLayoutAttr attr;
1304 ParseResult res = parser.parseAttribute(attr);
1305 if (mlir::failed(res))
1306 return {};
1307 layout = attr;
1308 }
1309
1310 // Parse literal '>'
1311 if (parser.parseGreater())
1312 return {};
1313
1314 MLIRContext *ctxt = parser.getContext();
1315 return MemDescType::getChecked(
1316 [&]() { return parser.emitError(parser.getNameLoc()); }, ctxt, shape,
1317 elementType, layout.value_or(MemLayoutAttr()));
1318}
1319
1320void MemDescType::print(AsmPrinter &printer) const {
1321 printer << "<";
1322
1323 printer.printDimensionList(getShape());
1324 printer << 'x';
1325 printer << getElementType();
1326
1327 if (auto layout = getMemLayout())
1328 printer << ", " << layout;
1329
1330 printer << ">";
1331}
1332
1333//===----------------------------------------------------------------------===//
1334// XeGPU_MemDescType
1335//===----------------------------------------------------------------------===//
1336
1337Attribute MemLayoutAttr::parse(AsmParser &parser, Type type) {
1338
1339 auto *context = parser.getContext();
1340 llvm::SMLoc loc = parser.getCurrentLocation();
1341
1342 llvm::SmallDenseSet<StringRef> seenKeys;
1343 SmallVector<NamedAttribute> attributes;
1344
1345 auto parseElt = [&]() -> ParseResult {
1346 StringRef nameId;
1347 if (failed(parser.parseKeyword(&nameId)))
1348 return parser.emitError(loc, "expected valid attribute name");
1349
1350 if (!seenKeys.insert(nameId).second)
1351 return parser.emitError(loc, "duplicate key '")
1352 << nameId << " in mem layout attribute";
1353
1354 if (failed(parser.parseEqual()))
1355 return failure();
1356
1357 Attribute attr;
1358 if (failed(parser.parseAttribute(attr)))
1359 return failure();
1360 attributes.emplace_back(nameId, attr);
1361 return success();
1362 };
1363
1364 // Parse literal '<'
1365 if (parser.parseLess())
1366 return {};
1367
1368 if (failed(parser.parseCommaSeparatedList(parseElt)))
1369 return {};
1370
1371 // Parse literal '>'
1372 if (parser.parseGreater())
1373 return {};
1374
1375 return parser.getChecked<MemLayoutAttr>(
1376 loc, context, DictionaryAttr::get(context, attributes));
1377}
1378
1379void MemLayoutAttr::print(AsmPrinter &printer) const {
1380 printer << "<";
1381 ArrayRef<NamedAttribute> attrs = getAttrs().getValue();
1382 for (size_t i = 0; i < attrs.size(); i++) {
1383 printer << attrs[i].getName().str() << " = " << attrs[i].getValue();
1384 if (i < attrs.size() - 1)
1385 printer << ", ";
1386 }
1387 printer << ">";
1388}
1389// a helper utility to perform binary operation on OpFoldResult.
1390// If both a and b are attributes, it will simply return the result.
1391// Otherwise, the corresponding arith op will be generated, and an
1392// contant op will be created if one of them is an attribute.
1393template <typename ArithOp>
1395 OpBuilder &builder) {
1396 auto aVal = getValueOrCreateConstantIndexOp(builder, loc, a);
1397 auto bVal = getValueOrCreateConstantIndexOp(builder, loc, b);
1398 return ArithOp::create(builder, loc, aVal, bVal).getResult();
1399}
1400
1401// a helper utility to perform division operation on OpFoldResult and int64_t.
1402#define div(a, b) \
1403 genBinOp<arith::DivSIOp>(a, builder.getIndexAttr(b), loc, builder)
1404
1405// a helper utility to perform reminder operation on OpFoldResult and int64_t.
1406#define rem(a, b) \
1407 genBinOp<arith::RemSIOp>(a, builder.getIndexAttr(b), loc, builder)
1408
1409// a helper utility to perform multiply operation on OpFoldResult and int64_t.
1410#define mul(a, b) \
1411 genBinOp<arith::MulIOp>(a, builder.getIndexAttr(b), loc, builder)
1412
1413// a helper utility to perform addition operation on two OpFoldResult.
1414#define add(a, b) genBinOp<arith::AddIOp>(a, b, loc, builder)
1415
1416// block the given offsets according to the block shape
1417// say the original offset is [y, x], and the block shape is [By, Bx],
1418// then the blocked offset is [y/By, x/Bx, y%By, x%Bx]
1420 ArrayRef<OpFoldResult> offsets,
1421 ArrayRef<int64_t> blockShape) {
1422
1423 assert(offsets.size() == blockShape.size() &&
1424 "offsets and blockShape must have the same size");
1425 SmallVector<OpFoldResult> blockedOffsets;
1426 SmallVector<OpFoldResult> divs, rems;
1427
1428 for (auto [offset, block] : llvm::zip(offsets, blockShape)) {
1429 divs.push_back(div(offset, block));
1430 rems.push_back(rem(offset, block));
1431 }
1432 blockedOffsets.append(divs.begin(), divs.end());
1433 blockedOffsets.append(rems.begin(), rems.end());
1434
1435 return blockedOffsets;
1436}
1437
1438// Get strides as vector of integer for MemDesc.
1439SmallVector<int64_t> MemDescType::getStrideShape() {
1440
1441 SmallVector<int64_t> matrixShape(getShape().begin(), getShape().end());
1442
1443 ArrayAttr strideAttr = getStrideAttr();
1444 SmallVector<int64_t> strides;
1445 for (Attribute attr : strideAttr.getValue()) {
1446 strides.push_back(cast<IntegerAttr>(attr).getInt());
1447 }
1448
1449 SmallVector<int64_t> innerBlkShape = getBlockShape();
1450
1451 // get perm from FCD to LCD
1452 // perm[i] = the dim with i-th smallest stride
1453 SmallVector<int, 4> perm =
1454 llvm::to_vector<4>(llvm::seq<int>(0, strides.size()));
1455 llvm::sort(perm, [&](int a, int b) { return strides[a] < strides[b]; });
1456
1457 assert(strides[perm[0]] == 1 && "inner most dim must have stride 1");
1458
1459 SmallVector<int64_t> innerBlkStride(innerBlkShape.size());
1460 innerBlkStride[perm[0]] = 1;
1461 for (size_t i = 1; i < perm.size(); ++i)
1462 innerBlkStride[perm[i]] =
1463 innerBlkStride[perm[i - 1]] * innerBlkShape[perm[i - 1]];
1464
1465 // compute the original matrix shape using the stride info
1466 // and compute the number of blocks in each dimension
1467 // The shape of highest dim can't be derived from stride info,
1468 // but doesn't impact the stride computation for blocked layout.
1469 SmallVector<int64_t> matrixShapeOrig(matrixShape.size());
1470 SmallVector<int64_t> BlkShapeOrig(matrixShape.size());
1471 for (size_t i = 0; i < perm.size() - 1; ++i) {
1472 matrixShapeOrig[perm[i]] = strides[perm[i + 1]] / strides[perm[i]];
1473 BlkShapeOrig[perm[i]] = matrixShapeOrig[perm[i]] / innerBlkShape[perm[i]];
1474 }
1475
1476 int64_t innerBlkSize = 1;
1477 for (auto s : innerBlkShape)
1478 innerBlkSize *= s;
1479
1480 SmallVector<int64_t> outerBlkStride(matrixShape.size());
1481 outerBlkStride[perm[0]] = innerBlkSize;
1482 for (size_t i = 0; i < perm.size() - 1; ++i) {
1483 outerBlkStride[perm[i + 1]] =
1484 outerBlkStride[perm[i]] * BlkShapeOrig[perm[i]];
1485 }
1486
1487 // combine the inner and outer strides
1488 SmallVector<int64_t> blockedStrides;
1489 blockedStrides.append(outerBlkStride.begin(), outerBlkStride.end());
1490 blockedStrides.append(innerBlkStride.begin(), innerBlkStride.end());
1491
1492 return blockedStrides;
1493}
1494
1495// Calculate the linear offset using the blocked offsets and stride
1496Value MemDescType::getLinearOffsets(OpBuilder &builder, Location loc,
1497 ArrayRef<OpFoldResult> offsets) {
1498
1499 SmallVector<int64_t> matrixShape(getShape().begin(), getShape().end());
1500 SmallVector<int64_t> blockShape = getBlockShape();
1501 SmallVector<int64_t> strides = getStrideShape();
1502 SmallVector<OpFoldResult> blockedOffsets;
1503
1504 // blockshape equal to matrixshape means no blocking
1505 if (llvm::equal(blockShape, matrixShape)) {
1506 // remove the outer dims from strides
1507 strides.erase(strides.begin(), strides.begin() + matrixShape.size());
1508 } else {
1509 assert(offsets.size() == blockShape.size() &&
1510 "offsets and blockShape must have the same size");
1511 // say the original offset is [y, x], and the block shape is [By, Bx],
1512 // then the blocked offset is [y/By, x/Bx, y%By, x%Bx]
1513
1514 SmallVector<OpFoldResult> divs, rems;
1515
1516 for (auto [offset, block] : llvm::zip(offsets, blockShape)) {
1517 divs.push_back(div(offset, block));
1518 rems.push_back(rem(offset, block));
1519 }
1520 blockedOffsets.append(divs.begin(), divs.end());
1521 blockedOffsets.append(rems.begin(), rems.end());
1522 offsets = blockedOffsets;
1523 }
1524
1525 // Start with initial value as matrix descriptor's base offset.
1526 Value linearOffset = arith::ConstantIndexOp::create(builder, loc, 0);
1527 for (size_t i = 0; i < offsets.size(); ++i) {
1528 OpFoldResult mulResult = mul(offsets[i], strides[i]);
1529 Value mulVal = getValueOrCreateConstantIndexOp(builder, loc, mulResult);
1530 linearOffset = arith::AddIOp::create(builder, loc, mulVal, linearOffset);
1531 }
1532
1533 return linearOffset;
1534}
1535
1536} // namespace xegpu
1537} // namespace mlir
1538
1539#include <mlir/Dialect/XeGPU/IR/XeGPUDialect.cpp.inc>
1540#define GET_ATTRDEF_CLASSES
1541#include <mlir/Dialect/XeGPU/IR/XeGPUAttrs.cpp.inc>
1542#define GET_TYPEDEF_CLASSES
1543#include <mlir/Dialect/XeGPU/IR/XeGPUTypes.cpp.inc>
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...
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)
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseDimensionList(SmallVectorImpl< int64_t > &dimensions, bool allowDynamic=true, bool withTrailingX=true)=0
Parse a dimension list of a tensor or memref type.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
auto getChecked(SMLoc loc, ParamsT &&...params)
Invoke the getChecked method of the given Attribute or Type class, using the provided location to emi...
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
void printDimensionList(ArrayRef< int64_t > shape)
Attributes are known-constant values of operations.
Definition Attributes.h:25
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
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
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
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:113
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:363
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.
constexpr unsigned generalPackedFormatBitSize
Definition uArchBase.h:32
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 SmallVector< SmallVector< Value > > genCoordinates(OpBuilder &builder, Location loc, SmallVector< Value > delinearizedId, ArrayRef< int64_t > subShapesLayout, ArrayRef< int64_t > subShape, ArrayRef< int64_t > srcShape)
SmallVector< int64_t > getPermForParentLayout(ArrayRef< int64_t > sliceDims, ArrayRef< int64_t > permutation)
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
SmallVector< int64_t > computeElementwiseMul(ArrayRef< int64_t > v1, ArrayRef< int64_t > v2)
Return a vector containing llvm::zip_equal(v1, v2) multiplied elementwise.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:112
std::optional< SmallVector< int64_t > > computeShapeRatio(ArrayRef< int64_t > shape, ArrayRef< int64_t > subShape)
Return the multi-dimensional integral ratio of subShape to the trailing dimensions of shape.
bool isPermutationVector(ArrayRef< int64_t > interchange)
Method to check if an interchange vector is a permutation.