19#include "llvm/Support/Casting.h"
31static bool isZeroVectorConstant(
Operation *op) {
32 auto constantOp = dyn_cast_if_present<arith::ConstantOp>(op);
36 if (!isa<VectorType>(constantOp.getType()))
39 auto denseAttr = dyn_cast<DenseElementsAttr>(constantOp.getValue());
40 if (!denseAttr || !denseAttr.isSplat())
55 if (!isa<scf::YieldOp>(user))
58 auto yield = cast<scf::YieldOp>(user);
68 ShapedType inputType = cast<ShapedType>(input.
getType());
69 int64_t firstDimToCollapse = inputType.getRank() - 2;
71 if (inputType.getRank() == 1)
75 for (
int64_t i = 0; i < firstDimToCollapse; ++i)
79 for (
int64_t i = firstDimToCollapse; i < inputType.getRank(); ++i)
80 collapsedIndices.push_back(i);
82 reassociation.push_back(collapsedIndices);
83 return memref::CollapseShapeOp::create(builder, loc, input, reassociation);
87static bool isReadSrcMemref(
Value operand) {
94 .Case<TransferReadOp, LoadOp>(
95 [&](
auto readOp) { srcBuff = readOp.getOperand(0); });
97 return srcBuff && isa<MemRefType>(srcBuff.
getType());
103 return llvm::any_of(values, [](
Value value) {
105 return readOp && (readOp.getMask() || readOp.hasOutOfBoundsDim());
111static bool isVnniOperandRead(
Value operand,
int64_t vnni) {
120 srcBuff = readOp.getBase();
121 vnniIndex = readOp.getIndices().back();
126 auto srcType = dyn_cast<MemRefType>(srcBuff.
getType());
127 return srcType && srcType.getRank() > 0 &&
128 srcType.getShape().back() == vnni &&
isZeroInteger(vnniIndex);
137 Value scaled = arith::MulIOp::create(rewriter, loc,
indices.back(), cVnni);
138 indices.back() = arith::AddIOp::create(rewriter, loc, scaled, inner);
143static FailureOr<std::pair<Value, SmallVector<Value>>>
153 .Case<TransferReadOp, LoadOp>([&](
auto readOp) {
155 readOp.getIndices().end());
156 srcBuff = readOp.getOperand(0);
159 if (!srcBuff || !isa<MemRefType>(srcBuff.
getType()))
163 indices.reserve(indexVals.size());
171 collapseVnniIndices(rewriter, loc,
indices,
172 cast<MemRefType>(srcBuff.
getType()).getShape().back());
176 return std::make_pair(srcBuff,
indices);
180static LogicalResult validateLoopStep(
OpBuilder &rewriter,
Value step,
187 if (cst.value() != value && cst.value() != 1)
194static LogicalResult validateContractOps(
OpBuilder &rewriter,
195 vector::ContractionOp contractOp,
196 unsigned int blockingFactor,
202 auto srcIndxLhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
203 contractOp.getLhs(),
false);
206 auto [buffLhs, indicesLhs] = *srcIndxLhs;
209 auto srcIndxRhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
210 contractOp.getRhs(),
false);
213 auto [buffRhs, indicesRhs] = *srcIndxRhs;
216 if (buffLhs != srcBuffLhs)
219 if (buffRhs != srcBuffRhs)
226 VectorType accTy = dyn_cast<VectorType>(contractOp.getAccType());
233 llvm::copy_if(accShape, std::back_inserter(nonUnitDimAcc),
234 [](
int64_t dim) {
return (dim != 16 && dim != 1); });
236 if (nonUnitDimAcc.size() != 0)
241 VectorType lhsTy = contractOp.getLhsType();
244 llvm::copy_if(lhsShape, std::back_inserter(nonUnitDimLhs),
245 [](
int64_t dim) {
return (dim != 16 && dim != 1); });
247 if (nonUnitDimLhs.size() != 1)
250 if (nonUnitDimLhs[0] != blockingFactor)
255 VectorType rhsTy = contractOp.getRhsType();
258 llvm::copy_if(rhsShape, std::back_inserter(nonUnitDimRhs),
259 [](
int64_t dim) {
return (dim != 16 && dim != 1); });
261 if (nonUnitDimRhs.size() != 1)
264 if (nonUnitDimRhs[0] != blockingFactor)
274 while (
auto arg = dyn_cast<BlockArgument>(
acc)) {
275 auto loop = dyn_cast_if_present<scf::ForOp>(arg.getOwner()->getParentOp());
276 if (!loop || !llvm::is_contained(loops, loop))
278 OpOperand *init = loop.getTiedLoopInit(arg);
288static unsigned getIndexPosition(
Value operand, scf::ForOp loop) {
289 Value iv = loop.getInductionVar();
293 .Case<TransferReadOp, LoadOp>(
294 [&](
auto readOp) { srcBuff = readOp.getOperand(0); });
300 auto offsets = subview.getOffsets();
302 for (
auto it : llvm::enumerate(offsets)) {
303 if (it.value() == iv)
313 unsigned int offset,
bool isVnni) {
315 auto srcIndx = getSrcIndxValue(rewriter, loc, operand,
false);
316 auto [srcBuff,
indices] = *srcIndx;
318 collapseVnniIndices(rewriter, loc,
indices,
319 cast<MemRefType>(srcBuff.
getType()).getShape().back());
321 amx::TileType tileType = amx::TileType::get({16, (16 * offset)}, ipType);
322 return amx::TileLoadOp::create(rewriter, loc, tileType, mat,
indices);
326 Type ipType,
unsigned int offset,
Value packedBuffer,
327 Value indxToStoreInBuffer) {
332 llvm::cast<MemRefType>(matB.
getType()).getRank(), c0);
340 rewriter, loc, c0, cBound, cStep,
ValueRange{},
343 subviewOffset[subviewOffset.size() - 2] = iv;
347 bool is16BitFloat = ipType.
isBF16() || ipType.
isF16();
348 auto vectorType = VectorType::get({2, (16 * (offset / 2))}, ipType);
350 vectorType = VectorType::get((16 * offset), ipType);
352 int64_t srcRank = (dyn_cast<ShapedType>(matB.
getType())).getRank();
353 Value padding = ub::PoisonOp::create(rewriter, loc, ipType);
357 Value vec1 = vector::TransferReadOp::create(
358 rewriter, loc, vectorType, matB,
ValueRange(subviewOffset), padding,
362 vec1 = vector::ShapeCastOp::create(
363 rewriter, loc, VectorType::get((16 * offset), ipType), vec1);
367 Value incIV = arith::AddIOp::create(rewriter, loc, offsetIndx, iv);
368 subviewOffset[subviewOffset.size() - 2] = incIV;
370 Value vec2 = vector::TransferReadOp::create(
371 rewriter, loc, vectorType, matB,
ValueRange(subviewOffset), padding,
374 vec2 = vector::ShapeCastOp::create(
375 rewriter, loc, VectorType::get((16 * offset), ipType), vec2);
377 vector::ShuffleOp writeVal1;
378 vector::ShuffleOp writeVal2;
382 writeVal1 = vector::ShuffleOp::create(
383 rewriter, loc, VectorType::get({(16 * offset)}, ipType), vec1,
385 ArrayRef<int64_t>{0, 32, 1, 33, 2, 34, 3, 35, 8, 40, 9,
386 41, 10, 42, 11, 43, 16, 48, 17, 49, 18, 50,
387 19, 51, 24, 56, 25, 57, 26, 58, 27, 59});
389 writeVal2 = vector::ShuffleOp::create(
390 rewriter, loc, VectorType::get({(16 * offset)}, ipType), vec1,
392 ArrayRef<int64_t>{4, 36, 5, 37, 6, 38, 7, 39, 12, 44, 13,
393 45, 14, 46, 15, 47, 20, 52, 21, 53, 22, 54,
394 23, 55, 28, 60, 29, 61, 30, 62, 31, 63});
400 writeVal1 = vector::ShuffleOp::create(
401 rewriter, loc, VectorType::get({(16 * offset)}, ipType), vec1,
404 0, 32, 64, 96, 1, 33, 65, 97, 2, 34, 66, 98, 3,
405 35, 67, 99, 8, 40, 72, 104, 9, 41, 73, 105, 10, 42,
406 74, 106, 11, 43, 75, 107, 16, 48, 80, 112, 17, 49, 81,
407 113, 18, 50, 82, 114, 19, 51, 83, 115, 24, 56, 88, 120,
408 25, 57, 89, 121, 26, 58, 90, 122, 27, 59, 91, 123});
410 writeVal2 = vector::ShuffleOp::create(
411 rewriter, loc, VectorType::get({(16 * offset)}, ipType), vec1,
414 4, 36, 68, 100, 5, 37, 69, 101, 6, 38, 70, 102, 7, 39,
415 71, 103, 12, 44, 76, 108, 13, 45, 77, 109, 14, 46, 78, 110,
416 15, 47, 79, 111, 20, 52, 84, 116, 21, 53, 85, 117, 22, 54,
417 86, 118, 23, 55, 87, 119, 28, 60, 92, 124, 29, 61, 93, 125,
418 30, 62, 94, 126, 31, 63, 95, 127});
422 Value ivShuff1 = arith::DivUIOp::create(rewriter, loc, iv, cStep);
423 Value ivShuff2 = arith::AddIOp::create(rewriter, loc, ivShuff1, c16);
425 vector::StoreOp::create(rewriter, loc, writeVal1, packedBuffer,
426 ValueRange{indxToStoreInBuffer, ivShuff1, c0});
427 vector::StoreOp::create(rewriter, loc, writeVal2, packedBuffer,
428 ValueRange{indxToStoreInBuffer, ivShuff2, c0});
430 scf::YieldOp::create(nestedBuilder, loc);
437 unsigned int offset,
Value packedBuffer,
bool pack,
438 Value indxToStoreInBuffer,
Value indxToLoadFromMatB) {
444 for (
size_t j = 0;
j < ops.size();
j++) {
445 for (
size_t i = 0; i < ops.size(); i++) {
449 Operation *readOpRhs = ops[
j].getRhs().getDefiningOp();
450 auto itRhs = readsToTileLoads.find(readOpRhs);
451 if (itRhs != readsToTileLoads.end()) {
456 performShuffle(rewriter, loc, matB, ipType, offset, packedBuffer,
457 indxToStoreInBuffer);
461 amx::TileType::get({16, (16 * offset)}, ipType);
463 amx::TileLoadOp::create(rewriter, loc, tileType, packedBuffer,
467 amx::TileLoadOp::create(rewriter, loc, tileType, packedBuffer,
470 readsToTileLoads.try_emplace(readOpRhs, loadRow1);
471 readsToTileLoads.try_emplace(ops[i].getRhs().getDefiningOp(), loadRow2);
476 return readsToTileLoads;
484 unsigned int offset,
bool isVnni,
Value packedBuffer,
bool pack,
485 Value indxToStoreInBuffer,
Value indxToLoadFromMatB) {
500 packInputs(rewriter, loc, ops, matB, ipType, offset, packedBuffer, pack,
501 indxToStoreInBuffer, indxToLoadFromMatB);
505 for (
size_t i = 0; i < ops.size(); i++) {
507 Operation *readOpLhs = ops[i].getLhs().getDefiningOp();
508 amx::TileLoadOp tilesLhs;
509 auto itLhs = readsToTileLoads.find(readOpLhs);
510 if (itLhs != readsToTileLoads.end()) {
511 tilesLhs = itLhs->second;
513 tilesLhs = createTileLoads(rewriter, loc, ops[i].getLhs(), matA, ipType,
515 readsToTileLoads.try_emplace(readOpLhs, tilesLhs);
518 Operation *readOpRhs = ops[i].getRhs().getDefiningOp();
519 amx::TileLoadOp tilesRhs;
520 auto itRhs = readsToTileLoads.find(readOpRhs);
521 if (itRhs != readsToTileLoads.end()) {
522 tilesRhs = itRhs->second;
524 tilesRhs = createTileLoads(rewriter, loc, ops[i].getRhs(), matB, ipType,
526 readsToTileLoads.try_emplace(readOpRhs, tilesRhs);
529 auto accTileType = amx::TileType::get({16, 16}, opType);
532 if (isa<FloatType>(ipType))
533 dp = amx::TileMulFOp::create(rewriter, loc, accTileType, tilesLhs,
534 tilesRhs, accIterArgs[i]);
537 dp = amx::TileMulIOp::create(rewriter, loc, accTileType, tilesLhs,
538 tilesRhs, accIterArgs[i]);
540 accumulators.push_back(dp);
546 Type opType, scf::ForOp outerLoop,
552 auto zeroTileType = amx::TileType::get({16, 16}, opType);
554 for (
int i = 0; i < size; i++) {
555 auto zeroTile = amx::TileZeroOp::create(rewriter, loc, zeroTileType);
556 loopItrArgs.push_back(zeroTile);
564static std::optional<std::pair<Value, SmallVector<Value>>>
572 if (
auto transfer = dyn_cast<VectorTransferOpInterface>(op)) {
573 if (transfer.getMask() || transfer.hasOutOfBoundsDim() ||
574 !transfer.getPermutationMap().isMinorIdentity())
576 base = transfer.getBase();
577 vecTy = transfer.getVectorType();
578 indices = transfer.getIndices();
579 }
else if (
auto load = dyn_cast<vector::LoadOp>(op)) {
580 base =
load.getBase();
581 vecTy =
load.getVectorType();
583 }
else if (
auto store = dyn_cast<vector::StoreOp>(op)) {
584 base = store.getBase();
585 vecTy = store.getVectorType();
591 auto memrefTy = dyn_cast<MemRefType>(base.
getType());
593 if (!memrefTy || memrefTy.getRank() < 2 || !memrefTy.isLastDimUnitStride() ||
595 llvm::any_of(
shape.drop_back(2), [](
int64_t d) { return d != 1; }))
605static std::pair<std::optional<SmallVector<Operation *>>,
606 std::optional<SmallVector<Operation *>>>
609 for (vector::ContractionOp op : ops) {
612 return {std::nullopt, std::nullopt};
614 if (!isa<vector::TransferWriteOp, vector::StoreOp>(write) ||
616 return {std::nullopt, std::nullopt};
617 writes.push_back(write);
623 if (!read || !getAccTileAccess(read))
624 return {std::nullopt, std::nullopt};
625 reads.push_back(read);
629 return {std::nullopt, writes};
630 return std::make_pair(reads, writes);
635 Type opType, scf::ForOp loop,
639 auto tileType = amx::TileType::get({16, 16}, opType);
642 auto [base,
indices] = *getAccTileAccess(read);
644 amx::TileLoadOp::create(rewriter, loc, tileType, base,
indices));
652 bool isInnerLoopUBHasOddQuot,
653 bool isInnerLoopUBLarger,
654 bool pack,
Value blockStride) {
662 Value quotientInnerLoop =
663 arith::DivUIOp::create(rewriter, loc, ivInnerLoop, blockStride);
664 Value remInnerLoop = arith::RemUIOp::create(
665 rewriter, loc, rewriter.
getIndexType(), quotientInnerLoop, c2);
667 if (!isInnerLoopUBLarger && !pack) {
668 remInnerLoop = arith::RemUIOp::create(
669 rewriter, loc, rewriter.
getIndexType(), ivOuterLoop, c2);
672 if (isInnerLoopUBHasOddQuot) {
673 auto remOuterLoop = arith::RemUIOp::create(
674 rewriter, loc, rewriter.
getIndexType(), ivOuterLoop, c2);
675 auto remAdd = arith::AddIOp::create(rewriter, loc, rewriter.
getIndexType(),
676 remInnerLoop, remOuterLoop);
677 remInnerLoop = arith::RemUIOp::create(rewriter, loc,
687 Type ipType,
Type opType,
unsigned int blockingFactor,
bool isVnni,
689 vector::ContractionOp contractOp, scf::ForOp outerLoop,
691 Value ivOuterLoop,
Value packedBuffer,
bool pack,
693 bool isInnerLoopUBHasOddQuot) {
699 int64_t offset = 16 * blockingFactor;
701 offset = cst.value();
703 auto newLoop = scf::ForOp::create(
704 rewriter, loc, lowerBound, upperBound, step, loopItrArgs,
710 getIndexPosition(contractOp.getLhs(), outerLoop) + 1),
714 getIndexPosition(contractOp.getLhs(), innerLoop) + 1),
716 auto lhsClone = rewriterNewInnerLoop.
clone(*vectorOpLhs, mapping);
718 Value indxToStoreInBuffer = c0;
719 Value indxToLoadFromBuffer = c0;
722 if (innerLoopIndex.
value() == 0) {
725 ivOuterLoop = arith::AddIOp::create(rewriter, locNewInnerLoop,
728 if (!isInnerLoopUBLarger || isInnerLoopUBHasOddQuot) {
729 indxToStoreInBuffer = arith::RemUIOp::create(
734 Value indxToLoadFromMatB = arith::AddIOp::create(
735 rewriter, loc, indxToStoreInBuffer, c1);
736 indxToLoadFromBuffer = arith::RemUIOp::create(
737 rewriter, loc, rewriter.
getIndexType(), indxToLoadFromMatB,
743 rewriter, locNewInnerLoop, offset);
744 ivNewInnerLoop = arith::AddIOp::create(rewriter, locNewInnerLoop,
745 nLoadIndx, ivNewInnerLoop);
746 indxToStoreInBuffer = getIndxToLoadStoreFromPckBuffer(
747 rewriter, loc, ivNewInnerLoop, ivOuterLoop,
748 isInnerLoopUBHasOddQuot, isInnerLoopUBLarger, pack, step);
749 Value indxToLoadFromMatB =
750 arith::AddIOp::create(rewriter, loc, indxToStoreInBuffer, c1);
751 indxToLoadFromBuffer =
752 arith::RemUIOp::create(rewriter, loc, rewriter.
getIndexType(),
753 indxToLoadFromMatB, c2);
758 rewriter, locNewInnerLoop, offset);
759 ivNewInnerLoop = arith::AddIOp::create(rewriter, locNewInnerLoop,
760 nLoadIndx, ivNewInnerLoop);
761 Value quotient_K = arith::DivUIOp::create(
762 rewriter, loc, ivNewInnerLoop, nLoadIndx);
763 indxToStoreInBuffer = arith::RemUIOp::create(
764 rewriter, loc, rewriter.
getIndexType(), quotient_K, c2);
766 Value indxToLoadFromMatB =
767 arith::AddIOp::create(rewriter, loc, indxToStoreInBuffer, c1);
768 indxToLoadFromBuffer =
769 arith::RemUIOp::create(rewriter, loc, rewriter.
getIndexType(),
770 indxToLoadFromMatB, c2);
783 int64_t outerPos = getIndexPosition(contractOp.getRhs(), outerLoop);
786 unsigned operandIdx =
static_cast<unsigned>(outerPos + 1);
788 if (operandIdx < rhsOp->getNumOperands())
793 int64_t innerPos = getIndexPosition(contractOp.getRhs(), innerLoop);
796 unsigned operandIdx =
static_cast<unsigned>(innerPos + 1);
798 if (operandIdx < rhsOp->getNumOperands())
799 rhsMapping.
map(rhsOp->
getOperand(operandIdx), ivNewInnerLoop);
802 auto rhsClone = rewriterNewInnerLoop.
clone(*rhsOp, rhsMapping);
803 matB = rhsClone->getResult(0);
814 indxToLoadFromBuffer = c0;
820 indxToLoadFromBuffer = getIndxToLoadStoreFromPckBuffer(
821 rewriter, loc, ivNewInnerLoop, ivOuterLoop,
822 isInnerLoopUBHasOddQuot, isInnerLoopUBLarger, pack, step);
827 rewriter, locNewInnerLoop, offset);
829 Value quotient_K = arith::DivUIOp::create(
830 rewriter, loc, ivNewInnerLoop, nLoadIndx);
831 indxToLoadFromBuffer = arith::RemUIOp::create(
832 rewriter, loc, rewriter.
getIndexType(), quotient_K, c2);
838 rewriter, locNewInnerLoop, ops, lhsClone->getResult(0), matB,
839 ipType, opType, iterArgsNewInnerLoop, blockingFactor, isVnni,
840 packedBuffer, pack, indxToStoreInBuffer, indxToLoadFromBuffer);
842 scf::YieldOp::create(rewriterNewInnerLoop, locNewInnerLoop,
917 matchAndRewriteAddContractOp(vector::ContractionOp contractOp,
918 PatternRewriter &rewriter)
const override {
920 Type lhsElemTy = contractOp.getLhsType().getElementType();
921 unsigned int blockingFactor =
925 contractOp.getIndexingMapsArray(), blockingFactor);
927 VectorType lhsTy = contractOp.getLhsType();
928 if (!lhsTy.getElementType().isBF16() && !lhsTy.getElementType().isF16() &&
929 !lhsTy.getElementType().isSignlessInteger(8) &&
930 !lhsTy.getElementType().isF8E4M3FN() &&
931 !lhsTy.getElementType().isF8E5M2())
933 contractOp,
"Only BF16/F16/Int8/F8 lowering is supported.");
935 if (lhsTy.getElementType() != contractOp.getRhsType().getElementType())
937 contractOp,
"Contraction should have same lhs and rhs type.");
939 VectorType accTy = dyn_cast<VectorType>(contractOp.getAccType());
943 if (((lhsTy.getElementType().isBF16() || lhsTy.getElementType().isF16() ||
944 lhsTy.getElementType().isF8E4M3FN() ||
945 lhsTy.getElementType().isF8E5M2()) &&
946 !accTy.getElementType().isF32()) ||
947 (lhsTy.getElementType().isSignlessInteger(8) &&
948 !accTy.getElementType().isSignlessInteger(32)))
950 contractOp,
"Only F32 for BF16/F16/F8 or Int32 for Int8 "
951 "accumulation type is supported.");
953 Operation *accReadOp =
961 if (!accReadOp || !resultChainEnd)
963 contractOp,
"The ACC operand of the vector.contract should be a "
964 "transfer_read or a load. And, the result should have a "
965 "single-use chain to its consumer.");
967 bool isAccZeroVectorConstant = isZeroVectorConstant(accReadOp);
972 if (lhsTy.getElementType().isSignlessInteger(8))
975 if (lhsTy.getElementType().isF16())
978 if (lhsTy.getElementType().isF8E4M3FN())
981 if (lhsTy.getElementType().isF8E5M2())
984 Type opType = isa<FloatType>(ipType) ? Type(rewriter.
getF32Type())
985 : Type(rewriter.getIntegerType(32));
987 if (accReadOp->
getBlock() == contractOp->getBlock() &&
988 resultBlock != contractOp->getBlock())
990 contractOp,
"The accumulator store is in different block.");
992 if (accReadOp->
getBlock() != contractOp->getBlock() &&
993 resultBlock == contractOp->getBlock())
995 contractOp,
"The accumulator read is in different block.");
997 if (!(isReadSrcMemref(contractOp.getLhs()) &&
998 isReadSrcMemref(contractOp.getRhs())))
1000 contractOp,
"The LHS or RHS src is not a MemRef type.");
1002 if (isVnni && !(isVnniOperandRead(contractOp.getLhs(), blockingFactor) &&
1003 isVnniOperandRead(contractOp.getRhs(), blockingFactor)))
1005 contractOp,
"The LHS or RHS src does not read whole VNNI groups.");
1007 unsigned int dimValue = blockingFactor;
1009 dimValue = 16 * blockingFactor;
1013 if (accReadOp->
getBlock() == contractOp->getBlock() &&
1014 resultBlock == contractOp->getBlock()) {
1016 if (!isReadSrcMemref(contractOp.getAcc()))
1017 return rewriter.notifyMatchFailure(contractOp,
1018 "The ACC src is not a MemRef type.");
1020 if (hasMaskedOrOutOfBoundsRead(
1021 {contractOp.getLhs(), contractOp.getRhs(), contractOp.getAcc()}))
1023 contractOp,
"The reads should be unmasked and in bounds.");
1025 bool collapse =
false;
1029 LogicalResult validate = validateContractOps(
1030 rewriter, contractOp, dimValue, Value(), Value(),
false);
1034 contractOp,
"The contract operation doesn't satisfy the operands "
1035 "dimensions. M, N, and vnni dims are 16, 16, and 2/4. "
1036 "The rest dims should be 1. Op should have one user.");
1038 Location loc = contractOp.getLoc();
1040 auto srcIndxLhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
1041 contractOp.getLhs(), collapse);
1044 "Failed to get the LHS src.");
1045 auto [srcBuffLhs, indicesLhs] = *srcIndxLhs;
1047 auto srcIndxRhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
1048 contractOp.getRhs(), collapse);
1051 "Failed to get the RHS src.");
1052 auto rhsSrc = *srcIndxRhs;
1053 auto srcBuffRhs = rhsSrc.first;
1054 auto indicesRhs = rhsSrc.second;
1056 auto srcIndxAcc = getSrcIndxValue(rewriter, contractOp.getLoc(),
1057 contractOp.getAcc(),
false);
1060 "Failed to get the ACC src.");
1061 auto [srcBuffAcc, indicesAcc] = *srcIndxAcc;
1066 auto tileType = amx::TileType::get({16, (16 * blockingFactor)}, ipType);
1067 auto loadLhs = amx::TileLoadOp::create(rewriter, loc, tileType,
1068 srcBuffLhs, indicesLhs);
1071 amx::TileLoadOp loadRhs;
1074 SmallVector<OpFoldResult> indexVals;
1075 llvm::TypeSwitch<Operation *>(contractOp.getRhs().getDefiningOp())
1076 .Case<TransferReadOp, LoadOp>([&](
auto readOp) {
1077 indexVals = SmallVector<OpFoldResult>(readOp.getIndices().begin(),
1078 readOp.getIndices().end());
1079 vecTy = readOp.getType();
1082 SmallVector<OpFoldResult> strides(indexVals.size(), one);
1085 SmallVector<int64_t> subviewShape(indexVals.size() - vecTy.getRank(),
1087 llvm::append_range(subviewShape, vecTy.getShape());
1088 SmallVector<OpFoldResult> sizes =
1090 auto subview = memref::SubViewOp::create(rewriter, loc, srcBuffRhs,
1091 indexVals, sizes, strides);
1092 auto bufferType = MemRefType::get({16, (16 * blockingFactor)}, ipType);
1093 auto packedBuffer = memref::AllocaOp::create(rewriter, loc, bufferType);
1099 (blockingFactor * 16));
1100 Value nextLoadIndx =
1103 rewriter, loc, 16 * (blockingFactor / 2));
1106 rewriter, loc, c0, uBound, step,
ValueRange{},
1107 [&](OpBuilder &nestedBuilder, Location loc, Value iv,
1110 arith::AddIOp::create(rewriter, loc, nextLoadIndx, iv);
1114 size_t numOffsets = indicesRhs.size();
1115 SmallVector<Value>
indices(numOffsets, c0);
1117 auto vec1 = vector::LoadOp::create(
1119 VectorType::get(16 * (blockingFactor / 2), ipType), subview,
1122 indices[numOffsets - 2] = i1_load;
1123 auto vec2 = vector::LoadOp::create(
1125 VectorType::get(16 * (blockingFactor / 2), ipType), subview,
1128 vector::ShuffleOp writeVal1;
1129 vector::ShuffleOp writeVal2;
1131 if (blockingFactor == 2) {
1133 writeVal1 = vector::ShuffleOp::create(
1134 rewriter, loc, VectorType::get({16}, ipType), vec1, vec2,
1135 ArrayRef<int64_t>{0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21,
1138 writeVal2 = vector::ShuffleOp::create(
1139 rewriter, loc, VectorType::get({16}, ipType), vec1, vec2,
1140 ArrayRef<int64_t>{8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13,
1141 29, 14, 30, 15, 31});
1144 if (blockingFactor == 4) {
1145 writeVal1 = vector::ShuffleOp::create(
1146 rewriter, loc, VectorType::get({32}, ipType), vec1, vec2,
1147 ArrayRef<int64_t>{0, 16, 32, 48, 1, 17, 33, 49,
1148 2, 18, 34, 50, 3, 19, 35, 51,
1149 4, 20, 36, 52, 5, 21, 37, 53,
1150 6, 22, 38, 54, 7, 23, 39, 55});
1152 writeVal2 = vector::ShuffleOp::create(
1153 rewriter, loc, VectorType::get({32}, ipType), vec1, vec2,
1154 ArrayRef<int64_t>{8, 24, 40, 56, 9, 25, 41, 57,
1155 10, 26, 42, 58, 11, 27, 43, 59,
1156 12, 28, 44, 60, 13, 29, 45, 61,
1157 14, 30, 46, 62, 15, 31, 47, 63});
1160 auto rem = arith::DivUIOp::create(
1163 vector::StoreOp::create(rewriter, loc, writeVal1, packedBuffer,
1165 vector::StoreOp::create(rewriter, loc, writeVal2, packedBuffer,
1168 scf::YieldOp::create(nestedBuilder, loc);
1170 loadRhs = amx::TileLoadOp::create(rewriter, loc, tileType, packedBuffer,
1174 loadRhs = amx::TileLoadOp::create(rewriter, loc, tileType, srcBuffRhs,
1178 auto tileTypeAcc = amx::TileType::get({16, 16}, opType);
1179 auto loadAcc = amx::TileLoadOp::create(rewriter, loc, tileTypeAcc,
1180 srcBuffAcc, indicesAcc);
1184 if (isa<FloatType>(ipType))
1185 dp = amx::TileMulFOp::create(rewriter, loc, tileTypeAcc, loadLhs,
1189 dp = amx::TileMulIOp::create(rewriter, loc, tileTypeAcc, loadLhs,
1192 auto bufferType = MemRefType::get({16, 16}, opType);
1193 auto resultBuffer = memref::AllocaOp::create(rewriter, loc, bufferType);
1195 amx::TileStoreOp::create(rewriter, loc, resultBuffer,
ValueRange{c0, c0},
1198 auto vectorType = VectorType::get({16, 16}, opType);
1200 (dyn_cast<ShapedType>(resultBuffer.getType())).getRank();
1201 Value padding = ub::PoisonOp::create(rewriter, loc, opType);
1204 SmallVector<bool> inBounds(vectorType.getRank(),
true);
1206 Value vecRow = vector::TransferReadOp::create(
1207 rewriter, loc, vectorType, resultBuffer,
ValueRange{c0, c0}, padding,
1211 if (
auto vecType = dyn_cast<VectorType>(resultOp.getType()))
1212 vecRow = vector::ShapeCastOp::create(rewriter, loc, vecType, vecRow);
1222 SmallVector<scf::ForOp> loopLists;
1223 Operation *current = contractOp;
1233 if (!loopLists.empty())
1237 "Accumulator read and contract op not within scf.for op");
1240 loopLists.push_back(dyn_cast<scf::ForOp>(parent));
1242 if (resultBlock == parent->
getBlock()) {
1249 if (loopLists.size() > 2 || loopLists.size() == 0)
1251 contractOp,
"Rewrite is supported until reduction loop depth of 2.");
1253 auto srcIndxLhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
1254 contractOp.getLhs(),
false);
1257 "Failed to get the LHS src.");
1258 auto [srcBuffLhs, indicesLhs] = *srcIndxLhs;
1260 auto srcIndxRhs = getSrcIndxValue(rewriter, contractOp.getLoc(),
1261 contractOp.getRhs(),
false);
1264 "Failed to get the RHS src.");
1265 auto [srcBuffRhs, indicesRhs] = *srcIndxRhs;
1266 Operation *vectorOpLhs;
1267 llvm::TypeSwitch<Operation *>(contractOp.getLhs().getDefiningOp())
1268 .Case<TransferReadOp, LoadOp>([&](
auto readOp) {
1269 vectorOpLhs = readOp.getBase().getDefiningOp();
1272 Operation *vectorOpRhs;
1273 llvm::TypeSwitch<Operation *>(contractOp.getRhs().getDefiningOp())
1274 .Case<TransferReadOp, LoadOp>([&](
auto readOp) {
1275 vectorOpRhs = readOp.getBase().getDefiningOp();
1278 if (!vectorOpLhs || !vectorOpRhs)
1280 contractOp,
"Failed to find LHS or RHS read source operation");
1283 SmallVector<vector::ContractionOp> ops;
1287 SmallVector<std::pair<size_t, Value>> carriedAccs;
1288 for (Operation &op : loopLists[0].getBody()->getOperations()) {
1290 if (
auto contract = dyn_cast<vector::ContractionOp>(op)) {
1291 if (isVnni && !(isVnniOperandRead(
contract.getLhs(), blockingFactor) &&
1292 isVnniOperandRead(
contract.getRhs(), blockingFactor)))
1294 contractOp,
"The LHS or RHS src of an associated contract "
1295 "operation does not read whole VNNI groups.");
1297 LogicalResult validate = validateContractOps(
1298 rewriter,
contract, dimValue, srcBuffLhs, srcBuffRhs,
true);
1303 "The associated contract operations doesn't satisfy "
1304 "the re-write conditions either the dimensions are "
1305 "wrong or MemRef source are different or many users.");
1307 Operation *contractReadOp =
1310 if (isAccZeroVectorConstant != isZeroVectorConstant(contractReadOp))
1312 contractOp,
"The input acc should be a zero constant or "
1313 "transfer_read for all contracts");
1315 Value accInit = getLoopNestInit(
contract.getAcc(), loopLists);
1316 if (hasMaskedOrOutOfBoundsRead(
1319 contractOp,
"The reads of an associated contract operation "
1320 "should be unmasked and in bounds.");
1322 bool carried = !isa_and_present<TransferReadOp, LoadOp>(accInitOp) &&
1323 !isZeroVectorConstant(accInitOp);
1325 if (loopLists.back().getRegion().isAncestor(
1328 contractOp,
"The accumulator should enter the reduction loops "
1329 "through their init args.");
1330 carriedAccs.emplace_back(ops.size(), accInit);
1339 if (!isAccZeroVectorConstant && !carriedAccs.empty() &&
1340 carriedAccs.size() != ops.size())
1342 contractOp,
"The accumulators read from memory can't be mixed with "
1343 "carried in accumulators.");
1346 unsigned int pairCount = 0;
1347 for (
size_t j = 0; j < ops.size(); j++) {
1348 for (
size_t i = j; i < ops.size(); i++) {
1350 pairCount = pairCount + 2;
1354 if (pairCount != ops.size())
1356 contractOp,
"Coudn't find the pair vector contract ");
1359 scf::ForOp innerLoop;
1360 scf::ForOp outerLoop;
1365 std::optional<SmallVector<Operation *>> inPlaceAccReads, inPlaceAccWrites;
1367 std::tie(inPlaceAccReads, inPlaceAccWrites) =
1368 getInPlaceAccAccesses(ops, isAccZeroVectorConstant);
1369 auto createInitTiles = [&](scf::ForOp loop) {
1370 if (inPlaceAccReads)
1371 return createAccTileLoads(rewriter, loop.getLoc(), opType, loop,
1373 return createTileZeros(rewriter, loop.getLoc(), opType, loop, ops.size());
1378 if (loopLists.size() == 2) {
1379 outerLoop = loopLists[1];
1380 innerLoop = loopLists[0];
1382 LogicalResult validateOuterLoopStep =
1383 validateLoopStep(rewriter, outerLoop.getStep(), 1);
1384 if (
failed(validateOuterLoopStep))
1387 int64_t stepValue = 16;
1389 stepValue = stepValue * blockingFactor;
1390 LogicalResult validateInnerLoopStep =
1391 validateLoopStep(rewriter, innerLoop.getStep(), stepValue);
1392 if (
failed(validateInnerLoopStep))
1395 "Invalid loop step. The step should be 32 for BF16/F16 and "
1398 SmallVector<Value> loopItrArgs = createInitTiles(outerLoop);
1402 newLoop = scf::ForOp::create(
1403 rewriter, outerLoop.getLoc(), outerLoop.getLowerBound(),
1404 outerLoop.getUpperBound(), outerLoop.getStep(), loopItrArgs,
1405 [&](OpBuilder &rewriterOuterLoop, Location locOuterLoop,
1406 Value ivOuterLoop,
ValueRange iterArgsOuterLoop) {
1407 auto newInnerLoop = createLoops(
1408 rewriter, innerLoop.getLoc(), innerLoop.getLowerBound(),
1409 innerLoop.getUpperBound(), innerLoop.getStep(),
1410 iterArgsOuterLoop, ipType, opType, blockingFactor, isVnni,
1411 vectorOpLhs, vectorOpRhs, contractOp, outerLoop, innerLoop,
1412 ops, ivOuterLoop, nullptr, true, nullptr, false, false);
1414 scf::YieldOp::create(rewriterOuterLoop, locOuterLoop,
1415 newInnerLoop.getResults());
1420 bool isInnerLoopUBLarger =
false;
1421 bool isInnerLoopUBHasOddQuot =
false;
1423 int64_t ubVal = 16 * blockingFactor;
1424 Value ub = innerLoop.getUpperBound();
1426 if (
auto intAttr = dyn_cast<IntegerAttr>(constOp.getValue())) {
1427 ubVal = intAttr.getInt();
1431 isInnerLoopUBLarger = ubVal > 16 * blockingFactor;
1432 isInnerLoopUBHasOddQuot =
1433 (((ubVal / (16 * blockingFactor)) % 2) == 1) && isInnerLoopUBLarger;
1442 rewriter, outerLoop.getLoc(), 16 * blockingFactor);
1444 Value spillOuterLoop = arith::SubIOp::create(
1445 rewriter, outerLoop.getLoc(), outerLoop.getUpperBound(), c1);
1446 Value spillInnerLoop =
1447 arith::SubIOp::create(rewriter, innerLoop.getLoc(),
1448 innerLoop.getUpperBound(), spillLoopBound);
1450 MemRefType::get({2, 32, (blockingFactor * 16)}, ipType);
1452 memref::AllocaOp::create(rewriter, outerLoop.getLoc(), bufferType);
1455 IRMapping rhsMapping;
1457 vectorOpRhs->getOperand(
1458 getIndexPosition(contractOp.getRhs(), outerLoop) + 1),
1459 outerLoop.getLowerBound());
1461 vectorOpRhs->getOperand(
1462 getIndexPosition(contractOp.getRhs(), innerLoop) + 1),
1463 innerLoop.getLowerBound());
1464 auto rhsClone = rewriter.
clone(*vectorOpRhs, rhsMapping);
1466 Value quotient_batch = arith::DivUIOp::create(
1467 rewriter, outerLoop.getLoc(), outerLoop.getLowerBound(),
1468 outerLoop.getStep());
1469 Value quotient_k = arith::DivUIOp::create(rewriter, outerLoop.getLoc(),
1470 innerLoop.getLowerBound(),
1471 innerLoop.getStep());
1473 Value quotient_add = arith::AddIOp::create(rewriter, outerLoop.getLoc(),
1474 quotient_batch, quotient_k);
1477 Value
rem = arith::RemUIOp::create(rewriter, outerLoop.getLoc(),
1480 performShuffle(rewriter, outerLoop.getLoc(), rhsClone->getResult(0),
1481 ipType, blockingFactor, packedBuffer,
rem);
1484 auto newLoopNonSpill = scf::ForOp::create(
1485 rewriter, outerLoop.getLoc(), outerLoop.getLowerBound(),
1486 spillOuterLoop, outerLoop.getStep(), loopItrArgs,
1487 [&](OpBuilder &rewriterOuterLoop, Location locOuterLoop,
1488 Value ivOuterLoop,
ValueRange iterArgsOuterLoop) {
1489 auto newInnerLoop1 = createLoops(
1490 rewriter, innerLoop.getLoc(), innerLoop.getLowerBound(),
1491 spillInnerLoop, innerLoop.getStep(), iterArgsOuterLoop,
1492 ipType, opType, blockingFactor, isVnni, vectorOpLhs,
1493 vectorOpRhs, contractOp, outerLoop, innerLoop, ops,
1494 ivOuterLoop, packedBuffer, true, spillLoopBound,
1495 isInnerLoopUBLarger, isInnerLoopUBHasOddQuot);
1497 auto newInnerLoop = createLoops(
1498 rewriter, innerLoop.getLoc(), spillInnerLoop,
1499 innerLoop.getUpperBound(), innerLoop.getStep(),
1500 newInnerLoop1.getResults(), ipType, opType, blockingFactor,
1501 isVnni, vectorOpLhs, vectorOpRhs, contractOp, outerLoop,
1502 innerLoop, ops, ivOuterLoop, packedBuffer, true, c0,
1503 isInnerLoopUBLarger, isInnerLoopUBHasOddQuot);
1505 scf::YieldOp::create(rewriterOuterLoop, locOuterLoop,
1506 newInnerLoop.getResults());
1510 newLoop = scf::ForOp::create(
1511 rewriter, outerLoop.getLoc(), spillOuterLoop,
1512 outerLoop.getUpperBound(), outerLoop.getStep(),
1513 newLoopNonSpill.getResults(),
1514 [&](OpBuilder &rewriterOuterLoop, Location locOuterLoop,
1515 Value ivOuterLoop,
ValueRange iterArgsOuterLoop) {
1516 auto newInnerLoop1 = createLoops(
1517 rewriter, innerLoop.getLoc(), innerLoop.getLowerBound(),
1518 spillInnerLoop, innerLoop.getStep(), iterArgsOuterLoop,
1519 ipType, opType, blockingFactor, isVnni, vectorOpLhs,
1520 vectorOpRhs, contractOp, outerLoop, innerLoop, ops,
1521 ivOuterLoop, packedBuffer, true, spillLoopBound,
1522 isInnerLoopUBLarger, isInnerLoopUBHasOddQuot);
1524 auto newInnerLoop = createLoops(
1525 rewriter, innerLoop.getLoc(), spillInnerLoop,
1526 innerLoop.getUpperBound(), innerLoop.getStep(),
1527 newInnerLoop1.getResults(), ipType, opType, blockingFactor,
1528 isVnni, vectorOpLhs, vectorOpRhs, contractOp, outerLoop,
1529 innerLoop, ops, ivOuterLoop, packedBuffer, false, c0,
1530 isInnerLoopUBLarger, isInnerLoopUBHasOddQuot);
1532 scf::YieldOp::create(rewriterOuterLoop, locOuterLoop,
1533 newInnerLoop.getResults());
1539 if (loopLists.size() == 1) {
1541 innerLoop = loopLists[0];
1542 int64_t stepValue = 16;
1544 stepValue = stepValue * blockingFactor;
1546 LogicalResult validateInnerLoopStep =
1547 validateLoopStep(rewriter, innerLoop.getStep(), stepValue);
1548 if (
failed(validateInnerLoopStep))
1551 "Invalid loop step. The step should be 32 for BF16/F16 and "
1552 "64 for Int8/F8 or 1 if it is rduction loop other than K.");
1554 SmallVector<Value> loopItrArgs = createInitTiles(innerLoop);
1558 newLoop = createLoops(
1559 rewriter, innerLoop.getLoc(), innerLoop.getLowerBound(),
1560 innerLoop.getUpperBound(), innerLoop.getStep(), loopItrArgs, ipType,
1561 opType, blockingFactor, isVnni, vectorOpLhs, vectorOpRhs,
1562 contractOp,
nullptr, innerLoop, ops,
nullptr,
nullptr,
true,
1563 nullptr,
false,
false);
1567 bool isInnerLoopUBLarger =
false;
1568 bool isInnerLoopUBHasOddQuot =
false;
1570 int64_t ubVal = 16 * blockingFactor;
1571 Value ub = innerLoop.getUpperBound();
1573 if (
auto intAttr = dyn_cast<IntegerAttr>(constOp.getValue())) {
1574 ubVal = intAttr.getInt();
1578 isInnerLoopUBLarger = ubVal > 16 * blockingFactor;
1579 isInnerLoopUBHasOddQuot =
1580 (((ubVal / (16 * blockingFactor)) % 2) == 1) && isInnerLoopUBLarger;
1586 int64_t offset = 16 * blockingFactor;
1588 innerLoop.getStep().getDefiningOp<arith::ConstantIndexOp>())
1589 offset = cst.value();
1592 rewriter, innerLoop.getLoc(), offset);
1593 Value spillInnerLoop =
1594 arith::SubIOp::create(rewriter, innerLoop.getLoc(),
1595 innerLoop.getUpperBound(), spillLoopBound);
1598 MemRefType::get({2, 32, (blockingFactor * 16)}, ipType);
1600 memref::AllocaOp::create(rewriter, innerLoop.getLoc(), bufferType);
1603 IRMapping rhsMapping;
1605 vectorOpRhs->getOperand(
1606 getIndexPosition(contractOp.getRhs(), innerLoop) + 1),
1607 innerLoop.getLowerBound());
1608 auto rhsClone = rewriter.
clone(*vectorOpRhs, rhsMapping);
1610 Value quotient_k = arith::DivUIOp::create(rewriter, innerLoop.getLoc(),
1611 innerLoop.getLowerBound(),
1612 innerLoop.getStep());
1615 Value
rem = arith::RemUIOp::create(rewriter, innerLoop.getLoc(),
1618 performShuffle(rewriter, innerLoop.getLoc(), rhsClone->getResult(0),
1619 ipType, blockingFactor, packedBuffer,
rem);
1621 auto newLoopNonSpill = createLoops(
1622 rewriter, innerLoop.getLoc(), innerLoop.getLowerBound(),
1623 spillInnerLoop, innerLoop.getStep(), loopItrArgs, ipType, opType,
1624 blockingFactor, isVnni, vectorOpLhs, vectorOpRhs, contractOp,
1625 nullptr, innerLoop, ops,
nullptr, packedBuffer,
true,
1626 spillLoopBound, isInnerLoopUBLarger, isInnerLoopUBHasOddQuot);
1628 newLoop = createLoops(rewriter, innerLoop.getLoc(), spillInnerLoop,
1629 innerLoop.getUpperBound(), innerLoop.getStep(),
1630 newLoopNonSpill.getResults(), ipType, opType,
1631 blockingFactor, isVnni, vectorOpLhs, vectorOpRhs,
1632 contractOp,
nullptr, innerLoop, ops,
nullptr,
1633 packedBuffer,
false, c0, isInnerLoopUBLarger,
1634 isInnerLoopUBHasOddQuot);
1639 outerLoop = innerLoop;
1644 Location loc = outerLoop.getLoc();
1646 if (inPlaceAccWrites) {
1650 for (
auto [i, write] : llvm::enumerate(*inPlaceAccWrites)) {
1651 auto [base,
indices] = *getAccTileAccess(write);
1653 amx::TileStoreOp::create(rewriter, write->
getLoc(), base,
indices,
1654 newLoop.getResult(i));
1661 bool addAccFromMemory = !isAccZeroVectorConstant && carriedAccs.empty();
1667 SmallVector<Value> indicesAcc;
1669 if (addAccFromMemory) {
1672 llvm::TypeSwitch<Operation *>(accReadOp).Case<TransferReadOp, LoadOp>(
1674 srcBuffAcc = readOp.getOperand(0);
1676 auto indices = readOp.getIndices();
1677 indicesAcc.reserve(
indices.size());
1679 llvm::transform(
indices, std::back_inserter(indicesAcc),
1680 [&](OpFoldResult ofr) {
1682 rewriter, loc, ofr);
1685 auto outputShapes = cast<MemRefType>(srcBuffAcc.
getType()).getShape();
1686 M = outputShapes[outputShapes.size() - 2];
1687 N = outputShapes[outputShapes.size() - 1];
1693 M = isVnni ? ops.size() * 16 : ops.size() / 2 * 16;
1694 N = isVnni ? 16 : 2 * 16;
1697 SmallVector<Value> dps = newLoop.getResults();
1698 auto bufferType = MemRefType::get({M, N}, opType);
1699 auto resultBuffer = memref::AllocaOp::create(rewriter, loc, bufferType);
1702 for (
unsigned int i = 0, k = 0; i < M; i = i + 16) {
1703 for (
unsigned int j = 0; j < N; j = j + 16) {
1706 amx::TileStoreOp::create(rewriter, loc, resultBuffer,
1717 if (!isVnni || addAccFromMemory) {
1722 rewriter, loc, c0, mBound, one,
ValueRange{},
1723 [&](OpBuilder &nestedBuilder, Location loc, Value iv,
1725 auto row = vector::LoadOp::create(rewriter, loc,
1726 VectorType::get(16, opType),
1729 auto row2 = vector::LoadOp::create(
1730 rewriter, loc, VectorType::get(16, opType), resultBuffer,
1733 Value writeVal1 = row;
1734 Value writeVal2 = row2;
1737 writeVal1 = vector::ShuffleOp::create(
1738 rewriter, loc, VectorType::get(16, opType), row, row2,
1739 ArrayRef<int64_t>{0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20,
1742 writeVal2 = vector::ShuffleOp::create(
1743 rewriter, loc, VectorType::get(16, opType), row, row2,
1744 ArrayRef<int64_t>{8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14,
1745 15, 28, 29, 30, 31});
1748 if (addAccFromMemory) {
1749 indicesAcc[indicesAcc.size() - 2] = iv;
1750 indicesAcc[indicesAcc.size() - 1] = c0;
1752 Value valueCRow1 = vector::LoadOp::create(
1753 rewriter, loc, VectorType::get(16, opType), srcBuffAcc,
1755 indicesAcc[indicesAcc.size() - 1] = c16;
1757 Value valueCRow2 = vector::LoadOp::create(
1758 rewriter, loc, VectorType::get(16, opType), srcBuffAcc,
1761 if (isa<FloatType>(ipType)) {
1763 arith::AddFOp::create(rewriter, loc, writeVal1, valueCRow1);
1766 arith::AddFOp::create(rewriter, loc, writeVal2, valueCRow2);
1771 arith::AddIOp::create(rewriter, loc, writeVal1, valueCRow1);
1774 arith::AddIOp::create(rewriter, loc, writeVal2, valueCRow2);
1778 vector::StoreOp::create(rewriter, loc, writeVal1, resultBuffer,
1780 vector::StoreOp::create(rewriter, loc, writeVal2, resultBuffer,
1783 scf::YieldOp::create(nestedBuilder, loc);
1787 SmallVector<Value> writeResults;
1788 for (
unsigned int i = 0; i < M; i = i + 16) {
1789 for (
unsigned int j = 0; j < N; j = j + 16) {
1793 auto vectorType = VectorType::get({16, 16}, opType);
1796 (dyn_cast<ShapedType>(resultBuffer.getType())).getRank();
1797 Value padding = ub::PoisonOp::create(rewriter, loc, opType);
1800 SmallVector<bool> inBounds(vectorType.getRank(),
true);
1802 auto vec1 = vector::TransferReadOp::create(
1803 rewriter, loc, vectorType, resultBuffer,
1804 ValueRange{indexOp_i, indexOp_j}, padding, map, inBounds);
1805 writeResults.push_back(vec1);
1809 for (
auto [idx, acc] : carriedAccs) {
1810 Type resultType = writeResults[idx].getType();
1811 if (acc.
getType() != resultType)
1812 acc = vector::ShapeCastOp::create(rewriter, loc, resultType, acc);
1813 if (isa<FloatType>(opType))
1815 arith::AddFOp::create(rewriter, loc, writeResults[idx], acc);
1818 arith::AddIOp::create(rewriter, loc, writeResults[idx], acc);
1822 for (
size_t i = 0; i < ops.size(); i++) {
1823 vector::ContractionOp contOp = ops[i];
1824 Value vecRow = writeResults[i];
1827 if (
auto vecType = dyn_cast<VectorType>(resultWriteOp.
getType()))
1828 vecRow = vector::ShapeCastOp::create(rewriter, loc, vecType,
1841 patterns.
add<VectorContractToAMXDotProduct>(patterns.
getContext());
static void contract(RootOrderingGraph &graph, ArrayRef< Value > cycle, const DenseMap< Value, unsigned > &parentDepths, DenseMap< Value, Value > &actualSource, DenseMap< Value, Value > &actualTarget)
Contracts the specified cycle in the given graph in-place.
static AffineMap getMinorIdentityMap(unsigned dims, unsigned results, MLIRContext *context)
Returns an identity affine map (d0, ..., dn) -> (dp, ..., dn) on the most minor dimensions.
Attributes are known-constant values of operations.
IntegerAttr getIndexAttr(int64_t value)
FloatType getF8E5M2Type()
IntegerType getIntegerType(unsigned width)
MLIRContext * getContext() const
FloatType getF8E4M3FNType()
This is a utility class for mapping one set of IR entities to another.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
IRValueT get() const
Return the current value being used by this operand.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
This class represents a single result from folding an operation.
This class represents an operand of an operation.
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
Operation is the basic unit of execution within MLIR.
Value getOperand(unsigned idx)
Block * getBlock()
Returns the operation block that contains this operation.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
unsigned getNumOperands()
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
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.
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
user_iterator user_begin() const
unsigned getNumUses() const
This method computes the number of uses of this Value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Region * getParentRegion()
Return the Region in which this Value is defined.
use_iterator use_begin() const
Specialization of arith.constant op that returns an integer of index type.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Operation * getOwner() const
Return the owner of this operand.
mlir::x86::AMXTileType TileType
bool isInVnniLayout(Operation *op, llvm::ArrayRef< AffineMap > indexingMaps, std::optional< unsigned > blockingFactor=std::nullopt)
Value contractionUsersAfterYield(Value v)
Operation * traceToVectorReadLikeParentOperation(Value v)
bool validatePairVectorContract(vector::ContractionOp contractOp, vector::ContractionOp pairContOp, bool rhsHasMultipleNonUnitDims, int64_t nonUnitDimValue)
void populateVectorContractToAMXDotProductPatterns(RewritePatternSet &patterns)
Include the generated interface declarations.
OpFoldResult getAsIndexOpFoldResult(MLIRContext *ctx, int64_t val)
Convert int64_t to integer attributes of index type and return them as OpFoldResult.
bool isZeroIntegerOrFloat(OpFoldResult v)
Return "true" if v is an integer/float value/attribute with constant value zero.
bool isZeroInteger(OpFoldResult v)
Return "true" if v is an integer value/attribute with constant value 0.
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
SmallVector< int64_t, 2 > ReassociationIndices
Convenience wrapper for patterns that are only intended for default contractions, i....
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.