MLIR 24.0.0git
X86Dialect.cpp
Go to the documentation of this file.
1//===- X86Dialect.cpp - MLIR X86 ops implementation -----------------------===//
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//
9// This file implements the X86 dialect and its operations.
10//
11//===----------------------------------------------------------------------===//
12
18#include "mlir/IR/Builders.h"
21
22using namespace mlir;
23
24#include "mlir/Dialect/X86/X86Interfaces.cpp.inc"
25
26#include "mlir/Dialect/X86/X86Dialect.cpp.inc"
27
28static Value getMemrefBuffPtr(Location loc, MemRefType type, Value buffer,
29 const LLVMTypeConverter &typeConverter,
30 RewriterBase &rewriter) {
31 MemRefDescriptor memRefDescriptor(buffer);
32 return memRefDescriptor.bufferPtr(rewriter, loc, typeConverter, type);
33}
34
35LogicalResult x86::avx512::MaskCompressOp::verify() {
36 if (getSrc() && getConstantSrc())
37 return emitError("cannot use both src and constant_src");
38
39 if (getSrc() && (getSrc().getType() != getDst().getType()))
40 return emitError("failed to verify that src and dst have same type");
41
42 if (getConstantSrc() && (getConstantSrc()->getType() != getDst().getType()))
43 return emitError(
44 "failed to verify that constant_src and dst have same type");
45
46 return success();
47}
48
49SmallVector<Value> x86::avx512::MaskCompressOp::getIntrinsicOperands(
50 ArrayRef<Value> operands, const LLVMTypeConverter &typeConverter,
51 RewriterBase &rewriter) {
52 auto loc = getLoc();
53 Adaptor adaptor(operands, *this);
54
55 auto opType = adaptor.getA().getType();
56 Value src;
57 if (adaptor.getSrc()) {
58 src = adaptor.getSrc();
59 } else if (adaptor.getConstantSrc()) {
60 src = LLVM::ConstantOp::create(rewriter, loc, opType,
61 adaptor.getConstantSrcAttr());
62 } else {
63 auto zeroAttr = rewriter.getZeroAttr(opType);
64 src = LLVM::ConstantOp::create(rewriter, loc, opType, zeroAttr);
65 }
66
67 return SmallVector<Value>{adaptor.getA(), src, adaptor.getK()};
68}
69
71x86::avx::DotOp::getIntrinsicOperands(ArrayRef<Value> operands,
72 const LLVMTypeConverter &typeConverter,
73 RewriterBase &rewriter) {
74 SmallVector<Value> intrinsicOperands(operands);
75 // Dot product of all elements, broadcasted to all elements.
76 Value scale =
77 LLVM::ConstantOp::create(rewriter, getLoc(), rewriter.getI8Type(), 0xff);
78 intrinsicOperands.push_back(scale);
79
80 return intrinsicOperands;
81}
82
83SmallVector<Value> x86::avx::BcstToPackedF32Op::getIntrinsicOperands(
84 ArrayRef<Value> operands, const LLVMTypeConverter &typeConverter,
85 RewriterBase &rewriter) {
86 Adaptor adaptor(operands, *this);
87 return {getMemrefBuffPtr(getLoc(), getA().getType(), adaptor.getA(),
88 typeConverter, rewriter)};
89}
90
91SmallVector<Value> x86::avx::CvtPackedEvenIndexedToF32Op::getIntrinsicOperands(
92 ArrayRef<Value> operands, const LLVMTypeConverter &typeConverter,
93 RewriterBase &rewriter) {
94 Adaptor adaptor(operands, *this);
95 return {getMemrefBuffPtr(getLoc(), getA().getType(), adaptor.getA(),
96 typeConverter, rewriter)};
97}
98
99SmallVector<Value> x86::avx::CvtPackedOddIndexedToF32Op::getIntrinsicOperands(
100 ArrayRef<Value> operands, const LLVMTypeConverter &typeConverter,
101 RewriterBase &rewriter) {
102 Adaptor adaptor(operands, *this);
103 return {getMemrefBuffPtr(getLoc(), getA().getType(), adaptor.getA(),
104 typeConverter, rewriter)};
105}
106
107/// Verify that AMX supports the implied tile shape.
108static LogicalResult verifyTileSize(Operation *op, x86::amx::TileType tp) {
109 const unsigned kMaxRows = 16;
110 const unsigned kBitsPerRow = 64 * 8;
111 unsigned col = tp.getDimSize(1) * tp.getElementType().getIntOrFloatBitWidth();
112 if (tp.getDimSize(0) > kMaxRows)
113 return op->emitOpError("bad row height: ") << tp.getDimSize(0);
114 if (col > kBitsPerRow || col & 0x1f)
115 return op->emitOpError("bad column width: ") << (col >> 3);
116 return success();
117}
118
119/// Verify that AMX supports the multiplication.
120static LogicalResult verifyMultShape(Operation *op, x86::amx::TileType atp,
122 x86::amx::TileType ctp, unsigned scale) {
123 unsigned am = atp.getDimSize(0), ak = atp.getDimSize(1) >> scale;
124 unsigned bk = btp.getDimSize(0), bn = btp.getDimSize(1) >> scale;
125 unsigned cm = ctp.getDimSize(0), cn = ctp.getDimSize(1);
126 if (cm != am || cn != bn || ak != bk)
127 return op->emitOpError("bad mult shape: ")
128 << cm << " x " << cn << " x " << ak;
129 return success();
130}
131
132/// Maps the 2-dim vector shape to the two 16-bit tile sizes. The first
133/// dimension directly translates into the number of rows of the tiles.
134/// The second dimensions needs to be scaled by the number of bytes.
136 RewriterBase &rewriter) {
137 Type llvmInt16Type = rewriter.getIntegerType(16);
138 unsigned width = tType.getElementType().getIntOrFloatBitWidth();
139 assert(llvm::isPowerOf2_64(width) && width >= 8);
140 unsigned bytes = width >> 3;
141 auto mattr = rewriter.getI16IntegerAttr(tType.getDimSize(0));
142 auto nattr = rewriter.getI16IntegerAttr(tType.getDimSize(1) * bytes);
143 return SmallVector<Value>{
144 LLVM::ConstantOp::create(rewriter, loc, llvmInt16Type, mattr),
145 LLVM::ConstantOp::create(rewriter, loc, llvmInt16Type, nattr)};
146}
147
148/// Returns stride expressed in number of bytes for the given `elementStride`
149/// stride encoded in number of elements of the type `mType`.
150static Value computeStrideInBytes(Location loc, MemRefType mType,
151 Value elementStride, RewriterBase &rewriter) {
152 Type llvmInt64Type = rewriter.getIntegerType(64);
153 unsigned bytes = mType.getElementType().getIntOrFloatBitWidth() / 8;
154 auto attr = rewriter.getI64IntegerAttr(bytes);
155 Value scale = LLVM::ConstantOp::create(rewriter, loc, llvmInt64Type, attr);
156 return LLVM::MulOp::create(rewriter, loc, llvmInt64Type, scale, elementStride)
157 .getResult();
158}
159
160/// Maps the 2-dim memref shape to the 64-bit stride. Note that the buffer
161/// shape may "envelop" the actual tile shape, and may be dynamically sized.
162static Value inferStride(Location loc, MemRefType mType, Value base,
163 RewriterBase &rewriter) {
164 assert(mType.getRank() >= 2 && "Invalid shape for AMX strides");
165 int64_t preLast = mType.getRank() - 2;
166 Type llvmInt64Type = rewriter.getIntegerType(64);
167 unsigned width = mType.getElementType().getIntOrFloatBitWidth();
168 assert(llvm::isPowerOf2_64(width) && width >= 8);
169 unsigned bytes = width >> 3;
170 auto [strides, offset] = mType.getStridesAndOffset();
171 if (strides[preLast] == ShapedType::kDynamic) {
172 // Dynamic stride needs code to compute the stride at runtime.
173 MemRefDescriptor memrefDescriptor(base);
175 loc, mType, memrefDescriptor.stride(rewriter, loc, preLast), rewriter);
176 }
177 // Use direct constant for static stride.
178 auto attr = rewriter.getI64IntegerAttr(strides[preLast] * bytes);
179 return LLVM::ConstantOp::create(rewriter, loc, llvmInt64Type, attr)
180 .getResult();
181}
182
183LogicalResult x86::amx::TileZeroOp::verify() {
184 return verifyTileSize(*this, getTileType());
185}
186
187SmallVector<Value> x86::amx::TileZeroOp::getIntrinsicOperands(
188 ArrayRef<Value> operands, const LLVMTypeConverter &typeConverter,
189 RewriterBase &rewriter) {
190 return getTileSizes(getLoc(), getTileType(), rewriter);
191}
192
193template <typename OpTy, typename = std::enable_if_t<
194 std::is_same_v<OpTy, x86::amx::TileLoadOp> ||
195 std::is_same_v<OpTy, x86::amx::TileStoreOp>>>
196static LogicalResult tileTransferVerifier(OpTy op) {
197 MemRefType memrefTy = op.getMemRefType();
198 unsigned rank = memrefTy.getRank();
199 if (op.getIndices().size() != rank)
200 return op.emitOpError("requires ") << rank << " indices";
201
202 if (failed(verifyTileSize(op, op.getTileType())))
203 return failure();
204
205 // Validate basic buffer properties when the stride is implicit.
206 if (!op.getStride()) {
207 if (rank < 2)
208 return op.emitOpError("requires at least 2D memref");
209 SmallVector<int64_t> strides;
210 int64_t offset;
211 if (failed(memrefTy.getStridesAndOffset(strides, offset)) ||
212 strides.back() != 1)
213 return op.emitOpError("requires memref with unit innermost stride");
214 }
215
216 return success();
217}
218
219void x86::amx::TileLoadOp::build(OpBuilder &builder, OperationState &state,
220 Type res, Value base, ValueRange indices) {
221 build(builder, state, res, base, indices, /*stride=*/nullptr);
222}
223
224LogicalResult x86::amx::TileLoadOp::verify() {
225 return tileTransferVerifier(*this);
226}
227
228SmallVector<Value> x86::amx::TileLoadOp::getIntrinsicOperands(
229 ArrayRef<Value> operands, const LLVMTypeConverter &typeConverter,
230 RewriterBase &rewriter) {
231 auto loc = getLoc();
232 Adaptor adaptor(operands, *this);
233
234 SmallVector<Value> intrinsicOperands;
235 intrinsicOperands.append(getTileSizes(loc, getTileType(), rewriter));
236 intrinsicOperands.push_back(
237 LLVM::getStridedElementPtr(rewriter, loc, typeConverter, getMemRefType(),
238 adaptor.getBase(), adaptor.getIndices()));
239 if (Value stride = adaptor.getStride())
240 intrinsicOperands.push_back(
241 computeStrideInBytes(loc, getMemRefType(), stride, rewriter));
242 else
243 intrinsicOperands.push_back(
244 inferStride(loc, getMemRefType(), adaptor.getBase(), rewriter));
245
246 return intrinsicOperands;
247}
248
249void x86::amx::TileStoreOp::build(OpBuilder &builder, OperationState &state,
250 Value base, ValueRange indices, Value val) {
251 build(builder, state, base, indices, val, /*stride=*/nullptr);
252}
253
254LogicalResult x86::amx::TileStoreOp::verify() {
255 return tileTransferVerifier(*this);
256}
257
258SmallVector<Value> x86::amx::TileStoreOp::getIntrinsicOperands(
259 ArrayRef<Value> operands, const LLVMTypeConverter &typeConverter,
260 RewriterBase &rewriter) {
261 auto loc = getLoc();
262 Adaptor adaptor(operands, *this);
263
264 SmallVector<Value> intrinsicOperands;
265 intrinsicOperands.append(getTileSizes(loc, getTileType(), rewriter));
266 intrinsicOperands.push_back(
267 LLVM::getStridedElementPtr(rewriter, loc, typeConverter, getMemRefType(),
268 adaptor.getBase(), adaptor.getIndices()));
269 if (Value stride = adaptor.getStride())
270 intrinsicOperands.push_back(
271 computeStrideInBytes(loc, getMemRefType(), stride, rewriter));
272 else
273 intrinsicOperands.push_back(
274 inferStride(loc, getMemRefType(), adaptor.getBase(), rewriter));
275 intrinsicOperands.push_back(adaptor.getVal());
276
277 return intrinsicOperands;
278}
279
280LogicalResult x86::amx::TileMulFOp::verify() {
281 x86::amx::TileType aType = getLhsTileType();
282 x86::amx::TileType bType = getRhsTileType();
283 x86::amx::TileType cType = getTileType();
284 unsigned scale = 1;
285 if (aType.getElementType().isF8E4M3FN() || aType.getElementType().isF8E5M2())
286 scale = 2;
287 if (failed(verifyTileSize(*this, aType)) ||
288 failed(verifyTileSize(*this, bType)) ||
289 failed(verifyTileSize(*this, cType)) ||
290 failed(verifyMultShape(*this, aType, bType, cType, scale)))
291 return failure();
292 Type ta = aType.getElementType();
293 Type tb = bType.getElementType();
294 Type tc = cType.getElementType();
295 bool flag1 = !ta.isBF16() && !ta.isF16() &&
296 !((ta.isF8E4M3FN() || ta.isF8E5M2()) &&
297 (tb.isF8E4M3FN() || tb.isF8E5M2()));
298 bool flag2 = (ta.isBF16() || ta.isF16()) ? (ta != tb) : false;
299 if (flag1 || flag2 || !tc.isF32())
300 return emitOpError("unsupported type combination");
301 return success();
302}
303
304SmallVector<Value> x86::amx::TileMulFOp::getIntrinsicOperands(
305 ArrayRef<Value> operands, const LLVMTypeConverter &typeConverter,
306 RewriterBase &rewriter) {
307 auto loc = getLoc();
308 Adaptor adaptor(operands, *this);
309
310 x86::amx::TileType aType = getLhsTileType();
311 x86::amx::TileType bType = getRhsTileType();
312 SmallVector<Value> tsza = getTileSizes(loc, aType, rewriter);
313 SmallVector<Value> tszb = getTileSizes(loc, bType, rewriter);
314
315 SmallVector<Value> intrinsicOperands = {tsza[0], tszb[1],
316 tsza[1], adaptor.getAcc(),
317 adaptor.getLhs(), adaptor.getRhs()};
318
319 return intrinsicOperands;
320}
321
322LogicalResult x86::amx::TileMulIOp::verify() {
323 x86::amx::TileType aType = getLhsTileType();
324 x86::amx::TileType bType = getRhsTileType();
325 x86::amx::TileType cType = getTileType();
326 if (failed(verifyTileSize(*this, aType)) ||
327 failed(verifyTileSize(*this, bType)) ||
328 failed(verifyTileSize(*this, cType)) ||
329 failed(verifyMultShape(*this, aType, bType, cType, 2)))
330 return failure();
331 Type ta = aType.getElementType();
332 Type tb = bType.getElementType();
333 Type tc = cType.getElementType();
334 if (!ta.isInteger(8) || !tb.isInteger(8) || !tc.isInteger(32))
335 return emitOpError("unsupported type combination");
336 return success();
337}
338
339SmallVector<Value> x86::amx::TileMulIOp::getIntrinsicOperands(
340 ArrayRef<Value> operands, const LLVMTypeConverter &typeConverter,
341 RewriterBase &rewriter) {
342 auto loc = getLoc();
343 Adaptor adaptor(operands, *this);
344
345 x86::amx::TileType aType = getLhsTileType();
346 x86::amx::TileType bType = getRhsTileType();
347 SmallVector<Value> tsza = getTileSizes(loc, aType, rewriter);
348 SmallVector<Value> tszb = getTileSizes(loc, bType, rewriter);
349
350 SmallVector<Value> intrinsicOperands = {tsza[0], tszb[1],
351 tsza[1], adaptor.getAcc(),
352 adaptor.getLhs(), adaptor.getRhs()};
353
354 return intrinsicOperands;
355}
356
357Type x86::amx::TileType::parse(AsmParser &parser) {
358 if (parser.parseLess())
359 return nullptr;
360
362 if (parser.parseDimensionList(shape, false, true))
363 return nullptr;
364
365 Type elementType;
366 if (parser.parseType(elementType))
367 return nullptr;
368
369 if (parser.parseGreater())
370 return nullptr;
371
372 return AMXTileType::getChecked(
373 [&] { return parser.emitError(parser.getNameLoc()); }, shape,
374 elementType);
375}
376
377void x86::amx::TileType::print(AsmPrinter &os) const {
378 os << "<";
380 os << 'x';
382 os << '>';
383}
384
385#define GET_OP_CLASSES
386#include "mlir/Dialect/X86/X86.cpp.inc"
387
388#define GET_TYPEDEF_CLASSES
389#include "mlir/Dialect/X86/X86Types.cpp.inc"
return success()
false
Parses a map_entries map type from a string format back into its numeric value.
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
static Value getMemrefBuffPtr(Location loc, MemRefType type, Value buffer, const LLVMTypeConverter &typeConverter, RewriterBase &rewriter)
static Value inferStride(Location loc, MemRefType mType, Value base, RewriterBase &rewriter)
Maps the 2-dim memref shape to the 64-bit stride.
static Value computeStrideInBytes(Location loc, MemRefType mType, Value elementStride, RewriterBase &rewriter)
Returns stride expressed in number of bytes for the given elementStride stride encoded in number of e...
static LogicalResult tileTransferVerifier(OpTy op)
static LogicalResult verifyMultShape(Operation *op, x86::amx::TileType atp, x86::amx::TileType btp, x86::amx::TileType ctp, unsigned scale)
Verify that AMX supports the multiplication.
static SmallVector< Value > getTileSizes(Location loc, x86::amx::TileType tType, RewriterBase &rewriter)
Maps the 2-dim vector shape to the two 16-bit tile sizes.
static LogicalResult verifyTileSize(Operation *op, x86::amx::TileType tp)
Verify that AMX supports the implied tile shape.
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseDimensionList(SmallVectorImpl< int64_t > &dimensions, bool allowDynamic=true, bool withTrailingX=true)=0
Parse a dimension list of a tensor or memref type.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
This base class exposes generic asm printer hooks, usable across the various derived printers.
virtual void printType(Type type)
void printDimensionList(ArrayRef< int64_t > shape)
IntegerAttr getI16IntegerAttr(int16_t value)
Definition Builders.cpp:225
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:120
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
IntegerType getI8Type()
Definition Builders.cpp:67
Conversion from types to the LLVM IR dialect.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
Helper class to produce LLVM dialect operations extracting or inserting elements of a MemRef descript...
Value bufferPtr(OpBuilder &builder, Location loc, const LLVMTypeConverter &converter, MemRefType type)
Builds IR for getting the start address of the buffer represented by this memref: memref....
Value stride(OpBuilder &builder, Location loc, unsigned pos)
Builds IR extracting the pos-th size from the descriptor.
This class helps build Operations.
Definition Builders.h:210
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isF8E5M2() const
Definition Types.cpp:45
bool isF8E4M3FN() const
Definition Types.cpp:44
bool isF32() const
Definition Types.cpp:40
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
bool isF16() const
Definition Types.cpp:38
bool isBF16() const
Definition Types.cpp:37
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
Value getStridedElementPtr(OpBuilder &builder, Location loc, const LLVMTypeConverter &converter, MemRefType type, Value memRefDesc, ValueRange indices, LLVM::GEPNoWrapFlags noWrapFlags=LLVM::GEPNoWrapFlags::none)
Performs the index computation to get to the element at indices of the memory pointed to by memRefDes...
Definition Pattern.cpp:628
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
MemRefType getMemRefType(T &&t)
Convenience method to abbreviate casting getType().
mlir::x86::AMXTileType TileType
Definition X86Dialect.h:33
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
This represents an operation in an abstracted form, suitable for use with the builder APIs.