MLIR 23.0.0git
XeGPUBlocking.cpp
Go to the documentation of this file.
1//===---- XeGPUBlocking.cpp ---- XeGPU Blocking 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//===----------------------------------------------------------------------===//
8
10
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/Support/DebugLog.h"
23
24namespace mlir {
25namespace xegpu {
26#define GEN_PASS_DEF_XEGPUBLOCKING
27#include "mlir/Dialect/XeGPU/Transforms/Passes.h.inc"
28} // namespace xegpu
29} // namespace mlir
30
31#define DEBUG_TYPE "xegpu-blocking"
32
33using namespace mlir;
34
35namespace {
37// reslove the unrealized conversion cast ops generated when doing SCF
38// Structural Type Conversion. It will have two formats, N:1 vector
39// cast and 1:N vector cast. vector::insert_strided_slice ops will be
40// used for the first case, and vector::extract_strided_slice ops will be
41// used for the second case.
42static void
43resolveUnrealizedConversionCastOp(UnrealizedConversionCastOp castOp) {
44 ValueRange inputs = castOp.getInputs();
45 ValueRange outputs = castOp.getOutputs();
47 auto hasIdenticalVectorTypes = [](ValueRange values) {
48 auto types = values.getTypes();
49 return llvm::all_of(types, [&](Type type) {
50 return isa<VectorType>(type) && type == types.front();
51 });
52 };
53
54 // We only interest in the case where all inputs and outputs have the
55 // identical VectorTypes
56 if (!hasIdenticalVectorTypes(inputs) || !hasIdenticalVectorTypes(outputs)) {
57 LDBG() << "skip unrealized conversion cast op not emulating pack/unpack.";
58 return;
59 }
60
61 VectorType outputTy = dyn_cast<VectorType>(outputs[0].getType());
62 OpBuilder builder(castOp);
63 if (inputs.size() > 1 && outputs.size() == 1) {
64 // the castOp is emulating an unpack op
65 ArrayRef<int64_t> shape = outputTy.getShape();
67 builder, castOp.getLoc(), inputs, shape);
68 castOp->replaceAllUsesWith(ValueRange(result));
69 castOp->erase();
70 } else if (castOp.getNumResults() > 1 && castOp.getNumOperands() == 1) {
71 // the castOp is emulating a pack op
72 ArrayRef<int64_t> tileShape = outputTy.getShape();
74 builder, castOp.getLoc(), inputs[0], tileShape);
75 castOp->replaceAllUsesWith(results);
76 castOp->erase();
77 }
78}
79
80//===------------------------------------------------------------------------===//
81// The XeGPUBlockingPass leverages the unroll patterns for XeGPU and Vector ops
82// to partition operations that process large shapes into multiple operations on
83// smaller shapes, as specified by the inst_data in the layout attribute. This
84// enables each resulting operation to be efficiently mapped to a hardware
85// instruction.
86//===------------------------------------------------------------------------===//
87
88class XeGPUBlockingPass final
89 : public xegpu::impl::XeGPUBlockingBase<XeGPUBlockingPass> {
90public:
91 void runOnOperation() override;
92
93private:
94 // Get the tile shape for a given OpOperand or OpResult by examining the
95 // corresponding layout attribute. If layout is not present or is not a
96 // subgroup level layout, it returns std::nullopt.
97 template <typename T,
98 typename = std::enable_if_t<std::is_same_v<T, OpOperand> ||
99 std::is_same_v<T, OpResult>>>
100 std::optional<SmallVector<int64_t>>
101 getTileShape(const T &operandOrResult) const;
102
103 // Get the tile shape for a given operation.
104 std::optional<SmallVector<int64_t>> getTileShape(Operation *op) const;
105
106 // Determine if the operation requires unrolling. Return false if all operands
107 // and results have tile shapes identical to their original types. Otherwise,
108 // return true.
109 bool needsUnroll(Operation *op) const;
110};
111} // namespace
112
113template <typename T, typename>
114std::optional<SmallVector<int64_t>>
115XeGPUBlockingPass::getTileShape(const T &operandOrResult) const {
116 Value value;
117 if constexpr (std::is_same_v<T, OpOperand>) {
118 value = operandOrResult.get();
119 } else {
120 value = (Value)operandOrResult;
121 }
122
123 xegpu::DistributeLayoutAttr layout =
124 xegpu::getDistributeLayoutAttr(operandOrResult);
125 if (layout && layout.isForSubgroup()) {
126 if (!layout.getEffectiveInstDataAsInt().empty()) {
127 SmallVector<int64_t> instData = layout.getEffectiveInstDataAsInt();
128 return instData;
129 }
130 if (auto type = dyn_cast<ShapedType>(value.getType()))
131 return llvm::to_vector(type.getShape());
132 }
133 LDBG() << "failed to getTileShape for: " << value;
134 return std::nullopt;
135}
136
137std::optional<SmallVector<int64_t>>
138XeGPUBlockingPass::getTileShape(Operation *op) const {
139 if (isa<xegpu::CreateNdDescOp, xegpu::UpdateNdOffsetOp, xegpu::CreateDescOp,
140 xegpu::UpdateOffsetOp, xegpu::LoadMatrixOp>(op))
141 return getTileShape(op->getOpResult(0));
142 if (isa<xegpu::PrefetchNdOp, xegpu::LoadNdOp, xegpu::PrefetchOp,
143 xegpu::StoreMatrixOp>(op))
144 return getTileShape(op->getOpOperand(0));
145 if (isa<xegpu::StoreNdOp>(op))
146 return getTileShape(op->getOpOperand(1));
147
148 // Handle LoadGatherOp and StoreScatterOp (with and without offset)
149 if (auto loadGatherOp = dyn_cast<xegpu::LoadGatherOp>(op)) {
150 if (loadGatherOp.getOffsets())
151 return getTileShape(loadGatherOp->getOpResult(0));
152 else
153 return getTileShape(loadGatherOp->getOpOperand(0));
154 }
155
156 if (auto convertLayoutOp = dyn_cast<xegpu::ConvertLayoutOp>(op)) {
157 auto inputInstData =
158 convertLayoutOp.getInputLayout().getEffectiveInstDataAsInt();
159 auto targetInstData =
160 convertLayoutOp.getTargetLayout().getEffectiveInstDataAsInt();
161 // return the one with larger size
162 if (computeProduct(inputInstData) >= computeProduct(targetInstData))
163 return inputInstData;
164 else
165 return targetInstData;
166 }
167
168 if (auto storeScatterOp = dyn_cast<xegpu::StoreScatterOp>(op))
169 return getTileShape(storeScatterOp.getOffsets()
170 ? storeScatterOp->getOpOperand(0)
171 : storeScatterOp->getOpOperand(1));
172
173 if (isa<xegpu::DpasOp>(op)) {
174 std::optional<SmallVector<int64_t>> aTile =
176 std::optional<SmallVector<int64_t>> bTile =
178
179 if (!aTile || aTile->size() != 2 || !bTile || bTile->size() != 2)
180 return std::nullopt;
181
182 // semantic check for A and B
183 if ((*aTile)[1] != (*bTile)[0])
184 return std::nullopt;
185
186 // semantic check for C
187 if (op->getNumOperands() == 3) {
188 std::optional<SmallVector<int64_t>> cTile =
190 int64_t expectedCTile[2] = {(*aTile)[0], (*bTile)[1]};
191 if (!cTile || !llvm::equal(*cTile, expectedCTile))
192 return std::nullopt;
193 }
194
195 return SmallVector<int64_t>({(*aTile)[0], (*aTile)[1], (*bTile)[1]});
196 }
197
199 return getTileShape(op->getOpResult(0));
200
201 if (isa<vector::MultiDimReductionOp>(op))
202 return getTileShape(op->getOpOperand(0));
203
204 if (isa<vector::TransposeOp, vector::BroadcastOp, vector::StepOp,
205 vector::ShapeCastOp, vector::ConstantMaskOp, vector::CreateMaskOp>(
206 op))
207 return getTileShape(op->getOpResult(0));
208
209 return std::nullopt;
210}
211
212bool XeGPUBlockingPass::needsUnroll(Operation *op) const {
213 // skip the op if any of its operands or results has workgroup level layouts
214 bool hasWgLayoutOperands =
215 llvm::any_of(op->getOpOperands(), [](OpOperand &opr) {
216 xegpu::DistributeLayoutAttr layout =
217 xegpu::getDistributeLayoutAttr(opr);
218 return layout && layout.isForWorkgroup();
219 });
220 bool hasWgLayoutResults =
221 llvm::any_of(op->getOpResults(), [](OpResult result) {
222 xegpu::DistributeLayoutAttr layout =
223 xegpu::getDistributeLayoutAttr(result);
224 return layout && layout.isForWorkgroup();
225 });
226 if (hasWgLayoutOperands || hasWgLayoutResults) {
227 LDBG() << "skip unrolling for op with workgroup level layout: " << *op;
228 return false;
229 }
230
231 auto isUnrollable = [](Value value, ArrayRef<int64_t> tileShape) {
232 Type valTy = value.getType();
233 if (auto tdescTy = dyn_cast<xegpu::TensorDescType>(valTy)) {
234 xegpu::DistributeLayoutAttr layout = tdescTy.getLayoutAttr();
235 return layout && !layout.getEffectiveInstDataAsInt().empty();
236 }
237 auto shapedType = dyn_cast<ShapedType>(valTy);
238 return shapedType && !llvm::equal(tileShape, shapedType.getShape());
239 };
240
241 bool hasUnrollableOperands =
242 llvm::any_of(op->getOpOperands(), [&](OpOperand &opr) {
243 std::optional<SmallVector<int64_t>> tileShape = getTileShape(opr);
244 return tileShape.has_value() && isUnrollable(opr.get(), *tileShape);
245 });
246 bool hasUnrollableResults =
247 llvm::any_of(op->getOpResults(), [&](OpResult result) {
248 std::optional<SmallVector<int64_t>> tileShape = getTileShape(result);
249 return tileShape.has_value() && isUnrollable(result, *tileShape);
250 });
251 // ConvertLayoutOp must be processed to drop the inst_data in the layout
252 bool isConvertLayoutWithInstData = false;
253 if (auto convertLayoutOp = dyn_cast<xegpu::ConvertLayoutOp>(op)) {
254 auto targettLayout = convertLayoutOp.getTargetLayout();
255 if (targettLayout && !targettLayout.getEffectiveInstDataAsInt().empty()) {
256 isConvertLayoutWithInstData = true;
257 }
258 }
259 return hasUnrollableOperands || hasUnrollableResults ||
260 isConvertLayoutWithInstData;
261}
262
263void XeGPUBlockingPass::runOnOperation() {
264 MLIRContext *ctx = &getContext();
265 Operation *op = getOperation();
266
268 signalPassFailure();
269 return;
270 }
271
272 auto getTileShapeAndCount = [](llvm::ArrayRef<int64_t> shape,
273 xegpu::LayoutAttr layout) {
274 int count = 1;
275 SmallVector<int64_t> tileShape(shape);
276 if (layout && layout.getInstData()) {
277 DenseI32ArrayAttr instData = layout.getInstData();
278 tileShape = llvm::to_vector_of<int64_t>(instData.asArrayRef());
279 count = computeProduct(shape) / computeProduct(tileShape);
280 }
281 return std::make_pair(tileShape, count);
282 };
283
284 // Perform type conversion for SCF control folow ops
285 TypeConverter converter;
286 converter.addConversion([](Type type) -> Type { return type; });
287 converter.addConversion(
288 [&](RankedTensorType type,
289 SmallVectorImpl<Type> &result) -> std::optional<LogicalResult> {
290 Type elemTy = type.getElementType();
291 ArrayRef<int64_t> shape = type.getShape();
292
293 auto layout =
294 llvm::dyn_cast_if_present<xegpu::LayoutAttr>(type.getEncoding());
295 if (layout && layout.isForWorkgroup())
296 return failure();
297
298 int count;
299 SmallVector<int64_t> subShape;
300 std::tie(subShape, count) = getTileShapeAndCount(shape, layout);
301 auto newTy = VectorType::get(subShape, elemTy);
302 result.append(count, newTy);
303 return success();
304 });
305 converter.addConversion(
306 [&](xegpu::TensorDescType type,
307 SmallVectorImpl<Type> &result) -> std::optional<LogicalResult> {
308 Type elemTy = type.getElementType();
309 ArrayRef<int64_t> shape = type.getShape();
310
311 xegpu::LayoutAttr layout = type.getLayoutAttr();
312 if (layout && layout.isForWorkgroup())
313 return failure();
314
315 int count;
316 SmallVector<int64_t> subShape;
317 std::tie(subShape, count) = getTileShapeAndCount(shape, layout);
318
319 if (layout)
320 layout = layout.dropInstData();
321
322 auto newTy = xegpu::TensorDescType::get(
323 type.getContext(), subShape, elemTy, type.getEncoding(), layout);
324 result.append(count, newTy);
325 return success();
326 });
327
329
330 xegpu::UnrollOptions options;
331 options.setFilterConstraint(
332 [&](Operation *op) -> LogicalResult { return success(needsUnroll(op)); });
333
334 options.setNativeShapeFn([&](Operation *op) { return getTileShape(op); });
335
336 options.setUnrolledTypesFn([&](ShapedType type, ArrayRef<int64_t> tileShape,
337 bool returnSingleType = false) {
338 Type elemTy = type.getElementType();
339 Type newTy;
340
341 if (auto tdescTy = dyn_cast<xegpu::TensorDescType>(type)) {
342
343 Attribute encoding = tdescTy.getEncoding();
344 // If the encoding is a ScatterTensorDescAttr, we need to
345 // potentially adjust the chunk size based on the inst_data.
346 if (tdescTy.isScattered()) {
347 int64_t chunkSize = tdescTy.getChunkSizeAsInt();
348
349 if (chunkSize > 1) {
350 int64_t blockedChunkSize = chunkSize;
351 auto instData = tdescTy.getLayoutAttr().getInstData();
352 if (!instData.empty())
353 blockedChunkSize = instData.asArrayRef().back();
354
355 // To create a new attribute with a different chunk_size:
356 auto newEncoding = xegpu::ScatterTensorDescAttr::get(
357 ctx, tdescTy.getMemorySpace(), blockedChunkSize);
358 encoding = newEncoding;
359 }
360 }
361
362 newTy =
363 xegpu::TensorDescType::get(ctx, tileShape, elemTy, encoding,
364 tdescTy.getLayoutAttr().dropInstData());
365 } else {
366 newTy = VectorType::get(tileShape, elemTy);
367 }
368
369 if (returnSingleType)
370 return SmallVector<Type>{newTy};
371 std::optional<SmallVector<int64_t>> ratio =
372 computeShapeRatio(type.getShape(), tileShape);
373 assert(ratio && "The shape of the type must be a multiple of tileShape.");
374 return SmallVector<Type>(computeProduct(*ratio), newTy);
375 });
376
377 RewritePatternSet patterns(ctx);
378 vector::UnrollVectorOptions vectorOptions;
379 vectorOptions.setNativeShapeFn(options.nativeShape);
380
382 vector::populateVectorUnrollPatterns(patterns, vectorOptions);
383
384 (void)applyPatternsGreedily(op, std::move(patterns));
385
386 op->walk([](Operation *op) {
387 // Remove the layout attributes cached per operands.
388 for (OpOperand &opr : op->getOpOperands()) {
389 std::string name = xegpu::getTemporaryLayoutName(opr);
390 if (op->hasAttrOfType<xegpu::DistributeLayoutAttr>(name))
391 op->removeAttr(name);
392 }
393
394 // Update the layout attributes per result.
395 for (OpResult result : op->getOpResults()) {
396 std::string name = xegpu::getTemporaryLayoutName(result);
397 if (auto layout = op->getAttrOfType<xegpu::DistributeLayoutAttr>(name)) {
398 op->removeAttr(name);
399 if (!isa<LoopLikeOpInterface>(op))
400 xegpu::setDistributeLayoutAttr(result, layout.dropInstData());
401 }
402 }
403
404 // Resolve unrealized conversion cast ops emulating pack/unpack
405 if (auto castOp = dyn_cast<UnrealizedConversionCastOp>(op))
406 resolveUnrealizedConversionCastOp(castOp);
407 });
408}
return success()
b getContext())
static std::array< int64_t, 2 > getTileShape(ArrayRef< int64_t > operandShape, Type elementType, int64_t lineSizeBits)
Returns the number of 8 x [128|256|512] bit tiles that compose the given operand shape.
Definition MMAUtils.cpp:37
static llvm::ManagedStatic< PassManagerOptions > options
This class helps build Operations.
Definition Builders.h:209
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
OpResult getOpResult(unsigned idx)
Definition Operation.h:429
AttrClass getAttrOfType(StringAttr name)
Definition Operation.h:558
bool hasAttrOfType(NameT &&name)
Definition Operation.h:583
MutableArrayRef< OpOperand > getOpOperands()
Definition Operation.h:391
unsigned getNumOperands()
Definition Operation.h:354
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:805
result_range getOpResults()
Definition Operation.h:428
Attribute removeAttr(StringAttr name)
Remove the attribute with the specified name if it exists.
Definition Operation.h:608
OpOperand & getOpOperand(unsigned idx)
Definition Operation.h:396
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:412
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:387
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
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
Value createVectorWithShapeFromValues(OpBuilder &builder, Location loc, ValueRange values, ArrayRef< int64_t > shape)
Create a vector of shape from a set of values using vector.insert_stride_slice.
void populateXeGPUUnrollPatterns(RewritePatternSet &patterns, const UnrollOptions &options)
Collect a set of patterns to unroll xegpu operations to a smaller shapes.
void setDistributeLayoutAttr(const OpResult &Result, const DistributeLayoutAttr layout)
[to-be-deprecated] Sets the DistributeLayoutAttr for a given OpResult user should use setAnchorLayout...
bool recoverTemporaryLayouts(Operation *rootOp)
Attach layout attributes to all vector-type operands of operations within the given operation's neste...
void doSCFStructuralTypeConversionWithTensorType(Operation *op, TypeConverter converter)
Do type conversion for SCF structural ops, e.g., scf.for using SCF structure type convertion patterns...
DistributeLayoutAttr getDistributeLayoutAttr(const Value value)
Retrieves the DistributeLayoutAttr associated with a given Value.
std::string getTemporaryLayoutName(const OpOperand &operand)
Return the attribute name for the OpOperand to attach DistributeLayoutAttr.
SmallVector< Value > extractVectorsWithShapeFromValue(OpBuilder &builder, Location loc, Value value, ArrayRef< int64_t > shape)
Extract a set of small vectors from a value with a given shape using vector.extract_stride_slice.
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:305
LogicalResult applyPatternsGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
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.
UnrollVectorOptions & setNativeShapeFn(NativeShapeFnType fn)