33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/TypeSwitch.h"
35#include "llvm/Support/DebugLog.h"
37#define DEBUG_TYPE "vector-to-nvgpu"
40#define GEN_PASS_DEF_CONVERTVECTORTONVGPUPASS
41#include "mlir/Conversion/Passes.h.inc"
52template <
typename TransferOpType>
56 indices.append(xferOp.getIndices().begin(), xferOp.getIndices().end());
58 unsigned offsetsIdx = 0;
59 for (
auto expr : xferOp.getPermutationMap().getResults()) {
60 if (
auto dim = dyn_cast<AffineDimExpr>(expr)) {
63 dims.push_back(prevIdx);
66 rewriter, loc, d0 + offsetMap.
getResult(offsetsIdx++), dims);
79 auto infer = [&](MapList m) {
84 auto iteratorTypes =
contract.getIteratorTypes().getValue();
92 if (
contract.getIndexingMapsArray() != infer({{m, k}, {n, k}, {m, n}}))
103 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
105 if (failed(warpMatrixInfo))
109 if (failed(contractOp))
116 return (cast<VectorType>(op->getResult(0).getType()) ==
117 cast<VectorType>((*contractOp).getRhs().getType()));
119 return (cast<VectorType>(op->getResult(0).getType()) ==
120 cast<VectorType>((*contractOp).getAcc().getType()));
126 if (isa<scf::ForOp, scf::YieldOp>(op))
131 auto maskableOp = dyn_cast<vector::MaskableOpInterface>(op);
132 if (maskableOp && maskableOp.isMasked())
134 if (
auto transferRead = dyn_cast<vector::TransferReadOp>(op))
136 if (
auto transferWrite = dyn_cast<vector::TransferWriteOp>(op))
138 if (
auto extractStridedSlice = dyn_cast<vector::ExtractStridedSliceOp>(op))
140 if (
auto contract = dyn_cast<vector::ContractionOp>(op))
142 if (
auto constant = dyn_cast<arith::ConstantOp>(op))
144 if (
auto broadcast = dyn_cast<vector::BroadcastOp>(op))
146 if (
auto signedExtend = dyn_cast<arith::ExtSIOp>(op))
148 if (
auto unsignedExtend = dyn_cast<arith::ExtUIOp>(op))
157 return llvm::any_of(op->
getResultTypes(), llvm::IsaPred<VectorType>);
160 backwardSliceOptions.
filter = hasVectorDest;
166 forwardSliceOptions.
filter = hasVectorSrc;
172 auto getCachedBackwardSlice =
174 auto [it,
inserted] = backwardSliceCache.try_emplace(currentOp);
181 assert(
result.succeeded() &&
"expected a backward slice");
183 it->second = backwardSlice.takeVector();
187 auto getCachedForwardSlice =
189 auto [it,
inserted] = forwardSliceCache.try_emplace(currentOp);
198 if (
auto forOp = dyn_cast<scf::ForOp>(currentOp)) {
199 for (
Value forOpResult : forOp.getResults())
206 it->second = forwardSlice.takeVector();
210 auto cachedSupportsMMAMatrixType = [&](
Operation *currentOp) {
212 supportsMMAMatrixTypeCache.try_emplace(currentOp,
false);
220 if (!isa<vector::ContractionOp>(nestedOp) &&
223 if (opToConvert.contains(nestedOp))
227 dependentOps.insert(nestedOp);
228 unsigned currentIndex = 0;
229 while (currentIndex != dependentOps.size()) {
230 Operation *currentOp = dependentOps[currentIndex++];
231 dependentOps.insert_range(getCachedBackwardSlice(currentOp));
232 dependentOps.insert_range(getCachedForwardSlice(currentOp));
237 if (llvm::any_of(dependentOps, [&](
Operation *op) {
238 if (!cachedSupportsMMAMatrixType(op)) {
239 LDBG() <<
"cannot convert op: " << *op;
246 opToConvert.insert_range(dependentOps);
256 regInfo.elementsPerRegister};
257 Type elType = regInfo.registerLLVMType;
258 if (
auto vecType = dyn_cast<VectorType>(elType))
259 elType = vecType.getElementType();
260 return VectorType::get(
shape, elType);
270 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
272 if (failed(warpMatrixInfo)) {
273 LDBG() <<
"no warpMatrixInfo";
277 FailureOr<nvgpu::FragmentElementInfo> regInfo =
278 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
279 if (failed(regInfo)) {
280 LDBG() <<
"not mma sync reg info";
285 auto dense = dyn_cast<SplatElementsAttr>(op.getValue());
287 LDBG() <<
"not a splat";
292 rewriter, op.getLoc(), vectorType,
294 valueMapping[op.getResult()] =
result;
309 LDBG() <<
"Failed because the result of `vector.transfer_read` "
310 "is not a 2d operand";
319 auto exprM = dyn_cast<AffineDimExpr>(dM);
320 auto exprN = dyn_cast<AffineDimExpr>(dN);
322 if (!exprM || !exprN) {
323 LDBG() <<
"Failed because expressions are not affine dim "
324 "expressions, then transpose cannot be determined.";
328 return exprM.getPosition() > exprN.getPosition();
338 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
340 if (failed(warpMatrixInfo)) {
341 LDBG() <<
"no warpMatrixInfo";
345 FailureOr<nvgpu::FragmentElementInfo> regInfo =
346 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
347 if (failed(regInfo)) {
348 LDBG() <<
"not mma sync reg info";
353 if (failed(transpose)) {
354 LDBG() <<
"failed to determine the transpose";
356 op,
"Op should likely not be converted to a nvgpu.ldmatrix call.");
359 FailureOr<nvgpu::LdMatrixParams> params =
360 nvgpu::getLdMatrixParams(*warpMatrixInfo, *transpose);
362 if (failed(params)) {
363 LDBG() <<
"failed to convert vector.transfer_read to ldmatrix. "
364 <<
"Op should likely not be converted to a nvgpu.ldmatrix call.";
366 op,
"failed to convert vector.transfer_read to ldmatrix; this op "
367 "likely should not be converted to a nvgpu.ldmatrix call.");
371 auto laneId = gpu::LaneIdOp::create(rewriter, loc,
nullptr);
372 FailureOr<AffineMap> offsets =
373 nvgpu::getLaneIdToLdMatrixMatrixCoord(rewriter, loc, *params);
374 if (failed(offsets)) {
375 LDBG() <<
"no offsets";
385 nvgpu::LdMatrixOp newOp =
386 nvgpu::LdMatrixOp::create(rewriter, loc, vectorType, op.getBase(),
387 indices, *transpose, params->numTiles);
388 valueMapping[op] = newOp->getResult(0);
399 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
401 if (failed(warpMatrixInfo))
403 FailureOr<nvgpu::FragmentElementInfo> regInfo =
404 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
405 if (failed(regInfo)) {
407 op,
"Failed to deduce register fragment type during "
408 "conversion to distributed non-ldmatrix compatible load");
411 Value laneId = gpu::LaneIdOp::create(rewriter, loc,
nullptr);
414 Type loadedElType = regInfo->registerLLVMType;
417 Value fill = arith::ConstantOp::create(
418 rewriter, op.getLoc(), vectorType.getElementType(),
419 rewriter.
getZeroAttr(vectorType.getElementType()));
421 vector::BroadcastOp::create(rewriter, op.getLoc(), vectorType, fill);
423 bool isTransposeLoad = !op.getPermutationMap().isMinorIdentity();
427 if (!isTransposeLoad) {
428 if (!isa<VectorType>(loadedElType)) {
429 loadedElType = VectorType::get({1}, loadedElType);
432 for (
int i = 0; i < vectorType.getShape()[0]; i++) {
433 FailureOr<AffineMap> coords = nvgpu::getLaneIdAndValueIdToOperandCoord(
434 rewriter, op.getLoc(), *warpMatrixInfo);
438 Value logicalValueId = arith::ConstantOp::create(
440 rewriter.
getIndexAttr(i * regInfo->elementsPerRegister));
443 rewriter, op, *coords, {laneId, logicalValueId}, newIndices);
445 Value el = vector::LoadOp::create(rewriter, loc, loadedElType,
446 op.getBase(), newIndices);
447 result = vector::InsertOp::create(rewriter, loc, el,
result, i);
450 if (
auto vecType = dyn_cast<VectorType>(loadedElType)) {
451 loadedElType = vecType.getElementType();
453 for (
int i = 0; i < vectorType.getShape()[0]; i++) {
454 for (
unsigned innerIdx = 0; innerIdx < vectorType.getShape()[1];
457 Value logicalValueId = arith::ConstantOp::create(
459 rewriter.
getIndexAttr(i * regInfo->elementsPerRegister + innerIdx));
460 FailureOr<AffineMap> coords = nvgpu::getLaneIdAndValueIdToOperandCoord(
461 rewriter, op.getLoc(), *warpMatrixInfo);
467 rewriter, op, *coords, {laneId, logicalValueId}, newIndices);
468 Value el = memref::LoadOp::create(rewriter, op.getLoc(), loadedElType,
469 op.getBase(), newIndices);
470 result = vector::InsertOp::create(rewriter, op.getLoc(), el,
result,
476 valueMapping[op.getResult()] =
result;
483 dyn_cast_or_null<gpu::AddressSpaceAttr>(type.getMemorySpace());
484 return addressSpace &&
485 addressSpace.getValue() == gpu::GPUDialect::getWorkgroupAddressSpace();
497 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
499 if (failed(warpMatrixInfo))
502 bool isLdMatrixCompatible =
504 nvgpu::inferTileWidthInBits(*warpMatrixInfo) == 128;
506 VectorType vecTy = op.getVectorType();
507 int64_t bitWidth = vecTy.getElementType().getIntOrFloatBitWidth();
512 if (!op.getPermutationMap().isMinorIdentity() &&
513 (bitWidth != 16 || vecTy.getDimSize(1) < 8 ||
514 vecTy.getDimSize(0) * bitWidth < 128))
515 isLdMatrixCompatible =
false;
517 if (!isLdMatrixCompatible)
530 auto it = valueMapping.find(op.getVector());
531 if (it == valueMapping.end())
533 Value matrix = it->second;
535 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
537 if (failed(warpMatrixInfo))
539 FailureOr<nvgpu::FragmentElementInfo> regInfo =
540 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
545 Value laneId = gpu::LaneIdOp::create(rewriter, loc,
nullptr);
547 for (
unsigned i = 0; i < vectorType.getShape()[0]; i++) {
548 Value logicalValueId = arith::ConstantOp::create(
550 rewriter.
getIndexAttr(i * regInfo->elementsPerRegister));
551 FailureOr<AffineMap> coords = nvgpu::getLaneIdAndValueIdToOperandCoord(
552 rewriter, op.getLoc(), *warpMatrixInfo);
560 rewriter, op, *coords, {laneId, logicalValueId}, newIndices);
561 vector::StoreOp::create(rewriter, loc, el, op.getBase(), newIndices);
564 LDBG() <<
"erase: " << op;
571 for (
auto attr : arrayAttr)
572 results.push_back(cast<IntegerAttr>(attr).getInt());
577 vector::ExtractStridedSliceOp op,
584 FailureOr<nvgpu::WarpMatrixInfo> warpMatrixInfo =
586 if (failed(warpMatrixInfo))
589 FailureOr<nvgpu::FragmentElementInfo> mmaSyncFragmentInfo =
590 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
591 if (failed(mmaSyncFragmentInfo))
595 auto transferReadOp = op.getSource().getDefiningOp<vector::TransferReadOp>();
600 if (failed(warpMatrixInfo))
603 FailureOr<nvgpu::FragmentElementInfo> ldFragmentInfo =
604 nvgpu::getMmaSyncRegisterType(*warpMatrixInfo);
605 if (failed(ldFragmentInfo))
609 (mmaSyncFragmentInfo->elementsPerRegister ==
610 ldFragmentInfo->elementsPerRegister) &&
611 "Number of elements per register should be same for load and mma.sync");
614 std::array<int64_t, 2> strides = {1,
616 std::array<int64_t, 2> sliceShape = {
617 mmaSyncFragmentInfo->numRegistersPerFragment,
618 mmaSyncFragmentInfo->elementsPerRegister};
619 auto it = valueMapping.find(transferReadOp);
620 if (it == valueMapping.end())
622 auto sourceVector = it->second;
635 std::array<int64_t, 2> sliceOffset = {0, 0};
637 if (offsets[0] && offsets[1])
638 return op->emitError() <<
"Slicing fragments in 2D is not supported. ";
640 sliceOffset[0] = (warpVectorShape[0] / offsets[0]);
642 sliceOffset[0] = (warpVectorShape[1] / offsets[1]);
644 Value newOp = vector::ExtractStridedSliceOp::create(
645 rewriter, loc, sourceVector, sliceOffset, sliceShape, strides);
647 valueMapping[op] = newOp;
657 auto itA = valueMapping.find(op.getLhs());
658 auto itB = valueMapping.find(op.getRhs());
659 auto itC = valueMapping.find(op.getAcc());
660 if (itA == valueMapping.end() || itB == valueMapping.end() ||
661 itC == valueMapping.end())
663 Value opA = itA->second, opB = itB->second, opC = itC->second;
664 int64_t m = cast<VectorType>(op.getLhs().getType()).getShape()[0];
665 int64_t n = cast<VectorType>(op.getRhs().getType()).getShape()[0];
666 int64_t k = cast<VectorType>(op.getLhs().getType()).getShape()[1];
667 Value matmul = nvgpu::MmaSyncOp::create(rewriter, op.getLoc(), opA, opB, opC,
669 valueMapping[op.getResult()] = matmul;
684 .Case([&](vector::TransferReadOp transferReadOp) {
688 .Case([&](vector::TransferWriteOp transferWriteOp) {
692 .Case([&](vector::ExtractStridedSliceOp extractStridedSliceOp) {
696 .Case([&](vector::ContractionOp contractionOp) {
700 .Case([&](scf::ForOp forOp) {
703 .Case([&](scf::YieldOp yieldOp) {
706 .Case([&](arith::ConstantOp constOp) {
710 return op->
emitError() <<
"unhandled vector to mma type: " << *op;
714 <<
"failed to convert op during vector-to-nvgpu conversion";
721struct ConvertVectorToNVGPUPass
722 :
public impl::ConvertVectorToNVGPUPassBase<ConvertVectorToNVGPUPass> {
724 void runOnOperation()
override {
728 return signalPassFailure();
732 return signalPassFailure();
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
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 Value broadcast(Location loc, Value toBroadcast, unsigned numElements, const TypeConverter &typeConverter, ConversionPatternRewriter &rewriter)
Broadcasts the value to vector with numElements number of elements.
static bool supportsMMaMatrixType(Operation *op)
static LogicalResult convertContractOpToMmaSync(RewriterBase &rewriter, vector::ContractionOp op, llvm::DenseMap< Value, Value > &valueMapping)
static bool isSharedMemory(MemRefType type)
Return true if this is a shared memory memref type.
static VectorType getMmaSyncVectorOperandType(const nvgpu::FragmentElementInfo ®Info)
Returns the vector type which represents a matrix fragment.
static void populateFromInt64AttrArray(ArrayAttr arrayAttr, SmallVectorImpl< int64_t > &results)
static FailureOr< bool > isTransposed(vector::TransferReadOp op)
Check if the loaded matrix operand requires transposed.
static LogicalResult convertTransferReadToLoads(RewriterBase &rewriter, vector::TransferReadOp op, llvm::DenseMap< Value, Value > &valueMapping)
Converts a vector.transfer_read operation directly to either a vector.load or a nvgpu....
static LogicalResult creatLdMatrixCompatibleLoads(RewriterBase &rewriter, vector::TransferReadOp op, llvm::DenseMap< Value, Value > &valueMapping)
static bool contractSupportsMMAMatrixType(vector::ContractionOp contract)
static bool extractStridedSliceSupportsMMAMatrixType(vector::ExtractStridedSliceOp op)
Returns true if the extract strided slice op is supported with mma.sync path.
static LogicalResult convertConstantOpMmaSync(RewriterBase &rewriter, arith::ConstantOp op, llvm::DenseMap< Value, Value > &valueMapping)
Convert a 2D splat ConstantOp to a SubgroupMmaConstantMatrix op.
static SetVector< Operation * > getOpToConvert(mlir::Operation *op)
static LogicalResult convertTransferWriteToStores(RewriterBase &rewriter, vector::TransferWriteOp op, llvm::DenseMap< Value, Value > &valueMapping)
static void getXferIndices(RewriterBase &rewriter, TransferOpType xferOp, AffineMap offsetMap, ArrayRef< Value > dimValues, SmallVector< Value, 4 > &indices)
For a vector TransferOpType xferOp, an empty indices vector, and an AffineMap representing offsets to...
static LogicalResult convertExtractStridedSlice(RewriterBase &rewriter, vector::ExtractStridedSliceOp op, llvm::DenseMap< Value, Value > &valueMapping)
static LogicalResult createNonLdMatrixLoads(RewriterBase &rewriter, vector::TransferReadOp op, llvm::DenseMap< Value, Value > &valueMapping)
Base type for affine expression.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
unsigned getNumDims() const
unsigned getNumResults() const
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
AffineExpr getResult(unsigned idx) const
static AffineMap getPermutationMap(ArrayRef< unsigned > permutation, MLIRContext *context)
Returns an AffineMap representing a permutation.
Attributes are known-constant values of operations.
This class represents an argument of a Block.
IntegerAttr getIndexAttr(int64_t value)
TypedAttr getZeroAttr(Type type)
AffineExpr getAffineDimExpr(unsigned position)
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
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.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Operation is the basic unit of execution within MLIR.
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
operand_type_range getOperandTypes()
result_type_range getResultTypes()
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),...
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...
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,...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
AffineApplyOp makeComposedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Returns a composed AffineApplyOp by composing map and operands with other AffineApplyOps supplying th...
FailureOr< vector::ContractionOp > getUserContract(Operation *op)
Returns the first user of the op that is vector.contract.
FailureOr< WarpMatrixInfo > getWarpMatrixInfo(Operation *op)
If op is a vector.transfer_write, return the WarpMatrixInfo for the vector operand.
bool canLowerToWarpMatrixOperation(vector::TransferWriteOp op)
Returns the number of bits in a single tile row.
bool isReductionIterator(Attribute attr)
Returns true if attr has "reduction" iterator type semantics.
bool isParallelIterator(Attribute attr)
Returns true if attr has "parallel" iterator type semantics.
void populateVectorContractCanonicalizeMatmulToMMT(RewritePatternSet &patterns, std::function< LogicalResult(vector::ContractionOp)> constraint=[](vector::ContractionOp) { return success();}, PatternBenefit=1)
Canonicalization of a vector.contract a, b, c with row-major matmul semantics to a contraction with M...
Include the generated interface declarations.
LogicalResult convertYieldOpForMMA(RewriterBase &rewriter, scf::YieldOp op, llvm::DenseMap< Value, Value > &valueMapping)
Update a yield operation to yield the converted values.
LogicalResult getBackwardSlice(Operation *op, SetVector< Operation * > *backwardSlice, const BackwardSliceOptions &options={})
Fills backwardSlice with the computed backward slice (i.e.
bool broadcastSupportsMMAMatrixType(vector::BroadcastOp broadcastOp)
Return true if this is a broadcast from scalar to a 2D vector.
bool elementwiseSupportsMMAMatrixType(Operation *op)
Return true if the operation is supported as elementwise on an MMA matrix.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
LogicalResult convertForOpForMMA(RewriterBase &rewriter, scf::ForOp op, llvm::DenseMap< Value, Value > &valueMapping)
Extend loop-carried values with their converted counterparts.
LogicalResult applyPatternsGreedily(Region ®ion, 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...
bool constantSupportsMMAMatrixType(arith::ConstantOp constantOp)
Return true if the constant is a splat to a 2D vector so that it can be converted to an MMA constant ...
llvm::SetVector< T, Vector, Set, N > SetVector
SliceOptions ForwardSliceOptions
LogicalResult convertVectorToNVVMCompatibleMMASync(RewriterBase &rewriter, Operation *rootOp)
Convert vector ops nested under rootOp to vector and GPU operations compatible with the nvvm....
void populateVectorTransferReadTransposePatterns(RewritePatternSet &patterns)
Populate patterns that fold vector.transpose into vector.transfer_read, including through arithmetic ...
template bool integerExtendSupportsMMAMatrixType< arith::ExtSIOp >(arith::ExtSIOp)
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
template bool integerExtendSupportsMMAMatrixType< arith::ExtUIOp >(arith::ExtUIOp)
void populatePrepareVectorToNVMMAPatterns(RewritePatternSet &patterns)
Populate patterns that prepare vector operations for lowering to nvgpu.mma.sync operations.
SetVector< Operation * > topologicalSort(const SetVector< Operation * > &toSort)
Sorts all operations in toSort topologically while also considering region semantics.
void getForwardSlice(Operation *op, SetVector< Operation * > *forwardSlice, const ForwardSliceOptions &options={})
Fills forwardSlice with the computed forward slice (i.e.