MLIR 24.0.0git
XeGPUSgToLaneDistribute.cpp
Go to the documentation of this file.
1//===- XeGPUSgToLaneDistribute.cpp - XeGPU SG to Lane Pass ----------------===//
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//===----------------------------------------------------------------------===//
21#include "mlir/IR/Builders.h"
23#include "mlir/IR/BuiltinOps.h"
25#include "mlir/IR/MLIRContext.h"
26#include "mlir/IR/Operation.h"
27#include "mlir/IR/Value.h"
28#include "mlir/IR/ValueRange.h"
30#include "llvm/ADT/SetVector.h"
31#include "llvm/Support/LogicalResult.h"
32#include "llvm/Support/raw_ostream.h"
33#include <optional>
34
35namespace mlir {
36namespace xegpu {
37#define GEN_PASS_DEF_XEGPUSGTOLANEDISTRIBUTE
38#include "mlir/Dialect/XeGPU/Transforms/Passes.h.inc"
39} // namespace xegpu
40} // namespace mlir
41
42using namespace mlir;
43
44#define DEBUG_TYPE "xegpu-sg-to-lane-distribute"
45#define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE "]: ")
46
47namespace {
48
49/// Casts the given vector value `v` to the expected vector type `expectedTy`.
50static Value castValueTo(ConversionPatternRewriter &rewriter,
51 TypedValue<VectorType> v, VectorType expectedTy) {
52 // If the type matches, simply return the value itself.
53 if (v.getType() == expectedTy)
54 return v;
55 // If only shape differs, use shape cast.
56 if (isa<VectorType>(v.getType()) &&
57 v.getType().getNumElements() == expectedTy.getNumElements())
58 return vector::ShapeCastOp::create(rewriter, v.getLoc(), expectedTy, v);
59
60 // Else create an unrealized cast.
61 auto newOp = UnrealizedConversionCastOp::create(rewriter, v.getLoc(),
62 expectedTy, ValueRange{v});
63 return newOp.getResult(0);
64}
65
66/// A vector::MultiDimReductionOp at subgroup level in expected form if, it has
67/// exactly 1 reduction dimension, it had valid result layout attribute, and
68/// result type can be distributed to lanes using the layout.
69static bool isValidSubgroupMultiReductionOp(vector::MultiDimReductionOp op) {
70 auto resLayout = xegpu::getTemporaryLayout(op->getOpResult(0));
71 // If no layout, not valid.
72 if (!resLayout || !resLayout.isForSubgroup())
73 return false;
74 // Scalar result (e.g., vector<32xf32> to f32) is valid.
75 if (op.getType().isIntOrFloat())
76 return op.getReductionDims().size() == 1;
77 VectorType resTy = dyn_cast<VectorType>(op.getType());
78 if (!resTy)
79 return false;
80 // Compute the distributed result vector type based on the layout.
81 FailureOr<VectorType> resDistTypeOrFailure =
82 getDistVecTypeBasedOnLaneLayout(resLayout, resTy);
83 if (failed(resDistTypeOrFailure))
84 return false;
85 return op.getReductionDims().size() == 1;
86}
87
88/// A vector::MultiDimReductionOp reduces lane-locally when no data is combined
89/// across lanes, which holds exactly when the source's lane_layout along the
90/// reduction dimension is 1: every reduced element then lives in one lane.
91static bool isReductionLaneLocal(vector::MultiDimReductionOp op) {
92 // Must be valid MultiDimReductionOp.
93 assert(isValidSubgroupMultiReductionOp(op) && "Expecting a valid subgroup "
94 "MultiDimReductionOp");
95 auto srcLayout = xegpu::getTemporaryLayout(op->getOpOperand(0));
96 ArrayRef<int64_t> reductionDims = op.getReductionDims();
97 assert(reductionDims.size() == 1 &&
98 "Expecting single reduction dimension for subgroup multi "
99 "reduction op");
100 int64_t reductionDim = reductionDims[0];
101 SmallVector<int64_t> srcLaneLayout = srcLayout.getEffectiveLaneLayoutAsInt();
102 assert(reductionDim < static_cast<int64_t>(srcLaneLayout.size()) &&
103 "Expecting a source lane_layout covering the reduction dimension");
104 return srcLaneLayout[reductionDim] == 1;
105}
106
107/// Given a vector type and its distributed vector type, return the list of
108/// dimensions that are distributed.
109static SmallVector<int64_t> getDistributedDims(VectorType originalType,
110 VectorType distributedType) {
111 assert(originalType.getRank() == distributedType.getRank() &&
112 "original and distributed vector types must have the same rank");
113 SmallVector<int64_t> distributedDims;
114 for (int64_t i = 0; i < originalType.getRank(); ++i) {
115 if (distributedType.getDimSize(i) != originalType.getDimSize(i))
116 distributedDims.push_back(i);
117 }
118 return distributedDims;
119}
120
121/// Distributes a subgroup-level CreateNdDesc op to lane-level CreateNdDesc
122/// op. This simply drops the layout attribute from the tensor descriptor type.
123struct SgToLaneCreateNdDesc
124 : public OpConversionPattern<xegpu::CreateNdDescOp> {
125 using OpConversionPattern<xegpu::CreateNdDescOp>::OpConversionPattern;
126
127 LogicalResult
128 matchAndRewrite(xegpu::CreateNdDescOp op, OpAdaptor adaptor,
129 ConversionPatternRewriter &rewriter) const override {
130 xegpu::TensorDescType resultType = op.getType();
131 // If no layout, nothing to do.
132 if (!resultType.getLayout())
133 return failure();
134
135 auto newOp = xegpu::CreateNdDescOp::create(
136 rewriter, op.getLoc(), TypeRange{resultType.dropLayouts()},
137 op.getOperands(), op.getProperties(),
138 op->getDiscardableAttrDictionary().getValue());
139 rewriter.replaceOp(op, newOp.getResult());
140 return success();
141 }
142};
143
144/// Distributes a subgroup-level LoadNd op to lane-level LoadNd op. Output
145/// of lane-level LoadNd op is 1D. ShapeCast is added to restore the
146/// original rank.
147struct SgToLaneLoadNd : public OpConversionPattern<xegpu::LoadNdOp> {
148 using OpConversionPattern<xegpu::LoadNdOp>::OpConversionPattern;
149
150 LogicalResult
151 matchAndRewrite(xegpu::LoadNdOp op, OpAdaptor adaptor,
152 ConversionPatternRewriter &rewriter) const override {
153 xegpu::DistributeLayoutAttr layout = op.getAnchorLayout();
154 // If no layout, nothing to do.
155 if (!layout)
156 return failure();
157 // Check if the layout attached to the tensor descriptor is same as the
158 // anchor layout. Otherwise, this is a conflict.
159 if (op.getTensorDescType().getLayout() != layout)
160 return rewriter.notifyMatchFailure(
161 op, "conflicting layout attributes on tensor descriptor and anchor");
162 const auto *uArch =
164 if (!uArch)
165 return rewriter.notifyMatchFailure(
166 op, "xegpu::LoadNdOp require target attribute attached to "
167 "determine transpose "
168 "requirement");
169 auto supportedLaneResultTyOrFailure =
170 xegpu::getDistributedVectorType(op.getTensorDescType());
171 auto expectedLaneResultTyOrFailure =
172 xegpu::getDistVecTypeBasedOnLaneLayout(layout, op.getType());
173 if (failed(supportedLaneResultTyOrFailure))
174 return rewriter.notifyMatchFailure(
175 op, "unable to compute the lane vector type for LoadNdOp");
176 if (failed(expectedLaneResultTyOrFailure))
177 return rewriter.notifyMatchFailure(
178 op, "unable to compute expected lane vector type from lane layout");
179 auto newOp = xegpu::LoadNdOp::create(
180 rewriter, op.getLoc(), supportedLaneResultTyOrFailure.value(),
181 adaptor.getTensorDesc(), op.getMixedOffsets(), op.getPackedAttr(),
182 op.getTransposeAttr(), op.getL1HintAttr(), op.getL2HintAttr(),
183 op.getL3HintAttr(), /**layout**/ nullptr);
184 // Set the packed attribute if the layout requires it.
185 newOp.setPacked(xegpu::requirePacked(cast<xegpu::LayoutAttr>(layout)));
186 // Set the transpose attribute if the layout requires it.
187 if (xegpu::requireTranspose(cast<xegpu::LayoutAttr>(layout), uArch))
188 newOp.setTranspose(DenseI64ArrayAttr::get(rewriter.getContext(), {1, 0}));
189 rewriter.replaceOp(op, castValueTo(rewriter, newOp.getResult(),
190 expectedLaneResultTyOrFailure.value()));
191 return success();
192 }
193};
194
195/// Distributes a subgroup-level StoreNd op to lane-level StoreNd op. Stored
196/// value in lane-level StoreNd op is 1D. ShapeCast is added to cast the
197/// incoming value to 1D.
198struct SgToLaneStoreNd : public OpConversionPattern<xegpu::StoreNdOp> {
199 using OpConversionPattern<xegpu::StoreNdOp>::OpConversionPattern;
200
201 LogicalResult
202 matchAndRewrite(xegpu::StoreNdOp op, OpAdaptor adaptor,
203 ConversionPatternRewriter &rewriter) const override {
204 xegpu::DistributeLayoutAttr layout = op.getAnchorLayout();
205 // If no layout, nothing to do.
206 if (!layout)
207 return failure();
208 // Check if the layout attached to the tensor descriptor and value layout is
209 // same as the anchor layout. Otherwise, this is a conflict.
210 if (op.getTensorDescType().getLayout() != layout)
211 return rewriter.notifyMatchFailure(
212 op, "conflicting layout attributes on tensor descriptor and anchor");
213 auto valueLayout = xegpu::getDistributeLayoutAttr(op->getOpOperand(0));
214 if (valueLayout != layout)
215 return rewriter.notifyMatchFailure(
216 op, "conflicting layout attributes on value and anchor");
217 auto supportedLaneValueTyOrFailure =
218 xegpu::getDistributedVectorType(op.getTensorDescType());
219 if (failed(supportedLaneValueTyOrFailure))
220 return rewriter.notifyMatchFailure(
221 op,
222 "unable to compute lane vector type for StoreNdOp value from tensor "
223 "descriptor");
224
225 xegpu::StoreNdOp::create(
226 rewriter, op.getLoc(),
227 castValueTo(rewriter, cast<TypedValue<VectorType>>(adaptor.getValue()),
228 supportedLaneValueTyOrFailure.value()),
229 adaptor.getTensorDesc(), op.getMixedOffsets(), op.getL1HintAttr(),
230 op.getL2HintAttr(), op.getL3HintAttr(), /**layout**/ nullptr);
231 rewriter.eraseOp(op);
232 return success();
233 }
234};
235
236/// Distributes a subgroup-level Dpas op to lane-level Dpas op. All inpputs
237/// and output of lane-level Dpas op are 1D. Necessary casts are added to
238/// convert the inputs and output to/from 1D.
239struct SgToLaneDpas : public OpConversionPattern<xegpu::DpasOp> {
240 using OpConversionPattern<xegpu::DpasOp>::OpConversionPattern;
241
242 LogicalResult
243 matchAndRewrite(xegpu::DpasOp op, OpAdaptor adaptor,
244 ConversionPatternRewriter &rewriter) const override {
245 // Check if the op has A, B and CD layouts attached.
246 auto layoutA = cast<xegpu::LayoutAttr>(op.getLayoutAAttr());
247 auto layoutB = cast<xegpu::LayoutAttr>(op.getLayoutBAttr());
248 auto layoutCd = cast<xegpu::LayoutAttr>(op.getLayoutCdAttr());
249 if (!layoutA || !layoutB || !layoutCd)
250 return failure();
251 auto laneResultTyOrFailure =
252 xegpu::getDistributedVectorType(op.getType(), layoutCd);
253 auto laneATypeOrFailure =
254 xegpu::getDistributedVectorType(op.getLhs().getType(), layoutA);
255 auto laneBTypeOrFailure =
256 xegpu::getDistributedVectorType(op.getRhs().getType(), layoutB);
257 auto expectedLaneResultTyOrFailure =
258 xegpu::getDistVecTypeBasedOnLaneLayout(layoutCd, op.getType());
259 if (failed(laneResultTyOrFailure) || failed(laneATypeOrFailure) ||
260 failed(laneBTypeOrFailure))
261 return rewriter.notifyMatchFailure(
262 op, "failed to calculate supported lane vector types for DpasOp "
263 "from layouts");
264 if (failed(expectedLaneResultTyOrFailure))
265 return rewriter.notifyMatchFailure(
266 op, "unable to compute expected lane vector type for DpasOp from "
267 "lane layout");
268
269 // Validate bit widths match uArch packed format requirements
270 const auto *uArch =
272 if (uArch) {
273 const auto *uArchInstruction =
274 dyn_cast<xegpu::uArch::SubgroupMatrixMultiplyAcc>(
275 uArch->getInstruction(
277 if (uArchInstruction) {
278 auto laneAType = laneATypeOrFailure.value();
279 auto laneBType = laneBTypeOrFailure.value();
280 // Calculate total packed bit width = element bit width * vector size
281 unsigned aPackedBitWidth =
282 laneAType.getElementTypeBitWidth() * laneAType.getNumElements();
283 unsigned bPackedBitWidth =
284 laneBType.getElementTypeBitWidth() * laneBType.getNumElements();
285 unsigned expectedABitSize = uArchInstruction->getPackedFormatBitSizeA();
286 unsigned expectedBBitSize = uArchInstruction->getPackedFormatBitSizeB();
287
288 if (aPackedBitWidth % expectedABitSize != 0)
289 return rewriter.notifyMatchFailure(
290 op,
291 "A operand packed bit width must be a multiple of uArch packed "
292 "format requirement");
293 if (bPackedBitWidth % expectedBBitSize != 0)
294 return rewriter.notifyMatchFailure(
295 op,
296 "B operand packed bit width must be a multiple of uArch packed "
297 "format requirement");
298 }
299 }
300
301 auto newOp = xegpu::DpasOp::create(
302 rewriter, op->getLoc(), laneResultTyOrFailure.value(),
303 castValueTo(rewriter, cast<TypedValue<VectorType>>(adaptor.getLhs()),
304 laneATypeOrFailure.value()),
305 castValueTo(rewriter, cast<TypedValue<VectorType>>(adaptor.getRhs()),
306 laneBTypeOrFailure.value()),
307 castValueTo(rewriter, cast<TypedValue<VectorType>>(adaptor.getAcc()),
308 laneResultTyOrFailure.value()),
309 /** layoutA**/ nullptr,
310 /** layoutB**/ nullptr, /** layoutCd**/ nullptr);
311 // Explicitly set the new types to enable correct type materializations.
312 rewriter.replaceOp(op, castValueTo(rewriter, newOp.getResult(),
313 expectedLaneResultTyOrFailure.value()));
314 return success();
318/// Distributes elementwise ops to lane-level elementwise ops. This
319/// currently handles elementwise ops with single result only.
320struct SgToLaneElementWise : public ConversionPattern {
321 SgToLaneElementWise(TypeConverter &typeConverter, MLIRContext *ctx)
322 : ConversionPattern(MatchAnyOpTypeTag(), /*benefit=*/1, ctx) {}
324 LogicalResult
325 matchAndRewrite(Operation *op, ArrayRef<Value> operands,
326 ConversionPatternRewriter &rewriter) const override {
327 // Only match ops with elementwise trait and single result.
329 return failure();
330
331 auto resultType = dyn_cast<VectorType>(op->getResult(0).getType());
332 if (!resultType)
333 return rewriter.notifyMatchFailure(
334 op, "operation result is not a vector type");
335
336 xegpu::DistributeLayoutAttr layout =
337 xegpu::getTemporaryLayout(llvm::cast<OpResult>(op->getResult(0)));
338 if (!layout || !layout.isForSubgroup())
339 return rewriter.notifyMatchFailure(
340 op, "operation result does not have subgroup distribute layout");
341
342 auto laneShapeOrFailure =
343 xegpu::getDistVecTypeBasedOnLaneLayout(layout, resultType);
345 if (failed(laneShapeOrFailure))
346 return rewriter.notifyMatchFailure(
347 op, "unable to compute lane vector type from the layout");
348
349 VectorType newResultType = laneShapeOrFailure.value();
350 OperationState state(op->getLoc(), op->getName());
351 state.addOperands(operands);
352 state.addTypes(newResultType);
353 // Copy all attributes except for DistributeLayoutAttr.
354 for (auto attr : op->getDiscardableAttrDictionary().getValue()) {
355 if (!isa<xegpu::DistributeLayoutAttr>(attr.getValue()))
356 state.addAttribute(attr.getName(), attr.getValue());
357 }
358 state.propertiesAttr = op->getPropertiesAsAttribute();
359 Operation *newOp = rewriter.create(state);
360
361 rewriter.replaceOp(op, newOp->getResult(0));
362 return success();
363 }
365
366/// Distributes a subgroup-level arith ConstantOp to lane-level arith
367/// ConstantOp.
368///
369/// Splat constants are rebuilt with the lane-local vector type. Non-splat
370/// constants are distributed by extracting each lane_data-sized block from
371/// the full constant and inserting it at the correct position in the
372/// distributed vector using insert_strided_slice.
373struct SgToLaneArithConstant : public OpConversionPattern<arith::ConstantOp> {
374 using OpConversionPattern<arith::ConstantOp>::OpConversionPattern;
375
376 LogicalResult
377 matchAndRewrite(arith::ConstantOp op, OpAdaptor adaptor,
378 ConversionPatternRewriter &rewriter) const override {
379 auto resultType = dyn_cast<VectorType>(op.getType());
380 if (!resultType)
381 return failure();
382
383 // Only handle dense vector constants.
384 auto denseAttr = dyn_cast<DenseElementsAttr>(op.getValue());
385 if (!denseAttr)
386 return rewriter.notifyMatchFailure(
387 op, "only dense vector constants are supported");
388
389 xegpu::DistributeLayoutAttr layout =
390 xegpu::getTemporaryLayout(llvm::cast<OpResult>(op.getResult()));
391 if (!layout || !layout.isForSubgroup())
392 return rewriter.notifyMatchFailure(
393 op, "operation result does not have subgroup distribute layout");
394
395 auto laneShapeOrFailure =
396 xegpu::getDistVecTypeBasedOnLaneLayout(layout, resultType);
397
398 if (failed(laneShapeOrFailure))
399 return rewriter.notifyMatchFailure(
400 op, "unable to compute lane vector type from the layout");
401
402 VectorType newResultType = laneShapeOrFailure.value();
403 Location loc = op.getLoc();
404
405 // Splat constants: every lane gets the same value, so just rebuild the
406 // splat with the distributed type.
407 if (denseAttr.isSplat()) {
408 auto scalarValue = denseAttr.getSplatValue<Attribute>();
409 auto newDenseAttr = DenseElementsAttr::get(newResultType, scalarValue);
410 auto newOp =
411 arith::ConstantOp::create(rewriter, loc, newResultType, newDenseAttr);
412 rewriter.replaceOp(op, newOp.getResult());
413 return success();
414 }
415
416 // Non-splat constants: each lane extracts the elements it owns from the
417 // full constant using the distributed coordinates from the layout.
418 auto fullConst =
419 arith::ConstantOp::create(rewriter, loc, resultType, denseAttr);
420
421 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
422 /*upperBound=*/mlir::IntegerAttr());
423 auto maybeCoordsVec = layout.computeDistributedCoords(
424 rewriter, loc, laneId, resultType.getShape());
425 if (failed(maybeCoordsVec))
426 return rewriter.notifyMatchFailure(
427 op, "failed to compute distributed coordinates from layout");
428
429 SmallVector<SmallVector<Value>> coordsVec = maybeCoordsVec.value();
430 SmallVector<int64_t> laneData = layout.getEffectiveLaneDataAsInt();
431 ArrayRef<int64_t> distShape = newResultType.getShape();
432 int64_t rank = newResultType.getRank();
433
434 // Each lane owns one lane_data-sized block per distribution unit.
435 // computeDistributedCoords returns those block starts in row-major order
436 // over the block grid (distShape / laneData).
437 SmallVector<int64_t> blockGridShape(rank);
438 for (int64_t d = 0; d < rank; d++)
439 blockGridShape[d] = distShape[d] / laneData[d];
440 SmallVector<int64_t> blockGridStrides = computeStrides(blockGridShape);
441
442 auto blockType = VectorType::get(laneData, newResultType.getElementType());
443 SmallVector<int64_t> unitTile(rank, 1);
444 SmallVector<int64_t> strides(rank, 1);
445
446 Value result = arith::ConstantOp::create(
447 rewriter, loc, newResultType, rewriter.getZeroAttr(newResultType));
448
449 for (auto [blockIdx, blockStart] : llvm::enumerate(coordsVec)) {
450 // Gather the block's elements from the full constant. The block start is
451 // lane-dynamic, so extract element-by-element (row-major over lane_data)
452 // instead.
453 SmallVector<Value> blockElems;
454 for (SmallVector<int64_t> off :
455 StaticTileOffsetRange(laneData, unitTile)) {
457 for (int64_t d = 0; d < rank; d++)
458 pos[d] = getAsOpFoldResult(arith::AddIOp::create(
459 rewriter, loc, blockStart[d],
460 arith::ConstantIndexOp::create(rewriter, loc, off[d])));
461 blockElems.push_back(vector::ExtractOp::create(
462 rewriter, loc, fullConst.getResult(), pos));
463 }
464
465 // Rebuild the block keeping its lane_data shape, then place it with
466 // insert_strided_slice so the block keeps its orientation in the
467 // distributed vector (e.g. a [2, 1] block stays a vertical 2x1 slice).
468 Value block =
469 vector::FromElementsOp::create(rewriter, loc, blockType, blockElems);
470 SmallVector<int64_t> blockGridPos =
471 delinearize(blockIdx, blockGridStrides);
472 SmallVector<int64_t> offsets(rank);
473 for (int64_t d = 0; d < rank; d++)
474 offsets[d] = blockGridPos[d] * laneData[d];
475 result = vector::InsertStridedSliceOp::create(rewriter, loc, block,
476 result, offsets, strides);
477 }
478
479 rewriter.replaceOp(op, result);
480 return success();
481 }
482};
483
484/// Distributes a subgroup-level PrefetchNd op to lane-level PrefetchNd op.
485struct SgToLanePrefetchNd : public OpConversionPattern<xegpu::PrefetchNdOp> {
486 using OpConversionPattern<xegpu::PrefetchNdOp>::OpConversionPattern;
487
488 LogicalResult
489 matchAndRewrite(xegpu::PrefetchNdOp op, OpAdaptor adaptor,
490 ConversionPatternRewriter &rewriter) const override {
491 xegpu::DistributeLayoutAttr layout = op.getAnchorLayout();
492 // If no layout, nothing to do.
493 if (!layout)
494 return failure();
495
496 xegpu::PrefetchNdOp::create(rewriter, op.getLoc(), adaptor.getTensorDesc(),
497 op.getMixedOffsets(), op.getL1HintAttr(),
498 op.getL2HintAttr(), op.getL3HintAttr(),
499 /**layout**/ nullptr);
500 rewriter.eraseOp(op);
501 return success();
502 }
503};
504
505/// Distributes a subgroup-level LoadGather (xegpu.load) op to lane-level.
506///
507/// Example 1 (1D):
508/// layout = #xegpu.layout<lane_layout = [16], lane_data = [1]>
509/// %mask = producer_op : vector<16xi1>
510/// %offset = producer_op : vector<16xindex>
511/// %0 = xegpu.load %src[%offset], %mask : memref<256xf16>,
512/// vector<16xindex>, vector<16xi1> -> vector<16xf16>
513/// Distributed to:
514/// %mask = producer_op : vector<1xi1>
515/// %offset = producer_op : vector<1xindex>
516/// %0 = xegpu.load %src[%offset], %mask : memref<256xf16>,
517/// vector<1xindex>, vector<1xi1> -> vector<1xf16>
518///
519/// Example 2 (3D with leading unit dims):
520/// layout = #xegpu.layout<lane_layout = [1, 1, 16], lane_data = [1, 1, 1]>
521/// %mask = producer_op : vector<1x1x16xi1>
522/// %offset = producer_op : vector<1x1x16xindex>
523/// %0 = xegpu.load %src[%offset], %mask : memref<256xf16>,
524/// vector<1x1x16xindex>, vector<1x1x16xi1> -> vector<1x1x16xf16>
525/// Distributed to:
526/// %mask = producer_op : vector<1x1x1xi1>
527/// %offset = producer_op : vector<1x1x1xindex>
528/// %0 = xegpu.load %src[%offset], %mask : memref<256xf16>,
529/// vector<1xindex>, vector<1xi1> -> vector<1xf16>
530struct SgToLaneLoadGather : public OpConversionPattern<xegpu::LoadGatherOp> {
531 using OpConversionPattern<xegpu::LoadGatherOp>::OpConversionPattern;
532
533 LogicalResult
534 matchAndRewrite(xegpu::LoadGatherOp op, OpAdaptor adaptor,
535 ConversionPatternRewriter &rewriter) const override {
536 xegpu::DistributeLayoutAttr layout = op.getAnchorLayout();
537 if (!layout)
538 return failure();
539
540 VectorType origResultTy = op.getValueType();
541 if (!origResultTy)
542 return failure();
543
544 // Check that leading dimensions are unit.
545 int effectiveVecRank = 1;
546 ArrayRef<int64_t> shape = origResultTy.getShape();
547 if (llvm::any_of(
548 shape.take_front(origResultTy.getRank() - effectiveVecRank),
549 [](int64_t d) { return d != 1; }))
550 return rewriter.notifyMatchFailure(
551 op, "Only unit dimensions allowed for the leading "
552 "dimensions of the load vector!");
553
554 auto distResultTyOrFailure =
555 xegpu::getDistVecTypeBasedOnLaneLayout(layout, origResultTy);
556 if (failed(distResultTyOrFailure))
557 return rewriter.notifyMatchFailure(
558 op, "unable to compute expected lane vector type from lane layout");
559
560 VectorType distResultTy = distResultTyOrFailure.value();
561 VectorType distResultTy1D = VectorType::get({distResultTy.getNumElements()},
562 distResultTy.getElementType());
563
564 // Flatten offsets and mask to 1D to match the 1D result type.
565 Value distOffsets = adaptor.getOffsets();
566 auto distOffsetsTy = cast<VectorType>(distOffsets.getType());
567 VectorType offsetsTy1D = VectorType::get({distOffsetsTy.getNumElements()},
568 distOffsetsTy.getElementType());
569 distOffsets = castValueTo(
570 rewriter, cast<TypedValue<VectorType>>(distOffsets), offsetsTy1D);
571
572 Value distMask = adaptor.getMask();
573 auto distMaskTy = cast<VectorType>(distMask.getType());
574 VectorType maskTy1D = VectorType::get({distMaskTy.getNumElements()},
575 distMaskTy.getElementType());
576 distMask =
577 castValueTo(rewriter, cast<TypedValue<VectorType>>(distMask), maskTy1D);
578
579 Value distSource = adaptor.getSource();
580 auto newOp = xegpu::LoadGatherOp::create(
581 rewriter, op.getLoc(), distResultTy1D, distSource, distOffsets,
582 distMask, op.getL1HintAttr(), op.getL2HintAttr(), op.getL3HintAttr(),
583 /*layout=*/nullptr, /*contiguity=*/nullptr);
584
585 Value result = newOp->getResult(0);
586 if (distResultTy1D != distResultTy)
587 result = castValueTo(rewriter, cast<TypedValue<VectorType>>(result),
588 distResultTy);
589 rewriter.replaceOp(op, result);
590 return success();
591 }
592};
593
594/// This pattern distributes a subgroup-level vector.reduction op to
595/// lane-level. This require shuffling the data across the lanes (using
596/// gpu::ShuffleOp) and reducing in stages until all lanes have the final
597/// result.
598struct SgToLaneVectorReduction
599 : public OpConversionPattern<vector::ReductionOp> {
600 using OpConversionPattern<vector::ReductionOp>::OpConversionPattern;
601
602 LogicalResult
603 matchAndRewrite(vector::ReductionOp op, OpAdaptor adaptor,
604 ConversionPatternRewriter &rewriter) const override {
605 auto layout = xegpu::getDistributeLayoutAttr(op.getVector());
606
607 // If no layout, nothing to do.
608 if (!layout || !layout.isForSubgroup())
609 return failure();
610
611 VectorType srcVecType = op.getSourceVectorType();
612 // Only rank 1 vectors supported.
613 if (srcVecType.getRank() != 1)
614 return rewriter.notifyMatchFailure(
615 op, "Only rank 1 reductions can be distributed.");
616 // Lane layout must have the same rank as the vector.
617 if (layout.getRank() != srcVecType.getRank())
618 return rewriter.notifyMatchFailure(
619 op, "Layout rank does not match vector rank.");
620
621 // Get the subgroup size from the layout.
622 int64_t sgSize = layout.getEffectiveLaneLayoutAsInt()[0];
623 const auto *uArch =
625 if (!uArch)
626 return rewriter.notifyMatchFailure(
627 op, "xegpu::ReductionOp require target attribute attached to "
628 "determine subgroup size");
629
630 // Only subgroup-sized vectors supported.
631 if (sgSize != uArch->getSubgroupSize() ||
632 srcVecType.getShape()[0] % sgSize != 0)
633 return rewriter.notifyMatchFailure(op,
634 "Invalid layout or reduction vector "
635 "dimension must match subgroup size.");
636
637 if (!op.getType().isIntOrFloat())
638 return rewriter.notifyMatchFailure(
639 op, "Reduction distribution currently only supports floats and "
640 "integer types.");
641
642 // Get the distributed vector (per lane portion).
643 Value laneValVec = adaptor.getVector();
644
645 // Distribute and reduce across lanes in the subgroup.
646 Value fullReduce =
647 xegpu::subgroupReduction(op.getLoc(), rewriter, laneValVec,
648 op.getKind(), sgSize, op.getFastmathAttr());
649
650 // If there's an accumulator, combine it with the reduced value.
651 if (adaptor.getAcc())
652 fullReduce = vector::makeArithReduction(
653 rewriter, op.getLoc(), op.getKind(), fullReduce, adaptor.getAcc(),
654 op.getFastmathAttr());
655
656 rewriter.replaceOp(op, fullReduce);
657 return success();
658 }
659};
660
661/// This pattern distributes a subgroup-level vector.multi_reduction op to
662/// lane-level only if the reduction is lane-local. This means that
663/// reduction dimension is not distributed to lanes and each lane does its own
664/// local reduction.
665struct SgToLaneMultiDimReduction
666 : public OpConversionPattern<vector::MultiDimReductionOp> {
667 using OpConversionPattern<vector::MultiDimReductionOp>::OpConversionPattern;
668
669 LogicalResult
670 matchAndRewrite(vector::MultiDimReductionOp op, OpAdaptor adaptor,
671 ConversionPatternRewriter &rewriter) const override {
672 Value result;
673 ArrayRef<int64_t> reductionDims = op.getReductionDims();
674 assert(reductionDims.size() == 1 &&
675 "Expecting single reduction dimension for subgroup multi "
676 "reduction op");
677 // For rank > 2, ensure leading dimensions are unit.
678 VectorType sourceType = op.getSourceVectorType();
679 int64_t rank = sourceType.getRank();
680 if (rank > 2) {
681 ArrayRef<int64_t> shape = sourceType.getShape();
682 if (llvm::any_of(shape.take_front(rank - 2),
683 [](int64_t d) { return d != 1; }))
684 return rewriter.notifyMatchFailure(
685 op, "only unit leading dimensions are supported for "
686 "multi_reduction with rank > 2");
687 }
688 int64_t reductionDim = reductionDims[0];
689 int64_t reductionDimSize = sourceType.getShape()[reductionDim];
690 // Handle scalar result: full reduction of a distributed vector to a
691 // scalar. First do a local vector reduction, then cross-lane shuffles.
692 if (op.getType().isIntOrFloat()) {
693 // Local reduction to scalar, then cross-lane butterfly shuffles.
694 result = xegpu::subgroupReduction(op.getLoc(), rewriter,
695 adaptor.getSource(), op.getKind(),
696 reductionDimSize, op.getFastmathAttr());
697 // Combine with accumulator if present.
698 if (adaptor.getAcc())
699 result = vector::makeArithReduction(rewriter, op.getLoc(), op.getKind(),
700 result, adaptor.getAcc(),
701 op.getFastmathAttr());
702 } else if (reductionDimSize == 1) {
703 // A unit reduction dim reduces to an elementwise combine with the acc.
704 Value acc = adaptor.getAcc();
705 Value src = vector::ShapeCastOp::create(
706 rewriter, op.getLoc(), acc.getType(), adaptor.getSource());
707 result = vector::makeArithReduction(rewriter, op.getLoc(), op.getKind(),
708 src, acc, op.getFastmathAttr());
709 } else if (isReductionLaneLocal(op)) {
710 // For lane-local reduction, lower to a sequence of vector.reduction ops
711 // over 1D slices extracted from the distributed source vector. This is
712 // required so we dont have 2D source vectors at xegpu-linearize.
714 cast<TypedValue<VectorType>>(adaptor.getSource()),
715 cast<TypedValue<VectorType>>(adaptor.getAcc()), op.getKind(),
716 reductionDim, op.getLoc(), rewriter, op.getFastmathAttr());
717 } else {
719 cast<TypedValue<VectorType>>(adaptor.getSource()),
720 cast<TypedValue<VectorType>>(adaptor.getAcc()), op.getKind(),
721 reductionDim, reductionDimSize, op.getLoc(), rewriter,
722 op.getFastmathAttr());
723 }
724 rewriter.replaceOp(op, result);
725 return success();
726 }
727};
728
729/// Helper to compute distributed coordinates for matrix ops.
730/// When not using subgroup_block_io, each lane computes its own
731/// coordinates based on the layout and lane ID.
732static SmallVector<Value> computeDistributedCoordsForMatrixOp(
733 ConversionPatternRewriter &rewriter, Location loc,
734 xegpu::DistributeLayoutAttr layout, ArrayRef<int64_t> payloadShape,
735 ValueRange origOffsets) {
736 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
737 /*upperBound=*/mlir::IntegerAttr());
738 auto maybeCoords =
739 layout.computeDistributedCoords(rewriter, loc, laneId, payloadShape);
740 if (failed(maybeCoords))
741 return {};
742 assert(maybeCoords.value().size() == 1 &&
743 "Expected one set of distributed offsets");
745 rewriter, loc, getAsOpFoldResult(maybeCoords.value()[0]),
746 getAsOpFoldResult(origOffsets));
747 return llvm::map_to_vector(ofrVec, llvm::CastTo<Value>);
748}
749
750/// This pattern distributes a subgroup-level LoadMatrix op to lane-level.
751struct SgToLaneLoadMatrix : public OpConversionPattern<xegpu::LoadMatrixOp> {
752 using OpConversionPattern<xegpu::LoadMatrixOp>::OpConversionPattern;
753
754 LogicalResult
755 matchAndRewrite(xegpu::LoadMatrixOp op, OpAdaptor adaptor,
756 ConversionPatternRewriter &rewriter) const override {
757 auto layout = op.getLayoutAttr();
758 // If no layout, nothing to do.
759 if (!layout)
760 return failure();
761
762 VectorType sgPayloadTy = dyn_cast<VectorType>(op.getResult().getType());
763 if (!sgPayloadTy)
764 return rewriter.notifyMatchFailure(
765 op, "the matrix op payload must be a vector type");
766
767 auto loc = op.getLoc();
768 auto offsets = op.getMixedOffsets();
769 if (offsets.empty())
770 return rewriter.notifyMatchFailure(op, "the load op must have offsets");
771
772 FailureOr<VectorType> distPayloadTyOrFailure =
773 getDistVecTypeBasedOnLaneLayout(layout, sgPayloadTy);
774 if (failed(distPayloadTyOrFailure))
775 return rewriter.notifyMatchFailure(
776 op, "Failed to distribute matrix op payload based on layout.");
777
778 SmallVector<Value> offsetsAsValues =
779 vector::getAsValues(rewriter, loc, offsets);
780
781 SmallVector<Value> newCoords = offsetsAsValues;
782 if (!op.getSubgroupBlockIoAttr()) {
783 newCoords = computeDistributedCoordsForMatrixOp(
784 rewriter, loc, layout, sgPayloadTy.getShape(), offsetsAsValues);
785 if (newCoords.empty())
786 return rewriter.notifyMatchFailure(
787 op, "Failed to compute distributed coordinates.");
788 }
789
790 SmallVector<int64_t> newConstOffsets(op.getConstOffsets().size(),
791 ShapedType::kDynamic);
792 DenseI64ArrayAttr newConstOffsetsAttr =
793 rewriter.getDenseI64ArrayAttr(newConstOffsets);
794
795 auto newOp = xegpu::LoadMatrixOp::create(
796 rewriter, loc, *distPayloadTyOrFailure, adaptor.getMemDesc(),
797 ValueRange(newCoords), newConstOffsetsAttr, op.getSubgroupBlockIoAttr(),
798 xegpu::DistributeLayoutAttr{});
799 rewriter.replaceOp(op, newOp.getResult());
800 return success();
801 }
802};
803
804/// Distributes a subgroup-level vector.transpose op to lane-level.
805struct SgToLaneVectorTranspose
806 : public OpConversionPattern<vector::TransposeOp> {
807 using OpConversionPattern<vector::TransposeOp>::OpConversionPattern;
808
809 LogicalResult
810 matchAndRewrite(vector::TransposeOp op, OpAdaptor adaptor,
811 ConversionPatternRewriter &rewriter) const override {
812 xegpu::DistributeLayoutAttr sourceLayout =
813 xegpu::getTemporaryLayout(op->getOpOperand(0));
814 xegpu::DistributeLayoutAttr resultLayout =
815 xegpu::getTemporaryLayout(op->getOpResult(0));
816 if (!sourceLayout || !resultLayout)
817 return rewriter.notifyMatchFailure(
818 op, "the source or result vector of the transpose op lacks layout "
819 "attribute");
820 ArrayRef<int64_t> perm = op.getPermutation();
821 // Result layout must be a transpose of source layout.
822 if (!resultLayout.isTransposeOf(sourceLayout, perm,
823 xegpu::LayoutKind::Lane))
824 return rewriter.notifyMatchFailure(
825 op, "the source or result vector layouts must be transposes of "
826 "each other");
827 FailureOr<VectorType> distributedResultTypeOrFailure =
828 getDistVecTypeBasedOnLaneLayout(resultLayout, op.getResultVectorType());
829 if (failed(distributedResultTypeOrFailure))
830 return rewriter.notifyMatchFailure(
831 op, "Failed to distribute the result vector type in "
832 "vector::Transpose op");
833 auto newOp = vector::TransposeOp::create(rewriter, op.getLoc(),
834 adaptor.getVector(), perm);
835 rewriter.replaceOp(op, castValueTo(rewriter, newOp.getResult(),
836 distributedResultTypeOrFailure.value()));
837 return success();
838 }
839};
840
841/// Distributes a subgroup-level vector.bitcast op to lane-level.
842/// Bitcast only impacts the innermost dimension of the source/result vectors.
843struct SgToLaneVectorBitcast : public OpConversionPattern<vector::BitCastOp> {
844 using OpConversionPattern<vector::BitCastOp>::OpConversionPattern;
845
846 LogicalResult
847 matchAndRewrite(vector::BitCastOp op, OpAdaptor adaptor,
848 ConversionPatternRewriter &rewriter) const override {
849 xegpu::DistributeLayoutAttr resultLayout =
850 xegpu::getTemporaryLayout(op->getOpResult(0));
851 if (!resultLayout)
852 return rewriter.notifyMatchFailure(
853 op, "result vector of the bitcast op lacks layout attribute");
854 FailureOr<VectorType> distributedResultTypeOrFailure =
855 getDistVecTypeBasedOnLaneLayout(resultLayout, op.getResultVectorType());
856 if (failed(distributedResultTypeOrFailure))
857 return rewriter.notifyMatchFailure(
858 op, "Failed to distribute the result vector type in "
859 "vector::BitCast op");
860 auto newOp = vector::BitCastOp::create(
861 rewriter, op.getLoc(), distributedResultTypeOrFailure.value(),
862 adaptor.getSource());
863 rewriter.replaceOp(op, newOp.getResult());
864 return success();
865 }
866};
867
868/// Distributes a subgroup-level vector.create_mask or vector.constant_mask op
869/// to lane-level.
870/// The pattern constructs a mask based on the following bounds check:
871/// ```
872/// for d in [0, ..., maskRank):
873/// mask &= (staticOffset[d] < (bound[d] - base[d]))
874/// ```
875/// where
876/// - `base` is the coordinate vector of the first distributed unit.
877/// - `staticOffset` is the offsets vector per element.
878/// - `bound` is the original mask bound for the corresponding dimension.
879/// The mask vector contains *all* elements (i.e., non-unit `lane_data` is
880/// flattened). For example,
881/// ```
882/// %mask = vector.create_mask %bound_0, %bound_1 {
883/// lane_layout = [1, 16], lane_data = [2, 1]
884/// }: vector<8x32xi1>
885/// ```
886/// Has 8 dist units (of shape [2, 1]) with offsets for lane 0:
887/// {
888/// [0, 0], [0, 16],
889/// [2, 0], [2, 16],
890/// [4, 0], [4, 16],
891/// [6, 0], [6, 16]
892/// }
893/// We check the distance to the bound from the first dist. unit:
894/// %base_0 = genCoords(gpu.lane_id, layout)[0][0]
895/// %base_1 = genCoords(gpu.lane_id, layout)[0][1]
896/// %baseDistanceToBound_0 = %bound_0 - %base_0
897/// %baseDistanceToBound_1 = %bound_1 - %base_1
898/// The pattern flattens the dimension d coordinates of each element:
899/// %staticOffset_0 = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7]
900/// %staticOffset_1 = [0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16]
901/// and compares each coordinate against the corresponding mask bound dim:
902/// %mask_0 = arith.cmpi slt, %staticOffset_0, bcast(%baseDistanceToBound_0)
903/// %mask_1 = arith.cmpi slt, %staticOffset_1, bcast(%baseDistanceToBound_1)
904/// %mask = shape_cast(%mask_0 & %mask_1) : vector<16xi1> to vector<8x2xi1>
905///
906template <typename OpType,
907 typename = std::enable_if_t<llvm::is_one_of<
908 OpType, vector::CreateMaskOp, vector::ConstantMaskOp>::value>>
909struct SgToLaneCreateMask : public OpConversionPattern<OpType> {
910 using OpConversionPattern<OpType>::OpConversionPattern;
911
912 LogicalResult
913 matchAndRewrite(OpType op, typename OpType::Adaptor adaptor,
914 ConversionPatternRewriter &rewriter) const override {
915 xegpu::DistributeLayoutAttr layout =
916 xegpu::getTemporaryLayout(op->getOpResult(0));
917 if (!layout || !layout.isForSubgroup())
918 return rewriter.notifyMatchFailure(
919 op, "operation result does not have subgroup distribute layout");
920
921 VectorType origType = op.getType();
922 FailureOr<VectorType> distTypeOrFailure =
923 getDistVecTypeBasedOnLaneLayout(layout, origType);
924 if (failed(distTypeOrFailure))
925 return rewriter.notifyMatchFailure(
926 op, "unable to compute lane vector type from the layout");
927
928 VectorType distType = distTypeOrFailure.value();
929 Location loc = op.getLoc();
930
931 // Materialize the original mask bounds as Values.
932 SmallVector<Value> origBounds;
933 if constexpr (std::is_same_v<OpType, vector::CreateMaskOp>) {
934 origBounds.append(op.getOperands().begin(), op.getOperands().end());
935 } else {
936 auto dimSizes = op.getMaskDimSizesAttr().asArrayRef();
937 for (auto dimSize : dimSizes)
938 origBounds.push_back(
939 arith::ConstantIndexOp::create(rewriter, loc, dimSize).getResult());
940 }
941
942 ArrayRef<int64_t> origShape = origType.getShape();
943
944 // Use computeDistributedCoords to get the coordinates each WI owns.
945 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
946 /*upperBound=*/mlir::IntegerAttr());
947 auto maybeCoordsVec =
948 layout.computeDistributedCoords(rewriter, loc, laneId, origShape);
949 if (failed(maybeCoordsVec))
950 return rewriter.notifyMatchFailure(
951 op, "failed to compute distributed coordinates from layout");
952
953 SmallVector<SmallVector<Value>> laneDataCoords = maybeCoordsVec.value();
954 SmallVector<int64_t> laneData = layout.getEffectiveLaneDataAsInt();
955 ArrayRef<int64_t> distShape = distType.getShape();
956 int64_t rank = distType.getRank();
957 int64_t numElements = distType.getNumElements();
958
959 if (static_cast<int64_t>(laneData.size()) != rank ||
960 !computeShapeRatio(distShape, laneData))
961 return rewriter.notifyMatchFailure(
962 op, "lane_data does not tile the distributed vector");
963
964 SmallVector<int64_t> distStrides = computeStrides(distShape);
965 assert(static_cast<int64_t>(laneDataCoords.size()) *
966 computeProduct(laneData) ==
967 numElements &&
968 "number of coordinate sets must match number of lane_data blocks");
969
970 // Static offsets to be applied to a dynamic lane's dist units coordinates.
971 SmallVector<SmallVector<int64_t>> staticLaneDataOffsetsOrig =
972 layout.computeStaticDistributedCoords(/*linearId=*/0, origShape);
973 if (staticLaneDataOffsetsOrig.empty() ||
974 staticLaneDataOffsetsOrig.size() != laneDataCoords.size())
975 return rewriter.notifyMatchFailure(
976 op, "static and dynamic coordinates disagree on the distribution "
977 "unit count");
978
979 SmallVector<int64_t> unitTile(rank, 1);
980 int64_t linearLaneDataIdx = 0;
981 // Layout and shape information is static, compute static offset of lane's
982 // elements in the source dimensions. Each dim is a flat vec of element
983 // offsets. We store dim-major to have an easy materialization as one const
984 // vector.
985 SmallVector<SmallVector<int64_t>> staticElemOffset(
986 rank, SmallVector<int64_t>(numElements));
987 // For each lane_data block in the lane's dist shape
988 for (SmallVector<int64_t> laneDataOffsetDist :
989 StaticTileOffsetRange(distShape, laneData)) {
990 ArrayRef<int64_t> staticLaneDataOffsetOrig =
991 staticLaneDataOffsetsOrig[linearLaneDataIdx++];
992 // For each element in the lane_data block
993 for (SmallVector<int64_t> elemOffsetInLaneData :
994 StaticTileOffsetRange(laneData, unitTile)) {
995 // For each dim of indexing space
996 SmallVector<int64_t> elementOffsetDist(rank);
997 for (int64_t d = 0; d < rank; d++)
998 elementOffsetDist[d] =
999 laneDataOffsetDist[d] + elemOffsetInLaneData[d];
1000 int64_t elemLinearizedIdxDist =
1001 linearize(elementOffsetDist, distStrides);
1002 for (int64_t d = 0; d < rank; d++)
1003 staticElemOffset[d][elemLinearizedIdxDist] =
1004 staticLaneDataOffsetOrig[d] + elemOffsetInLaneData[d];
1005 }
1006 }
1007
1008 // Check, whether ALL elements of the distributed mask are within the valid
1009 // extent of EACH source dimension.
1010 // Expressed as dyn_offset[d] + static_offset[d] < dyn_mask_bound[d],
1011 // or equivalently,
1012 // static_offset[d] < dyn_mask_bound[d] - dyn_offset[d]
1013 auto flatIndexType = VectorType::get(numElements, rewriter.getIndexType());
1014 Value inBounds;
1015 for (int64_t d = 0; d < rank; d++) {
1016 std::optional<int64_t> constBound = getConstantIntValue(origBounds[d]);
1017 if (constBound && *constBound >= origShape[d])
1018 continue;
1019
1020 Value materializedStaticOffset = arith::ConstantOp::create(
1021 rewriter, loc, rewriter.getIndexVectorAttr(staticElemOffset[d]));
1022 // Consider only the first unit, all others are compile-time multiple
1023 // offsets of the first one and are already encoded in staticOffsets.
1024 Value validDimExtent = arith::SubIOp::create(rewriter, loc, origBounds[d],
1025 laneDataCoords[0][d]);
1026 // Dim extent applies to all elements.
1027 Value validDimExtentPerElement = vector::BroadcastOp::create(
1028 rewriter, loc, flatIndexType, validDimExtent);
1029 Value elementMaskInDim = arith::CmpIOp::create(
1030 rewriter, loc, arith::CmpIPredicate::slt, materializedStaticOffset,
1031 validDimExtentPerElement);
1032 // An element is valid iff it is within the valid extent of ALL
1033 // dimensions.
1034 inBounds = inBounds ? arith::AndIOp::create(rewriter, loc, inBounds,
1035 elementMaskInDim)
1036 .getResult()
1037 : elementMaskInDim;
1038 }
1039 // Every dim's bound saturates the mask extent, so no comparison was
1040 // emitted at all: every element of every lane is in bounds.
1041 if (!inBounds) {
1042 rewriter.replaceOp(op, arith::ConstantOp::create(
1043 rewriter, loc, distType,
1044 DenseElementsAttr::get(distType, true)));
1045 return success();
1046 }
1047 auto resMask =
1048 rewriter.createOrFold<vector::ShapeCastOp>(loc, distType, inBounds);
1049 rewriter.replaceOp(op, resMask);
1050 return success();
1051 }
1052};
1053
1054/// This pattern distributes a subgroup-level StoreMatrix op to lane-level.
1055struct SgToLaneStoreMatrix : public OpConversionPattern<xegpu::StoreMatrixOp> {
1056 using OpConversionPattern<xegpu::StoreMatrixOp>::OpConversionPattern;
1057
1058 LogicalResult
1059 matchAndRewrite(xegpu::StoreMatrixOp op, OpAdaptor adaptor,
1060 ConversionPatternRewriter &rewriter) const override {
1061 auto layout = op.getLayoutAttr();
1062 // If no layout, nothing to do.
1063 if (!layout)
1064 return failure();
1065
1066 VectorType sgPayloadTy = dyn_cast<VectorType>(op.getData().getType());
1067 if (!sgPayloadTy)
1068 return rewriter.notifyMatchFailure(
1069 op, "the matrix op payload must be a vector type");
1070
1071 auto loc = op.getLoc();
1072 auto offsets = op.getMixedOffsets();
1073 if (offsets.empty())
1074 return rewriter.notifyMatchFailure(op, "the store op must have offsets");
1075
1076 FailureOr<VectorType> distPayloadTyOrFailure =
1077 getDistVecTypeBasedOnLaneLayout(layout, sgPayloadTy);
1078 if (failed(distPayloadTyOrFailure))
1079 return rewriter.notifyMatchFailure(
1080 op, "Failed to distribute matrix op payload based on layout.");
1081
1082 SmallVector<Value> offsetsAsValues =
1083 vector::getAsValues(rewriter, loc, offsets);
1084
1085 SmallVector<Value> newCoords = offsetsAsValues;
1086 if (!op.getSubgroupBlockIoAttr()) {
1087 newCoords = computeDistributedCoordsForMatrixOp(
1088 rewriter, loc, layout, sgPayloadTy.getShape(), offsetsAsValues);
1089 if (newCoords.empty())
1090 return rewriter.notifyMatchFailure(
1091 op, "Failed to compute distributed coordinates.");
1092 }
1093
1094 SmallVector<int64_t> newConstOffsets(op.getConstOffsets().size(),
1095 ShapedType::kDynamic);
1096 DenseI64ArrayAttr newConstOffsetsAttr =
1097 rewriter.getDenseI64ArrayAttr(newConstOffsets);
1098
1099 xegpu::StoreMatrixOp::create(
1100 rewriter, loc, TypeRange{},
1101 castValueTo(rewriter, cast<TypedValue<VectorType>>(adaptor.getData()),
1102 distPayloadTyOrFailure.value()),
1103 adaptor.getMemDesc(), ValueRange(newCoords), newConstOffsetsAttr,
1104 op.getSubgroupBlockIoAttr(), xegpu::DistributeLayoutAttr{});
1105 rewriter.eraseOp(op);
1106 return success();
1107 }
1108};
1109
1110/// Distributes a subgroup-level StoreScatter (xegpu.store) op to
1111/// lane-level.
1112///
1113/// Example 1 (1D):
1114/// layout = #xegpu.layout<lane_layout = [16], lane_data = [1]>
1115/// %mask = producer_op : vector<16xi1>
1116/// %offset = producer_op : vector<16xindex>
1117/// xegpu.store %payload, %src[%offset], %mask : vector<16xf16>,
1118/// memref<256xf16>, vector<16xindex>, vector<16xi1>
1119/// Distributed to:
1120/// %mask = producer_op : vector<1xi1>
1121/// %offset = producer_op : vector<1xindex>
1122/// xegpu.store %payload, %src[%offset], %mask : vector<1xf16>,
1123/// memref<256xf16>, vector<1xindex>, vector<1xi1>
1124///
1125/// Example 2 (3D with leading unit dims):
1126/// layout = #xegpu.layout<lane_layout = [1, 1, 16], lane_data = [1, 1, 1]>
1127/// %mask = producer_op : vector<1x1x16xi1>
1128/// %offset = producer_op : vector<1x1x16xindex>
1129/// xegpu.store %payload, %src[%offset], %mask : vector<1x1x16xf16>,
1130/// memref<256xf16>, vector<1x1x16xindex>, vector<1x1x16xi1>
1131/// Distributed to:
1132/// %mask = producer_op : vector<1x1x1xi1>
1133/// %offset = producer_op : vector<1x1x1xindex>
1134/// xegpu.store %payload, %src[%offset], %mask : vector<1xf16>,
1135/// memref<256xf16>, vector<1xindex>, vector<1xi1>
1136struct SgToLaneStoreScatter
1137 : public OpConversionPattern<xegpu::StoreScatterOp> {
1138 using OpConversionPattern<xegpu::StoreScatterOp>::OpConversionPattern;
1139
1140 LogicalResult
1141 matchAndRewrite(xegpu::StoreScatterOp op, OpAdaptor adaptor,
1142 ConversionPatternRewriter &rewriter) const override {
1143 xegpu::DistributeLayoutAttr layout = op.getAnchorLayout();
1144 if (!layout)
1145 return failure();
1146
1147 VectorType origValueTy = op.getValueType();
1148 if (!origValueTy)
1149 return failure();
1150
1151 // Check that all leading dimensions are unit dimensions.
1152 int effectiveVecRank = 1;
1153 ArrayRef<int64_t> shape = origValueTy.getShape();
1154 if (llvm::any_of(shape.take_front(origValueTy.getRank() - effectiveVecRank),
1155 [](int64_t d) { return d != 1; }))
1156 return rewriter.notifyMatchFailure(
1157 op, "Only unit dimensions allowed for the leading "
1158 "dimensions of the store vector!");
1159
1160 auto distValueTyOrFailure =
1161 xegpu::getDistVecTypeBasedOnLaneLayout(layout, origValueTy);
1162 if (failed(distValueTyOrFailure))
1163 return rewriter.notifyMatchFailure(
1164 op, "unable to compute expected lane vector type from lane layout");
1165
1166 VectorType distValueTy = distValueTyOrFailure.value();
1167 VectorType distValueTy1D = VectorType::get({distValueTy.getNumElements()},
1168 distValueTy.getElementType());
1169
1170 Value distValue = adaptor.getValue();
1171 if (distValue.getType() != distValueTy1D)
1172 distValue = castValueTo(rewriter, cast<TypedValue<VectorType>>(distValue),
1173 distValueTy1D);
1174
1175 // Flatten offsets and mask to 1D to match the 1D value type.
1176 Value distOffsets = adaptor.getOffsets();
1177 auto distOffsetsTy = cast<VectorType>(distOffsets.getType());
1178 VectorType offsetsTy1D = VectorType::get({distOffsetsTy.getNumElements()},
1179 distOffsetsTy.getElementType());
1180 distOffsets = castValueTo(
1181 rewriter, cast<TypedValue<VectorType>>(distOffsets), offsetsTy1D);
1182
1183 Value distMask = adaptor.getMask();
1184 auto distMaskTy = cast<VectorType>(distMask.getType());
1185 VectorType maskTy1D = VectorType::get({distMaskTy.getNumElements()},
1186 distMaskTy.getElementType());
1187 distMask =
1188 castValueTo(rewriter, cast<TypedValue<VectorType>>(distMask), maskTy1D);
1189
1190 Value distDest = adaptor.getDest();
1191 xegpu::StoreScatterOp::create(rewriter, op.getLoc(), distValue, distDest,
1192 distOffsets, distMask, op.getL1HintAttr(),
1193 op.getL2HintAttr(), op.getL3HintAttr(),
1194 /*layout=*/nullptr,
1195 /*contiguity=*/nullptr);
1196 rewriter.eraseOp(op);
1197 return success();
1198 }
1199};
1200
1201/// Distribute a vector::StepOp to lane-level.
1202/// The layout must have exactly 1 effective lane dimension.
1203/// We completely resolve the vector::StepOp by computing the lane_data-sized
1204/// subranges.
1205struct SgToLaneVectorStep : public OpConversionPattern<vector::StepOp> {
1206 using OpConversionPattern<vector::StepOp>::OpConversionPattern;
1207
1208 LogicalResult
1209 matchAndRewrite(vector::StepOp op, OpAdaptor adaptor,
1210 ConversionPatternRewriter &rewriter) const override {
1211 xegpu::DistributeLayoutAttr resultLayout =
1212 xegpu::getTemporaryLayout(op->getResult(0));
1213 if (!resultLayout || !resultLayout.isForSubgroup())
1214 return rewriter.notifyMatchFailure(
1215 op, "the result vector of the step op lacks subgroup layout");
1216
1217 auto loc = op.getLoc();
1218 auto stepResultVecTy = op.getResult().getType();
1219 auto laneShapeOrFailure =
1220 xegpu::getDistVecTypeBasedOnLaneLayout(resultLayout, stepResultVecTy);
1221 if (failed(laneShapeOrFailure))
1222 return rewriter.notifyMatchFailure(
1223 op, "unable to compute lane vector type from the layout");
1224 VectorType newVecTy = laneShapeOrFailure.value();
1225
1226 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
1227 /*upperBound=*/mlir::IntegerAttr());
1228 auto laneDataBlockCoords = resultLayout.computeDistributedCoords(
1229 rewriter, loc, laneId, stepResultVecTy.getShape());
1230 if (failed(laneDataBlockCoords))
1231 return rewriter.notifyMatchFailure(
1232 op, "failed to compute lane data block coordinates");
1233
1234 auto laneDataBlockCoordsVec = laneDataBlockCoords.value();
1235 auto laneDataBlockLength = resultLayout.getEffectiveLaneDataAsInt()[0];
1236 assert(static_cast<int64_t>(laneDataBlockCoordsVec.size()) ==
1237 newVecTy.getNumElements() / laneDataBlockLength);
1238 SmallVector<Value> stepVals;
1239 // For each lane_data block, reconstruct its sub-range
1240 // from the range of SG-level vector.step.Example: vector.step
1241 // {slice<layout<lane_layout=[2,4,2], lane_data=[1,2,1]>, dims=[0,2]>} :
1242 // vector<16xindex>
1243 // Each logical lane holds 4 elements as 2 blocks of 2 elements each.
1244 // The blocks are round-robin distributed, so logical lane id 0
1245 // holds values [0,1, 8,9].
1246 for (auto &laneDataBlockCoords : laneDataBlockCoordsVec) {
1247 auto laneDataBlockStartCoord = laneDataBlockCoords[0];
1248 stepVals.push_back(laneDataBlockStartCoord);
1249 for (int i = 1; i < laneDataBlockLength; ++i) {
1250 auto offset = arith::ConstantIndexOp::create(rewriter, loc, i);
1251 stepVals.push_back(arith::AddIOp::create(
1252 rewriter, loc, laneDataBlockStartCoord, offset));
1253 }
1254 }
1255 assert(static_cast<int64_t>(stepVals.size()) == newVecTy.getNumElements() &&
1256 "Expecting the number of step values to match the number of "
1257 "elements in the vector");
1258 auto stepOpVal =
1259 vector::FromElementsOp::create(rewriter, loc, newVecTy, stepVals);
1260 rewriter.replaceOp(op, stepOpVal);
1261 return success();
1262 }
1263};
1264
1265/// Distributes a subgroup-level vector.extract op to lane-level. Only
1266/// handles sub-vector extraction (result is VectorType, not scalar).
1267struct SgToLaneVectorExtract : public OpConversionPattern<vector::ExtractOp> {
1268 using OpConversionPattern<vector::ExtractOp>::OpConversionPattern;
1269
1270 LogicalResult
1271 matchAndRewrite(vector::ExtractOp op, OpAdaptor adaptor,
1272 ConversionPatternRewriter &rewriter) const override {
1273 // Only handle vector results (not scalar extraction).
1274 auto resultType = dyn_cast<VectorType>(op.getType());
1275 if (!resultType)
1276 return rewriter.notifyMatchFailure(op, "scalar extract not supported");
1277
1278 xegpu::DistributeLayoutAttr layout =
1279 xegpu::getTemporaryLayout(op->getOpResult(0));
1280 if (!layout || !layout.isForSubgroup())
1281 return failure();
1282
1283 // This implementation assumes distribution only happens on the innermost
1284 // dimension. Verify that lane_layout[0...n-2] are all unit.
1285 auto laneLayout = layout.getEffectiveLaneLayoutAsInt();
1286 if (llvm::any_of(ArrayRef<int64_t>(laneLayout).drop_back(1),
1287 [](int64_t v) { return v != 1; }))
1288 return rewriter.notifyMatchFailure(
1289 op, "only innermost dimension distribution is supported for "
1290 "vector.extract");
1291
1292 auto newOp = vector::ExtractOp::create(
1293 rewriter, op.getLoc(), adaptor.getSource(), op.getMixedPosition());
1294 rewriter.replaceOp(op, newOp.getResult());
1295 return success();
1296 }
1297};
1298
1299/// This pattern distributes a subgroup-level ShapeCast op to lane-level.
1300struct SgToLaneVectorShapeCast
1301 : public OpConversionPattern<vector::ShapeCastOp> {
1302 using OpConversionPattern<vector::ShapeCastOp>::OpConversionPattern;
1303
1304 LogicalResult
1305 matchAndRewrite(vector::ShapeCastOp op, OpAdaptor adaptor,
1306 ConversionPatternRewriter &rewriter) const override {
1307 xegpu::DistributeLayoutAttr resultLayout =
1308 xegpu::getTemporaryLayout(op->getOpResult(0));
1309 if (!resultLayout || !resultLayout.isForSubgroup())
1310 return rewriter.notifyMatchFailure(
1311 op, "the result vector of the shape_cast op lacks subgroup layout");
1312
1313 auto resultDistTypeOrFailure = xegpu::getDistVecTypeBasedOnLaneLayout(
1314 resultLayout, op.getResultVectorType());
1315 if (failed(resultDistTypeOrFailure))
1316 return rewriter.notifyMatchFailure(
1317 op, "failed to get distributed vector type for result");
1318
1319 Value source = adaptor.getSource();
1320 auto newShapeCast = vector::ShapeCastOp::create(
1321 rewriter, op.getLoc(), resultDistTypeOrFailure.value(), source);
1322 rewriter.replaceOp(op, newShapeCast);
1323 return success();
1324 }
1325};
1326
1327/// Distributes a subgroup-level vector.extract_strided_slice op to
1328/// lane-level. If the result is distributed, the offsets and sizes are
1329/// adjusted to match the distributed types.
1330struct SgToLaneVectorExtractStridedSlice
1331 : public OpConversionPattern<vector::ExtractStridedSliceOp> {
1332 using OpConversionPattern<vector::ExtractStridedSliceOp>::OpConversionPattern;
1333
1334 LogicalResult
1335 matchAndRewrite(vector::ExtractStridedSliceOp op, OpAdaptor adaptor,
1336 ConversionPatternRewriter &rewriter) const override {
1337 xegpu::DistributeLayoutAttr resultLayout =
1338 xegpu::getTemporaryLayout(op->getOpResult(0));
1339 if (!resultLayout || !resultLayout.isForSubgroup())
1340 return failure();
1341
1342 VectorType resultType = op.getType();
1343 auto distResultTyOrFailure =
1344 xegpu::getDistVecTypeBasedOnLaneLayout(resultLayout, resultType);
1345 if (failed(distResultTyOrFailure))
1346 return rewriter.notifyMatchFailure(
1347 op, "unable to compute distributed vector type from lane layout");
1348 VectorType distResultTy = *distResultTyOrFailure;
1349
1350 SmallVector<int64_t> distributedDims =
1351 getDistributedDims(resultType, distResultTy);
1352
1353 // Collect updated sizes, offsets, strides. Pad to full source rank.
1354 int64_t sourceRank = op.getSourceVectorType().getRank();
1355 SmallVector<Attribute> updatedSizes =
1356 llvm::map_to_vector(op.getSizes(), [](Attribute attr) { return attr; });
1357 SmallVector<Attribute> updatedOffsets = llvm::map_to_vector(
1358 op.getOffsets(), [](Attribute attr) { return attr; });
1359 SmallVector<Attribute> updatedStrides = llvm::map_to_vector(
1360 op.getStrides(), [](Attribute attr) { return attr; });
1361 for (int64_t i = op.getSizes().size(); i < sourceRank; ++i) {
1362 updatedSizes.push_back(
1363 rewriter.getI64IntegerAttr(op.getSourceVectorType().getDimSize(i)));
1364 updatedOffsets.push_back(rewriter.getI64IntegerAttr(0));
1365 updatedStrides.push_back(rewriter.getI64IntegerAttr(1));
1366 }
1367
1368 // Each distributed dim shrinks by its own lane count, so its size and
1369 // offset are rescaled by that count.
1370 if (!distributedDims.empty()) {
1371 auto sourceLayout = xegpu::getTemporaryLayout(op->getOpOperand(0));
1372 if (!sourceLayout || sourceLayout.getEffectiveLaneLayoutAsInt().empty())
1373 return rewriter.notifyMatchFailure(
1374 op, "source of extract_strided_slice lacks distribution layout");
1375 SmallVector<int64_t> laneLayout =
1376 sourceLayout.getEffectiveLaneLayoutAsInt();
1377 SmallVector<int64_t> laneData = sourceLayout.getEffectiveLaneDataAsInt();
1378 ArrayRef<int64_t> sourceShape = op.getSourceVectorType().getShape();
1379 for (int64_t distDim : distributedDims) {
1380 int64_t lanes = laneLayout[distDim];
1381 if (lanes == 0 || sourceShape[distDim] % lanes != 0)
1382 return rewriter.notifyMatchFailure(
1383 op, "source size along a distributed dim is not a multiple of "
1384 "its lane count");
1385 int64_t distrDimOffset =
1386 cast<IntegerAttr>(updatedOffsets[distDim]).getInt();
1387 if (distrDimOffset % (lanes * laneData[distDim]) != 0)
1388 return rewriter.notifyMatchFailure(
1389 op, "offset along a distributed dim is not a multiple of its "
1390 "lane tile");
1391 updatedSizes[distDim] =
1392 rewriter.getI64IntegerAttr(distResultTy.getDimSize(distDim));
1393 updatedOffsets[distDim] =
1394 rewriter.getI64IntegerAttr(distrDimOffset / lanes);
1395 }
1396 }
1397
1398 auto newOp = vector::ExtractStridedSliceOp::create(
1399 rewriter, op.getLoc(), distResultTy, adaptor.getSource(),
1400 ArrayAttr::get(rewriter.getContext(), updatedOffsets),
1401 ArrayAttr::get(rewriter.getContext(), updatedSizes),
1402 ArrayAttr::get(rewriter.getContext(), updatedStrides));
1403 rewriter.replaceOp(op, newOp.getResult());
1404 return success();
1405 }
1406};
1407
1408/// This pattern distributes a subgroup-level `vector.broadcast` op to
1409/// lane-level. The pattern supports three cases:
1410///
1411/// 1) Broadcast a low-rank vector to high-rank vector: The low-rank input
1412/// vector must have a slice layout of the result. If the distributed source
1413/// and target vector types are identical, this lowers to a no-op; otherwise,
1414/// it remains a broadcast but operates on distributed vectors.
1415///
1416/// 2) Broadcast a same-rank vector with identical layouts for source and
1417/// target: The source vector must have unit dimensions, and lane_data must
1418/// be unit size for those unit dims. This always lowers to a no-op.
1419///
1420/// 3) Broadcast a scalar with no layout: This always lowers to a broadcast
1421/// from scalar to distributed result type.
1422///
1423/// Example 1 (low-rank to high-rank broadcast):
1424/// ```
1425/// %0 = "some_op"() {layout_result_0 =
1426/// #xegpu.slice<#xegpu.layout<lane_layout = [1, 16], lane_data = [1, 1]>,
1427/// dims = [0]>} : () -> vector<16xf16>
1428/// %1 = vector.broadcast %0 {layout_result_0 =
1429/// #xegpu.layout<lane_layout = [1, 16], lane_data = [1, 1]>}
1430/// : vector<16xf16> to vector<16x16xf16>
1431/// ```
1432/// is distributed to:
1433/// ```
1434/// %0 = "some_op"() : () -> vector<1xf16>
1435/// %1 = vector.broadcast %0 : vector<1xf16> to vector<16x1xf16>
1436/// ```
1437///
1438/// Example 2 (same-rank broadcast, no-op):
1439/// ```
1440/// %0 = "some_op"() {layout_result_0 =
1441/// #xegpu.layout<lane_layout = [1, 16], lane_data = [1, 1]>}
1442/// : () -> vector<16x1xf16>
1443/// %1 = vector.broadcast %0 {layout_result_0 =
1444/// #xegpu.layout<lane_layout = [1, 16], lane_data = [1, 1]>}
1445/// : vector<16x1xf16> to vector<16x16xf16>
1446/// ```
1447/// is distributed to (no-op, source already matches distributed result type):
1448/// ```
1449/// %0 = "some_op"() : () -> vector<16x1xf16>
1450/// // broadcast is eliminated, %0 is used directly
1451/// ```
1452///
1453/// Example 3 (scalar to vector broadcast):
1454/// ```
1455/// %0 = "some_op"() : () -> f16
1456/// %1 = vector.broadcast %0 {layout_result_0 =
1457/// #xegpu.layout<lane_layout = [1, 16], lane_data = [1, 1]>}
1458/// : f16 to vector<16x16xf16>
1459/// ```
1460/// is distributed to:
1461/// ```
1462/// %0 = "some_op"() : f16
1463/// %1 = vector.broadcast %0 : f16 to vector<16x1xf16>
1464/// ```
1465struct SgToLaneBroadcast : public OpConversionPattern<vector::BroadcastOp> {
1466 using OpConversionPattern<vector::BroadcastOp>::OpConversionPattern;
1467
1468 LogicalResult
1469 matchAndRewrite(vector::BroadcastOp op, OpAdaptor adaptor,
1470 ConversionPatternRewriter &rewriter) const override {
1471 xegpu::DistributeLayoutAttr resultLayout =
1472 xegpu::getTemporaryLayout(cast<OpResult>(op.getResult()));
1473 if (!resultLayout || !resultLayout.isForSubgroup())
1474 return rewriter.notifyMatchFailure(
1475 op, "result does not have subgroup distribute layout");
1476
1477 VectorType destType = op.getResultVectorType();
1478 VectorType sourceType = dyn_cast<VectorType>(op.getSourceType());
1479
1480 xegpu::DistributeLayoutAttr sourceLayout =
1481 xegpu::getTemporaryLayout(op->getOpOperand(0));
1482
1483 if (sourceType) {
1484 int64_t rankDiff = destType.getRank() - sourceType.getRank();
1485 if (rankDiff > 0) {
1486 // Case 1: Low-rank to high-rank broadcast.
1487 if (!sourceLayout || !sourceLayout.isSliceOf(resultLayout))
1488 op.emitWarning(
1489 "broadcast source layout must be a slice of result layout");
1490 } else if (rankDiff == 0) {
1491 // Case 2: Same-rank broadcast.
1492 auto broadcastUnitDimsSet = op.computeBroadcastedUnitDims();
1493 SmallVector<int64_t> broadcastUnitDims(broadcastUnitDimsSet.begin(),
1494 broadcastUnitDimsSet.end());
1495 assert(sourceLayout.isEqualTo(
1496 sourceLayout.setUnitDimData(broadcastUnitDims)) &&
1497 "The sg_data for unit dimensions should be set as 1");
1498 sourceLayout = sourceLayout.setUnitDimLayout(broadcastUnitDims);
1499 }
1500 } else {
1501 // Case 3: Scalar to vector broadcast.
1502 if (sourceLayout)
1503 return rewriter.notifyMatchFailure(
1504 op, "broadcast from scalar must not have a layout attribute");
1505 }
1506
1507 auto destDistType =
1508 xegpu::getDistVecTypeBasedOnLaneLayout(resultLayout, destType);
1509 if (failed(destDistType))
1510 return rewriter.notifyMatchFailure(
1511 op, "failed to distribute the result vector type");
1512
1513 Value source = adaptor.getSource();
1514 // If the adapted source already matches the dest dist type, it's a no-op.
1515 if (source.getType() == destDistType.value()) {
1516 rewriter.replaceOp(op, source);
1517 return success();
1518 }
1519
1520 auto newOp = vector::BroadcastOp::create(rewriter, op.getLoc(),
1521 destDistType.value(), source);
1522 rewriter.replaceOp(op, newOp);
1523 return success();
1524 }
1525};
1526
1527/// Distributes a subgroup-level vector.insert_strided_slice op to
1528/// lane-level. If the dest is distributed, the offsets are adjusted to
1529/// match the distributed types.
1530struct SgToLaneVectorInsertStridedSlice
1531 : public OpConversionPattern<vector::InsertStridedSliceOp> {
1532 using OpConversionPattern<vector::InsertStridedSliceOp>::OpConversionPattern;
1533
1534 LogicalResult
1535 matchAndRewrite(vector::InsertStridedSliceOp op, OpAdaptor adaptor,
1536 ConversionPatternRewriter &rewriter) const override {
1537 xegpu::DistributeLayoutAttr resultLayout =
1538 xegpu::getTemporaryLayout(op->getOpResult(0));
1539 if (!resultLayout || !resultLayout.isForSubgroup())
1540 return failure();
1541
1542 VectorType destType = op.getDestVectorType();
1543 auto distDestTyOrFailure =
1544 xegpu::getDistVecTypeBasedOnLaneLayout(resultLayout, destType);
1545 if (failed(distDestTyOrFailure))
1546 return rewriter.notifyMatchFailure(
1547 op, "unable to compute distributed vector type from lane layout");
1548 VectorType distDestTy = *distDestTyOrFailure;
1549
1550 SmallVector<int64_t> destDistributedDims =
1551 getDistributedDims(destType, distDestTy);
1552
1553 SmallVector<Attribute> updatedOffsets = llvm::map_to_vector(
1554 op.getOffsets(), [](Attribute attr) { return attr; });
1555
1556 if (!destDistributedDims.empty()) {
1557 if (destDistributedDims.size() != 1)
1558 return rewriter.notifyMatchFailure(
1559 op, "only single dimension distribution is supported");
1560 int64_t destDistDim = destDistributedDims[0];
1561
1562 VectorType srcType = op.getSourceVectorType();
1563 // The distributed dim must be in the last k (source rank) dims of dest.
1564 int64_t sourceDistDim =
1565 destDistDim - (destType.getRank() - srcType.getRank());
1566 if (sourceDistDim < 0)
1567 return rewriter.notifyMatchFailure(
1568 op, "distributed dimension must be in the last k dims of dest");
1569
1570 auto destLayout = xegpu::getTemporaryLayout(op->getOpOperand(1));
1571 auto sourceLayout = xegpu::getTemporaryLayout(op->getOpOperand(0));
1572 if (!destLayout || !sourceLayout ||
1573 destLayout.getEffectiveLaneLayoutAsInt().empty() ||
1574 sourceLayout.getEffectiveLaneLayoutAsInt().empty())
1575 return rewriter.notifyMatchFailure(
1576 op, "source or dest of insert_strided_slice lacks distribution "
1577 "layout");
1578
1579 auto destLaneData = destLayout.getEffectiveLaneDataAsInt();
1580 auto sourceLaneData = sourceLayout.getEffectiveLaneDataAsInt();
1581 // Only check lane_data for the distributed dimension. Non-distributed
1582 // dimensions may have non-unit lane_data (e.g., packed layouts).
1583 if ((destDistDim < static_cast<int64_t>(destLaneData.size()) &&
1584 destLaneData[destDistDim] != 1) ||
1585 (sourceDistDim < static_cast<int64_t>(sourceLaneData.size()) &&
1586 sourceLaneData[sourceDistDim] != 1))
1587 return rewriter.notifyMatchFailure(
1588 op, "expecting unit lane data along the distributed dimension");
1589
1590 // The distributed dimension may span only a subset of the subgroup, so
1591 // divide its size and offset by the lanes that actually cover it.
1592 auto destLaneLayout = destLayout.getEffectiveLaneLayoutAsInt();
1593 int64_t numLanesAlongDim =
1594 destDistDim < static_cast<int64_t>(destLaneLayout.size())
1595 ? destLaneLayout[destDistDim]
1596 : 1;
1597
1598 int64_t srcDistrDimSize = srcType.getDimSize(sourceDistDim);
1599 if (srcDistrDimSize % numLanesAlongDim != 0)
1600 return rewriter.notifyMatchFailure(
1601 op, "source distributed dim size is not a multiple of "
1602 "the number of lanes along that dimension");
1603
1604 int64_t destDistrDimOffset =
1605 cast<IntegerAttr>(op.getOffsets()[destDistDim]).getInt();
1606 if (destDistrDimOffset % numLanesAlongDim != 0)
1607 return rewriter.notifyMatchFailure(
1608 op, "offset along distributed dim is not a multiple of "
1609 "the number of lanes along that dimension");
1610 // Adjust offset for the distributed dimension.
1611 updatedOffsets[destDistDim] =
1612 rewriter.getI64IntegerAttr(destDistrDimOffset / numLanesAlongDim);
1613 }
1614
1615 auto newOp = vector::InsertStridedSliceOp::create(
1616 rewriter, op.getLoc(), distDestTy, adaptor.getValueToStore(),
1617 adaptor.getDest(),
1618 ArrayAttr::get(rewriter.getContext(), updatedOffsets), op.getStrides());
1619 rewriter.replaceOp(op, newOp.getResult());
1620 return success();
1621 }
1622};
1623
1624/// Distributes a subgroup-level vector.insert op to lane-level. Only
1625/// handles sub-vector insertion (value to store is VectorType, not scalar).
1626struct SgToLaneVectorInsert : public OpConversionPattern<vector::InsertOp> {
1627 using OpConversionPattern<vector::InsertOp>::OpConversionPattern;
1628
1629 LogicalResult
1630 matchAndRewrite(vector::InsertOp op, OpAdaptor adaptor,
1631 ConversionPatternRewriter &rewriter) const override {
1632 // Only handle vector value-to-store (not scalar insertion).
1633 auto valueType = dyn_cast<VectorType>(op.getValueToStoreType());
1634 if (!valueType)
1635 return rewriter.notifyMatchFailure(op, "scalar insert not supported");
1636
1637 xegpu::DistributeLayoutAttr layout =
1638 xegpu::getTemporaryLayout(op->getOpResult(0));
1639 if (!layout || !layout.isForSubgroup())
1640 return failure();
1641
1642 // verify that the outer k dimensions (for offsets)
1643 // don't have non-unit lane_layout.
1644 auto laneLayout = layout.getEffectiveLaneLayoutAsInt();
1645 if (llvm::any_of(ArrayRef<int64_t>(laneLayout).drop_back(1),
1646 [](int64_t v) { return v != 1; }))
1647 return rewriter.notifyMatchFailure(
1648 op, "only innermost dimension distribution is supported for "
1649 "vector.insert");
1650
1651 auto newOp = vector::InsertOp::create(
1652 rewriter, op.getLoc(), adaptor.getValueToStore(), adaptor.getDest(),
1653 op.getMixedPosition());
1654 rewriter.replaceOp(op, newOp.getResult());
1655 return success();
1656 }
1657};
1658
1659/// Redistributes `src` for a `convert_layout` that changes only the
1660/// `lane_layout` along the outer (distributed) dimension, shrinking it from
1661/// `currentLaneNum` to `targetLaneNum` lanes (a partial-subgroup
1662/// distribution). Because the data is no longer replicated across all lanes,
1663/// each surviving lane must gather the values that previously lived in the
1664/// lanes that are dropped. The values are gathered with `gpu.shuffle` and
1665/// concatenated with the lane-local data using `vector.shuffle`, which doubles
1666/// the distributed outer dimension when the lane count is halved.
1667///
1668/// Only halving the lane count (a factor of two) is currently supported.
1669/// Returns the redistributed value on success, or failure if `src` cannot be
1670/// shuffled (e.g. it is not a rank-2 vector or its bit width is not a multiple
1671/// of 32).
1672static FailureOr<Value>
1673shuffleDataAsLaneLayoutChange(ConversionPatternRewriter &rewriter, Location loc,
1674 Value src, int64_t currentLaneNum,
1675 int64_t targetLaneNum) {
1676 VectorType srcTy = dyn_cast<VectorType>(src.getType());
1677 if (!srcTy || srcTy.getRank() != 2)
1678 return failure();
1679 // Only halving the lane count (factor of two) is supported for now.
1680 if (targetLaneNum <= 0 || currentLaneNum != targetLaneNum * 2)
1681 return failure();
1682 // gpu.shuffle operates on i32, so the data must be a multiple of 32 bits.
1683 int64_t vectorBitWidth =
1684 srcTy.getNumElements() * srcTy.getElementTypeBitWidth();
1685 if (vectorBitWidth % 32 != 0)
1686 return failure();
1687
1688 // A vector cannot be shuffled across lanes directly:
1689 // -- cast the source to a 1D vector of i32
1690 // -- create a temp 1D vector of i32 initialized to zero
1691 // -- for each i32 element:
1692 // ---- extract it from the source bundle
1693 // ---- gpu.shuffle to gather the value from the partner lane
1694 // ---- insert it into the temp bundle
1695 // -- cast the temp back to the source vector type
1696 // -- vector.shuffle the source and temp to concatenate along the outer dim
1697 Type shuffleElemTy = rewriter.getI32Type();
1698 int64_t numShuffles = vectorBitWidth / 32;
1699 VectorType shuffleBundleTy = VectorType::get({numShuffles}, shuffleElemTy);
1700 // Initialize temp to zero.
1701 Value temp = arith::ConstantOp::create(
1702 rewriter, loc,
1703 DenseElementsAttr::get(shuffleBundleTy,
1704 IntegerAttr::get(shuffleElemTy, 0)));
1705 VectorType flatSrcTy =
1706 VectorType::get({srcTy.getNumElements()}, srcTy.getElementType());
1707 Value flatSrc = vector::ShapeCastOp::create(rewriter, loc, flatSrcTy, src);
1708 Value shuffleBundle =
1709 vector::BitCastOp::create(rewriter, loc, shuffleBundleTy, flatSrc);
1710 for (int64_t i = 0; i < numShuffles; i++) {
1711 Value shuffleElem =
1712 vector::ExtractOp::create(rewriter, loc, shuffleBundle, i);
1713 shuffleElem = gpu::ShuffleOp::create(rewriter, loc, shuffleElem, 0,
1714 targetLaneNum, gpu::ShuffleMode::UP)
1715 .getResult(0);
1716 temp = vector::InsertOp::create(rewriter, loc, shuffleElem, temp, i);
1717 }
1718 temp = vector::BitCastOp::create(rewriter, loc, flatSrcTy, temp);
1719 temp = vector::ShapeCastOp::create(rewriter, loc, srcTy, temp);
1720
1721 // Concatenate the lane-local and gathered data along the outer dimension.
1722 SmallVector<int64_t> indices(srcTy.getShape()[0] * 2);
1723 std::iota(indices.begin(), indices.end(), 0);
1724 Value res = vector::ShuffleOp::create(rewriter, loc, src, temp, indices);
1725 return res;
1726}
1727
1728/// Repacks `src`'s `lane_data` along `repackDim` between round-robin and
1729/// contiguous form with an `xegpu.lane_shuffle`, which moves each lane's run of
1730/// `k` elements across lanes while preserving the element type.
1731///
1732/// `inputData`/`targetData` are the `repackDim` `lane_data` of the input and
1733/// target layouts; exactly one must be 1 (round-robin) and the other `k`
1734/// (contiguous). Returns failure if that does not hold.
1735static FailureOr<Value> repackLaneData(ConversionPatternRewriter &rewriter,
1736 Location loc, Value src,
1737 int64_t repackDim, int64_t inputData,
1738 int64_t targetData) {
1739 auto srcTy = dyn_cast<VectorType>(src.getType());
1740 if (!srcTy)
1741 return failure();
1742 int64_t rank = srcTy.getRank();
1743 Type elemTy = srcTy.getElementType();
1744 int64_t k = srcTy.getShape()[repackDim];
1745
1746 bool roundRobinToContig = inputData == 1 && targetData == k;
1747 bool contigToRoundRobin = inputData == k && targetData == 1;
1748 if (!roundRobinToContig && !contigToRoundRobin)
1749 return failure();
1750
1751 // Round-robin -> contiguous gathers a lane's strided elements into
1752 // consecutive positions (pack); the reverse scatters them back (unpack).
1753 xegpu::LaneShuffleMode mode = roundRobinToContig
1754 ? xegpu::LaneShuffleMode::Pack
1755 : xegpu::LaneShuffleMode::Unpack;
1756 VectorType runTy = VectorType::get({k}, elemTy);
1757
1758 // Common case: the lane fragment is a single run (every dimension other than
1759 // `repackDim` is unit), so collapse it to 1D, shuffle once, and restore it.
1760 if (srcTy.getNumElements() == k) {
1761 if (rank == 1)
1762 return Value(
1763 xegpu::LaneShuffleOp::create(rewriter, loc, runTy, src, mode));
1764 Value flat = vector::ShapeCastOp::create(rewriter, loc, runTy, src);
1765 Value shuffled =
1766 xegpu::LaneShuffleOp::create(rewriter, loc, runTy, flat, mode);
1767 return Value(vector::ShapeCastOp::create(rewriter, loc, srcTy, shuffled));
1768 }
1769
1770 // When `repackDim` is innermost each run is a contiguous sub-vector, so it is
1771 // extracted and re-inserted as a whole.
1772 if (repackDim == rank - 1) {
1773 SmallVector<int64_t> outerShape(srcTy.getShape().drop_back());
1774 int64_t numRuns = computeProduct(outerShape);
1775 SmallVector<int64_t> outerStrides = computeStrides(outerShape);
1776 Value result = arith::ConstantOp::create(rewriter, loc, srcTy,
1777 rewriter.getZeroAttr(srcTy));
1778 for (int64_t i = 0; i < numRuns; ++i) {
1779 SmallVector<int64_t> pos = delinearize(i, outerStrides);
1780 Value run = vector::ExtractOp::create(rewriter, loc, src, pos);
1781 Value shuffled =
1782 xegpu::LaneShuffleOp::create(rewriter, loc, runTy, run, mode);
1783 result = vector::InsertOp::create(rewriter, loc, shuffled, result, pos);
1784 }
1785 return result;
1786 }
1787
1788 // Otherwise each run is strided along `repackDim`: extract the `k`-long slice
1789 // (a sub-vector that is unit along every other dim), flatten it to 1D,
1790 // shuffle, and insert it back.
1791 SmallVector<int64_t> keptShape;
1792 SmallVector<int64_t> keptDims;
1793 for (int64_t d = 0; d < rank; ++d)
1794 if (d != repackDim) {
1795 keptShape.push_back(srcTy.getShape()[d]);
1796 keptDims.push_back(d);
1797 }
1798 int64_t numRuns = computeProduct(keptShape);
1799 SmallVector<int64_t> keptStrides = computeStrides(keptShape);
1800 SmallVector<int64_t> sliceSizes(rank, 1);
1801 sliceSizes[repackDim] = k;
1802 SmallVector<int64_t> sliceStrides(rank, 1);
1803 VectorType sliceTy = VectorType::get(sliceSizes, elemTy);
1804 Value result = arith::ConstantOp::create(rewriter, loc, srcTy,
1805 rewriter.getZeroAttr(srcTy));
1806 for (int64_t i = 0; i < numRuns; ++i) {
1807 SmallVector<int64_t> keptPos = delinearize(i, keptStrides);
1808 SmallVector<int64_t> offsets(rank, 0);
1809 for (auto [dim, coord] : llvm::zip_equal(keptDims, keptPos))
1810 offsets[dim] = coord;
1811 Value slice = vector::ExtractStridedSliceOp::create(
1812 rewriter, loc, src, offsets, sliceSizes, sliceStrides);
1813 Value run = vector::ShapeCastOp::create(rewriter, loc, runTy, slice);
1814 Value repacked =
1815 xegpu::LaneShuffleOp::create(rewriter, loc, runTy, run, mode);
1816 Value repackedSlice =
1817 vector::ShapeCastOp::create(rewriter, loc, sliceTy, repacked);
1818 result = vector::InsertStridedSliceOp::create(
1819 rewriter, loc, repackedSlice, result, offsets, sliceStrides);
1820 }
1821 return result;
1822}
1823
1824/// Folds a subgroup-level ConvertLayout op with compatible lane layouts.
1825struct SgToLaneConvertLayout
1826 : public OpConversionPattern<xegpu::ConvertLayoutOp> {
1827 using OpConversionPattern<xegpu::ConvertLayoutOp>::OpConversionPattern;
1828
1829 LogicalResult
1830 matchAndRewrite(xegpu::ConvertLayoutOp op, OpAdaptor adaptor,
1831 ConversionPatternRewriter &rewriter) const override {
1832 auto inputLayout = op.getEffectiveInputLayout();
1833 auto targetLayout = op.getTargetLayoutAttr();
1834 Type valType = op.getResult().getType();
1835
1836 if (valType.isIntOrFloat()) {
1837 rewriter.replaceOp(op, op.getSource());
1838 return success();
1839 }
1840
1841 auto resShape = cast<VectorType>(valType).getShape();
1842 SmallVector<int64_t> resShapeVec(resShape.begin(), resShape.end());
1843
1844 // Equivalent layouts: the convert_layout is a no-op and folds to its
1845 // source.
1846 if (inputLayout.isCompatibleWith(targetLayout, resShapeVec,
1847 xegpu::LayoutKind::Lane)) {
1848 rewriter.replaceOp(op, adaptor.getSource());
1849 return success();
1850 }
1851
1852 // Handle the special case where the conversion redistributes a value
1853 // across a fraction of the subgroup: the lane_layout shrinks along the
1854 // outer (distributed) dimension while lane_data stays the same. Only a
1855 // pure outer-dimension lane_layout change is supported, so the inner
1856 // lane_layout must be unit (making the outer dim the only distributed one)
1857 // and the outer lane_layout must be genuinely distributed (> 1), which
1858 // also rules out the degenerate [1, 1] layout.
1859 if (inputLayout.getEffectiveOrderAsInt() ==
1860 targetLayout.getEffectiveOrderAsInt() &&
1861 inputLayout.getRank() == 2 && targetLayout.getRank() == 2) {
1862 auto laneLayout = inputLayout.getEffectiveLaneLayoutAsInt();
1863 auto targetLaneLayout = targetLayout.getEffectiveLaneLayoutAsInt();
1864 auto laneData = inputLayout.getEffectiveLaneDataAsInt();
1865 auto targetLaneData = targetLayout.getEffectiveLaneDataAsInt();
1866 if (laneLayout.size() == 2 && targetLaneLayout.size() == 2 &&
1867 laneData == targetLaneData && laneLayout[1] == 1 &&
1868 targetLaneLayout[1] == 1 && laneLayout[0] > 1 &&
1869 laneLayout[0] != targetLaneLayout[0]) {
1870 FailureOr<Value> res = shuffleDataAsLaneLayoutChange(
1871 rewriter, op.getLoc(), adaptor.getSource(), laneLayout[0],
1872 targetLaneLayout[0]);
1873 if (succeeded(res)) {
1874 rewriter.replaceOp(op, *res);
1875 return success();
1876 }
1877 }
1878 }
1879
1880 // Handle a pure `lane_data` repack: `lane_layout` and `order` are unchanged
1881 // and exactly one dimension's `lane_data` switches between round-robin
1882 // (lane_data 1) and contiguous (lane_data == run length). The elements per
1883 // lane are unchanged, but their assignment to lanes is not, so the data is
1884 // moved across lanes with `xegpu.lane_shuffle`. The changed dimension must
1885 // be one of the two innermost ones, since sg-to-lane distribution is 2D.
1886 if (inputLayout.getEffectiveOrderAsInt() ==
1887 targetLayout.getEffectiveOrderAsInt() &&
1888 inputLayout.getEffectiveLaneLayoutAsInt() ==
1889 targetLayout.getEffectiveLaneLayoutAsInt()) {
1890 auto laneLayout = inputLayout.getEffectiveLaneLayoutAsInt();
1891 auto laneData = inputLayout.getEffectiveLaneDataAsInt();
1892 auto targetLaneData = targetLayout.getEffectiveLaneDataAsInt();
1893 // Find the single dimension whose lane_data changed; bail out if more
1894 // than one differs.
1895 int64_t rank = laneData.size();
1896 int64_t repackDim = -1;
1897 bool multipleChanged = false;
1898 for (int64_t d = 0; d < rank; ++d)
1899 if (laneData[d] != targetLaneData[d]) {
1900 if (repackDim != -1)
1901 multipleChanged = true;
1902 repackDim = d;
1903 }
1904
1905 // `repackDim` must be the distributed dim (lane_layout != 1) and the
1906 // other innermost dim non-distributed (lane_layout == 1).
1907 int64_t otherDim = repackDim == rank - 1 ? rank - 2 : rank - 1;
1908 bool laneLayoutOk = repackDim != -1 && laneLayout[repackDim] != 1 &&
1909 (rank < 2 || laneLayout[otherDim] == 1);
1910
1911 // Exactly one dimension must change, and it must be one of the two
1912 // innermost (>= rank - 2).
1913 if (repackDim != -1 && repackDim >= rank - 2 && !multipleChanged &&
1914 laneLayoutOk) {
1915 FailureOr<Value> res = repackLaneData(
1916 rewriter, op.getLoc(), adaptor.getSource(), repackDim,
1917 laneData[repackDim], targetLaneData[repackDim]);
1918 if (succeeded(res)) {
1919 rewriter.replaceOp(op, *res);
1920 return success();
1921 }
1922 }
1923 }
1924
1925 return rewriter.notifyMatchFailure(
1926 op, "lowering incompatible convert_layout not yet supported");
1927 }
1928};
1929
1930/// The offsets and shape of one `lane_data`-sized piece of a lane's fragment.
1931/// `computeDistributedCoords` returns one coordinate per distribution unit,
1932/// enumerated row major over `shape / (lane_layout * lane_data)`, and unit `u`
1933/// owns the piece of the fragment at `delinearize(u) * lane_data`.
1934struct LaneFragmentPiece {
1935 SmallVector<int64_t> offsets;
1936 SmallVector<int64_t> sizes;
1937};
1938
1939static LaneFragmentPiece getLaneFragmentPiece(int64_t unit,
1941 ArrayRef<int64_t> laneLayout,
1942 ArrayRef<int64_t> laneData) {
1943 int64_t rank = shape.size();
1944 SmallVector<int64_t> units(rank);
1945 for (int64_t d = 0; d < rank; ++d)
1946 units[d] = shape[d] / std::min(shape[d], laneLayout[d] * laneData[d]);
1947 SmallVector<int64_t> unitCoords = delinearize(unit, computeStrides(units));
1948 LaneFragmentPiece piece;
1949 for (int64_t d = 0; d < rank; ++d) {
1950 piece.offsets.push_back(unitCoords[d] * laneData[d]);
1951 piece.sizes.push_back(laneData[d]);
1952 }
1953 return piece;
1954}
1955
1956/// Last-resort lowering for a `convert_layout` that none of the patterns above
1957/// handle: round-trip the value through shared local memory, writing each
1958/// lane's fragment to the coordinates `input_layout` gives it and reading it
1959/// back from the ones `target_layout` gives it. Any pair of layouts that can
1960/// both distribute the value works, at the cost of an SLM write and read.
1961///
1962/// The op is subgroup level, but every subgroup of the workgroup executes it on
1963/// its own data, so the scratch holds one tile per subgroup and each subgroup
1964/// addresses its own through a `gpu.subgroup_id` offset on the outermost
1965/// dimension. The subgroup count comes from the kernel's `known_block_size`.
1966///
1967/// A lane's fragment is one `lane_data`-sized piece per distribution unit, so
1968/// the transfer is one `store_matrix`/`load_matrix` per unit; layouts with
1969/// a single unit, which is the common case, give a single pair.
1970struct SgToLaneConvertLayoutViaSLM
1971 : public OpConversionPattern<xegpu::ConvertLayoutOp> {
1972 using OpConversionPattern<xegpu::ConvertLayoutOp>::OpConversionPattern;
1973
1974 LogicalResult
1975 matchAndRewrite(xegpu::ConvertLayoutOp op, OpAdaptor adaptor,
1976 ConversionPatternRewriter &rewriter) const override {
1977 xegpu::DistributeLayoutAttr inputLayout = op.getEffectiveInputLayout();
1978 xegpu::DistributeLayoutAttr targetLayout = op.getTargetLayoutAttr();
1979 if (!inputLayout || !targetLayout || !inputLayout.isForSubgroup() ||
1980 !targetLayout.isForSubgroup())
1981 return rewriter.notifyMatchFailure(op, "both layouts must be lane level");
1982
1983 auto valueTy = dyn_cast<VectorType>(op.getResult().getType());
1984 if (!valueTy)
1985 return rewriter.notifyMatchFailure(op, "value type must be a vector");
1986 Type elemTy = valueTy.getElementType();
1987 // The scratch is sized in bytes, so sub-byte elements would not get a
1988 // well-defined address.
1989 if (!elemTy.isIntOrFloat() || elemTy.getIntOrFloatBitWidth() % 8 != 0)
1990 return rewriter.notifyMatchFailure(
1991 op, "element type must be a whole number of bytes");
1992
1993 ArrayRef<int64_t> sgShape = valueTy.getShape();
1994 int64_t rank = sgShape.size();
1995 if (rank != inputLayout.getRank() || rank != targetLayout.getRank())
1996 return rewriter.notifyMatchFailure(
1997 op, "both layouts must have the rank of the value");
1998
1999 FailureOr<VectorType> distInputTy =
2000 xegpu::getDistVecTypeBasedOnLaneLayout(inputLayout, valueTy);
2001 FailureOr<VectorType> distTargetTy =
2002 xegpu::getDistVecTypeBasedOnLaneLayout(targetLayout, valueTy);
2003 if (failed(distInputTy) || failed(distTargetTy))
2004 return rewriter.notifyMatchFailure(
2005 op, "value type must be distributable by both layouts");
2006
2007 const auto *uArch =
2008 xegpu::uArch::getUArch(xegpu::getChipStr(op).value_or(""));
2009 if (!uArch)
2010 return rewriter.notifyMatchFailure(
2011 op, "target attribute is required to determine the subgroup size");
2012 FailureOr<int64_t> numSubgroups =
2013 xegpu::getNumSubgroupsFromBlockSize(op, uArch->getSubgroupSize());
2014 if (failed(numSubgroups))
2015 return rewriter.notifyMatchFailure(
2016 op, "the scratch holds one tile per subgroup, so @known_block_size "
2017 "must be attached to the kernel, with power-of-two dimensions "
2018 "covering at least one subgroup");
2019
2020 Location loc = op.getLoc();
2021
2022 // One tile per subgroup, stacked along the outermost dimension.
2023 SmallVector<int64_t> slmShape(sgShape);
2024 slmShape[0] *= *numSubgroups;
2025 int64_t slmBytes =
2026 computeProduct(slmShape) * elemTy.getIntOrFloatBitWidth() / 8;
2027 auto slmTy = MemRefType::get({slmBytes}, rewriter.getI8Type(), {}, 3);
2028 Value slm = memref::AllocaOp::create(rewriter, loc, slmTy);
2029 Value memDesc = xegpu::CreateMemDescOp::create(
2030 rewriter, loc,
2031 xegpu::MemDescType::get(rewriter.getContext(), slmShape, elemTy,
2032 nullptr),
2033 slm);
2034
2035 // This subgroup's tile starts at `subgroup_id` tiles into the scratch.
2036 Value sgId = gpu::SubgroupIdOp::create(rewriter, loc,
2037 rewriter.getIndexType(), nullptr);
2038 SmallVector<Value> base(rank);
2039 base[0] = arith::MulIOp::create(
2040 rewriter, loc, sgId,
2041 arith::ConstantIndexOp::create(rewriter, loc, sgShape[0]));
2042 for (int64_t d = 1; d < rank; ++d)
2043 base[d] = arith::ConstantIndexOp::create(rewriter, loc, 0);
2044
2045 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
2046 /*upperBound=*/mlir::IntegerAttr());
2047 auto dynamicOffsets = rewriter.getDenseI64ArrayAttr(
2048 SmallVector<int64_t>(rank, ShapedType::kDynamic));
2049
2050 // Adds this subgroup's base to one distribution unit's coordinates.
2051 auto withBase = [&](ArrayRef<Value> coords) {
2052 SmallVector<Value> offsets;
2053 for (auto [coord, b] : llvm::zip_equal(coords, base))
2054 offsets.push_back(arith::AddIOp::create(rewriter, loc, coord, b));
2055 return offsets;
2056 };
2057
2058 // Write phase: every lane stores the pieces `input_layout` gives it.
2059 auto storeCoords =
2060 inputLayout.computeDistributedCoords(rewriter, loc, laneId, sgShape);
2061 if (failed(storeCoords))
2062 return rewriter.notifyMatchFailure(
2063 op, "failed to compute the input_layout coordinates");
2064 SmallVector<int64_t> inputLaneLayout =
2065 inputLayout.getEffectiveLaneLayoutAsInt();
2066 SmallVector<int64_t> inputLaneData =
2067 inputLayout.getEffectiveLaneDataAsInt();
2068 Value fragment =
2069 castValueTo(rewriter, cast<TypedValue<VectorType>>(adaptor.getSource()),
2070 *distInputTy);
2071 for (auto [unit, coords] : llvm::enumerate(*storeCoords)) {
2072 LaneFragmentPiece piece =
2073 getLaneFragmentPiece(unit, sgShape, inputLaneLayout, inputLaneData);
2074 Value data = fragment;
2075 if (piece.sizes != SmallVector<int64_t>(distInputTy->getShape()))
2076 data = vector::ExtractStridedSliceOp::create(
2077 rewriter, loc, fragment, piece.offsets, piece.sizes,
2078 SmallVector<int64_t>(rank, 1));
2079 xegpu::StoreMatrixOp::create(rewriter, loc, TypeRange{}, data, memDesc,
2080 ValueRange(withBase(coords)), dynamicOffsets,
2081 nullptr, xegpu::DistributeLayoutAttr{});
2082 }
2083
2084 // The scratch is only exchanged between the lanes of one subgroup, which is
2085 // a single hardware thread, so ordering the write before the read is enough
2086 // and no workgroup barrier is needed.
2087 xegpu::FenceOp::create(rewriter, loc, xegpu::MemorySpace::SLM,
2088 xegpu::FenceScope::Workgroup);
2089
2090 // Read phase: every lane loads the pieces `target_layout` gives it.
2091 auto loadCoords =
2092 targetLayout.computeDistributedCoords(rewriter, loc, laneId, sgShape);
2093 if (failed(loadCoords))
2094 return rewriter.notifyMatchFailure(
2095 op, "failed to compute the target_layout coordinates");
2096 SmallVector<int64_t> targetLaneLayout =
2097 targetLayout.getEffectiveLaneLayoutAsInt();
2098 SmallVector<int64_t> targetLaneData =
2099 targetLayout.getEffectiveLaneDataAsInt();
2100 Value result;
2101 if (loadCoords->size() > 1)
2102 result = arith::ConstantOp::create(rewriter, loc, *distTargetTy,
2103 rewriter.getZeroAttr(*distTargetTy));
2104 for (auto [unit, coords] : llvm::enumerate(*loadCoords)) {
2105 LaneFragmentPiece piece =
2106 getLaneFragmentPiece(unit, sgShape, targetLaneLayout, targetLaneData);
2107 auto pieceTy = VectorType::get(piece.sizes, elemTy);
2108 Value loaded = xegpu::LoadMatrixOp::create(
2109 rewriter, loc, pieceTy, memDesc, ValueRange(withBase(coords)),
2110 dynamicOffsets, nullptr, xegpu::DistributeLayoutAttr{});
2111 if (!result) {
2112 result = loaded;
2113 break;
2114 }
2115 result = vector::InsertStridedSliceOp::create(
2116 rewriter, loc, loaded, result, piece.offsets,
2117 SmallVector<int64_t>(rank, 1));
2118 }
2119
2120 rewriter.replaceOp(op, castValueTo(rewriter,
2122 *distTargetTy));
2123 return success();
2124 }
2125};
2126
2127/// `getEffectiveLaneDataAsInt` is empty when `lane_data` is unset, so the unit
2128/// check also rejects layouts that are not lane level.
2129static bool hasDefaultOrderAndUnitLaneData(xegpu::DistributeLayoutAttr layout) {
2130 if (layout.getRank() != 2)
2131 return false;
2132 return layout.getEffectiveLaneDataAsInt() == SmallVector<int64_t>{1, 1} &&
2133 layout.getEffectiveOrderAsInt() == SmallVector<int64_t>{1, 0};
2134}
2135
2136/// The quantities every element-to-lane redistribution needs, see
2137/// `matchElementLaneRedistribution`.
2138struct ElementLaneRedistribution {
2139 /// Subgroup-level type of the converted value.
2140 VectorType valueType;
2141 /// `valueType` as distributed by `input_layout` and by `target_layout`.
2142 VectorType distributedInput;
2143 VectorType distributedTarget;
2144 /// Effective `lane_layout` of `input_layout` and of `target_layout`. These
2145 /// always differ, otherwise the conversion would already have folded.
2146 SmallVector<int64_t> inputLaneLayout;
2147 SmallVector<int64_t> targetLaneLayout;
2148 int64_t subgroupSize;
2149};
2150
2151/// Recognizes an `xegpu.convert_layout` that redistributes individual elements
2152/// between the lanes of a subgroup, which is the common condition the three
2153/// slice-attributed lowerings below have.
2154/// Both input and target layouts must satisfy `hasDefaultOrderAndUnitLaneData`
2155/// and must be able to distribute the value, the two can only differ in which
2156/// lane owns which element.
2157static FailureOr<ElementLaneRedistribution>
2158matchElementLaneRedistribution(xegpu::ConvertLayoutOp op,
2159 ConversionPatternRewriter &rewriter) {
2160 xegpu::DistributeLayoutAttr inputLayout = op.getEffectiveInputLayout();
2161 xegpu::DistributeLayoutAttr targetLayout = op.getTargetLayoutAttr();
2162 if (!hasDefaultOrderAndUnitLaneData(inputLayout) ||
2163 !hasDefaultOrderAndUnitLaneData(targetLayout))
2164 return rewriter.notifyMatchFailure(
2165 op, "both layouts must be rank 2 with effective lane_data [1, 1] and "
2166 "effective order [1, 0]");
2167
2168 auto valueType = dyn_cast<VectorType>(op.getResult().getType());
2169 if (!valueType)
2170 return rewriter.notifyMatchFailure(op, "value type must be a vector");
2171
2172 FailureOr<VectorType> distributedInput =
2173 xegpu::getDistVecTypeBasedOnLaneLayout(inputLayout, valueType);
2174 FailureOr<VectorType> distributedTarget =
2175 xegpu::getDistVecTypeBasedOnLaneLayout(targetLayout, valueType);
2176 if (failed(distributedInput) || failed(distributedTarget))
2177 return rewriter.notifyMatchFailure(
2178 op, "value type must be distributable by both layouts");
2179
2180 const auto *uArch =
2181 xegpu::uArch::getUArch(xegpu::getChipStr(op).value_or(""));
2182 if (!uArch)
2183 return rewriter.notifyMatchFailure(
2184 op, "target attribute is required to determine the subgroup size");
2185
2186 ElementLaneRedistribution redistribution;
2187 redistribution.valueType = valueType;
2188 redistribution.distributedInput = *distributedInput;
2189 redistribution.distributedTarget = *distributedTarget;
2190 redistribution.inputLaneLayout = inputLayout.getEffectiveLaneLayoutAsInt();
2191 redistribution.targetLaneLayout = targetLayout.getEffectiveLaneLayoutAsInt();
2192 redistribution.subgroupSize = uArch->getSubgroupSize();
2193 return redistribution;
2194}
2195
2196/// Returns the lane stride of the single distributed dimension of `slice`, i.e.
2197/// the distance in lane ids between two adjacent coordinates along that
2198/// dimension. `slice` must have exactly one non-sliced dimension whose parent
2199/// `lane_layout` extent is greater than one; the stride is the product of the
2200/// parent `lane_layout` extents that precede it in the parent `order`.
2201///
2202/// Example: for
2203/// #xegpu.slice<#xegpu.layout<lane_layout = [8, 1, 2], lane_data = [4, 1, 1],
2204/// order = [0, 2, 1]>, dims = [0]>
2205/// the only such dimension is parent dim 2, of extent 2. `order` makes dim 0
2206/// the fastest varying, with extent 8, so lanes 0..7 hold coordinate 0 and
2207/// lanes 8..15 hold coordinate 1: the stride is 8.
2208static FailureOr<int64_t> getDistributedDimLaneStride(xegpu::SliceAttr slice) {
2209 xegpu::SliceAttr flattened = slice.flatten();
2210 auto parent = dyn_cast<xegpu::LayoutAttr>(flattened.getParent());
2211 if (!parent)
2212 return failure();
2213
2214 SmallVector<int64_t> parentLaneLayout = parent.getEffectiveLaneLayoutAsInt();
2215 SmallVector<int64_t> parentOrder = parent.getEffectiveOrderAsInt();
2216 if (parentLaneLayout.size() != parentOrder.size())
2217 return failure();
2218
2219 ArrayRef<int64_t> slicedDims = flattened.getDims().asArrayRef();
2220 std::optional<int64_t> distributedDim;
2221 for (int64_t dim = 0, rank = static_cast<int64_t>(parentLaneLayout.size());
2222 dim < rank; ++dim) {
2223 if (llvm::is_contained(slicedDims, dim) || parentLaneLayout[dim] == 1)
2224 continue;
2225 if (distributedDim)
2226 return failure();
2227 distributedDim = dim;
2228 }
2229 if (!distributedDim)
2230 return failure();
2231
2232 int64_t stride = 1;
2233 for (int64_t dim : parentOrder) {
2234 if (dim == *distributedDim)
2235 return stride;
2236 stride *= parentLaneLayout[dim];
2237 }
2238 return failure();
2239}
2240
2241/// Distributes the slice-attributed `xegpu.convert_layout` whose source is
2242/// fully broadcast, i.e. every lane holds the whole value, onto the rows of a
2243/// subset of the lanes. Each lane keeps a single element, so no data crosses
2244/// lanes and one `vector.extract` suffices.
2245///
2246/// The input layout has effective `lane_layout` [1, 1], so the distributed
2247/// source is the whole value; the target has [n, 1], so lane `l` keeps row
2248/// `l % n` and the distributed result is `vector<1x1>`.
2249///
2250/// The source is flattened first because `xegpu-vector-linearize` cannot
2251/// linearize a `vector.extract` with a dynamic position out of a rank-2 value.
2252struct SgToLaneConvertLayoutBroadcastExtract
2253 : public OpConversionPattern<xegpu::ConvertLayoutOp> {
2254 using OpConversionPattern<xegpu::ConvertLayoutOp>::OpConversionPattern;
2255
2256 LogicalResult
2257 matchAndRewrite(xegpu::ConvertLayoutOp op, OpAdaptor adaptor,
2258 ConversionPatternRewriter &rewriter) const override {
2259 xegpu::DistributeLayoutAttr inputLayout = op.getEffectiveInputLayout();
2260 xegpu::DistributeLayoutAttr targetLayout = op.getTargetLayoutAttr();
2261
2262 if (!isa<xegpu::SliceAttr>(inputLayout))
2263 return rewriter.notifyMatchFailure(op,
2264 "input_layout must be #xegpu.slice");
2265 if (!isa<xegpu::LayoutAttr>(targetLayout))
2266 return rewriter.notifyMatchFailure(op,
2267 "target_layout must be #xegpu.layout");
2268
2269 FailureOr<ElementLaneRedistribution> redistribution =
2270 matchElementLaneRedistribution(op, rewriter);
2271 if (failed(redistribution))
2272 return failure();
2273
2274 if (redistribution->inputLaneLayout != SmallVector<int64_t>{1, 1})
2275 return rewriter.notifyMatchFailure(
2276 op, "input_layout effective lane_layout must be [1, 1]");
2277 SmallVector<int64_t> targetLaneLayout = redistribution->targetLaneLayout;
2278 if (targetLaneLayout[0] <= 1 || targetLaneLayout[1] != 1)
2279 return rewriter.notifyMatchFailure(
2280 op, "target_layout effective lane_layout must be [n, 1] with n > 1");
2281 if (redistribution->distributedInput != redistribution->valueType)
2282 return rewriter.notifyMatchFailure(
2283 op, "distributed input_layout type must equal the value type");
2284 if (redistribution->distributedTarget.getShape() != ArrayRef<int64_t>{1, 1})
2285 return rewriter.notifyMatchFailure(
2286 op, "distributed target_layout type must be vector<1x1>");
2287 if (targetLaneLayout[0] > redistribution->subgroupSize)
2288 return rewriter.notifyMatchFailure(
2289 op, "target_layout effective lane_layout[0] must not exceed the "
2290 "subgroup size");
2291
2292 VectorType valueType = redistribution->valueType;
2293 Location loc = op.getLoc();
2294 Value src =
2295 castValueTo(rewriter, cast<TypedValue<VectorType>>(adaptor.getSource()),
2296 redistribution->distributedInput);
2297 auto flatType = VectorType::get({valueType.getNumElements()},
2298 valueType.getElementType());
2299 Value flat = vector::ShapeCastOp::create(rewriter, loc, flatType, src);
2300 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
2301 /*upperBound=*/mlir::IntegerAttr());
2302 Value rowCount =
2303 arith::ConstantIndexOp::create(rewriter, loc, targetLaneLayout[0]);
2304 Value row = arith::RemUIOp::create(rewriter, loc, laneId, rowCount);
2305 Value element = vector::ExtractOp::create(rewriter, loc, flat,
2306 ArrayRef<OpFoldResult>{row});
2307 rewriter.replaceOpWithNewOp<vector::FromElementsOp>(
2308 op, redistribution->distributedTarget, element);
2309 return success();
2310 }
2311};
2312
2313/// Distributes the slice-attributed `xegpu.convert_layout` whose source is
2314/// broadcast over two lane groups onto the rows of a subset of the lanes.
2315/// Column `c` of row `r` is owned by lane `r + c * stride`, where `stride` is
2316/// the lane stride of the input's distributed dimension (see
2317/// `getDistributedDimLaneStride`), so each lane extracts its own element and
2318/// gathers the columns of its row with one `gpu.shuffle idx` per column.
2319///
2320/// The input layout has effective `lane_layout` [1, 2], so the distributed
2321/// source holds one column per lane group; the target has [n, 1], so lane `l`
2322/// keeps row `l % n` of both columns and the distributed result is
2323/// `vector<1x2>`.
2324///
2325/// xegpu.convert_layout %src
2326/// <{input_layout = #xegpu.slice<#xegpu.layout<lane_layout = [8, 1, 2],
2327/// lane_data = [4, 1, 1],
2328/// order = [0, 2, 1]>,
2329/// dims = [0]>,
2330/// target_layout = #xegpu.layout<lane_layout = [8, 1],
2331/// lane_data = [1, 1]>}>
2332/// : vector<8x2xf8E8M0FNU>
2333///
2334/// becomes, with lane `l` holding all 8 rows of column `l / 8`:
2335///
2336/// %flat = vector.shape_cast %src : vector<8x1xf8E8M0FNU> to
2337/// vector<8xf8E8M0FNU>
2338/// %lane = gpu.lane_id
2339/// %row = arith.remui %lane, %c8 : index
2340/// %own = vector.extract %flat[%row] : f8E8M0FNU from
2341/// vector<8xf8E8M0FNU>
2342/// %rowI32 = arith.index_cast %row : index to i32
2343/// %owner1 = arith.addi %rowI32, %c8_i32 : i32
2344/// %col0, %v0 = gpu.shuffle idx %own, %rowI32, %c16_i32 : f8E8M0FNU
2345/// %col1, %v1 = gpu.shuffle idx %own, %owner1, %c16_i32 : f8E8M0FNU
2346/// %res = vector.from_elements %col0, %col1 : vector<1x2xf8E8M0FNU>
2347///
2348/// The source is flattened first because `xegpu-vector-linearize` cannot
2349/// linearize a `vector.extract` with a dynamic position out of a rank-2 value.
2350///
2351/// All lanes gather every column, including the one they already hold, so that
2352/// lanes outside the target `lane_layout` hold replicas as partial lane layouts
2353/// require.
2354struct SgToLaneConvertLayoutPartialBroadcastExtractShuffle
2355 : public OpConversionPattern<xegpu::ConvertLayoutOp> {
2356 using OpConversionPattern<xegpu::ConvertLayoutOp>::OpConversionPattern;
2357
2358 LogicalResult
2359 matchAndRewrite(xegpu::ConvertLayoutOp op, OpAdaptor adaptor,
2360 ConversionPatternRewriter &rewriter) const override {
2361 xegpu::DistributeLayoutAttr inputLayout = op.getEffectiveInputLayout();
2362 xegpu::DistributeLayoutAttr targetLayout = op.getTargetLayoutAttr();
2363
2364 auto inputSlice = dyn_cast<xegpu::SliceAttr>(inputLayout);
2365 if (!inputSlice)
2366 return rewriter.notifyMatchFailure(op,
2367 "input_layout must be #xegpu.slice");
2368 if (!isa<xegpu::LayoutAttr>(targetLayout))
2369 return rewriter.notifyMatchFailure(op,
2370 "target_layout must be #xegpu.layout");
2371
2372 FailureOr<ElementLaneRedistribution> redistribution =
2373 matchElementLaneRedistribution(op, rewriter);
2374 if (failed(redistribution))
2375 return failure();
2376
2377 VectorType valueType = redistribution->valueType;
2378 Type elementType = valueType.getElementType();
2379 if (!elementType.isIntOrFloat() ||
2380 !llvm::is_contained({8u, 16u, 32u, 64u},
2381 elementType.getIntOrFloatBitWidth()))
2382 return rewriter.notifyMatchFailure(
2383 op, "element type must be an int or float of bit width 8, 16, 32 or "
2384 "64 to be carried by gpu.shuffle");
2385
2386 if (redistribution->inputLaneLayout != SmallVector<int64_t>{1, 2})
2387 return rewriter.notifyMatchFailure(
2388 op, "input_layout effective lane_layout must be [1, 2]");
2389 SmallVector<int64_t> targetLaneLayout = redistribution->targetLaneLayout;
2390 if (targetLaneLayout[0] <= 1 || targetLaneLayout[1] != 1)
2391 return rewriter.notifyMatchFailure(
2392 op, "target_layout effective lane_layout must be [n, 1] with n > 1");
2393 if (redistribution->distributedInput.getShape() !=
2394 ArrayRef<int64_t>{valueType.getDimSize(0), 1})
2395 return rewriter.notifyMatchFailure(
2396 op, "distributed input_layout type must be vector<shape[0]x1>");
2397 if (redistribution->distributedTarget.getShape() != ArrayRef<int64_t>{1, 2})
2398 return rewriter.notifyMatchFailure(
2399 op, "distributed target_layout type must be vector<1x2>");
2400
2401 FailureOr<int64_t> stride = getDistributedDimLaneStride(inputSlice);
2402 if (failed(stride))
2403 return rewriter.notifyMatchFailure(
2404 op, "input_layout parent must have exactly one non-sliced dimension "
2405 "with lane_layout extent greater than one");
2406 // The two broadcast groups must together cover the whole subgroup, so that
2407 // lane `r + c * stride` is the lane holding column `c` of row `r`.
2408 if (*stride * redistribution->inputLaneLayout[1] !=
2409 redistribution->subgroupSize)
2410 return rewriter.notifyMatchFailure(
2411 op, "input_layout distributed dimension lane stride times its extent "
2412 "must equal the subgroup size");
2413 // Lane `r + c * stride` must hold row `r`, i.e. (r + stride) %
2414 // lane_layout[0] must be r, which requires the row count to divide the
2415 // stride.
2416 if (*stride % targetLaneLayout[0] != 0)
2417 return rewriter.notifyMatchFailure(
2418 op, "target_layout effective lane_layout[0] must divide the "
2419 "input_layout distributed dimension lane stride");
2420
2421 Location loc = op.getLoc();
2422 Value src =
2423 castValueTo(rewriter, cast<TypedValue<VectorType>>(adaptor.getSource()),
2424 redistribution->distributedInput);
2425 auto flatType =
2426 VectorType::get({redistribution->distributedInput.getNumElements()},
2427 valueType.getElementType());
2428 Value flat = vector::ShapeCastOp::create(rewriter, loc, flatType, src);
2429 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
2430 /*upperBound=*/mlir::IntegerAttr());
2431 Value rowCount =
2432 arith::ConstantIndexOp::create(rewriter, loc, targetLaneLayout[0]);
2433 Value row = arith::RemUIOp::create(rewriter, loc, laneId, rowCount);
2434 Value own = vector::ExtractOp::create(rewriter, loc, flat,
2435 ArrayRef<OpFoldResult>{row});
2436 // Gather column `c` of `row` from lane `row + c * stride`, which owns it.
2437 Type i32Type = rewriter.getI32Type();
2438 Value width = arith::ConstantIntOp::create(rewriter, loc, i32Type,
2439 redistribution->subgroupSize);
2440 Value rowI32 = arith::IndexCastOp::create(rewriter, loc, i32Type, row);
2441 Value strideI32 =
2442 arith::ConstantIntOp::create(rewriter, loc, i32Type, *stride);
2443 Value otherOwner = arith::AddIOp::create(rewriter, loc, rowI32, strideI32);
2444 Value column0 = gpu::ShuffleOp::create(rewriter, loc, own, rowI32, width,
2445 gpu::ShuffleMode::IDX)
2446 .getShuffleResult();
2447 Value column1 = gpu::ShuffleOp::create(rewriter, loc, own, otherOwner,
2448 width, gpu::ShuffleMode::IDX)
2449 .getShuffleResult();
2450 rewriter.replaceOpWithNewOp<vector::FromElementsOp>(
2451 op, redistribution->distributedTarget, ValueRange{column0, column1});
2452 return success();
2453 }
2454};
2455
2456/// Distributes the slice-attributed `xegpu.convert_layout` whose source is
2457/// fully broadcast and whose target splits the two columns of the value over
2458/// two lane groups. Each lane keeps one whole column, which is a stride-2
2459/// subset of the row-major source, so the two columns are separated with one
2460/// `vector.deinterleave` and the lane's group selects between them.
2461///
2462/// The input layout has effective `lane_layout` [1, 1], so the distributed
2463/// source is the whole value; the target has [1, 2] and its two groups tile the
2464/// subgroup, so the first half of the lanes keeps column 0 and the second half
2465/// column 1, one column per lane.
2466struct SgToLaneConvertLayoutDeinterleaveSelect
2467 : public OpConversionPattern<xegpu::ConvertLayoutOp> {
2468 using OpConversionPattern<xegpu::ConvertLayoutOp>::OpConversionPattern;
2469
2470 LogicalResult
2471 matchAndRewrite(xegpu::ConvertLayoutOp op, OpAdaptor adaptor,
2472 ConversionPatternRewriter &rewriter) const override {
2473 xegpu::DistributeLayoutAttr inputLayout = op.getEffectiveInputLayout();
2474 xegpu::DistributeLayoutAttr targetLayout = op.getTargetLayoutAttr();
2475
2476 if (!isa<xegpu::SliceAttr>(inputLayout))
2477 return rewriter.notifyMatchFailure(op,
2478 "input_layout must be #xegpu.slice");
2479 auto targetSlice = dyn_cast<xegpu::SliceAttr>(targetLayout);
2480 if (!targetSlice)
2481 return rewriter.notifyMatchFailure(op,
2482 "target_layout must be #xegpu.slice");
2483
2484 FailureOr<ElementLaneRedistribution> redistribution =
2485 matchElementLaneRedistribution(op, rewriter);
2486 if (failed(redistribution))
2487 return failure();
2488
2489 VectorType valueType = redistribution->valueType;
2490 if (redistribution->inputLaneLayout != SmallVector<int64_t>{1, 1})
2491 return rewriter.notifyMatchFailure(
2492 op, "input_layout effective lane_layout must be [1, 1]");
2493 SmallVector<int64_t> targetLaneLayout = redistribution->targetLaneLayout;
2494 if (targetLaneLayout != SmallVector<int64_t>{1, 2})
2495 return rewriter.notifyMatchFailure(
2496 op, "target_layout effective lane_layout must be [1, 2]");
2497 if (redistribution->distributedInput != valueType)
2498 return rewriter.notifyMatchFailure(
2499 op, "distributed input_layout type must equal the value type");
2500 if (redistribution->distributedTarget.getShape() !=
2501 ArrayRef<int64_t>{valueType.getDimSize(0), 1})
2502 return rewriter.notifyMatchFailure(
2503 op, "distributed target_layout type must be vector<shape[0]x1>");
2504
2505 FailureOr<int64_t> stride = getDistributedDimLaneStride(targetSlice);
2506 if (failed(stride))
2507 return rewriter.notifyMatchFailure(
2508 op, "target_layout parent must have exactly one non-sliced dimension "
2509 "with lane_layout extent greater than one");
2510 // The two lane groups must together cover the whole subgroup, so that
2511 // `lane_id / stride` is the index of the column the lane keeps.
2512 if (*stride * targetLaneLayout[1] != redistribution->subgroupSize)
2513 return rewriter.notifyMatchFailure(
2514 op, "target_layout distributed dimension lane stride times its "
2515 "extent must equal the subgroup size");
2516
2517 Location loc = op.getLoc();
2518 Value src =
2519 castValueTo(rewriter, cast<TypedValue<VectorType>>(adaptor.getSource()),
2520 redistribution->distributedInput);
2521 auto flatType = VectorType::get({valueType.getNumElements()},
2522 valueType.getElementType());
2523 Value flat = vector::ShapeCastOp::create(rewriter, loc, flatType, src);
2524 auto deinterleaved = vector::DeinterleaveOp::create(rewriter, loc, flat);
2525 Value laneId = gpu::LaneIdOp::create(rewriter, loc, rewriter.getIndexType(),
2526 /*upperBound=*/mlir::IntegerAttr());
2527 Value strideVal = arith::ConstantIndexOp::create(rewriter, loc, *stride);
2528 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
2529 Value group = arith::DivUIOp::create(rewriter, loc, laneId, strideVal);
2530 Value isFirstGroup = arith::CmpIOp::create(
2531 rewriter, loc, arith::CmpIPredicate::eq, group, zero);
2532 Value selected = arith::SelectOp::create(rewriter, loc, isFirstGroup,
2533 deinterleaved.getResultEven(),
2534 deinterleaved.getResultOdd());
2535 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(
2536 op, redistribution->distributedTarget, selected);
2537 return success();
2538 }
2539};
2540
2541// Trivially distribute `vector.interleave`
2542struct SgToLaneVectorInterleave
2543 : public OpConversionPattern<vector::InterleaveOp> {
2544 using OpConversionPattern<vector::InterleaveOp>::OpConversionPattern;
2545
2546 LogicalResult
2547 matchAndRewrite(vector::InterleaveOp op, OpAdaptor adaptor,
2548 ConversionPatternRewriter &rewriter) const override {
2549
2550 auto newOp = vector::InterleaveOp::create(
2551 rewriter, op.getLoc(), adaptor.getLhs(), adaptor.getRhs());
2552 rewriter.replaceOp(op, newOp.getResult());
2553 return success();
2554 }
2555};
2556
2557// Trivially distribute `vector.deinterleave`
2558struct SgToLaneVectorDeinterleave
2559 : public OpConversionPattern<vector::DeinterleaveOp> {
2560 using OpConversionPattern<vector::DeinterleaveOp>::OpConversionPattern;
2561
2562 LogicalResult
2563 matchAndRewrite(vector::DeinterleaveOp op, OpAdaptor adaptor,
2564 ConversionPatternRewriter &rewriter) const override {
2565
2566 auto newOp = vector::DeinterleaveOp::create(rewriter, op.getLoc(),
2567 adaptor.getSource());
2568 rewriter.replaceOp(op, newOp.getResults());
2569 return success();
2570 }
2571};
2572
2573struct SgToLaneDpasMx : public OpConversionPattern<xegpu::DpasMxOp> {
2574 using OpConversionPattern<xegpu::DpasMxOp>::OpConversionPattern;
2575
2576 LogicalResult
2577 matchAndRewrite(xegpu::DpasMxOp op, OpAdaptor adaptor,
2578 ConversionPatternRewriter &rewriter) const override {
2579 const auto *uArch =
2580 xegpu::uArch::getUArch(xegpu::getChipStr(op).value_or(""));
2581 if (!uArch)
2582 return failure();
2583 if (!uArch->isSupportedInstruction(
2584 xegpu::uArch::InstructionKind::SubgroupScaledMatrixMultiplyAcc))
2585 return rewriter.notifyMatchFailure(
2586 op, "target uArch does not support scaled subgroup mma");
2587 // Check if the op has A, B and CD layouts attached.
2588 auto layoutA = cast<xegpu::LayoutAttr>(op.getLayoutAAttr());
2589 auto layoutB = cast<xegpu::LayoutAttr>(op.getLayoutBAttr());
2590 auto layoutCd = cast<xegpu::LayoutAttr>(op.getLayoutCdAttr());
2591 if (!layoutA || !layoutB || !layoutCd)
2592 return rewriter.notifyMatchFailure(
2593 op, "missing required layout attributes for DpasMxOp distribution");
2594
2595 // Retrieve expected types, according to anchor layouts.
2596 auto expected1DTypeResult =
2597 xegpu::getDistributedVectorType(op.getType(), layoutCd);
2598 auto expected1DTypeA =
2599 xegpu::getDistributedVectorType(op.getA().getType(), layoutA);
2600 auto expected1DTypeB =
2601 xegpu::getDistributedVectorType(op.getB().getType(), layoutB);
2602
2603 VectorType expected1DTypeScaleA, expected1DTypeScaleB;
2604 if (op.getScaleA()) {
2605 auto layoutScaleA = cast<xegpu::LayoutAttr>(op.getLayoutAScaleAttr());
2606 auto expected1DTypeScaleAOrFailure = xegpu::getDistributedVectorType(
2607 cast<VectorType>(op.getScaleA().getType()), layoutScaleA);
2608 if (failed(expected1DTypeScaleAOrFailure))
2609 return rewriter.notifyMatchFailure(
2610 op, "failed to calculate expected 1D vector type for scale A");
2611 expected1DTypeScaleA = expected1DTypeScaleAOrFailure.value();
2612 }
2613 if (op.getScaleB()) {
2614 auto layoutScaleB = cast<xegpu::LayoutAttr>(op.getLayoutBScaleAttr());
2615 auto expected1DTypeScaleBOrFailure = xegpu::getDistributedVectorType(
2616 cast<VectorType>(op.getScaleB().getType()), layoutScaleB);
2617 if (failed(expected1DTypeScaleBOrFailure))
2618 return rewriter.notifyMatchFailure(
2619 op, "failed to calculate expected 1D vector type for scale B");
2620 expected1DTypeScaleB = expected1DTypeScaleBOrFailure.value();
2621 }
2622
2623 auto expectedNDTypeResult =
2624 xegpu::getDistVecTypeBasedOnLaneLayout(layoutCd, op.getType());
2625 if (failed(expected1DTypeResult) || failed(expected1DTypeA) ||
2626 failed(expected1DTypeB))
2627 return rewriter.notifyMatchFailure(
2628 op,
2629 "failed to calculate supported workitem 1D vector types for DpasOp "
2630 "from layouts");
2631 if (failed(expectedNDTypeResult))
2632 return rewriter.notifyMatchFailure(
2633 op, "unable to compute expected workitem vector type for DpasOp from "
2634 "lane layout");
2635
2636 // Validate bit widths match uArch packed format requirements
2637 const auto *uArchInstruction = dyn_cast<
2638 xegpu::uArch::SubgroupScaledMatrixMultiplyAcc>(uArch->getInstruction(
2639 xegpu::uArch::InstructionKind::SubgroupScaledMatrixMultiplyAcc));
2640 assert(uArchInstruction);
2641 auto wiAType = expected1DTypeA.value();
2642 auto wiBType = expected1DTypeB.value();
2643 // Calculate total packed bit width = element bit width * vector size
2644 unsigned aPackedBitWidth =
2645 wiAType.getElementTypeBitWidth() * wiAType.getNumElements();
2646 unsigned bPackedBitWidth =
2647 wiBType.getElementTypeBitWidth() * wiBType.getNumElements();
2648 if (aPackedBitWidth % uArchInstruction->getPackedFormatBitSizeA())
2649 return rewriter.notifyMatchFailure(
2650 op, "A operand packed bit width must be a multiple of uArch packed "
2651 "format requirement");
2652 if (bPackedBitWidth % uArchInstruction->getPackedFormatBitSizeB())
2653 return rewriter.notifyMatchFailure(
2654 op, "B operand packed bit width must be a multiple of uArch packed "
2655 "format requirement");
2656
2657 auto newOp = xegpu::DpasMxOp::create(
2658 rewriter, op->getLoc(), expected1DTypeResult.value(),
2659 castValueTo(rewriter, cast<TypedValue<VectorType>>(adaptor.getA()),
2660 expected1DTypeA.value()),
2661 castValueTo(rewriter, cast<TypedValue<VectorType>>(adaptor.getB()),
2662 expected1DTypeB.value()),
2663 op.getAcc()
2664 ? castValueTo(rewriter,
2665 cast<TypedValue<VectorType>>(adaptor.getAcc()),
2666 expected1DTypeResult.value())
2667 : nullptr,
2668
2669 op.getScaleA()
2670 ? castValueTo(rewriter,
2671 cast<TypedValue<VectorType>>(adaptor.getScaleA()),
2672 expected1DTypeScaleA)
2673 : nullptr,
2674 op.getScaleB()
2675 ? castValueTo(rewriter,
2676 cast<TypedValue<VectorType>>(adaptor.getScaleB()),
2677 expected1DTypeScaleB)
2678 : nullptr,
2679 /** layoutA**/ nullptr,
2680 /** layoutB**/ nullptr, /** layoutCd**/ nullptr,
2681 /** layoutAScale**/ nullptr, /** layoutBScale**/ nullptr);
2682 // Explicitly set the new types to enable correct type materializations.
2683 rewriter.replaceOp(op, castValueTo(rewriter, newOp.getResult(),
2684 expectedNDTypeResult.value()));
2685 return success();
2686 }
2687};
2688
2689struct XeGPUSgToLaneDistributePass
2691 XeGPUSgToLaneDistributePass> {
2692 void runOnOperation() override;
2693};
2694
2695} // namespace
2696
2697void XeGPUSgToLaneDistributePass::runOnOperation() {
2698
2699 // Recover temporary operand layouts for usage in patterns.
2700 Operation *root = getOperation();
2701 if (!xegpu::recoverTemporaryLayouts(root)) {
2702 signalPassFailure();
2703 return;
2704 }
2705
2706 // Collect existing UnrealizedConversionCastOps. These must be preserved.
2707 llvm::SmallSetVector<UnrealizedConversionCastOp, 8> existingCasts;
2708 root->walk(
2709 [&](UnrealizedConversionCastOp castOp) { existingCasts.insert(castOp); });
2710 // Perform a structural type conversion to convert structural ops to have WI
2711 // types. This will insert UnrealizedConversionCastOps to make the IR
2712 // valid.
2713 {
2714 ConversionTarget target(getContext());
2715 TypeConverter typeConverter;
2716 RewritePatternSet patterns(&getContext());
2717 // Source (N:1) and target (1:1) materializations using
2718 // UnrealizedConversionCastOp.
2719 auto materializeCast = [](OpBuilder &builder, Type type, ValueRange inputs,
2720 Location loc) -> Value {
2721 return UnrealizedConversionCastOp::create(builder, loc, type, inputs)
2722 .getResult(0);
2723 };
2724 typeConverter.addSourceMaterialization(materializeCast);
2725 typeConverter.addTargetMaterialization(materializeCast);
2728 patterns, target);
2730 typeConverter, patterns, target, root);
2731 target.addLegalOp<UnrealizedConversionCastOp>();
2732 // Fold only after the patterns. A fold builds new ops without the
2733 // temporary layout attribute, so they are never distributed. For example,
2734 // an all-ones vector.constant_mask folds to an arith.constant that stays
2735 // at subgroup size behind an unrealized cast.
2736 ConversionConfig config;
2737 config.foldingMode = DialectConversionFoldingMode::AfterPatterns;
2738 if (failed(
2739 applyPartialConversion(root, target, std::move(patterns), config)))
2740 return signalPassFailure();
2741 }
2742 // Fold cancelling cast chains and erase dead casts.
2743 xegpu::cleanupUnrealizedConversionCasts(root, existingCasts);
2744 xegpu::removeTemporaryLayoutAttrs(getOperation());
2745}
2746
2748 TypeConverter &typeConverter, Operation *topLevelOp) {
2749 // Pass through any type by default; more specific conversions registered
2750 // below override this for TensorDescType and (distributing) VectorType.
2751 typeConverter.addConversion([](Type type) -> Type { return type; });
2752 // For TensorDescType, drop the layout attribute if any.
2753 typeConverter.addConversion([](TensorDescType type) -> Type {
2754 if (type.getLayoutAttr()) {
2755 return type.dropLayouts();
2756 }
2757 return type;
2758 });
2759 // For VectorType, distribute based on the lane layout (1:1 shape-changing
2760 // conversion). Uses xegpu::addVectorTypeConversion with a pre-computed
2761 // map for SCF loop block args (see precomputeLoopBlockArgTypes for the
2762 // rationale).
2763 auto getSubShapeAndCount = [](VectorType vecTy,
2764 xegpu::DistributeLayoutAttr layout)
2765 -> std::pair<SmallVector<int64_t>, int> {
2766 auto distTyOrFailure = getDistVecTypeBasedOnLaneLayout(layout, vecTy);
2767 if (failed(distTyOrFailure))
2768 return {{}, 0};
2769 return {SmallVector<int64_t>(distTyOrFailure->getShape()), 1};
2770 };
2771 auto loopArgTypes =
2772 xegpu::precomputeLoopBlockArgTypes(topLevelOp, getSubShapeAndCount);
2773 xegpu::addVectorTypeConversion(typeConverter, getSubShapeAndCount,
2774 std::move(loopArgTypes));
2775}
2776
2778 TypeConverter &typeConverter, RewritePatternSet &patterns,
2779 ConversionTarget &target, Operation *topLevelOp) {
2780 populateXeGPUSgToLaneDistributeTypeConversions(typeConverter, topLevelOp);
2781 // CreateNdDescOp is legal only if its result type has no layout attribute.
2782 target.addDynamicallyLegalOp<xegpu::CreateNdDescOp>(
2783 [&](xegpu::CreateNdDescOp op) { return !op.getType().getLayoutAttr(); });
2784 // Any anchor XeGPU op is legal only if it has no anchor layout.
2785 target.addDynamicallyLegalDialect<xegpu::XeGPUDialect>([](Operation *op) {
2786 if (isa<xegpu::ConvertLayoutOp>(op))
2787 return false;
2788 auto anchorOp = dyn_cast<AnchorLayoutInterface>(op);
2789 if (!anchorOp)
2790 return true;
2791 return !anchorOp.getAnchorLayout();
2792 });
2793 // Arith constants are legal only if they have no temporary layout attribute.
2794 target.addDynamicallyLegalOp<arith::ConstantOp>(
2795 [=](arith::ConstantOp op) -> bool {
2796 // If the result type is not a vector, it's legal.
2797 if (!isa<VectorType>(op.getResult().getType()))
2798 return true;
2799 return !xegpu::getTemporaryLayout(dyn_cast<OpResult>(op.getResult()));
2800 });
2801 // In math and arith dialects, only handle elementwise ops with a single
2802 // result and with a result layout attribute.
2803 target.addDynamicallyLegalDialect<math::MathDialect, arith::ArithDialect>(
2804 [=](Operation *op) -> std::optional<bool> {
2805 // Only handle elementwise mappable ops
2807 return true;
2808 // Only handle ops with single vector result
2809 if (op->getNumResults() != 1)
2810 return true;
2811
2812 VectorType resultType =
2813 dyn_cast<VectorType>(op->getResult(0).getType());
2814 if (!resultType)
2815 return true;
2816
2817 // Check if all operands are vectors of the same shape
2818 for (Value operand : op->getOperands()) {
2819 VectorType operandType = dyn_cast<VectorType>(operand.getType());
2820 if (!operandType || operandType.getShape() != resultType.getShape()) {
2821 return true;
2822 }
2823 }
2824 return !xegpu::getTemporaryLayout(dyn_cast<OpResult>(op->getResult(0)));
2825 });
2826 // vector::ReductionOp is legal only if its source has no distribute layout
2827 // attribute.
2828 target.addDynamicallyLegalOp<vector::ReductionOp>(
2829 [=](vector::ReductionOp op) -> bool {
2830 auto layout = xegpu::getDistributeLayoutAttr(op.getVector());
2831 return !layout;
2832 });
2833 // vector::MultiDimReductionOp op legality.
2834 target.addDynamicallyLegalOp<vector::MultiDimReductionOp>(
2835 [=](vector::MultiDimReductionOp op) -> bool {
2836 return !isValidSubgroupMultiReductionOp(op);
2837 });
2838 target.addDynamicallyLegalOp<vector::CreateMaskOp, vector::ConstantMaskOp,
2839 vector::TransposeOp, vector::BitCastOp,
2840 vector::ShapeCastOp, vector::StepOp,
2841 vector::BroadcastOp>([=](Operation *op) -> bool {
2842 return !xegpu::getTemporaryLayout(op->getOpResult(0));
2843 });
2844 target.addDynamicallyLegalOp<vector::ExtractOp>(
2845 [=](vector::ExtractOp op) -> bool {
2846 if (!isa<VectorType>(op.getType()))
2847 return true;
2848 return !xegpu::getTemporaryLayout(op->getOpResult(0));
2849 });
2850 target.addDynamicallyLegalOp<vector::InsertOp>(
2851 [=](vector::InsertOp op) -> bool {
2852 return !xegpu::getTemporaryLayout(op->getOpResult(0));
2853 });
2854 target.addDynamicallyLegalOp<vector::ExtractStridedSliceOp>(
2855 [=](vector::ExtractStridedSliceOp op) -> bool {
2856 return !xegpu::getTemporaryLayout(op->getOpResult(0));
2857 });
2858 target.addDynamicallyLegalOp<vector::InsertStridedSliceOp>(
2859 [=](vector::InsertStridedSliceOp op) -> bool {
2860 return !xegpu::getTemporaryLayout(op->getOpResult(0));
2861 });
2862 target.addDynamicallyLegalOp<vector::InterleaveOp, vector::DeinterleaveOp>(
2863 [=](Operation *op) -> bool {
2864 return !xegpu::getTemporaryLayout(op->getOpResult(0));
2865 });
2866 target.markUnknownOpDynamicallyLegal([](Operation *op) { return true; });
2867 patterns
2868 .add<SgToLaneCreateNdDesc, SgToLaneLoadNd, SgToLaneStoreNd, SgToLaneDpas,
2869 SgToLaneElementWise, SgToLaneArithConstant, SgToLanePrefetchNd,
2870 SgToLaneLoadGather, SgToLaneStoreScatter, SgToLaneVectorReduction,
2871 SgToLaneMultiDimReduction, SgToLaneVectorExtract,
2872 SgToLaneVectorInsert, SgToLaneVectorExtractStridedSlice,
2873 SgToLaneVectorInsertStridedSlice, SgToLaneLoadMatrix,
2874 SgToLaneStoreMatrix, SgToLaneConvertLayout, SgToLaneVectorTranspose,
2875 SgToLaneVectorBitcast, SgToLaneVectorStep, SgToLaneVectorShapeCast,
2876 SgToLaneBroadcast, SgToLaneCreateMask<vector::CreateMaskOp>,
2877 SgToLaneCreateMask<vector::ConstantMaskOp>,
2878 SgToLaneVectorDeinterleave, SgToLaneVectorInterleave, SgToLaneDpasMx,
2879 SgToLaneConvertLayoutBroadcastExtract,
2880 SgToLaneConvertLayoutPartialBroadcastExtractShuffle,
2881 SgToLaneConvertLayoutDeinterleaveSelect>(typeConverter,
2882 patterns.getContext());
2883 // The SLM round-trip handles any pair of layouts but pays for a memory
2884 // round-trip, so it only runs when every pattern above has declined.
2885 patterns.add<SgToLaneConvertLayoutViaSLM>(typeConverter,
2886 patterns.getContext(),
2887 /*benefit=*/PatternBenefit(0));
2888}
return success()
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
b getContext())
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
Attributes are known-constant values of operations.
Definition Attributes.h:25
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Attribute getPropertiesAsAttribute()
Return the properties converted to an attribute.
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
Definition Operation.h:555
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
result_range getResults()
Definition Operation.h:442
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
A range-style iterator that allows for iterating over the offsets of all potential tiles of size tile...
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
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 provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
Definition ArithOps.cpp:352
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int64_t > content)
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
void populateSCFStructuralTypeConversionsAndLegality(const TypeConverter &typeConverter, RewritePatternSet &patterns, ConversionTarget &target, PatternBenefit benefit=1)
Populates patterns for SCF structural type conversions and sets up the provided ConversionTarget with...
Value makeArithReduction(OpBuilder &b, Location loc, CombiningKind kind, Value v1, Value acc, arith::FastMathFlagsAttr fastmath=nullptr, Value mask=nullptr)
Returns the result value of reducing two scalar/vector values with the corresponding arith operation.
SmallVector< Value > getAsValues(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > foldResults)
Convert foldResults into Values.
const uArch * getUArch(llvm::StringRef archName)
Definition uArchCommon.h:24
void populateXeGPUSgToLaneDistributeTypeConversionAndLegality(TypeConverter &typeConverter, RewritePatternSet &patterns, ConversionTarget &target, Operation *topLevelOp)
Defines type conversions and legality for XeGPU subgroup to lane distribution and appends the require...
bool requirePacked(const DistributeLayoutAttr layout)
Helper function to check if the layout is packed.
void removeTemporaryLayoutAttrs(Operation *op)
Removes the temporary layout attributes for each OpOperand and OpResult of the given operation.
bool recoverTemporaryLayouts(Operation *rootOp)
Attach layout attributes to all vector-type operands of operations within the given operation's neste...
FailureOr< int64_t > getNumSubgroupsFromBlockSize(Operation *op, int64_t subgroupSize)
Returns the number of subgroups the kernel enclosing op runs, derived from the known_block_size of it...
FailureOr< VectorType > getDistVecTypeBasedOnLaneLayout(DistributeLayoutAttr layout, VectorType originalType)
Helper function to get distributed vector type for a source vector type according to the lane_layout.
bool requireTranspose(const DistributeLayoutAttr layout, const uArch::uArch *uArch)
Helper function to check if the layout requires a transpose effect.
DistributeLayoutAttr getDistributeLayoutAttr(const Value value)
Retrieves the DistributeLayoutAttr associated with a given Value, or nullptr if none is found.
DenseMap< Value, SmallVector< Type > > precomputeLoopBlockArgTypes(Operation *topLevelOp, SubShapeAndCountFn getSubShapeAndCount)
Pre-computes distributed VectorType mappings for every value carried through an SCF loop under topLev...
std::optional< std::string > getChipStr(Operation *op)
Retrieves the chip string from the XeVM target attribute of the parent GPU module operation.
void addVectorTypeConversion(TypeConverter &converter, SubShapeAndCountFn getSubShapeAndCount, DenseMap< Value, SmallVector< Type > > loopArgTypes)
Adds a context-aware VectorType conversion to converter (1:1 shape-changing or 1:N,...
Value lowerToVectorReductions(TypedValue< VectorType > src, TypedValue< VectorType > acc, vector::CombiningKind kind, int64_t reductionDim, Location loc, PatternRewriter &rewriter, arith::FastMathFlagsAttr fastmath=nullptr)
Given a src and an acc argumments from a vector::MultiDimReductionOp, lower to a set of vector::Reduc...
DistributeLayoutAttr getTemporaryLayout(const T &operandOrResult)
get and set distribute layout attribute for non-anchor operations (and offsets/masks of load/store op...
Value lowerCrossLaneReductionToShuffles(TypedValue< VectorType > src, TypedValue< VectorType > acc, vector::CombiningKind kind, int64_t reductionDim, int64_t reductionSize, Location loc, PatternRewriter &rewriter, arith::FastMathFlagsAttr fastmath=nullptr)
Lowers cross-lane reductions to shuffle operations on a 2D vector.
void populateXeGPUSgToLaneDistributeTypeConversions(TypeConverter &typeConverter, Operation *topLevelOp)
Define only the type conversions needed for XeGPU subgroup to lane distribution.
void cleanupUnrealizedConversionCasts(Operation *root, const llvm::SmallSetVector< UnrealizedConversionCastOp, 8 > &existingCasts)
Cleans up UnrealizedConversionCastOps inserted during SCF structural type conversion and/or XeGPU unr...
SmallVector< OpFoldResult > addWithRightAligned(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > lhs, ArrayRef< OpFoldResult > rhs)
Generates element-wise addition ops of two arrays with automatic alignment.
FailureOr< VectorType > getDistributedVectorType(xegpu::TensorDescType tdescTy)
If tensor descriptor has a layout attribute it is used in SIMT mode.
Value subgroupReduction(Location loc, OpBuilder &builder, Value input, vector::CombiningKind kind, uint32_t size, arith::FastMathFlagsAttr fastmath=nullptr)
Given an input value representing per-lane data, this function returns the result after performing a ...
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
SmallVector< int64_t > computeStrides(ArrayRef< int64_t > sizes)
SmallVector< int64_t > delinearize(int64_t linearIndex, ArrayRef< int64_t > strides)
Given the strides together with a linear index in the dimension space, return the vector-space offset...
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
Definition Value.h:496
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
int64_t linearize(ArrayRef< int64_t > offsets, ArrayRef< int64_t > basis)
Return the linearized index of 'offsets' w.r.t.
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.
This represents an operation in an abstracted form, suitable for use with the builder APIs.